File: ScaleTickIntervals.h

package info (click to toggle)
sonic-visualiser 5.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,744 kB
  • sloc: cpp: 158,888; ansic: 11,920; sh: 1,785; makefile: 517; xml: 64; perl: 31
file content (403 lines) | stat: -rw-r--r-- 12,903 bytes parent folder | download | duplicates (2)
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
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Sonic Visualiser
    An audio file viewer and annotation editor.
    Centre for Digital Music, Queen Mary, University of London.
    This file copyright 2006-2017 Chris Cannam and QMUL.
    
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/

#ifndef SV_SCALE_TICK_INTERVALS_H
#define SV_SCALE_TICK_INTERVALS_H

#include <string>
#include <vector>
#include <cmath>

#include "LogRange.h"
#include "Debug.h"

// Can't have this on by default, as we're called on every refresh
//#define DEBUG_SCALE_TICK_INTERVALS 1

namespace sv {

class ScaleTickIntervals
{
public:
    struct Range {
        double min;        // start of value range
        double max;        // end of value range
        int n;             // number of divisions (approximate only)
    };

    struct Tick {
        double value;      // value this tick represents
        std::string label; // value as written 
    };

    typedef std::vector<Tick> Ticks;

    /**
     * Return a set of ticks that divide the range r linearly into
     * roughly r.n equal divisions, in such a way as to yield
     * reasonably human-readable labels.
     */
    static Ticks linear(Range r) {
        return linearTicks(r);
    }

    /**
     * Return a set of ticks that divide the range r into roughly r.n
     * logarithmic divisions, in such a way as to yield reasonably
     * human-readable labels.
     */
    static Ticks logarithmic(Range r) {
        LogRange::mapRange(r.min, r.max);
        return logarithmicAlready(r);
    }

    /**
     * Return a set of ticks that divide the range r into roughly r.n
     * logarithmic divisions, on the asssumption that r.min and r.max
     * already represent the logarithms of the boundary values rather
     * than the values themselves.
     */
    static Ticks logarithmicAlready(Range r) {
        return logTicks(r);
    }
    
private:
    enum Display {
        Fixed,
        Scientific,
        Auto
    };
    
    struct Instruction {
        double initial;    // value of first tick
        double limit;      // max from original range
        double spacing;    // increment between ticks
        double roundTo;    // what all displayed values should be rounded to
                           // (if 0.0, then calculate based on precision)
        Display display;   // whether to use fixed precision (%e, %f, or %g)
        int precision;     // number of dp (%f) or sf (%e)
        bool logUnmap;     // true if values represent logs of display values
    };
    
