File: monotone_cubic_spline.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (252 lines) | stat: -rw-r--r-- 6,801 bytes parent folder | download | duplicates (5)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/power/auto_screen_brightness/monotone_cubic_spline.h"

#include <cmath>

#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"

namespace ash {
namespace power {
namespace auto_screen_brightness {

namespace {
constexpr double kTol = 1e-10;

// Entries should not be renumbered and numeric values should never be reused.
enum class InvalidCurveReason {
  kTooFewPoints = 0,
  kUnequalXY = 1,
  kKnotsNotIncreasing = 2,
  kControlsDecreasing = 3,
  kMaxValue = kControlsDecreasing
};

void LogError(InvalidCurveReason reason) {
  base::UmaHistogramEnumeration("AutoScreenBrightness.InvalidCurveReason",
                                reason);
}

bool IsIncreasing(const std::vector<double>& data, bool is_strict) {
  DCHECK_GT(data.size(), 1u);
  for (size_t i = 1; i < data.size(); ++i) {
    if (data[i] < data[i - 1] || (data[i] <= data[i - 1] && is_strict))
      return false;
  }
  return true;
}

bool IsDataValid(const std::vector<double>& xs, const std::vector<double>& ys) {
  const size_t num_points = xs.size();
  if (num_points < 2) {
    LogError(InvalidCurveReason::kTooFewPoints);
    return false;
  }

  if (num_points != ys.size()) {
    LogError(InvalidCurveReason::kUnequalXY);
    return false;
  }

  if (!IsIncreasing(xs, true /* is_strict */)) {
    LogError(InvalidCurveReason::kKnotsNotIncreasing);
    return false;
  }

  if (!IsIncreasing(ys, false /* is_strict */)) {
    LogError(InvalidCurveReason::kControlsDecreasing);
    return false;
  }

  return true;
}

// Computes the tangents at every control point as the average of the secants,
// while ensuring monotonicity is preserved.
std::vector<double> ComputeTangents(const std::vector<double>& xs,
                                    const std::vector<double>& ys,
                                    size_t num_points) {
  // Calculate the slopes of the secant lines between successive points.
  std::vector<double> ds;
  std::vector<double> ms;
  for (size_t i = 0; i < num_points - 1; ++i) {
    const double slope = (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]);
    DCHECK_GE(slope, 0);
    ds.push_back(slope);
  }

  // Initialize the tangents at every point as the average of the secants, and
  // use one-sided differences for endpoints.
  ms.push_back(ds[0]);
  for (size_t i = 1; i < num_points - 1; ++i) {
    ms.push_back(0.5 * (ds[i - 1] + ds[i]));
  }
  ms.push_back(ds[num_points - 2]);

  // Refine tangents to ensure spline monotonicity.
  for (size_t i = 0; i < num_points - 1; ++i) {
    if (ds[i] < kTol) {
      // Successive points are equal, spline needs to be flat.
      ms[i] = 0;
      ms[i + 1] = 0;
    } else {
      const double a = ms[i] / ds[i];
      const double b = ms[i + 1] / ds[i];
      DCHECK_GE(a, 0.0);
      DCHECK_GE(b, 0.0);

      const double r = std::hypot(a, b);
      if (r > 3.0) {
        const double t = 3.0 / r;
        ms[i] *= t;
        ms[i + 1] *= t;
      }
    }
  }

  return ms;
}

}  // namespace

MonotoneCubicSpline::MonotoneCubicSpline(const MonotoneCubicSpline& spline) =
    default;

MonotoneCubicSpline& MonotoneCubicSpline::operator=(
    const MonotoneCubicSpline& spline) = default;

MonotoneCubicSpline::~MonotoneCubicSpline() = default;

std::optional<MonotoneCubicSpline> MonotoneCubicSpline::FromString(
    const std::string& data) {
  std::vector<double> xs;
  std::vector<double> ys;

  if (data.empty())
    return std::nullopt;

  base::StringPairs key_value_pairs;
  if (!base::SplitStringIntoKeyValuePairs(data, ',', '\n', &key_value_pairs)) {
    LOG(ERROR) << "Ill-formatted spline";
    return std::nullopt;
  }

  for (base::StringPairs::iterator it = key_value_pairs.begin();
       it != key_value_pairs.end(); ++it) {
    double x;
    if (!base::StringToDouble(it->first, &x)) {
      LOG(ERROR) << "Ill-formatted xs";
      return std::nullopt;
    }

    double y;
    if (!base::StringToDouble(it->second, &y)) {
      LOG(ERROR) << "Ill-formatted ys";
      return std::nullopt;
    }
    xs.push_back(x);
    ys.push_back(y);
  }

  if (!IsDataValid(xs, ys))
    return std::nullopt;

  return MonotoneCubicSpline(xs, ys);
}

std::optional<MonotoneCubicSpline>
MonotoneCubicSpline::CreateMonotoneCubicSpline(const std::vector<double>& xs,
                                               const std::vector<double>& ys) {
  if (!IsDataValid(xs, ys))
    return std::nullopt;

  return MonotoneCubicSpline(xs, ys);
}

bool MonotoneCubicSpline::operator==(const MonotoneCubicSpline& spline) const {
  if (xs_.size() != spline.xs_.size()) {
    return false;
  }

  for (size_t i = 0; i < xs_.size(); ++i) {
    if (std::abs(xs_[i] - spline.xs_[i]) >= kTol ||
        std::abs(ys_[i] - spline.ys_[i]) >= kTol) {
      return false;
    }
  }

  return true;
}

double MonotoneCubicSpline::Interpolate(double x) const {
  DCHECK_GT(num_points_, 1u);

  if (x <= xs_[0])
    return ys_[0];

  if (x >= xs_.back())
    return ys_.back();

  // Get |x_lower| and |x_upper| so that |x_lower| <= |x| <= |x_upper|.
  // Size of |xs_| is small, so linear search for upper & lower
  // bounds will be ok.
  size_t i = 1;
  while (i < num_points_) {
    const double curr = xs_[i];
    if (curr == x) {
      // Return exact value if |x| is a control point.
      return ys_[i];
    }
    if (curr > x) {
      break;
    }
    ++i;
  }

  DCHECK_LT(i, num_points_);
  const double x_upper = xs_[i];
  const double x_lower = xs_[i - 1];
  DCHECK_GE(x, x_lower);
  DCHECK_LE(x, x_upper);

  const double h = x_upper - x_lower;
  const double t = (x - x_lower) / h;

  return (ys_[i - 1] * (2 * t + 1) + h * ms_[i - 1] * t) * (t - 1) * (t - 1) +
         (ys_[i] * (-2 * t + 3) + h * ms_[i] * (t - 1)) * t * t;
}

std::vector<double> MonotoneCubicSpline::GetControlPointsX() const {
  return xs_;
}

std::vector<double> MonotoneCubicSpline::GetControlPointsY() const {
  return ys_;
}

std::string MonotoneCubicSpline::ToString() const {
  std::vector<std::string> rows;
  for (size_t i = 0; i < num_points_; ++i) {
    rows.push_back(base::JoinString(
        {base::NumberToString(xs_[i]), base::NumberToString(ys_[i])}, ","));
  }

  return base::JoinString(rows, "\n");
}

MonotoneCubicSpline::MonotoneCubicSpline(const std::vector<double>& xs,
                                         const std::vector<double>& ys)
    : xs_(xs),
      ys_(ys),
      num_points_(xs.size()),
      ms_(ComputeTangents(xs, ys, num_points_)) {}

}  // namespace auto_screen_brightness
}  // namespace power
}  // namespace ash