test_ds.cpp 76.5 KB
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
#include "test_precomp.hpp"

using namespace cv;
using namespace std;

typedef  struct  CvTsSimpleSeq
{
    schar* array;
    int   count;
    int   max_count;
    int   elem_size;
} CvTsSimpleSeq;


static CvTsSimpleSeq*  cvTsCreateSimpleSeq( int max_count, int elem_size )
{
    CvTsSimpleSeq* seq = (CvTsSimpleSeq*)cvAlloc( sizeof(*seq) + max_count * elem_size );
    seq->elem_size = elem_size;
    seq->max_count = max_count;
    seq->count = 0;
    seq->array = (schar*)(seq + 1);
    return seq;
}


static void cvTsReleaseSimpleSeq( CvTsSimpleSeq** seq )
{
    cvFree( seq );
}


static schar*  cvTsSimpleSeqElem( CvTsSimpleSeq* seq, int index )
{
    assert( 0 <= index && index < seq->count );
    return seq->array + index * seq->elem_size;
}


static void  cvTsClearSimpleSeq( CvTsSimpleSeq* seq )
{
    seq->count = 0;
}


static void cvTsSimpleSeqShiftAndCopy( CvTsSimpleSeq* seq, int from_idx, int to_idx, void* elem=0 )
{
    int elem_size = seq->elem_size;
48

49 50 51
    if( from_idx == to_idx )
        return;
    assert( (from_idx > to_idx && !elem) || (from_idx < to_idx && elem) );
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66
    if( from_idx < seq->count )
    {
        memmove( seq->array + to_idx*elem_size, seq->array + from_idx*elem_size,
                (seq->count - from_idx)*elem_size );
    }
    seq->count += to_idx - from_idx;
    if( elem && to_idx > from_idx )
        memcpy( seq->array + from_idx*elem_size, elem, (to_idx - from_idx)*elem_size );
}

static void cvTsSimpleSeqInvert( CvTsSimpleSeq* seq )
{
    int i, k, len = seq->count, elem_size = seq->elem_size;
    schar *data = seq->array, t;
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
    for( i = 0; i < len/2; i++ )
    {
        schar* a = data + i*elem_size;
        schar* b = data + (len - i - 1)*elem_size;
        for( k = 0; k < elem_size; k++ )
            CV_SWAP( a[k], b[k], t );
    }
}

/****************************************************************************************\
 *                                simple cvset implementation                               *
 \****************************************************************************************/

typedef  struct  CvTsSimpleSet
{
    schar* array;
    int   count, max_count;
    int   elem_size;
    int*  free_stack;
    int   free_count;
} CvTsSimpleSet;


static void  cvTsClearSimpleSet( CvTsSimpleSet* set_header )
{
    int i;
    int elem_size = set_header->elem_size;
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    for( i = 0; i < set_header->max_count; i++ )
    {
        set_header->array[i*elem_size] = 0;
        set_header->free_stack[i] = set_header->max_count - i - 1;
    }
    set_header->free_count = set_header->max_count;
    set_header->count = 0;
}


static CvTsSimpleSet*  cvTsCreateSimpleSet( int max_count, int elem_size )
{
    CvTsSimpleSet* set_header = (CvTsSimpleSet*)cvAlloc( sizeof(*set_header) + max_count *
                                                        (elem_size + 1 + sizeof(int)));
    set_header->elem_size = elem_size + 1;
    set_header->max_count = max_count;
    set_header->free_stack = (int*)(set_header + 1);
    set_header->array = (schar*)(set_header->free_stack + max_count);
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    cvTsClearSimpleSet( set_header );
    return set_header;
}


static void cvTsReleaseSimpleSet( CvTsSimpleSet** set_header )
{
    cvFree( set_header );
}


static schar*  cvTsSimpleSetFind( CvTsSimpleSet* set_header, int index )
{
    int idx = index * set_header->elem_size;
    assert( 0 <= index && index < set_header->max_count );
    return set_header->array[idx] ? set_header->array + idx + 1 : 0;
}


static int  cvTsSimpleSetAdd( CvTsSimpleSet* set_header, void* elem )
{
    int idx, idx2;
    assert( set_header->free_count > 0 );
138

139 140 141 142 143 144 145
    idx = set_header->free_stack[--set_header->free_count];
    idx2 = idx * set_header->elem_size;
    assert( set_header->array[idx2] == 0 );
    set_header->array[idx2] = 1;
    if( set_header->elem_size > 1 )
        memcpy( set_header->array + idx2 + 1, elem, set_header->elem_size - 1 );
    set_header->count = MAX( set_header->count, idx + 1 );
146

147 148 149 150 151 152 153 154 155
    return idx;
}


static void  cvTsSimpleSetRemove( CvTsSimpleSet* set_header, int index )
{
    assert( set_header->free_count < set_header->max_count &&
           0 <= index && index < set_header->max_count );
    assert( set_header->array[index * set_header->elem_size] == 1 );
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
    set_header->free_stack[set_header->free_count++] = index;
    set_header->array[index * set_header->elem_size] = 0;
}


/****************************************************************************************\
 *                              simple graph implementation                               *
 \****************************************************************************************/

typedef  struct  CvTsSimpleGraph
{
    char* matrix;
    int   edge_size;
    int   oriented;
    CvTsSimpleSet* vtx;
} CvTsSimpleGraph;


static void  cvTsClearSimpleGraph( CvTsSimpleGraph* graph )
{
    int max_vtx_count = graph->vtx->max_count;
    cvTsClearSimpleSet( graph->vtx );
    memset( graph->matrix, 0, max_vtx_count * max_vtx_count * graph->edge_size );
}


static CvTsSimpleGraph*  cvTsCreateSimpleGraph( int max_vtx_count, int vtx_size,
                                               int edge_size, int oriented )
{
    CvTsSimpleGraph* graph;
187

188 189 190 191 192 193 194
    assert( max_vtx_count > 1 && vtx_size >= 0 && edge_size >= 0 );
    graph = (CvTsSimpleGraph*)cvAlloc( sizeof(*graph) +
                                      max_vtx_count * max_vtx_count * (edge_size + 1));
    graph->vtx = cvTsCreateSimpleSet( max_vtx_count, vtx_size );
    graph->edge_size = edge_size + 1;
    graph->matrix = (char*)(graph + 1);
    graph->oriented = oriented;
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
    cvTsClearSimpleGraph( graph );
    return graph;
}


static void cvTsReleaseSimpleGraph( CvTsSimpleGraph** graph )
{
    if( *graph )
    {
        cvTsReleaseSimpleSet( &(graph[0]->vtx) );
        cvFree( graph );
    }
}


static int  cvTsSimpleGraphAddVertex( CvTsSimpleGraph* graph, void* vertex )
{
    return cvTsSimpleSetAdd( graph->vtx, vertex );
}


static void  cvTsSimpleGraphRemoveVertex( CvTsSimpleGraph* graph, int index )
{
    int i, max_vtx_count = graph->vtx->max_count;
    int edge_size = graph->edge_size;
    cvTsSimpleSetRemove( graph->vtx, index );
222

223 224 225 226 227 228 229 230 231 232 233 234
    /* remove all the corresponding edges */
    for( i = 0; i < max_vtx_count; i++ )
    {
        graph->matrix[(i*max_vtx_count + index)*edge_size] =
        graph->matrix[(index*max_vtx_count + i)*edge_size] = 0;
    }
}


static void cvTsSimpleGraphAddEdge( CvTsSimpleGraph* graph, int idx1, int idx2, void* edge )
{
    int i, t, n = graph->oriented ? 1 : 2;
235

236 237
    assert( cvTsSimpleSetFind( graph->vtx, idx1 ) &&
           cvTsSimpleSetFind( graph->vtx, idx2 ));
238

239 240 241 242 243 244 245
    for( i = 0; i < n; i++ )
    {
        int ofs = (idx1*graph->vtx->max_count + idx2)*graph->edge_size;
        assert( graph->matrix[ofs] == 0 );
        graph->matrix[ofs] = 1;
        if( graph->edge_size > 1 )
            memcpy( graph->matrix + ofs + 1, edge, graph->edge_size - 1 );
246

247 248 249 250 251 252 253 254
        CV_SWAP( idx1, idx2, t );
    }
}


static void  cvTsSimpleGraphRemoveEdge( CvTsSimpleGraph* graph, int idx1, int idx2 )
{
    int i, t, n = graph->oriented ? 1 : 2;
255

256 257
    assert( cvTsSimpleSetFind( graph->vtx, idx1 ) &&
           cvTsSimpleSetFind( graph->vtx, idx2 ));
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
    for( i = 0; i < n; i++ )
    {
        int ofs = (idx1*graph->vtx->max_count + idx2)*graph->edge_size;
        assert( graph->matrix[ofs] == 1 );
        graph->matrix[ofs] = 0;
        CV_SWAP( idx1, idx2, t );
    }
}


static schar*  cvTsSimpleGraphFindVertex( CvTsSimpleGraph* graph, int index )
{
    return cvTsSimpleSetFind( graph->vtx, index );
}


static char*  cvTsSimpleGraphFindEdge( CvTsSimpleGraph* graph, int idx1, int idx2 )
{
    if( cvTsSimpleGraphFindVertex( graph, idx1 ) &&
       cvTsSimpleGraphFindVertex( graph, idx2 ))
    {
        char* edge = graph->matrix + (idx1 * graph->vtx->max_count + idx2)*graph->edge_size;
        if( edge[0] ) return edge + 1;
    }
    return 0;
}


static int  cvTsSimpleGraphVertexDegree( CvTsSimpleGraph* graph, int index )
{
    int i, count = 0;
    int edge_size = graph->edge_size;
    int max_vtx_count = graph->vtx->max_count;
    assert( cvTsSimpleGraphFindVertex( graph, index ) != 0 );
293

294 295 296 297 298
    for( i = 0; i < max_vtx_count; i++ )
    {
        count += graph->matrix[(i*max_vtx_count + index)*edge_size] +
        graph->matrix[(index*max_vtx_count + i)*edge_size];
    }
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
    if( !graph->oriented )
    {
        assert( count % 2 == 0 );
        count /= 2;
    }
    return count;
}


///////////////////////////////////// the tests //////////////////////////////////

