Debian Codegraph @

LogKmerCount/plc.h

raw
1 /**
2 * A minifloat like datatype for probablistic log counts (PLC) of elements
3 * Unsigned generic implementation
4 * Mantissa = 3 bits
5 * Exponent = 5 bits
6 * Copyright 2014 bcgsc
7 */
8 #include <cmath>
9 #include <cstdlib>
10 #include <iostream>
11 #include <stdint.h>
12
13 using namespace std;
14
15 static const unsigned mantissa = 3;
16 static const uint8_t mantiMask = 0xFF >> (8 - mantissa);
17 static const uint8_t addMask = 0x80 >> (7 - mantissa);
18
19 class plc {
20 public:
21 plc()
22 {
23 m_val = 0;
24 }
25
26 void operator++()
27 {
28 //from 0-1
29 if (m_val <= mantiMask) {
30 ++m_val;
31 } else {
32 //this shifts the first bit off and creates the value
33 //need to get the correct transition probability
34 size_t shiftVal = 1 << ((m_val >> mantissa) - 1);
35 if (rand() % shiftVal == 0) {
36 ++m_val;
37 }
38 }
39 }
40
41 bool operator==(plc val)
42 {
43 return val.rawValue() == m_val;
44 }
45
46 operator bool()
47 {
48 return m_val;
49 }
50
51 float toFloat()
52 {
53 if (m_val <= mantiMask)
54 return float(m_val);
55 return ldexp((m_val & mantiMask) | addMask, (m_val >> mantissa) - 1);
56 }
57
58 /*
59 * return raw value of byte use to store value
60 */
61 uint8_t rawValue()
62 {
63 return m_val;
64 }
65
66 private:
67 uint8_t m_val;
68 };