    static Instruction linearInstruction(Range r)
    {
        Display display = Auto;

        if (std::isnan(r.min) || std::isinf(r.min) ||
            std::isnan(r.max) || std::isinf(r.max)) {
            SVDEBUG << "WARNING: ScaleTickIntervals::linearInstruction: NaN or Inf found in range (" << r.min << " -> " << r.max << ")" << endl;
            return { 0.0, 1.0, 1.0, 0.0, display, 1, false };
        }
        if (r.max < r.min) {
            return linearInstruction({ r.max, r.min, r.n });
        }
        if (r.n < 1 || r.max == r.min) {
            return { r.min, r.min, 1.0, r.min, display, 1, false };
        }
        
        double inc = (r.max - r.min) / r.n;

        double digInc = log10(inc);
        double digMax = log10(fabs(r.max));
        double digMin = log10(fabs(r.min));

        int precInc = int(floor(digInc));
        double roundTo = pow(10.0, precInc);

        if (precInc > -4 && precInc < 4) {
            display = Fixed;
        } else if ((digMax >= -2.0 && digMax <= 3.0) &&
                   (digMin >= -3.0 && digMin <= 3.0)) {
            display = Fixed;
        } else {
            display = Scientific;
        }
        
        int precRange = int(ceil(digMax - digInc));

        int prec = 1;
        
        if (display == Fixed) {
            if (digInc < 0) {
                prec = -precInc;
            } else {
                prec = 0;
            }
        } else {
            prec = precRange;
        }

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "ScaleTickIntervals: calculating linearInstruction" << endl
                << "ScaleTickIntervals: min = " << r.min << ", max = " << r.max
                << ", n = " << r.n << ", inc = " << inc << endl;
        SVDEBUG << "ScaleTickIntervals: digMax = " << digMax
                << ", digInc = " << digInc << endl;
        SVDEBUG << "ScaleTickIntervals: display = " << display
                << ", inc = " << inc << ", precInc = " << precInc
                << ", precRange = " << precRange
                << ", prec = " << prec << ", roundTo = " << roundTo
                << endl;
#endif

        double min = r.min;
        
        if (roundTo != 0.0) {
            // Round inc to the nearest multiple of roundTo, and min
            // to the next multiple of roundTo up. The small offset of
            // eps is included to avoid inc of 2.49999999999 rounding
            // to 2 or a min of -0.9999999999 rounding to 0, both of
            // which would prevent some of our test cases from getting
            // the most natural results.
            double eps = 1e-7;
            inc = round(inc / roundTo + eps) * roundTo;
            if (inc < roundTo) inc = roundTo;
            min = ceil(min / roundTo - eps) * roundTo;
            if (min > r.max) min = r.max;
            if (min == -0.0) min = 0.0;
#ifdef DEBUG_SCALE_TICK_INTERVALS
            SVDEBUG << "ScaleTickIntervals: rounded inc to " << inc
                    << " and min to " << min << endl;
#endif
        }

        if (display == Scientific && min != 0.0) {
            double digNewMin = log10(fabs(min));
            if (digNewMin < digInc) {
                prec = int(ceil(digMax - digNewMin));
#ifdef DEBUG_SCALE_TICK_INTERVALS
                SVDEBUG << "ScaleTickIntervals: min is smaller than increment, adjusting prec to " << prec << endl;
#endif
            }
        }
        
        return { min, r.max, inc, roundTo, display, prec, false };
    }
    
    static Instruction logInstruction(Range r)
    {
        Display display = Auto;

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "ScaleTickIntervals::logInstruction: Range is "
                << r.min << " to " << r.max << endl;
#endif
        
        if (std::isnan(r.min) || std::isinf(r.min) ||
            std::isnan(r.max) || std::isinf(r.max)) {
            SVDEBUG << "WARNING: ScaleTickIntervals::logInstruction: NaN or Inf found in range (" << r.min << " -> " << r.max << ")" << endl;
            return { 0.0, 1.0, 1.0, 0.0, display, 1, false };
        }
        if (r.n < 1) {
            return {};
        }
        if (r.max < r.min) {
            return logInstruction({ r.max, r.min, r.n });
        }
        if (r.max == r.min) {
            return { r.min, r.max, 1.0, r.min, display, 1, true };
        }
        
        double inc = (r.max - r.min) / r.n;

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "ScaleTickIntervals::logInstruction: "
                << "Naive increment is " << inc << endl;
#endif

        int precision = 1;

        if (inc < 1.0) {
            precision = int(ceil(1.0 - inc)) + 1;
        }

        double digInc = log10(inc);
        int precInc = int(floor(digInc));
        double roundIncTo = pow(10.0, precInc);

        inc = round(inc / roundIncTo) * roundIncTo;
        if (inc < roundIncTo) inc = roundIncTo;

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "ScaleTickIntervals::logInstruction: "
                << "Rounded increment to " << inc << endl;
#endif

        // if inc is close to giving us powers of two, nudge it
        if (fabs(inc - 0.301) < 0.01) {
            inc = log10(2.0);

#ifdef DEBUG_SCALE_TICK_INTERVALS
            SVDEBUG << "ScaleTickIntervals::logInstruction: "
                    << "Nudged increment to " << inc << " to get powers of two"
                    << endl;
#endif
        }

        double min = r.min;
        if (inc != 0.0) {
            min = ceil(r.min / inc) * inc;
            if (min > r.max) min = r.max;
        }

        return { min, r.max, inc, 0.0, display, precision, true };
    }