#define CV_TS_SEQ_CHECK_CONDITION( expr, err_msg )          \
if( !(expr) )                                               \
{                                                           \
set_error_context( #expr, err_msg, __FILE__, __LINE__ );    \
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );\
throw -1;                                                   \
}

class Core_DynStructBaseTest : public cvtest::BaseTest
{
public:
    Core_DynStructBaseTest();
    virtual ~Core_DynStructBaseTest();
    bool can_do_fast_forward();
    void clear();
326

327 328 329 330 331 332 333 334
protected:
    int read_params( CvFileStorage* fs );
    void run_func(void);
    void set_error_context( const char* condition,
                           const char* err_msg,
                           const char* file, int line );
    int test_seq_block_consistence( int _struct_idx, CvSeq* seq, int total );
    void update_progressbar();
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
    int struct_count, max_struct_size, iterations, generations;
    int min_log_storage_block_size, max_log_storage_block_size;
    int min_log_elem_size, max_log_elem_size;
    int gen, struct_idx, iter;
    int test_progress;
    int64 start_time;
    double cpu_freq;
    vector<void*> cxcore_struct;
    vector<void*> simple_struct;
    Ptr<CvMemStorage> storage;
};


Core_DynStructBaseTest::Core_DynStructBaseTest()
{
    struct_count = 2;
    max_struct_size = 2000;
    min_log_storage_block_size = 7;
    max_log_storage_block_size = 12;
    min_log_elem_size = 0;
    max_log_elem_size = 8;
    generations = 10;
    iterations = max_struct_size*2;
    gen = struct_idx = iter = -1;
    test_progress = -1;
}


Core_DynStructBaseTest::~Core_DynStructBaseTest()
{
    clear();
}


void Core_DynStructBaseTest::run_func()
{
}

bool Core_DynStructBaseTest::can_do_fast_forward()
{
    return false;
}


void Core_DynStructBaseTest::clear()
{
    cvtest::BaseTest::clear();
}


int Core_DynStructBaseTest::read_params( CvFileStorage* fs )
{
    int code = cvtest::BaseTest::read_params( fs );
    double sqrt_scale = sqrt(ts->get_test_case_count_scale());
    if( code < 0 )
        return code;
392

393 394 395 396 397 398
    struct_count = cvReadInt( find_param( fs, "struct_count" ), struct_count );
    max_struct_size = cvReadInt( find_param( fs, "max_struct_size" ), max_struct_size );
    generations = cvReadInt( find_param( fs, "generations" ), generations );
    iterations = cvReadInt( find_param( fs, "iterations" ), iterations );
    generations = cvRound(generations*sqrt_scale);
    iterations = cvRound(iterations*sqrt_scale);
399

400 401 402 403 404 405
    min_log_storage_block_size = cvReadInt( find_param( fs, "min_log_storage_block_size" ),
                                           min_log_storage_block_size );
    max_log_storage_block_size = cvReadInt( find_param( fs, "max_log_storage_block_size" ),
                                           max_log_storage_block_size );
    min_log_elem_size = cvReadInt( find_param( fs, "min_log_elem_size" ), min_log_elem_size );
    max_log_elem_size = cvReadInt( find_param( fs, "max_log_elem_size" ), max_log_elem_size );
406

407 408 409 410
    struct_count = cvtest::clipInt( struct_count, 1, 100 );
    max_struct_size = cvtest::clipInt( max_struct_size, 1, 1<<20 );
    generations = cvtest::clipInt( generations, 1, 100 );
    iterations = cvtest::clipInt( iterations, 100, 1<<20 );
411

412 413 414
    min_log_storage_block_size = cvtest::clipInt( min_log_storage_block_size, 7, 20 );
    max_log_storage_block_size = cvtest::clipInt( max_log_storage_block_size,
                                             min_log_storage_block_size, 20 );
415

416 417
    min_log_elem_size = cvtest::clipInt( min_log_elem_size, 0, 8 );
    max_log_elem_size = cvtest::clipInt( max_log_elem_size, min_log_elem_size, 10 );
418

419 420 421 422 423 424 425
    return 0;
}


void Core_DynStructBaseTest::update_progressbar()
{
    int64 t;
426

427 428 429 430 431 432
    if( test_progress < 0 )
    {
        test_progress = 0;
        cpu_freq = cv::getTickFrequency();
        start_time = cv::getTickCount();
    }
433

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    t = cv::getTickCount();
    test_progress = update_progress( test_progress, 0, 0, (double)(t - start_time)/cpu_freq );
}


void Core_DynStructBaseTest::set_error_context( const char* condition,
                                                const char* err_msg,
                                                const char* filename, int lineno )
{
    ts->printf( cvtest::TS::LOG, "file %s, line %d: %s\n(\"%s\" failed).\n"
               "generation = %d, struct_idx = %d, iter = %d\n",
               filename, lineno, err_msg, condition, gen, struct_idx, iter );
    ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
}


int Core_DynStructBaseTest::test_seq_block_consistence( int _struct_idx, CvSeq* seq, int total )
{
    int sum = 0;
    struct_idx = _struct_idx;
454

455
    CV_TS_SEQ_CHECK_CONDITION( seq != 0, "Null sequence pointer" );
456

457 458 459 460
    if( seq->first )
    {
        CvSeqBlock* block = seq->first;
        CvSeqBlock* prev_block = block->prev;
461

462
        int delta_idx = seq->first->start_index;
463

464 465 466 467 468 469 470 471 472 473 474
        for( ;; )
        {
            CV_TS_SEQ_CHECK_CONDITION( sum == block->start_index - delta_idx &&
                                      block->count > 0 && block->prev == prev_block &&
                                      prev_block->next == block,
                                      "sequence blocks are inconsistent" );
            sum += block->count;
            prev_block = block;
            block = block->next;
            if( block == seq->first ) break;
        }
475

476 477 478 479
        CV_TS_SEQ_CHECK_CONDITION( block->prev->count * seq->elem_size +
                                  block->prev->data <= seq->block_max,
                                  "block->data or block_max pointer are incorrect" );
    }
480

481 482
    CV_TS_SEQ_CHECK_CONDITION( seq->total == sum && sum == total,
                              "total number of elements is incorrect" );
483

484 485 486 487 488 489 490 491 492 493
    return 0;
}


/////////////////////////////////// sequence tests ////////////////////////////////////

class Core_SeqBaseTest : public Core_DynStructBaseTest
{
public:
    Core_SeqBaseTest();
494
    virtual ~Core_SeqBaseTest();
495 496
    void clear();
    void run( int );
497

498 499 500 501 502 503 504 505 506 507 508
protected:
    int test_multi_create();
    int test_get_seq_elem( int _struct_idx, int iters );
    int test_get_seq_reading( int _struct_idx, int iters );
    int test_seq_ops( int iters );
};

Core_SeqBaseTest::Core_SeqBaseTest()
{
}

509 510 511 512
Core_SeqBaseTest::~Core_SeqBaseTest()
{
    clear();
}
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

void Core_SeqBaseTest::clear()
{
    for( size_t i = 0; i < simple_struct.size(); i++ )
        cvTsReleaseSimpleSeq( (CvTsSimpleSeq**)&simple_struct[i] );
    Core_DynStructBaseTest::clear();
}


int Core_SeqBaseTest::test_multi_create()
{
    vector<CvSeqWriter> writer(struct_count);
    vector<int> pos(struct_count);
    vector<int> index(struct_count);
    int  cur_count, elem_size;
    RNG& rng = ts->get_rng();
529

530 531 532 533
    for( int i = 0; i < struct_count; i++ )
    {
        double t;
        CvTsSimpleSeq* sseq;
534

535 536
        pos[i] = -1;
        index[i] = i;
537

538 539 540 541
        t = cvtest::randReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size;
        elem_size = cvRound( exp(t * CV_LOG2) );
        elem_size = MIN( elem_size, (int)(storage->block_size - sizeof(void*) -
                                          sizeof(CvSeqBlock) - sizeof(CvMemBlock)) );
542

543 544 545 546 547 548 549
        cvTsReleaseSimpleSeq( (CvTsSimpleSeq**)&simple_struct[i] );
        simple_struct[i] = sseq = cvTsCreateSimpleSeq( max_struct_size, elem_size );
        cxcore_struct[i] = 0;
        sseq->count = cvtest::randInt( rng ) % max_struct_size;
        Mat m( 1, MAX(sseq->count,1)*elem_size, CV_8UC1, sseq->array );
        cvtest::randUni( rng, m, Scalar::all(0), Scalar::all(256) );
    }
550

551 552 553 554 555 556 557
    for( cur_count = struct_count; cur_count > 0; cur_count-- )
    {
        for(;;)
        {
            int k = cvtest::randInt( rng ) % cur_count;
            struct_idx = index[k];
            CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[struct_idx];
558

559 560 561 562 563
            if( pos[struct_idx] < 0 )
            {
                int hdr_size = (cvtest::randInt(rng) % 10)*4 + sizeof(CvSeq);
                hdr_size = MIN( hdr_size, (int)(storage->block_size - sizeof(CvMemBlock)) );
                elem_size = sseq->elem_size;
564

565 566 567 568 569 570 571 572 573 574
                if( cvtest::randInt(rng) % 2 )
                {
                    cvStartWriteSeq( 0, hdr_size, elem_size, storage, &writer[struct_idx] );
                }
                else
                {
                    CvSeq* s;
                    s = cvCreateSeq( 0, hdr_size, elem_size, storage );
                    cvStartAppendToSeq( s, &writer[struct_idx] );
                }
575

576 577 578
                cvSetSeqBlockSize( writer[struct_idx].seq, cvtest::randInt( rng ) % 10000 );
                pos[struct_idx] = 0;
            }
579

580 581 582 583 584 585 586 587 588
            update_progressbar();
            if( pos[struct_idx] == sseq->count )
            {
                cxcore_struct[struct_idx] = cvEndWriteSeq( &writer[struct_idx] );
                /* del index */
                for( ; k < cur_count-1; k++ )
                    index[k] = index[k+1];
                break;
            }
589

590 591 592 593 594 595 596
            {
                schar* el = cvTsSimpleSeqElem( sseq, pos[struct_idx] );
                CV_WRITE_SEQ_ELEM_VAR( el, writer[struct_idx] );
            }
            pos[struct_idx]++;
        }
    }
597

598 599 600 601 602 603 604
    return 0;
}


