summaryrefslogtreecommitdiffstats
path: root/ml/Dimension.h
blob: 3ec56e0981cec8e0a1cbbfc2b466dfe1a4ecfc75 (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

#ifndef ML_DIMENSION_H
#define ML_DIMENSION_H

#include "Query.h"
#include "Config.h"

#include "ml-private.h"

namespace ml {

enum class MLResult {
    Success = 0,
    MissingData,
    NaN,
};

static inline std::string getMLDimensionID(RRDDIM *RD) {
    RRDSET *RS = RD->rrdset;

    std::stringstream SS;
    SS << rrdset_context(RS) << "|" << rrdset_id(RS) << "|" << rrddim_name(RD);
    return SS.str();
}

class Dimension {
public:
    Dimension(RRDDIM *RD) :
        RD(RD),
        LastTrainedAt(Seconds(0)),
        Trained(false),
        ConstantModel(false),
        AnomalyScore(0.0),
        AnomalyBit(0)
    { }

    RRDDIM *getRD() const {
        return RD;
    }

    unsigned updateEvery() const {
        return RD->update_every;
    }

    time_t latestTime() const {
        return Query(RD).latestTime();
    }

    time_t oldestTime() const {
        return Query(RD).oldestTime();
    }

    bool isTrained() const {
        return Trained;
    }

    bool isAnomalous() const {
        return AnomalyBit;
    }

    bool shouldTrain(const TimePoint &TP) const;

    bool isActive() const;

    MLResult trainModel();

    bool predict(CalculatedNumber Value, bool Exists);

    std::pair<bool, double> detect(size_t WindowLength, bool Reset);

    std::array<KMeans, 1> getModels();

private:
    std::pair<CalculatedNumber *, size_t> getCalculatedNumbers();

public:
    RRDDIM *RD;

    TimePoint LastTrainedAt;
    std::atomic<bool> Trained;
    std::atomic<bool> ConstantModel;

    CalculatedNumber AnomalyScore;
    std::atomic<bool> AnomalyBit;

    std::vector<CalculatedNumber> CNs;
    std::array<KMeans, 1> Models;
    std::mutex Mutex;
};

} // namespace ml

#endif /* ML_DIMENSION_H */