KASKADE 7 development version
Loading...
Searching...
No Matches
alphabet.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2002-2021 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef ALPHABET__HH
14#define ALPHABET__HH
15
16#include <algorithm>
17#include <cmath>
18#include <iostream>
19#include <iterator>
20#include <limits>
21#include <numeric>
22#include <map>
23#include <vector>
24
25// Optional: helper alias for readability
26template <typename T>
27using IndexType = std::size_t;
28
29// Frequencies class with symbol remapping
30template <typename Freq, typename Symbol = uint32_t>
32{
33public:
34 std::vector<Freq> freq; // Dense frequency table
35 std::vector<Symbol> symbolTable; // Maps internal index back to original symbol
36 std::map<Symbol, IndexType<Symbol>> indexMap; // Maps original symbol -> internal dense index
37
38 template <typename InputIt>
39 Frequencies(InputIt first, InputIt last)
40 {
41 for (auto it = first; it != last; ++it)
42 {
43 Symbol symbol = *it;
44 auto [pos, inserted] = indexMap.emplace(symbol, indexMap.size());
45 if (inserted) {
46 freq.push_back(Freq(1)); // first occurrence
47 symbolTable.push_back(symbol); // preserve original value
48 } else {
49 freq[pos->second] += Freq(1); // increment existing
50 }
51 }
52 }
53
54 // Legacy accessor for compatibility
55 std::vector<Freq> const& frequencies() const { return freq; }
56
57 std::size_t size() const { return freq.size(); }
58
59 Freq operator[](std::size_t i) const { return freq[i]; }
60
61 Symbol originalSymbol(std::size_t i) const { return symbolTable[i]; }
62
64 auto it = indexMap.find(s);
65 if (it == indexMap.end()) throw std::out_of_range("Symbol not found");
66 return it->second;
67 }
68};
69
70
71
80template <class UInt>
81class Alphabet
82{
83public:
90 template <class InIter>
91 Alphabet(InIter first, InIter last, UInt maxRange=std::numeric_limits<UInt>::max())
92 : cumFreq(std::distance(first,last)+1)
93 {
94 // Compute the cumulated frequencies of the symbols.
95 cumFreq[0] = 0;
96 std::partial_sum(first,last,cumFreq.begin()+1,std::plus<UInt>());
97
98 // If the total range covered by the cumulated frequencies exceeds our allowed maximum
99 // range, we scale down the frequencies such that the resulting cumulated frequencies
100 // fit into the allowed range. Since the scaling has to result in integer values,
101 // this introduces a small error in symbol frequency (which we accept in favor of
102 // a smaller range to handle).
103 if (UInt tr = totalRange(); tr > maxRange)
104 {
105 double scale = 0.9 * maxRange / tr;
106 for (int i=1; i<cumFreq.size(); ++i)
107 cumFreq[i] = std::max(static_cast<UInt>(std::ceil(scale*cumFreq[i])),cumFreq[i-1]+1);
108std::cout << "alphabet rescaling cumulated frequencies from " << tr << " to " << cumFreq.back() << " < " << maxRange << "\n";
109 }
110
111 // Getting symbols from a cumulative frequency is essentially the inverse function of
112 // cumulative frequency distribution. It can be computed either by binary search in the
113 // cumulative frequency table, or we precompute the inverse function and store it in a
114 // lookup table. We do the latter, if the total frequency is small enough, i.e. the
115 // table gets not too large. Then there's a decided performance benefit in lookup.
116 if (totalRange() < 4096)
117 {
118 symbolLookup.resize(totalRange());
119 for (int s=0; s<size(); ++s)
120 std::fill(symbolLookup.begin()+cumFreq[s],symbolLookup.begin()+cumFreq[s+1],s);
121 }
122 }
123
131 template <class InIter>
132 void update(InIter first, InIter last)
133 {
134 assert(std::distance(first,last)==size()); // check that all symbols are covered
135 assert(std::find(first,last,0)==last); // check that all frequencies are greater than zero
136 std::partial_sum(first,last,cumFreq.begin()+1,std::plus<UInt>()); // compute cumulative distribution
137 }
138
142 UInt totalRange() const
143 {
144 return cumFreq.back();
145 }
146
150 UInt size() const
151 {
152 return cumFreq.size()-1;
153 }
154
161 double entropy() const
162 {
163 double H = 0;
164 double total = totalRange();
165 for (int i=0; i<size(); ++i)
166 {
167 double p = (cumFreq[i+1]-cumFreq[i]) / total;
168 H -= p*std::log2(p);
169 }
170 return H;
171 }
172
176 UInt symbol(UInt value) const
177 {
178 if (!symbolLookup.empty()) // If lookup table exists, use it.
179 return symbolLookup[value]; // Otherwise, just do a binary search.
180
181
182 auto i = std::upper_bound(cumFreq.begin(),cumFreq.end(), value);
183 assert(i==cumFreq.end() || *i>value);
184 assert(i!=cumFreq.begin());
185
186 return i-cumFreq.begin()-1;
187 }
188
192 std::pair<UInt,UInt> range(UInt symbol) const
193 {
194 assert(symbol<size());
195 return std::make_pair(cumFreq[symbol],cumFreq[symbol+1]);
196 }
197
198
199private:
200 std::vector<UInt> cumFreq; // cumulated frequencies for the symbols
201 std::vector<int> symbolLookup; // symbol for cumulated frequency
202};
203
204
205#endif
std::size_t IndexType
Definition alphabet.hh:27
A simple alphabet of symbols with frequencies to be used with the range coder.
double entropy() const
Returns the entropy of the alphabet.
Definition alphabet.hh:161
UInt totalRange() const
Returns the total range, i.e. the maximum upper range bound of any symbol in the alphabet.
UInt symbol(UInt value) const
Returns the symbol that contains the given value.
Definition alphabet.hh:176
UInt size() const
Returns the number of symbols in the alphabet.
Alphabet(InIter first, InIter last, UInt maxRange=std::numeric_limits< UInt >::max())
Constructor. Constructs an alphabet from a sequence of frequencies of symbols. Note that for each sym...
Definition alphabet.hh:91
void update(InIter first, InIter last)
Modifies the symbols' half-open ranges to represent the symbols' frequencies given in the range [firs...
Definition alphabet.hh:132
std::pair< UInt, UInt > range(UInt symbol) const
Returns the symbol's half-open cumulative frequency range.
Definition alphabet.hh:192
std::map< Symbol, IndexType< Symbol > > indexMap
Definition alphabet.hh:36
Frequencies(InputIt first, InputIt last)
Definition alphabet.hh:39
Symbol originalSymbol(std::size_t i) const
Definition alphabet.hh:61
std::vector< Freq > const & frequencies() const
Definition alphabet.hh:55
Freq operator[](std::size_t i) const
Definition alphabet.hh:59
std::size_t size() const
Definition alphabet.hh:57
IndexType< Symbol > remappedIndex(Symbol s) const
Definition alphabet.hh:63
std::vector< Symbol > symbolTable
Definition alphabet.hh:35
std::vector< Freq > freq
Definition alphabet.hh:34