int  Core_SeqBaseTest::test_get_seq_elem( int _struct_idx, int iters )
{
    RNG& rng = ts->get_rng();
605

606 607 608
    CvSeq* seq = (CvSeq*)cxcore_struct[_struct_idx];
    CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[_struct_idx];
    struct_idx = _struct_idx;
609

610
    assert( seq->total == sseq->count );
611

612 613
    if( sseq->count == 0 )
        return 0;
614

615 616 617 618 619 620 621 622
    for( int i = 0; i < iters; i++ )
    {
        int idx = cvtest::randInt(rng) % (sseq->count*3) - sseq->count*3/2;
        int idx0 = (unsigned)idx < (unsigned)(sseq->count) ? idx : idx < 0 ?
        idx + sseq->count : idx - sseq->count;
        int bad_range = (unsigned)idx0 >= (unsigned)(sseq->count);
        schar* elem;
         elem = cvGetSeqElem( seq, idx );
623

624 625 626 627 628 629 630 631 632 633 634
        if( bad_range )
        {
            CV_TS_SEQ_CHECK_CONDITION( elem == 0,
                                      "cvGetSeqElem doesn't "
                                      "handle \"out of range\" properly" );
        }
        else
        {
            CV_TS_SEQ_CHECK_CONDITION( elem != 0 &&
                                      !memcmp( elem, cvTsSimpleSeqElem(sseq, idx0), sseq->elem_size ),
                                      "cvGetSeqElem returns wrong element" );
635

636 637 638 639 640
             idx = cvSeqElemIdx(seq, elem );
            CV_TS_SEQ_CHECK_CONDITION( idx >= 0 && idx == idx0,
                                      "cvSeqElemIdx is incorrect" );
        }
    }
641

642 643 644 645 646 647 648 649 650 651 652 653 654 655
    return 0;
}


int  Core_SeqBaseTest::test_get_seq_reading( int _struct_idx, int iters )
{
    const int max_val = 3*5 + 2;
    CvSeq* seq = (CvSeq*)cxcore_struct[_struct_idx];
    CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[_struct_idx];
    int total = seq->total;
    RNG& rng = ts->get_rng();
    CvSeqReader reader;
    vector<schar> _elem(sseq->elem_size);
    schar* elem = &_elem[0];
656

657 658
    assert( total == sseq->count );
    this->struct_idx = _struct_idx;
659

660 661
    int pos = cvtest::randInt(rng) % 2;
    cvStartReadSeq( seq, &reader, pos );
662

663 664 665 666 667
    if( total == 0 )
    {
        CV_TS_SEQ_CHECK_CONDITION( reader.ptr == 0, "Empty sequence reader pointer is not NULL" );
        return 0;
    }
668

669
    pos = pos ? seq->total - 1 : 0;
670

671 672
    CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos(&reader),
                              "initial reader position is wrong" );
673

674 675 676
    for( iter = 0; iter < iters; iter++ )
    {
        int op = cvtest::randInt(rng) % max_val;
677

678 679 680 681 682
        if( op >= max_val - 2 )
        {
            int new_pos, new_pos0;
            int bad_range;
            int is_relative = op == max_val - 1;
683

684 685
            new_pos = cvtest::randInt(rng) % (total*2) - total;
            new_pos0 = new_pos + (is_relative ? pos : 0 );
686

687 688
            if( new_pos0 < 0 ) new_pos0 += total;
            if( new_pos0 >= total ) new_pos0 -= total;
689

690 691
            bad_range = (unsigned)new_pos0 >= (unsigned)total;
             cvSetSeqReaderPos( &reader, new_pos, is_relative );
692

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
            if( !bad_range )
            {
                CV_TS_SEQ_CHECK_CONDITION( new_pos0 == cvGetSeqReaderPos( &reader ),
                                          "cvset reader position doesn't work" );
                pos = new_pos0;
            }
            else
            {
                CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos( &reader ),
                                          "reader doesn't stay at the current position after wrong positioning" );
            }
        }
        else
        {
            int direction = (op % 3) - 1;
            memcpy( elem, reader.ptr, sseq->elem_size );
709

710 711 712 713 714 715 716 717
            if( direction > 0 )
            {
                CV_NEXT_SEQ_ELEM( sseq->elem_size, reader );
            }
            else if( direction < 0 )
            {
                CV_PREV_SEQ_ELEM( sseq->elem_size, reader );
            }
718

719 720 721
            CV_TS_SEQ_CHECK_CONDITION( memcmp(elem, cvTsSimpleSeqElem(sseq, pos),
                                              sseq->elem_size) == 0, "reading is incorrect" );
            pos += direction;
Andrey Kamaev's avatar
Andrey Kamaev committed
722
            if( -pos > 0 ) pos += total;
723
            if( pos >= total ) pos -= total;
724

725 726 727 728
            CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos( &reader ),
                                      "reader doesn't move correctly after reading" );
        }
    }
729

730 731 732 733 734 735 736 737 738 739
    return 0;
}


int  Core_SeqBaseTest::test_seq_ops( int iters )
{
    const int max_op = 14;
    int max_elem_size = 0;
    schar* elem2 = 0;
    RNG& rng = ts->get_rng();
740

741 742
    for( int i = 0; i < struct_count; i++ )
        max_elem_size = MAX( max_elem_size, ((CvSeq*)cxcore_struct[i])->elem_size );
743

744 745 746
    vector<schar> elem_buf(max_struct_size*max_elem_size);
    schar* elem = (schar*)&elem_buf[0];
    Mat elem_mat;
747

748 749 750 751 752 753 754 755
    for( iter = 0; iter < iters; iter++ )
    {
        struct_idx = cvtest::randInt(rng) % struct_count;
        int op = cvtest::randInt(rng) % max_op;
        CvSeq* seq = (CvSeq*)cxcore_struct[struct_idx];
        CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[struct_idx];
        int elem_size = sseq->elem_size;
        int whence = 0, pos = 0, count = 0;
756

757 758 759 760 761 762 763
        switch( op )
        {
            case 0:
            case 1:
            case 2:  // push/pushfront/insert
                if( sseq->count == sseq->max_count )
                    break;
764

765 766
                elem_mat = Mat(1, elem_size, CV_8U, elem);
                cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
767

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                whence = op - 1;
                if( whence < 0 )
                {
                    pos = 0;
                    cvSeqPushFront( seq, elem );
                }
                else if( whence > 0 )
                {
                    pos = sseq->count;
                    cvSeqPush( seq, elem );
                }
                else
                {
                    pos = cvtest::randInt(rng) % (sseq->count + 1);
                    cvSeqInsert( seq, pos, elem );
                }
784

785 786 787 788 789 790 791
                cvTsSimpleSeqShiftAndCopy( sseq, pos, pos + 1, elem );
                elem2 = cvGetSeqElem( seq, pos );
                CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "The inserted element could not be retrieved" );
                CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count &&
                                          memcmp(elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
                                          "The inserted sequence element is wrong" );
                break;
792

793 794 795 796 797
            case 3:
            case 4:
            case 5: // pop/popfront/remove
                if( sseq->count == 0 )
                    break;
798

799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
                whence = op - 4;
                if( whence < 0 )
                {
                    pos = 0;
                     cvSeqPopFront( seq, elem );
                }
                else if( whence > 0 )
                {
                    pos = sseq->count-1;
                     cvSeqPop( seq, elem );
                }
                else
                {
                    pos = cvtest::randInt(rng) % sseq->count;
                     cvSeqRemove( seq, pos );
                }
815

816 817 818 819
                if( whence != 0 )
                    CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count - 1 &&
                                              memcmp( elem, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
                                              "The popped sequence element isn't correct" );
820

821
                cvTsSimpleSeqShiftAndCopy( sseq, pos + 1, pos );
822

823 824 825 826
                if( sseq->count > 0 )
                {
                     elem2 = cvGetSeqElem( seq, pos < sseq->count ? pos : -1 );
                    CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "GetSeqElem fails after removing the element" );
827

828 829 830 831 832 833 834 835 836 837
                    CV_TS_SEQ_CHECK_CONDITION( memcmp( elem2,
                                                      cvTsSimpleSeqElem(sseq, pos - (pos == sseq->count)), elem_size) == 0,
                                              "The first shifted element is not correct after removing another element" );
                }
                else
                {
                    CV_TS_SEQ_CHECK_CONDITION( seq->first == 0,
                                              "The sequence doesn't become empty after the final remove" );
                }
                break;
838

839 840 841 842 843
            case 6:
            case 7:
            case 8: // push [front] multi/insert slice
                if( sseq->count == sseq->max_count )
                    break;
844

845 846 847
                count = cvtest::randInt( rng ) % (sseq->max_count - sseq->count + 1);
                elem_mat = Mat(1, MAX(count,1) * elem_size, CV_8U, elem);
                cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
848

849
                whence = op - 7;
850
                pos = whence < 0 ? 0 : whence > 0 ? sseq->count : (int)(cvtest::randInt(rng) % (sseq->count+1));
851 852 853 854 855 856 857 858 859 860 861 862
                if( whence != 0 )
                {
                     cvSeqPushMulti( seq, elem, count, whence < 0 );
                }
                else
                {
                    CvSeq header;
                    CvSeqBlock block;
                    cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC, sizeof(CvSeq),
                                                     sseq->elem_size,
                                                     elem, count,
                                                     &header, &block );
863

864 865 866
                    cvSeqInsertSlice( seq, pos, &header );
                }
                cvTsSimpleSeqShiftAndCopy( sseq, pos, pos + count, elem );
867

868 869 870
                if( sseq->count > 0 )
                {
                    // choose the random element among the added
871 872
                    pos = count > 0 ? (int)(cvtest::randInt(rng) % count + pos) : MAX(pos-1,0);
                    elem2 = cvGetSeqElem( seq, pos );
873 874 875 876 877 878 879 880 881 882 883
                    CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "multi push operation doesn't add elements" );
                    CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count &&
                                              memcmp( elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
                                              "One of the added elements is wrong" );
                }
                else
                {
                    CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0,
                                              "Adding no elements to empty sequence fails" );
                }
                break;
884

885 886 887 888 889
            case 9:
            case 10:
            case 11: // pop [front] multi
                if( sseq->count == 0 )
                    break;
890

891 892 893
                count = cvtest::randInt(rng) % (sseq->count+1);
                whence = op - 10;
                pos = whence < 0 ? 0 : whence > 0 ? sseq->count - count :