    static Ticks linearTicks(Range r) {
        Instruction instruction = linearInstruction(r);
        Ticks ticks = explode(instruction);
        return ticks;
    }

    static Ticks logTicks(Range r) {
        Instruction instruction = logInstruction(r);
        Ticks ticks = explode(instruction);
        return ticks;
    }
    
    static Tick makeTick(Display display, int precision, double value) {

        if (value == -0.0) {
            value = 0.0;
        }
        
        const int buflen = 40;
        char buffer[buflen];

        if (display == Auto) {

            double eps = 1e-7;
            
            int digits = (value != 0.0 ?
                          1 + int(floor(eps + log10(fabs(value)))) :
                          0);

#ifdef DEBUG_SCALE_TICK_INTERVALS
            SVDEBUG << "makeTick: display = Auto, precision = "
                    << precision << ", value = " << value
                    << ", resulting digits = " << digits << endl;
#endif
            
            // This is not the same logic as %g uses for determining
            // whether to delegate to use scientific or fixed notation

            if (digits < -3 || digits > 4) {

                display = Auto; // delegate planning to %g

            } else {

                display = Fixed;
                
                // in %.*f, the * indicates decimal places, not sig figs
                if (precision >= digits) {
                    precision -= digits;
                } else {
                    precision = 0;
                }
            }
        }

        const char *spec = (display == Auto ? "%.*g" :
                            display == Scientific ? "%.*e" :
                            "%.*f");

#pragma GCC diagnostic ignored "-Wformat-nonliteral"
        
        snprintf(buffer, buflen, spec, precision, value);

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "makeTick: spec = \"" << spec
                << "\", prec = " << precision << ", value = " << value
                << ", label = \"" << buffer << "\"" << endl;
#endif
        
        return Tick({ value, std::string(buffer) });
    }
    
    static Ticks explode(Instruction instruction) {

#ifdef DEBUG_SCALE_TICK_INTERVALS
        SVDEBUG << "ScaleTickIntervals::explode:" << endl
                << "initial = " << instruction.initial
                << ", limit = " << instruction.limit
                << ", spacing = " << instruction.spacing
                << ", roundTo = " << instruction.roundTo
                << ", display = " << instruction.display
                << ", precision = " << instruction.precision
                << ", logUnmap = " << instruction.logUnmap
                << endl;
#endif

        if (instruction.spacing == 0.0) {
            return {};
        }

        double eps = 1e-7;
        if (instruction.spacing < eps * 10.0) {
            eps = instruction.spacing / 10.0;
        }

        double max = instruction.limit;
        int n = 0;

        Ticks ticks;
        int hardLimit = 500;
        
        while (n < hardLimit) { // (Just to avoid an infinite loop if
                                // the instruction is mathematically
                                // ill-behaved - the break just below
                                // is the normal exit condition)

            double value = instruction.initial + n * instruction.spacing;

            if (value >= max + eps) {
                break;
            }

            if (instruction.logUnmap) {
                value = pow(10.0, value);
            }

            double roundTo = instruction.roundTo;

            if (roundTo == 0.0 && value != 0.0) {
                // We don't want the internal value secretly not
                // matching the displayed one
                roundTo =
                    pow(10, ceil(log10(fabs(value))) - instruction.precision);
            }
                                           
            if (roundTo != 0.0) {
                value = roundTo * round(value / roundTo);
            }

            if (fabs(value) < eps) {
                value = 0.0;
            }
            
            ticks.push_back(makeTick(instruction.display,
                                     instruction.precision,
                                     value));
            ++n;
        }

        return ticks;
    }
};

} // end namespace sv

#endif