entropy_encoder_model_kernel_5.h 25.5 KB
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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
// Copyright (C) 2005  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_
#define DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_

#include "../algs.h"
#include "entropy_encoder_model_kernel_abstract.h"
#include "../assert.h"



namespace dlib
{

    namespace eemk5
    {
        struct node
        {            
            node* next;
            node* child_context;
            node* parent_context;

            unsigned short symbol;
            unsigned short count;
            unsigned short total;
            unsigned short escapes;
        };
    }


    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    class entropy_encoder_model_kernel_5 
    {
        /*!
            REQUIREMENTS ON total_nodes
                - 4096 < total_nodes
                - this is the total number of nodes that we will use in the tree

            REQUIREMENTS ON order
                - 0 <= order
                - this is the maximum depth-1 the tree will be allowed to go (note 
                  that the root level is depth 0).  

            GENERAL NOTES
                This implementation follows more or less the implementation 
                strategy laid out by Alistair Moffat in his paper
                Implementing the PPM data compression scheme.  Published in IEEE 
                Transactions on Communications, 38(11):1917-1921, 1990.

                The escape method used will be method D. 

                This also uses Dmitry Shkarin's Information Inheritance scheme.
                (described in "PPM: one step to practicality" and "Improving the 
                Efficiency of the PPM Algorithm")


            INITIAL VALUE
                - root == pointer to an array of total_nodes nodes
                - next_node == 1
                - cur == root
                - cur_order = 0
                - root->next == 0
                - root->parent_context == 0
                - root->child_context == 0
                - root->escapes == 0
                - root->total == 0
                - stack_size == 0
                - exc_used == false
                - for all i: exc[i] == 0

            CONVENTION
                - pop() == stack[stack_size-1].n and stack[stack_size-1].nc
                - exc_used == something_is_excluded()
                - is_excluded(symbol) == bit symbol&0x1F from exc[symbol>>5]
                - &get_entropy_encoder() == coder
                - root == pointer to an array of total_nodes nodes.
                  this is also the root of the tree.
                - if (next_node < total_nodes) then
                    - next_node == the next node in root that has not yet been allocated                                

                - root->next == 0
                - root->parent_context == 0
              

                - for every node in the tree:
                  {
                    - NOTATION: 
                        - The "context" of a node is the string of symbols seen
                          when you go from the root of the tree down (down though
                          child context pointers) to the node, including the symbol at 
                          the node itself.  (note that the context of the root node 
                          is "" or the empty string)
                        - A set of nodes is in the same "context set" if all the node's
                          contexts are of length n and all the node's contexts share
                          the same prefix of length n-1.
                        - The "child context set" of a node is a set of nodes with
                          contexts that are one symbol longer and prefixed by the node's 
                          context.  For example, if a node has a context "abc" then the 
                          nodes for contexts "abca", "abcb", "abcc", etc... are all in 
                          the child context set of the node.
                        - The "parent context" of a node is the context that is one 
                          symbol shorter than the node's context and includes the 
                          symbol in the node.  So the parent context of a node with 
                          context "abcd" would be the context "bcd".


                    - if (next != 0) then 
                        - next == pointer to the next node in the same context set
                    - if (child_context != 0) then
                        - child_context == pointer to the first node of the child 
                          context set for this node.
                        - escapes > 0
                    - if (parent_context != 0) then
                        - parent_context == pointer to the parent context of this node.
                    - else
                        - this node is the root node of the tree
                  

                    - if (this is not the root node) then
                        - symbol == the symbol represented with this node
                        - count == the number of times this symbol has been seen in its
                          parent context.
                    - else
                        - the root doesn't have a symbol.  i.e. the context for the
                          root node is "" or the empty string.

                    - total == The sum of the counts of all the nodes 
                      in the child context set + escapes. 
                    - escapes == the escape count for the context represented
                      by the node.                   
                    - count > 0                    
                }


                - cur_order < order
                - cur_order == the depth of the node cur in the tree.
                  (note that the root node has depth 0)
                - cur == pointer to the node in the tree who's context matches
                  the most recent symbols we have seen.


        !*/

        typedef eemk5::node node;


    public:

        typedef entropy_encoder entropy_encoder_type;

        entropy_encoder_model_kernel_5 (
            entropy_encoder& coder
        );

        virtual ~entropy_encoder_model_kernel_5 (
        );
        
        inline void clear(
        );

        inline void encode (
            unsigned long symbol
        );

        entropy_encoder& get_entropy_encoder (
        ) { return coder; }

        static unsigned long get_alphabet_size (
        ) { return alphabet_size; }

    private:

        inline eemk5::node* allocate_node (
        );
        /*!
            requires
                - space_left() == true
            ensures
                - returns a pointer to a new node
        !*/

        inline bool space_left (
        ) const;
        /*!
            ensures
                - returns true if there is at least 1 free node left.
                - returns false otherwise
        !*/

        inline void exclude (
            unsigned short symbol
        );
        /*!
            ensures
                - #is_excluded(symbol) == true
                - #something_is_excluded() == true
        !*/

        inline bool something_is_excluded (
        );
        /*!
            ensures
                - returns true if some symbol has been excluded.
                  returns false otherwise
        !*/

        inline bool is_excluded (
            unsigned short symbol
        );
        /*!
            ensures
                - if (symbol has been excluded) then
                    - returns true
                - else
                    - returns false
        !*/

        inline void clear_exclusions (
        );
        /*!
            ensures
                - for all symbols #is_excluded(symbol) == false
                - #something_is_excluded() == true
        !*/

        inline void scale_counts (
            node* n
        );
        /*!
            ensures
                - divides all the counts in the child context set of n by 2.
                - none of the nodes in the child context set will have a count of 0
        !*/

        inline void push (
            node* n,
            node* nc
        );
        /*!
            requires
                - stack_size < order
            ensures
                - #pop(a,b): a == n && b == nc
        !*/

        inline void pop (
            node*& n,
            node*& nc
        );
        /*!
            requires
                - stack_size > 0
            ensures
                - returns the two nodes at the top of the stack
        !*/

        struct nodes
        {
            node* n;
            node* nc;
        };

        unsigned long next_node;        
        entropy_encoder& coder;
        node* root;
        node* cur;
        unsigned long cur_order;
        unsigned long exc[alphabet_size/32+1];
        bool exc_used;
        nodes stack[order+1];
        unsigned long stack_size;
        
        // restricted functions
        entropy_encoder_model_kernel_5(entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>&);        // copy constructor
        entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>& operator=(entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>&);    // assignment operator

    };   

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    entropy_encoder_model_kernel_5 (
        entropy_encoder& coder_
    ) : 
        next_node(1),
        coder(coder_),
        cur_order(0),
        stack_size(0) 
    {
        COMPILE_TIME_ASSERT( 1 < alphabet_size && alphabet_size < 65535 );
        COMPILE_TIME_ASSERT( 4096 < total_nodes );

        root = new node[total_nodes];  
        cur = root;

        root->child_context = 0;
        root->escapes = 0;
        root->next = 0;
        root->parent_context = 0;
        root->total = 0;

        clear_exclusions();
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    ~entropy_encoder_model_kernel_5 (
    )
    {
        delete [] root;
    }
    
// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    clear(
    )
    {
        next_node = 1;
        root->child_context = 0;
        root->escapes = 0;
        root->total = 0;
        cur = root;
        cur_order = 0;
        stack_size = 0;

        clear_exclusions();
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    encode (
        unsigned long sym
    )
    {
        unsigned short symbol = static_cast<unsigned short>(sym);
        node* temp = cur;
        cur = 0;
        unsigned short low_count, high_count, total_count;
        node* new_node = 0;

        // local_order will track the level of temp in the tree
        unsigned long local_order = cur_order;


        unsigned short c; // c == t(a|sk)
        unsigned short t; // t == T(sk)

 
        if (something_is_excluded())
            clear_exclusions();

        while (true)
        {
            low_count = 0;
            high_count = 0;
            if (space_left())
            {
                total_count = temp->total;
                
                if (total_count > 0)
                {
                    // check if we need to scale the counts
                    if (total_count > 10000)
                    {
                        scale_counts(temp);
                        total_count = temp->total;
                    }


                    // find the symbol we are looking for and put a pointer to it
                    // into found_symbol.  If it isn't found then found_symbol == 0.
                    // also, low_count and high_count will be correctly set.
                    node* n = temp->child_context;
                    node* found_symbol = 0;
                    node* last = 0;
                    if (something_is_excluded())
                    {
                        node* templast = 0;
                        while (true)
                        {
                            if (is_excluded(n->symbol) == false)
                            {
                                exclude(n->symbol);
                                if (found_symbol == 0)
                                {
                                    high_count += n->count;
                                    if (n->symbol == symbol)
                                    {
                                        found_symbol = n;
                                        last = templast;
                                        low_count = high_count - n->count;
                                    }
                                }
                            }
                            else
                            {
                                total_count -= n->count;
                            }
                            
                            if (n->next == 0)
                                break;
                            templast = n;
                            n = n->next;
                        }                         
                    }
                    else
                    {
                        while (true)
                        {
                            high_count += n->count;
                            exclude(n->symbol);
                           
                            if (n->symbol == symbol)
                            {
                                found_symbol = n;
                                low_count = high_count - n->count;
                                break;
                            }

                            if (n->next == 0)
                                break;
                            last = n;
                            n = n->next;
                        }   
                    }





                    // if we found the symbol
                    if (found_symbol)
                    {
                        n = found_symbol;
                        if (new_node != 0)
                        {
                            new_node->parent_context = found_symbol;
                        }


                        coder.encode(low_count,high_count,total_count);
                        c = n->count += 8;
                        t = temp->total += 8;

                        // move this node to the front 
                        if (last)
                        {
                            last->next = n->next;
                            n->next = temp->child_context;
                            temp->child_context = n;
                        }


                        if (cur == 0)
                        {
                            if (local_order >= order)
                            {
                                cur = n->parent_context;
                                cur_order = local_order;
                            }  
                            else
                            {
                                cur_order = local_order+1;
                                cur = n;
                            }
                        }

                        break;
                
                    }
                    // if we hit the end of the context set without finding the symbol
                    else
                    {   
                        // finish excluding all the symbols
                        while (n->next)
                        {
                            exclude(n->symbol);
                            n = n->next;
                        }

                        if (new_node != 0)
                        {
                            new_node->parent_context = allocate_node();
                            new_node = new_node->parent_context;
                        }
                        else
                        {
                            new_node = allocate_node();
                        }

                        n->next = new_node;

                        // write an escape to a lower context
                        coder.encode(high_count,total_count,total_count);
                    }
                        
                } 
                else // if (total_count == 0)
                {
                    // this means that temp->child_context == 0 so we should make
                    // a new node here.
                    if (new_node != 0)
                    {
                        new_node->parent_context = allocate_node();
                        new_node = new_node->parent_context;
                    }
                    else
                    {
                        new_node = allocate_node();
                    }

                    temp->child_context = new_node;
                }

                if (cur == 0 && local_order < order)
                {
                    cur = new_node;
                    cur_order = local_order+1;
                }

                // fill out the new node
                new_node->child_context = 0;
                new_node->escapes = 0;
                new_node->next = 0;           
                new_node->total = 0;
                push(new_node,temp);
              
                if (temp != root)
                {
                    temp = temp->parent_context;
                    --local_order;
                    continue; 
                }
                
                t = 2056;
                c = 8;

                // since this is the root we are going to the order-(-1) context
                // so we can just take care of that here.
                new_node->parent_context = root;
                coder.encode(symbol,symbol+1,alphabet_size);

                if (cur == 0)
                {
                    cur = root;
                    cur_order = 0;
                }
                break;
            }
            else 
            {
                // there isn't enough space so we should throw away the tree
                clear();
                temp = cur;
                local_order = cur_order;
                cur = 0;      
                new_node = 0;
            }
        } // while (true)


        // initialize the counts and symbol for any new nodes we have added
        // to the tree.
        node* n, *nc;
        while (stack_size > 0)
        {            
            pop(n,nc);        

            n->symbol = static_cast<unsigned short>(symbol);

            // if nc is not a determnistic context
            if (nc->total)
            {
                unsigned long temp2 = t-c+nc->total - nc->escapes - nc->escapes;
                unsigned long temp = nc->total;
                temp *= c;
                temp /= (temp2|1); // this oring by 1 is just to make sure that temp2 is never zero
                temp += 2;
                if (temp > 50000) temp = 50000;
                n->count = static_cast<unsigned short>(temp);

               
                nc->escapes += 4;
                nc->total += static_cast<unsigned short>(temp) + 4;
            }
            else
            {
                n->count = 3 + 5*(c)/(t-c);

                nc->escapes = 4;
                nc->total = n->count + 4;
            }
        
            while (nc->total > 10000)
            {
                scale_counts(nc);
            }
        }
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // private member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    eemk5::node* entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    allocate_node (
    )    
    {
        node* temp;
        temp = root + next_node;
        ++next_node;
        return temp;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    space_left (
    ) const
    {
        return (next_node < total_nodes);
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    exclude (
        unsigned short symbol
    )
    {
        exc_used = true;
        unsigned long temp = 1;
        temp <<= symbol&0x1F;
        exc[symbol>>5] |= temp;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    is_excluded (
        unsigned short symbol
    )
    {
        unsigned long temp = 1;
        temp <<= symbol&0x1F;
        return ((exc[symbol>>5]&temp) != 0);     
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    clear_exclusions (
    )
    {
        exc_used = false;
        for (unsigned long i = 0; i < alphabet_size/32+1; ++i)
        {
            exc[i] = 0;
        }
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    something_is_excluded (
    )
    {
        return exc_used;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    push (
        node* n,
        node* nc
    )
    {
        stack[stack_size].n = n;
        stack[stack_size].nc = nc;
        ++stack_size;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    pop (
        node*& n,
        node*& nc
    )
    {   
        --stack_size;
        n = stack[stack_size].n;
        nc = stack[stack_size].nc;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        typename entropy_encoder,
        unsigned long total_nodes,
        unsigned long order
        >
    void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>::
    scale_counts (
        node* temp
    )
    {
        if (temp->escapes > 1)
            temp->escapes >>= 1;
        temp->total = temp->escapes;

        node* n = temp->child_context;
        while (n != 0)
        {
            if (n->count > 1)
                n->count >>= 1;

            temp->total += n->count;
            n = n->next;
        }
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_