894
                    (int)(cvtest::randInt(rng) % (sseq->count - count + 1));
895

896 897 898
                if( whence != 0 )
                {
                     cvSeqPopMulti( seq, elem, count, whence < 0 );
899

900 901 902 903 904 905 906 907 908 909 910
                    if( count > 0 )
                    {
                        CV_TS_SEQ_CHECK_CONDITION( memcmp(elem,
                                                          cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
                                                  "The first (in the sequence order) removed element is wrong after popmulti" );
                    }
                }
                else
                {
                     cvSeqRemoveSlice( seq, cvSlice(pos, pos + count) );
                }
911

912 913
                CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count - count,
                                          "The popmulti left a wrong number of elements in the sequence" );
914

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
                cvTsSimpleSeqShiftAndCopy( sseq, pos + count, pos, 0 );
                if( sseq->count > 0 )
                {
                    pos = whence < 0 ? 0 : MIN( pos, sseq->count - 1 );
                    elem2 = cvGetSeqElem( seq, pos );
                    CV_TS_SEQ_CHECK_CONDITION( elem2 &&
                                              memcmp( elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
                                              "The last sequence element is wrong after POP" );
                }
                else
                {
                    CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0,
                                              "The sequence doesn't become empty after final POP" );
                }
                break;
            case 12: // seqslice
            {
                CvMemStoragePos storage_pos;
                cvSaveMemStoragePos( storage, &storage_pos );
934

935 936 937 938
                int copy_data = cvtest::randInt(rng) % 2;
                count = cvtest::randInt(rng) % (seq->total + 1);
                pos = cvtest::randInt(rng) % (seq->total - count + 1);
                CvSeq* seq_slice = cvSeqSlice( seq, cvSlice(pos, pos + count), storage, copy_data );
939

940 941
                CV_TS_SEQ_CHECK_CONDITION( seq_slice && seq_slice->total == count,
                                          "cvSeqSlice returned incorrect slice" );
942

943 944 945 946 947 948 949 950 951 952 953
                if( count > 0 )
                {
                    int test_idx = cvtest::randInt(rng) % count;
                    elem2 = cvGetSeqElem( seq_slice, test_idx );
                    schar* elem3 = cvGetSeqElem( seq, pos + test_idx );
                    CV_TS_SEQ_CHECK_CONDITION( elem2 &&
                                              memcmp( elem2, cvTsSimpleSeqElem(sseq,pos + test_idx), elem_size) == 0,
                                              "The extracted slice elements are not correct" );
                    CV_TS_SEQ_CHECK_CONDITION( (elem2 == elem3) ^ copy_data,
                                              "copy_data flag is handled incorrectly" );
                }
954

955 956 957 958 959 960 961 962 963 964 965 966 967
                cvRestoreMemStoragePos( storage, &storage_pos );
            }
                break;
            case 13: // clear
                cvTsClearSimpleSeq( sseq );
                cvClearSeq( seq );
                CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0,
                                          "The sequence doesn't become empty after clear" );
                break;
            default:
                assert(0);
                return -1;
        }
968

969 970
        if( test_seq_block_consistence(struct_idx, seq, sseq->count) < 0 )
            return -1;
971

972 973
        if( test_get_seq_elem(struct_idx, 7) < 0 )
            return -1;
974

975 976
        update_progressbar();
    }
977

978 979 980 981 982 983 984 985 986 987 988
    return 0;
}


void Core_SeqBaseTest::run( int )
{
    try
    {
        RNG& rng = ts->get_rng();
        int i;
        double t;
989

990 991
        clear();
        test_progress = -1;
992

993 994
        simple_struct.resize(struct_count, 0);
        cxcore_struct.resize(struct_count, 0);
995

996 997 998
        for( gen = 0; gen < generations; gen++ )
        {
            struct_idx = iter = -1;
999

1000 1001 1002 1003
            if( !storage )
            {
                t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size)
                + min_log_storage_block_size;
Roman Donchenko's avatar
Roman Donchenko committed
1004
                storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ));
1005
            }
1006

1007 1008
            iter = struct_idx = -1;
            test_multi_create();
1009

1010 1011 1012 1013 1014
            for( i = 0; i < struct_count; i++ )
            {
                if( test_seq_block_consistence(i, (CvSeq*)cxcore_struct[i],
                                               ((CvTsSimpleSeq*)simple_struct[i])->count) < 0 )
                    return;
1015

1016 1017
                if( test_get_seq_elem( i, MAX(iterations/3,7) ) < 0 )
                    return;
1018

1019 1020 1021 1022
                if( test_get_seq_reading( i, MAX(iterations/3,7) ) < 0 )
                    return;
                update_progressbar();
            }
1023

1024 1025
            if( test_seq_ops( iterations ) < 0 )
                return;
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
            if( cvtest::randInt(rng) % 2 )
                storage.release();
            else
                cvClearMemStorage( storage );
        }
    }
    catch(int)
    {
    }
}


////////////////////////////// more sequence tests //////////////////////////////////////

class Core_SeqSortInvTest : public Core_SeqBaseTest
{
public:
    Core_SeqSortInvTest();
    void run( int );
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
protected:
};


Core_SeqSortInvTest::Core_SeqSortInvTest()
{
}


static int icvCmpSeqElems( const void* a, const void* b, void* userdata )
{
    return memcmp( a, b, ((CvSeq*)userdata)->elem_size );
}

static int icvCmpSeqElems2_elem_size = 0;
static int icvCmpSeqElems2( const void* a, const void* b )
{
    return memcmp( a, b, icvCmpSeqElems2_elem_size );
}


void Core_SeqSortInvTest::run( int )
{
    try
    {
        RNG& rng = ts->get_rng();
        int i, k;
        double t;
        schar *elem0, *elem, *elem2;
        vector<uchar> buffer;
1077

1078 1079
        clear();
        test_progress = -1;
1080

1081 1082
        simple_struct.resize(struct_count, 0);
        cxcore_struct.resize(struct_count, 0);
1083

1084 1085 1086
        for( gen = 0; gen < generations; gen++ )
        {
            struct_idx = iter = -1;
1087

Roman Donchenko's avatar
Roman Donchenko committed
1088
            if( !storage )
1089 1090 1091
            {
                t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size)
                + min_log_storage_block_size;
Roman Donchenko's avatar
Roman Donchenko committed
1092
                storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ));
1093
            }
1094

1095 1096 1097 1098
            for( iter = 0; iter < iterations/10; iter++ )
            {
                int max_size = 0;
                test_multi_create();
1099

1100 1101 1102 1103 1104
                for( i = 0; i < struct_count; i++ )
                {
                    CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[i];
                    max_size = MAX( max_size, sseq->count*sseq->elem_size );
                }
1105

1106
                buffer.resize(max_size);
1107

1108 1109 1110 1111 1112
                for( i = 0; i < struct_count; i++ )
                {
                    CvSeq* seq = (CvSeq*)cxcore_struct[i];
                    CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[i];
                    CvSlice slice = CV_WHOLE_SEQ;
1113

1114
                    //printf("%d. %d. %d-th size = %d\n", gen, iter, i, sseq->count );
1115

1116 1117
                    cvSeqInvert( seq );
                    cvTsSimpleSeqInvert( sseq );
1118

1119 1120
                    if( test_seq_block_consistence( i, seq, sseq->count ) < 0 )
                        return;
1121

1122 1123 1124 1125 1126 1127
                    if( sseq->count > 0 && cvtest::randInt(rng) % 2 == 0 )
                    {
                        slice.end_index = cvtest::randInt(rng) % sseq->count + 1;
                        slice.start_index = cvtest::randInt(rng) % (sseq->count - slice.end_index + 1);
                        slice.end_index += slice.start_index;
                    }
1128

1129
                    cvCvtSeqToArray( seq, &buffer[0], slice );
1130

1131 1132 1133 1134 1135
                    slice.end_index = MIN( slice.end_index, sseq->count );
                    CV_TS_SEQ_CHECK_CONDITION( sseq->count == 0 || memcmp( &buffer[0],
                                                                          sseq->array + slice.start_index*sseq->elem_size,
                                                                          (slice.end_index - slice.start_index)*sseq->elem_size ) == 0,
                                              "cvSeqInvert returned wrong result" );
1136

1137 1138 1139 1140 1141 1142
                    for( k = 0; k < (sseq->count > 0 ? 10 : 0); k++ )
                    {
                        int idx0 = cvtest::randInt(rng) % sseq->count, idx = 0;
                        elem0 = cvTsSimpleSeqElem( sseq, idx0 );
                        elem = cvGetSeqElem( seq, idx0 );
                        elem2 = cvSeqSearch( seq, elem0, k % 2 ? icvCmpSeqElems : 0, 0, &idx, seq );
1143

1144 1145 1146 1147 1148 1149 1150 1151
                        CV_TS_SEQ_CHECK_CONDITION( elem != 0 &&
                                                  memcmp( elem0, elem, seq->elem_size ) == 0,
                                                  "cvSeqInvert gives incorrect result" );
                        CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 &&
                                                  memcmp( elem0, elem2, seq->elem_size ) == 0 &&
                                                  elem2 == cvGetSeqElem( seq, idx ),
                                                  "cvSeqSearch failed (linear search)" );
                    }
1152

1153
                    cvSeqSort( seq, icvCmpSeqElems, seq );
1154

1155 1156
                    if( test_seq_block_consistence( i, seq, sseq->count ) < 0 )
                        return;
1157

1158 1159 1160 1161 1162
                    if( sseq->count > 0 )
                    {
                        // !!! This is not thread-safe !!!
                        icvCmpSeqElems2_elem_size = sseq->elem_size;
                        qsort( sseq->array, sseq->count, sseq->elem_size, icvCmpSeqElems2 );
1163

1164 1165 1166 1167 1168 1169 1170
                        if( cvtest::randInt(rng) % 2 == 0 )
                        {
                            slice.end_index = cvtest::randInt(rng) % sseq->count + 1;
                            slice.start_index = cvtest::randInt(rng) % (sseq->count - slice.end_index + 1);
                            slice.end_index += slice.start_index;
                        }
                    }
1171

1172 1173 1174 1175 1176
                    cvCvtSeqToArray( seq, &buffer[0], slice );
                    CV_TS_SEQ_CHECK_CONDITION( sseq->count == 0 || memcmp( &buffer[0],
                                                                          sseq->array + slice.start_index*sseq->elem_size,
                                                                          (slice.end_index - slice.start_index)*sseq->elem_size ) == 0,
                                              "cvSeqSort returned wrong result" );
1177

1178 1179 1180 1181 1182 1183
                    for( k = 0; k < (sseq->count > 0 ? 10 : 0); k++ )
                    {
                        int idx0 = cvtest::randInt(rng) % sseq->count, idx = 0;
                        elem0 = cvTsSimpleSeqElem( sseq, idx0 );
                        elem = cvGetSeqElem( seq, idx0 );
                        elem2 = cvSeqSearch( seq, elem0, icvCmpSeqElems, 1, &idx, seq );
1184

1185 1186 1187 1188 1189 1190 1191 1192 1193
                        CV_TS_SEQ_CHECK_CONDITION( elem != 0 &&
                                                  memcmp( elem0, elem, seq->elem_size ) == 0,
                                                  "cvSeqSort gives incorrect result" );
                        CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 &&
                                                  memcmp( elem0, elem2, seq->elem_size ) == 0 &&
                                                  elem2 == cvGetSeqElem( seq, idx ),
                                                  "cvSeqSearch failed (binary search)" );
                    }
                }
