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
|
/*
* Copyright (c) 2020-2021 Vasile Vilvoiu <vasi@vilvoiu.ro>
*
* specgram is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "value-map.hpp"
#include <cmath>
ValueMap::ValueMap(double lower, double upper, const std::string& unit) : lower_(lower), upper_(upper), unit_(unit)
{
if (std::isnan(lower) || std::isnan(upper) || std::isinf(lower) || std::isinf(upper)) {
throw std::runtime_error("bounds cannot be nan or inf");
}
if (lower > upper) {
throw std::runtime_error("lower bound cannot exceed upper bound");
}
}
std::string
ValueMap::GetUnit() const
{
return unit_;
}
std::unique_ptr<ValueMap>
ValueMap::Build(ValueMapType type, double lower, double upper, std::string unit)
{
switch (type) {
case ValueMapType::kLinear:
return std::make_unique<LinearValueMap>(lower, upper, unit);
case ValueMapType::kDecibel:
return std::make_unique<DecibelValueMap>(lower, upper, unit);
default:
throw std::runtime_error("unknown value map type");
}
}
LinearValueMap::LinearValueMap(double lower, double upper, const std::string &unit)
: ValueMap(lower, upper, unit)
{
}
RealWindow LinearValueMap::Map(const RealWindow &input)
{
auto n = input.size();
RealWindow output(n);
for (unsigned int i = 0; i < n; i ++) {
output[i] = std::clamp<double>(input[i], this->lower_, this->upper_);
output[i] = (output[i] - this->lower_) / (this->upper_ - this->lower_);
}
return output;
}
DecibelValueMap::DecibelValueMap(double lower, double upper, const std::string &unit)
: ValueMap(lower, upper, unit)
{
}
RealWindow DecibelValueMap::Map(const RealWindow &input)
{
auto n = input.size();
RealWindow output(n);
for (unsigned int i = 0; i < n; i ++) {
output[i] = 20.0 * std::log10(input[i]);
output[i] = std::clamp<double>(output[i], this->lower_, this->upper_);
output[i] = (output[i] - this->lower_) / (this->upper_ - this->lower_);
}
return output;
}
std::string DecibelValueMap::GetUnit() const
{
return "dB" + unit_;
}
|