1194

1195 1196
                cvClearMemStorage( storage );
            }
1197

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
            storage.release();
        }
    }
    catch (int)
    {
    }
}


/////////////////////////////////////// set tests ///////////////////////////////////////

class Core_SetTest : public Core_DynStructBaseTest
{
public:
    Core_SetTest();
1213
    virtual ~Core_SetTest();
1214 1215
    void clear();
    void run( int );
1216

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
protected:
    //int test_seq_block_consistence( int struct_idx );
    int test_set_ops( int iters );
};


Core_SetTest::Core_SetTest()
{
}

1227 1228 1229 1230
Core_SetTest::~Core_SetTest()
{
    clear();
}
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

void Core_SetTest::clear()
{
    for( size_t i = 0; i < simple_struct.size(); i++ )
        cvTsReleaseSimpleSet( (CvTsSimpleSet**)&simple_struct[i] );
    Core_DynStructBaseTest::clear();
}


int  Core_SetTest::test_set_ops( int iters )
{
    const int max_op = 4;
    int max_elem_size = 0;
    int idx, idx0;
    CvSetElem *elem = 0, *elem2 = 0, *elem3 = 0;
    schar* elem_data = 0;
    RNG& rng = ts->get_rng();
    //int max_active_count = 0, mean_active_count = 0;
1249

1250 1251
    for( int i = 0; i < struct_count; i++ )
        max_elem_size = MAX( max_elem_size, ((CvSeq*)cxcore_struct[i])->elem_size );
1252

1253 1254
    vector<schar> elem_buf(max_elem_size);
    Mat elem_mat;
1255

1256 1257 1258
    for( iter = 0; iter < iters; iter++ )
    {
        struct_idx = cvtest::randInt(rng) % struct_count;
1259

1260 1261 1262 1263 1264 1265 1266 1267 1268
        CvSet* cvset = (CvSet*)cxcore_struct[struct_idx];
        CvTsSimpleSet* sset = (CvTsSimpleSet*)simple_struct[struct_idx];
        int pure_elem_size = sset->elem_size - 1;
        int prev_total = cvset->total, prev_count = cvset->active_count;
        int op = cvtest::randInt(rng) % (iter <= iters/10 ? 2 : max_op);
        int by_ptr = op % 2 == 0;
        CvSetElem* first_free = cvset->free_elems;
        CvSetElem* next_free = first_free ? first_free->next_free : 0;
        int pass_data = 0;
1269

1270 1271
        if( iter > iters/10 && cvtest::randInt(rng)%200 == 0 ) // clear set
        {
Andrey Kamaev's avatar
Andrey Kamaev committed
1272
            prev_count = cvset->total;
1273 1274
            cvClearSet( cvset );
            cvTsClearSimpleSet( sset );
1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            CV_TS_SEQ_CHECK_CONDITION( cvset->active_count == 0 && cvset->total == 0 &&
                                      cvset->first == 0 && cvset->free_elems == 0 &&
                                      (cvset->free_blocks != 0 || prev_count == 0),
                                      "cvClearSet doesn't remove all the elements" );
            continue;
        }
        else if( op == 0 || op == 1 ) // add element
        {
            if( sset->free_count == 0 )
                continue;
1286

1287 1288 1289
            elem_mat = Mat(1, cvset->elem_size, CV_8U, &elem_buf[0]);
            cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
            elem = (CvSetElem*)&elem_buf[0];
1290

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
            if( by_ptr )
            {
                elem2 = cvSetNew( cvset );
                CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "cvSetNew returned NULL pointer" );
            }
            else
            {
                pass_data = cvtest::randInt(rng) % 2;
                idx = cvSetAdd( cvset, pass_data ? elem : 0, &elem2 );
                CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 && elem2->flags == idx,
                                          "cvSetAdd returned NULL pointer or a wrong index" );
            }
1303

1304
            elem_data = (schar*)elem + sizeof(int);
1305

1306 1307
            if( !pass_data )
                memcpy( (schar*)elem2 + sizeof(int), elem_data, pure_elem_size );
1308

1309 1310 1311
            idx = elem2->flags;
            idx0 = cvTsSimpleSetAdd( sset, elem_data );
            elem3 = cvGetSetElem( cvset, idx );
1312

1313 1314 1315 1316
            CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(elem3) &&
                                      idx == idx0 && elem3 == elem2 && (!pass_data ||
                                                                        memcmp( (char*)elem3 + sizeof(int), elem_data, pure_elem_size) == 0),
                                      "The added element is not correct" );
1317

1318 1319 1320 1321 1322 1323 1324 1325
            CV_TS_SEQ_CHECK_CONDITION( (!first_free || elem3 == first_free) &&
                                      (!next_free || cvset->free_elems == next_free) &&
                                      cvset->active_count == prev_count + 1,
                                      "The free node list is modified incorrectly" );
        }
        else if( op == 2 || op == 3 ) // remove element
        {
            idx = cvtest::randInt(rng) % sset->max_count;
1326

1327 1328
            if( sset->free_count == sset->max_count || idx >= sset->count )
                continue;
1329

1330 1331 1332
            elem_data = cvTsSimpleSetFind(sset, idx);
            if( elem_data == 0 )
                continue;
1333

1334 1335 1336 1337
            elem = cvGetSetElem( cvset, idx );
            CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(elem) && elem->flags == idx &&
                                      memcmp((char*)elem + sizeof(int), elem_data, pure_elem_size) == 0,
                                      "cvGetSetElem returned wrong element" );
1338

1339 1340 1341 1342 1343 1344 1345 1346
            if( by_ptr )
            {
                 cvSetRemoveByPtr( cvset, elem );
            }
            else
            {
                 cvSetRemove( cvset, idx );
            }
1347

1348
            cvTsSimpleSetRemove( sset, idx );
1349

1350 1351 1352
            CV_TS_SEQ_CHECK_CONDITION( !CV_IS_SET_ELEM(elem) && !cvGetSetElem(cvset, idx) &&
                                      (elem->flags & CV_SET_ELEM_IDX_MASK) == idx,
                                      "cvSetRemove[ByPtr] didn't release the element properly" );
1353

1354 1355 1356 1357 1358
            CV_TS_SEQ_CHECK_CONDITION( elem->next_free == first_free &&
                                      cvset->free_elems == elem &&
                                      cvset->active_count == prev_count - 1,
                                      "The free node list has not been updated properly" );
        }
1359

1360 1361 1362 1363 1364 1365
        //max_active_count = MAX( max_active_count, cvset->active_count );
        //mean_active_count += cvset->active_count;
        CV_TS_SEQ_CHECK_CONDITION( cvset->active_count == sset->max_count - sset->free_count &&
                                  cvset->total >= cvset->active_count &&
                                  (cvset->total == 0 || cvset->total >= prev_total),
                                  "The total number of cvset elements is not correct" );
1366

Ilya Lavrenov's avatar
Ilya Lavrenov committed
1367
        // CvSet and simple set do not necessary have the same "total" (active & free) number,
1368 1369 1370 1371
        // so pass "set->total" to skip that check
        test_seq_block_consistence( struct_idx, (CvSeq*)cvset, cvset->total );
        update_progressbar();
    }
1372

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    return 0;
}


void Core_SetTest::run( int )
{
    try
    {
        RNG& rng = ts->get_rng();
        double t;
1383

1384 1385
        clear();
        test_progress = -1;
1386

1387 1388
        simple_struct.resize(struct_count, 0);
        cxcore_struct.resize(struct_count, 0);
1389

1390 1391 1392 1393
        for( gen = 0; gen < generations; gen++ )
        {
            struct_idx = iter = -1;
            t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size;
Roman Donchenko's avatar
Roman Donchenko committed
1394
            storage.reset(cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ));
1395

1396 1397 1398 1399 1400 1401 1402 1403 1404
            for( int i = 0; i < struct_count; i++ )
            {
                t = cvtest::randReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size;
                int pure_elem_size = cvRound( exp(t * CV_LOG2) );
                int elem_size = pure_elem_size + sizeof(int);
                elem_size = (elem_size + sizeof(size_t) - 1) & ~(sizeof(size_t)-1);
                elem_size = MAX( elem_size, (int)sizeof(CvSetElem) );
                elem_size = MIN( elem_size, (int)(storage->block_size - sizeof(void*) - sizeof(CvMemBlock) - sizeof(CvSeqBlock)) );
                pure_elem_size = MIN( pure_elem_size, elem_size-(int)sizeof(CvSetElem) );
1405

1406 1407
                cvTsReleaseSimpleSet( (CvTsSimpleSet**)&simple_struct[i] );
                simple_struct[i] = cvTsCreateSimpleSet( max_struct_size, pure_elem_size );
Roman Donchenko's avatar
Roman Donchenko committed
1408
                cxcore_struct[i] = cvCreateSet( 0, sizeof(CvSet), elem_size, storage );
1409
            }
1410

1411 1412
            if( test_set_ops( iterations*100 ) < 0 )
                return;
1413

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
            storage.release();
        }
    }
    catch(int)
    {
    }
}


/////////////////////////////////////// graph tests //////////////////////////////////

class Core_GraphTest : public Core_DynStructBaseTest
{
public:
    Core_GraphTest();
1429
    virtual ~Core_GraphTest();
1430 1431
    void clear();
    void run( int );
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
protected:
    //int test_seq_block_consistence( int struct_idx );
    int test_graph_ops( int iters );
};


Core_GraphTest::Core_GraphTest()
{
}

1443 1444 1445 1446
Core_GraphTest::~Core_GraphTest()
{
    clear();
}
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465

void Core_GraphTest::clear()
{
    for( size_t i = 0; i < simple_struct.size(); i++ )
        cvTsReleaseSimpleGraph( (CvTsSimpleGraph**)&simple_struct[i] );
    Core_DynStructBaseTest::clear();
}


int  Core_GraphTest::test_graph_ops( int iters )
{
    const int max_op = 4;
    int i, k;
    int max_elem_size = 0;
    int idx, idx0;
    CvGraphVtx *vtx = 0, *vtx2 = 0, *vtx3 = 0;
    CvGraphEdge* edge = 0, *edge2 = 0;
    RNG& rng = ts->get_rng();
    //int max_active_count = 0, mean_active_count = 0;
1466

1467 1468 1469 1470 1471 1472
    for( i = 0; i < struct_count; i++ )
    {
        CvGraph* graph = (CvGraph*)cxcore_struct[i];
        max_elem_size = MAX( max_elem_size, graph->elem_size );
        max_elem_size = MAX( max_elem_size, graph->edges->elem_size );
    }
1473

1474 1475
    vector<schar> elem_buf(max_elem_size);
    Mat elem_mat;
1476

1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    for( iter = 0; iter < iters; iter++ )
    {
        struct_idx = cvtest::randInt(rng) % struct_count;
        CvGraph* graph = (CvGraph*)cxcore_struct[struct_idx];
        CvTsSimpleGraph* sgraph = (CvTsSimpleGraph*)simple_struct[struct_idx];
        CvSet* edges = graph->edges;
        schar *vtx_data;
        char *edge_data;
        int pure_vtx_size = sgraph->vtx->elem_size - 1,
        pure_edge_size = sgraph->edge_size - 1;
        int prev_vtx_total = graph->total,
        prev_edge_total = graph->edges->total,
        prev_vtx_count = graph->active_count,
        prev_edge_count = graph->edges->active_count;
        int op = cvtest::randInt(rng) % max_op;
        int pass_data = 0, vtx_degree0 = 0, vtx_degree = 0;
        CvSetElem *first_free, *next_free;
1494

1495 1496
        if( cvtest::randInt(rng) % 200 == 0 ) // clear graph
        {
Andrey Kamaev's avatar
Andrey Kamaev committed
1497
            int prev_vtx_count2 = graph->total, prev_edge_count2 = graph->edges->total;
1498

1499 1500
            cvClearGraph( graph );
            cvTsClearSimpleGraph( sgraph );
1501

1502 1503
            CV_TS_SEQ_CHECK_CONDITION( graph->active_count == 0 && graph->total == 0 &&
                                      graph->first == 0 && graph->free_elems == 0 &&
Andrey Kamaev's avatar
Andrey Kamaev committed
1504
                                      (graph->free_blocks != 0 || prev_vtx_count2 == 0),
1505
                                      "The graph is not empty after clearing" );
1506

1507 1508
            CV_TS_SEQ_CHECK_CONDITION( edges->active_count == 0 && edges->total == 0 &&
                                      edges->first == 0 && edges->free_elems == 0 &&
Andrey Kamaev's avatar
Andrey Kamaev committed
1509
                                      (edges->free_blocks != 0 || prev_edge_count2 == 0),
1510 1511 1512 1513 1514 1515
                                      "The graph is not empty after clearing" );
        }
        else if( op == 0 ) // add vertex
        {
            if( sgraph->vtx->free_count == 0 )
                continue;
1516

1517 1518
            first_free = graph->free_elems;
            next_free = first_free ? first_free->next_free : 0;
1519

1520 1521 1522 1523 1524
            if( pure_vtx_size )
            {
                elem_mat = Mat(1, graph->elem_size, CV_8U, &elem_buf[0]);
                cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
            }
1525

1526 1527
            vtx = (CvGraphVtx*)&elem_buf[0];
            idx0 = cvTsSimpleGraphAddVertex( sgraph, vtx + 1 );
1528

1529 1530
            pass_data = cvtest::randInt(rng) % 2;
            idx = cvGraphAddVtx( graph, pass_data ? vtx : 0, &vtx2 );
1531

1532 1533
            if( !pass_data && pure_vtx_size > 0 )
                memcpy( vtx2 + 1, vtx + 1, pure_vtx_size );
1534

1535
            vtx3 = cvGetGraphVtx( graph, idx );
1536

1537 1538 1539 1540 1541
            CV_TS_SEQ_CHECK_CONDITION( (CV_IS_SET_ELEM(vtx3) && vtx3->flags == idx &&
                                        vtx3->first == 0) || (idx == idx0 && vtx3 == vtx2 &&
                                                              (!pass_data || pure_vtx_size == 0 ||
                                                               memcmp(vtx3 + 1, vtx + 1, pure_vtx_size) == 0)),
                                      "The added element is not correct" );
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
            CV_TS_SEQ_CHECK_CONDITION( (!first_free || first_free == (CvSetElem*)vtx3) &&
                                      (!next_free || graph->free_elems == next_free) &&
                                      graph->active_count == prev_vtx_count + 1,
                                      "The free node list is modified incorrectly" );
        }
        else if( op == 1 ) // remove vertex
        {
            idx = cvtest::randInt(rng) % sgraph->vtx->max_count;
            if( sgraph->vtx->free_count == sgraph->vtx->max_count || idx >= sgraph->vtx->count )
                continue;
1553

1554 1555 1556
            vtx_data = cvTsSimpleGraphFindVertex(sgraph, idx);
            if( vtx_data == 0 )
                continue;
1557

1558 1559
            vtx_degree0 = cvTsSimpleGraphVertexDegree( sgraph, idx );
            first_free = graph->free_elems;
1560

1561 1562 1563 1564
            vtx = cvGetGraphVtx( graph, idx );
            CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(vtx) && vtx->flags == idx &&
                                      (pure_vtx_size == 0 || memcmp( vtx + 1, vtx_data, pure_vtx_size) == 0),
                                      "cvGetGraphVtx returned wrong element" );
1565

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
            if( cvtest::randInt(rng) % 2 )
            {
                 vtx_degree = cvGraphVtxDegreeByPtr( graph, vtx );
                 cvGraphRemoveVtxByPtr( graph, vtx );
            }
            else
            {
                 vtx_degree = cvGraphVtxDegree( graph, idx );
                 cvGraphRemoveVtx( graph, idx );
            }
1576

1577
            cvTsSimpleGraphRemoveVertex( sgraph, idx );
1578

1579 1580
            CV_TS_SEQ_CHECK_CONDITION( vtx_degree == vtx_degree0,
                                      "Number of incident edges is different in two graph representations" );
1581

1582 1583 1584
            CV_TS_SEQ_CHECK_CONDITION( !CV_IS_SET_ELEM(vtx) && !cvGetGraphVtx(graph, idx) &&
                                      (vtx->flags & CV_SET_ELEM_IDX_MASK) == idx,
                                      "cvGraphRemoveVtx[ByPtr] didn't release the vertex properly" );
1585

1586 1587 1588
            CV_TS_SEQ_CHECK_CONDITION( graph->edges->active_count == prev_edge_count - vtx_degree,
                                      "cvGraphRemoveVtx[ByPtr] didn't remove all the incident edges "
                                      "(or removed some extra)" );
1589

1590 1591 1592 1593 1594 1595 1596 1597 1598
            CV_TS_SEQ_CHECK_CONDITION( ((CvSetElem*)vtx)->next_free == first_free &&
                                      graph->free_elems == (CvSetElem*)vtx &&
                                      graph->active_count == prev_vtx_count - 1,
                                      "The free node list has not been updated properly" );
        }
        else if( op == 2 ) // add edge
        {
            int v_idx[2] = {0,0}, res = 0;
            int v_prev_degree[2] = {0,0}, v_degree[2] = {0,0};
1599

1600 1601
            if( sgraph->vtx->free_count >= sgraph->vtx->max_count-1 )
                continue;
1602

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
            for( i = 0, k = 0; i < 10; i++ )
            {
                int j = cvtest::randInt(rng) % sgraph->vtx->count;
                vtx_data = cvTsSimpleGraphFindVertex( sgraph, j );
                if( vtx_data )
                {
                    v_idx[k] = j;
                    if( k == 0 )
                        k++;
                    else if( v_idx[0] != v_idx[1] &&
                            cvTsSimpleGraphFindEdge( sgraph, v_idx[0], v_idx[1] ) == 0 )
                    {
                        k++;
                        break;
                    }
                }
            }
1620

1621 1622
            if( k < 2 )
                continue;
1623

1624 1625
            first_free = graph->edges->free_elems;
            next_free = first_free ? first_free->next_free : 0;
1626

1627 1628
            edge = cvFindGraphEdge( graph, v_idx[0], v_idx[1] );
            CV_TS_SEQ_CHECK_CONDITION( edge == 0, "Extra edge appeared in the graph" );
1629

1630 1631 1632 1633 1634 1635
            if( pure_edge_size > 0 )
            {
                elem_mat = Mat(1, graph->edges->elem_size, CV_8U, &elem_buf[0]);
                cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
            }
            edge = (CvGraphEdge*)&elem_buf[0];
1636

1637 1638 1639 1640 1641
            // assign some default weight that is easy to check for
            // consistensy, 'cause an edge weight is not stored
            // in the simple graph
            edge->weight = (float)(v_idx[0] + v_idx[1]);
            pass_data = cvtest::randInt(rng) % 2;
1642

1643 1644 1645 1646
            vtx = cvGetGraphVtx( graph, v_idx[0] );
            vtx2 = cvGetGraphVtx( graph, v_idx[1] );
            CV_TS_SEQ_CHECK_CONDITION( vtx != 0 && vtx2 != 0 && vtx->flags == v_idx[0] &&
                                      vtx2->flags == v_idx[1], "Some of the vertices are missing" );
1647

1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
            if( cvtest::randInt(rng) % 2 )
            {
                 v_prev_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx );
                 v_prev_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 );
                 res = cvGraphAddEdgeByPtr(graph, vtx, vtx2, pass_data ? edge : 0, &edge2);
                 v_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx );
                 v_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 );
            }
            else
            {
                 v_prev_degree[0] = cvGraphVtxDegree( graph, v_idx[0] );
                 v_prev_degree[1] = cvGraphVtxDegree( graph, v_idx[1] );
                 res = cvGraphAddEdge(graph, v_idx[0], v_idx[1], pass_data ? edge : 0, &edge2);
                 v_degree[0] = cvGraphVtxDegree( graph, v_idx[0] );
                 v_degree[1] = cvGraphVtxDegree( graph, v_idx[1] );
            }
1664

1665 1666 1667 1668 1669 1670
            //edge3 = (CvGraphEdge*)cvGetSetElem( graph->edges, idx );
            CV_TS_SEQ_CHECK_CONDITION( res == 1 && edge2 != 0 && CV_IS_SET_ELEM(edge2) &&
                                      ((edge2->vtx[0] == vtx && edge2->vtx[1] == vtx2) ||
                                       (!CV_IS_GRAPH_ORIENTED(graph) && edge2->vtx[0] == vtx2 && edge2->vtx[1] == vtx)) &&
                                      (!pass_data || pure_edge_size == 0 || memcmp( edge2 + 1, edge + 1, pure_edge_size ) == 0),
                                      "The edge has been added incorrectly" );
1671

1672 1673 1674 1675 1676 1677
            if( !pass_data )
            {
                if( pure_edge_size > 0 )
                    memcpy( edge2 + 1, edge + 1, pure_edge_size );
                edge2->weight = edge->weight;
            }
1678

1679 1680 1681
            CV_TS_SEQ_CHECK_CONDITION( v_degree[0] == v_prev_degree[0] + 1 &&
                                      v_degree[1] == v_prev_degree[1] + 1,
                                      "The vertices lists have not been updated properly" );
1682

1683
            cvTsSimpleGraphAddEdge( sgraph, v_idx[0], v_idx[1], edge + 1 );
1684

1685 1686 1687 1688 1689 1690 1691 1692 1693
            CV_TS_SEQ_CHECK_CONDITION( (!first_free || first_free == (CvSetElem*)edge2) &&
                                      (!next_free || graph->edges->free_elems == next_free) &&
                                      graph->edges->active_count == prev_edge_count + 1,
                                      "The free node list is modified incorrectly" );
        }
        else if( op == 3 ) // find & remove edge
        {
            int v_idx[2] = {0,0}, by_ptr;
            int v_prev_degree[2] = {0,0}, v_degree[2] = {0,0};
1694

1695 1696
            if( sgraph->vtx->free_count >= sgraph->vtx->max_count-1 )
                continue;
1697

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
            edge_data = 0;
            for( i = 0, k = 0; i < 10; i++ )
            {
                int j = cvtest::randInt(rng) % sgraph->vtx->count;
                vtx_data = cvTsSimpleGraphFindVertex( sgraph, j );
                if( vtx_data )
                {
                    v_idx[k] = j;
                    if( k == 0 )
                        k++;
                    else
                    {
                        edge_data = cvTsSimpleGraphFindEdge( sgraph, v_idx[0], v_idx[1] );
                        if( edge_data )
                        {
                            k++;
                            break;
                        }
                    }
                }
            }
1719

1720 1721
            if( k < 2 )
                continue;
1722

1723 1724
            by_ptr = cvtest::randInt(rng) % 2;
            first_free = graph->edges->free_elems;
1725

1726 1727 1728 1729
            vtx = cvGetGraphVtx( graph, v_idx[0] );
            vtx2 = cvGetGraphVtx( graph, v_idx[1] );
            CV_TS_SEQ_CHECK_CONDITION( vtx != 0 && vtx2 != 0 && vtx->flags == v_idx[0] &&
                                      vtx2->flags == v_idx[1], "Some of the vertices are missing" );
1730

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
            if( by_ptr )
            {
                 edge = cvFindGraphEdgeByPtr( graph, vtx, vtx2 );
                 v_prev_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx );
                 v_prev_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 );
            }
            else
            {
                 edge = cvFindGraphEdge( graph, v_idx[0], v_idx[1] );
                 v_prev_degree[0] = cvGraphVtxDegree( graph, v_idx[0] );
                 v_prev_degree[1] = cvGraphVtxDegree( graph, v_idx[1] );
            }
1743

1744
            idx = edge->flags;
1745

1746 1747 1748 1749 1750
            CV_TS_SEQ_CHECK_CONDITION( edge != 0 && edge->weight == v_idx[0] + v_idx[1] &&
                                      ((edge->vtx[0] == vtx && edge->vtx[1] == vtx2) ||
                                       (!CV_IS_GRAPH_ORIENTED(graph) && edge->vtx[1] == vtx && edge->vtx[0] == vtx2)) &&
                                      (pure_edge_size == 0 || memcmp(edge + 1, edge_data, pure_edge_size) == 0),
                                      "An edge is missing or incorrect" );
1751

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
            if( by_ptr )
            {
                 cvGraphRemoveEdgeByPtr( graph, vtx, vtx2 );
                 edge2 = cvFindGraphEdgeByPtr( graph, vtx, vtx2 );
                 v_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx );
                 v_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 );
            }
            else
            {
                 cvGraphRemoveEdge(graph, v_idx[0], v_idx[1] );
                 edge2 = cvFindGraphEdge( graph, v_idx[0], v_idx[1] );
                 v_degree[0] = cvGraphVtxDegree( graph, v_idx[0] );
                 v_degree[1] = cvGraphVtxDegree( graph, v_idx[1] );
            }
1766

1767 1768
            CV_TS_SEQ_CHECK_CONDITION( !edge2 && !CV_IS_SET_ELEM(edge),
                                      "The edge has not been removed from the edge set" );
1769

1770 1771 1772
            CV_TS_SEQ_CHECK_CONDITION( v_degree[0] == v_prev_degree[0] - 1 &&
                                      v_degree[1] == v_prev_degree[1] - 1,
                                      "The vertices lists have not been updated properly" );
1773

1774
            cvTsSimpleGraphRemoveEdge( sgraph, v_idx[0], v_idx[1] );
1775

1776 1777 1778 1779 1780
            CV_TS_SEQ_CHECK_CONDITION( graph->edges->free_elems == (CvSetElem*)edge &&
                                      graph->edges->free_elems->next_free == first_free &&
                                      graph->edges->active_count == prev_edge_count - 1,
                                      "The free edge list has not been modified properly" );
        }
1781

1782 1783
        //max_active_count = MAX( max_active_count, graph->active_count );
        //mean_active_count += graph->active_count;
1784

1785 1786 1787 1788
        CV_TS_SEQ_CHECK_CONDITION( graph->active_count == sgraph->vtx->max_count - sgraph->vtx->free_count &&
                                  graph->total >= graph->active_count &&
                                  (graph->total == 0 || graph->total >= prev_vtx_total),
                                  "The total number of graph vertices is not correct" );
1789

1790 1791 1792
        CV_TS_SEQ_CHECK_CONDITION( graph->edges->total >= graph->edges->active_count &&
                                  (graph->edges->total == 0 || graph->edges->total >= prev_edge_total),
                                  "The total number of graph vertices is not correct" );
1793

Ilya Lavrenov's avatar
Ilya Lavrenov committed
1794
        // CvGraph and simple graph do not necessary have the same "total" (active & free) number,
1795 1796 1797 1798 1799
        // so pass "graph->total" (or "graph->edges->total") to skip that check
        test_seq_block_consistence( struct_idx, (CvSeq*)graph, graph->total );
        test_seq_block_consistence( struct_idx, (CvSeq*)graph->edges, graph->edges->total );
        update_progressbar();
    }
1800

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    return 0;
}


void Core_GraphTest::run( int )
{
    try
    {
        RNG& rng = ts->get_rng();
        int i, k;
        double t;
1812

1813 1814
        clear();
        test_progress = -1;
1815

1816 1817
        simple_struct.resize(struct_count, 0);
        cxcore_struct.resize(struct_count, 0);
1818

1819 1820 1821 1822 1823 1824
        for( gen = 0; gen < generations; gen++ )
        {
            struct_idx = iter = -1;
            t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size;
            int block_size = cvRound( exp(t * CV_LOG2) );
            block_size = MAX(block_size, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock)));
1825

Roman Donchenko's avatar
Roman Donchenko committed
1826
            storage.reset(cvCreateMemStorage(block_size));
1827

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
            for( i = 0; i < struct_count; i++ )
            {
                int pure_elem_size[2], elem_size[2];
                int is_oriented = (gen + i) % 2;
                for( k = 0; k < 2; k++ )
                {
                    t = cvtest::randReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size;
                    int pe = cvRound( exp(t * CV_LOG2) ) - 1; // pure_elem_size==0 does also make sense
                    int delta = k == 0 ? sizeof(CvGraphVtx) : sizeof(CvGraphEdge);
                    int e = pe + delta;
                    e = (e + sizeof(size_t) - 1) & ~(sizeof(size_t)-1);
                    e = MIN( e, (int)(storage->block_size - sizeof(CvMemBlock) -
                                      sizeof(CvSeqBlock) - sizeof(void*)) );
                    pe = MIN(pe, e - delta);
                    pure_elem_size[k] = pe;
                    elem_size[k] = e;
                }
1845

1846 1847 1848 1849 1850 1851 1852
                cvTsReleaseSimpleGraph( (CvTsSimpleGraph**)&simple_struct[i] );
                simple_struct[i] = cvTsCreateSimpleGraph( max_struct_size/4, pure_elem_size[0],
                                                         pure_elem_size[1], is_oriented );
                cxcore_struct[i] = cvCreateGraph( is_oriented ? CV_ORIENTED_GRAPH : CV_GRAPH,
                                                          sizeof(CvGraph), elem_size[0], elem_size[1],
                                                          storage );
            }
1853

1854 1855
            if( test_graph_ops( iterations*10 ) < 0 )
                return;
1856

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
            storage.release();
        }
    }
    catch(int)
    {
    }
}


//////////// graph scan test //////////////

class Core_GraphScanTest : public Core_DynStructBaseTest
{
public:
    Core_GraphScanTest();
    void run( int );
1873

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
protected:
    //int test_seq_block_consistence( int struct_idx );
    int create_random_graph( int );
};


Core_GraphScanTest::Core_GraphScanTest()
{
    iterations = 100;
    struct_count = 1;
}


int Core_GraphScanTest::create_random_graph( int _struct_idx )
{
    RNG& rng = ts->get_rng();
    int is_oriented = cvtest::randInt(rng) % 2;
    int i, vtx_count = cvtest::randInt(rng) % max_struct_size;
    int edge_count = cvtest::randInt(rng) % MAX(vtx_count*20, 1);
    CvGraph* graph;
1894

1895 1896 1897 1898 1899
    struct_idx = _struct_idx;
    cxcore_struct[_struct_idx] = graph =
        cvCreateGraph(is_oriented ? CV_ORIENTED_GRAPH : CV_GRAPH,
                      sizeof(CvGraph), sizeof(CvGraphVtx),
                      sizeof(CvGraphEdge), storage );
1900

1901 1902
    for( i = 0; i < vtx_count; i++ )
         cvGraphAddVtx( graph );
1903

1904
    assert( graph->active_count == vtx_count );
1905

1906 1907 1908 1909
    for( i = 0; i < edge_count; i++ )
    {
        int j = cvtest::randInt(rng) % vtx_count;
        int k = cvtest::randInt(rng) % vtx_count;
1910

1911 1912 1913
        if( j != k )
             cvGraphAddEdge( graph, j, k );
    }
1914

1915
    assert( graph->active_count == vtx_count && graph->edges->active_count <= edge_count );
1916

1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
    return 0;
}


void Core_GraphScanTest::run( int )
{
    CvGraphScanner* scanner = 0;
    try
    {
        RNG& rng = ts->get_rng();
        vector<uchar> vtx_mask, edge_mask;
        double t;
        int i;
1930

1931 1932
        clear();
        test_progress = -1;
1933

1934
        cxcore_struct.resize(struct_count, 0);
1935

1936 1937 1938 1939 1940 1941 1942 1943
        for( gen = 0; gen < generations; gen++ )
        {
            struct_idx = iter = -1;
            t = cvtest::randReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size;
            int storage_blocksize = cvRound( exp(t * CV_LOG2) );
            storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock)));
            storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphEdge) + sizeof(CvMemBlock) + sizeof(CvSeqBlock)));
            storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphVtx) + sizeof(CvMemBlock) + sizeof(CvSeqBlock)));
Roman Donchenko's avatar
Roman Donchenko committed
1944
            storage.reset(cvCreateMemStorage(storage_blocksize));
1945

1946 1947 1948 1949 1950 1951
            if( gen == 0 )
            {
                // special regression test for one sample graph.
                // !!! ATTENTION !!! The test relies on the particular order of the inserted edges
                // (LIFO: the edge inserted last goes first in the list of incident edges).
                // if it is changed, the test will have to be modified.
1952

1953 1954 1955 1956 1957
                int vtx_count = -1, edge_count = 0, edges[][3] =
                {
                    {0,4,'f'}, {0,1,'t'}, {1,4,'t'}, {1,2,'t'}, {2,3,'t'}, {4,3,'c'}, {3,1,'b'},
                    {5,7,'t'}, {7,5,'b'}, {5,6,'t'}, {6,0,'c'}, {7,6,'c'}, {6,4,'c'}, {-1,-1,0}
                };
1958

1959 1960
                CvGraph* graph = cvCreateGraph( CV_ORIENTED_GRAPH, sizeof(CvGraph),
                                               sizeof(CvGraphVtx), sizeof(CvGraphEdge), storage );
1961

1962 1963 1964 1965 1966 1967
                for( i = 0; edges[i][0] >= 0; i++ )
                {
                    vtx_count = MAX( vtx_count, edges[i][0] );
                    vtx_count = MAX( vtx_count, edges[i][1] );
                }
                vtx_count++;
1968

1969 1970
                for( i = 0; i < vtx_count; i++ )
                     cvGraphAddVtx( graph );
1971

1972 1973 1974 1975 1976 1977
                for( i = 0; edges[i][0] >= 0; i++ )
                {
                    CvGraphEdge* edge;
                     cvGraphAddEdge( graph, edges[i][0], edges[i][1], 0, &edge );
                    edge->weight = (float)edges[i][2];
                }
1978

1979 1980
                edge_count = i;
                scanner = cvCreateGraphScanner( graph, 0, CV_GRAPH_ALL_ITEMS );
1981

1982 1983 1984 1985 1986
                for(;;)
                {
                    int code, a = -1, b = -1;
                    const char* event = "";
                     code = cvNextGraphItem( scanner );
1987

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
                    switch( code )
                    {
                        case CV_GRAPH_VERTEX:
                            event = "Vertex";
                            vtx_count--;
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            break;
                        case CV_GRAPH_TREE_EDGE:
                            event = "Tree Edge";
                            edge_count--;
                            CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'t',
                                                      "Invalid edge type" );
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            b = cvGraphVtxIdx( graph, scanner->dst );
                            break;
                        case CV_GRAPH_BACK_EDGE:
                            event = "Back Edge";
                            edge_count--;
                            CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'b',
                                                      "Invalid edge type" );
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            b = cvGraphVtxIdx( graph, scanner->dst );
                            break;
                        case CV_GRAPH_CROSS_EDGE:
                            event = "Cross Edge";
                            edge_count--;
                            CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'c',
                                                      "Invalid edge type" );
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            b = cvGraphVtxIdx( graph, scanner->dst );
                            break;
                        case CV_GRAPH_FORWARD_EDGE:
                            event = "Forward Edge";
                            edge_count--;
                            CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'f',
                                                      "Invalid edge type" );
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            b = cvGraphVtxIdx( graph, scanner->dst );
                            break;
                        case CV_GRAPH_BACKTRACKING:
                            event = "Backtracking";
                            a = cvGraphVtxIdx( graph, scanner->vtx );
                            break;
                        case CV_GRAPH_NEW_TREE:
                            event = "New search tree";
                            break;
                        case CV_GRAPH_OVER:
                            event = "End of procedure";
                            break;
                        default:
                            CV_TS_SEQ_CHECK_CONDITION( 0, "Invalid code appeared during graph scan" );
                    }
2040

2041 2042 2043 2044 2045 2046 2047 2048
                    ts->printf( cvtest::TS::LOG, "%s", event );
                    if( a >= 0 )
                    {
                        if( b >= 0 )
                            ts->printf( cvtest::TS::LOG, ": (%d,%d)", a, b );
                        else
                            ts->printf( cvtest::TS::LOG, ": %d", a );
                    }
2049

2050
                    ts->printf( cvtest::TS::LOG, "\n" );
2051

2052 2053 2054
                    if( code < 0 )
                        break;
                }
2055

2056 2057 2058
                CV_TS_SEQ_CHECK_CONDITION( vtx_count == 0 && edge_count == 0,
                                          "Not every vertex/edge has been visited" );
                update_progressbar();
2059 2060

                cvReleaseGraphScanner( &scanner );
2061
            }
2062

2063 2064 2065 2066 2067 2068
            // for a random graph the test just checks that every graph vertex and
            // every edge is vitisted during the scan
            for( iter = 0; iter < iterations; iter++ )
            {
                create_random_graph(0);
                CvGraph* graph = (CvGraph*)cxcore_struct[0];
2069

2070 2071 2072 2073 2074
                // iterate twice to check that scanner doesn't damage the graph
                for( i = 0; i < 2; i++ )
                {
                    CvGraphVtx* start_vtx = cvtest::randInt(rng) % 2 || graph->active_count == 0 ? 0 :
                    cvGetGraphVtx( graph, cvtest::randInt(rng) % graph->active_count );
2075

2076
                    scanner = cvCreateGraphScanner( graph, start_vtx, CV_GRAPH_ALL_ITEMS );
2077

2078 2079 2080 2081
                    vtx_mask.resize(0);
                    vtx_mask.resize(graph->active_count, 0);
                    edge_mask.resize(0);
                    edge_mask.resize(graph->edges->active_count, 0);
2082

2083 2084 2085
                    for(;;)
                    {
                        int code = cvNextGraphItem( scanner );
2086

2087 2088 2089 2090 2091
                        if( code == CV_GRAPH_OVER )
                            break;
                        else if( code & CV_GRAPH_ANY_EDGE )
                        {
                            int edge_idx = scanner->edge->flags & CV_SET_ELEM_IDX_MASK;
2092

2093 2094 2095 2096 2097 2098 2099 2100
                            CV_TS_SEQ_CHECK_CONDITION( edge_idx < graph->edges->active_count &&
                                                      edge_mask[edge_idx] == 0,
                                                      "The edge is not found or visited for the second time" );
                            edge_mask[edge_idx] = 1;
                        }
                        else if( code & CV_GRAPH_VERTEX )
                        {
                            int vtx_idx = scanner->vtx->flags & CV_SET_ELEM_IDX_MASK;
2101

2102 2103 2104 2105 2106 2107
                            CV_TS_SEQ_CHECK_CONDITION( vtx_idx < graph->active_count &&
                                                      vtx_mask[vtx_idx] == 0,
                                                      "The vtx is not found or visited for the second time" );
                            vtx_mask[vtx_idx] = 1;
                        }
                    }
2108

2109
                    cvReleaseGraphScanner( &scanner );
2110

2111 2112 2113 2114 2115 2116 2117
                    CV_TS_SEQ_CHECK_CONDITION( cvtest::norm(Mat(vtx_mask),CV_L1) == graph->active_count &&
                                              cvtest::norm(Mat(edge_mask),CV_L1) == graph->edges->active_count,
                                              "Some vertices or edges have not been visited" );
                    update_progressbar();
                }
                cvClearMemStorage( storage );
            }
2118

2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
            storage.release();
        }
    }
    catch(int)
    {
    }
}


TEST(Core_DS_Seq, basic_operations) { Core_SeqBaseTest test; test.safe_run(); }
TEST(Core_DS_Seq, sort_invert) { Core_SeqSortInvTest test; test.safe_run(); }
TEST(Core_DS_Set, basic_operations) { Core_SetTest test; test.safe_run(); }
TEST(Core_DS_Graph, basic_operations) { Core_GraphTest test; test.safe_run(); }
TEST(Core_DS_Graph, scan) { Core_GraphScanTest test; test.safe_run(); }