summaryrefslogtreecommitdiff
path: root/src/dumps.cpp
blob: 90716b978c545bb933017b87ff8582678f7050a6 (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
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
#include "dumps.h"

#include <QDebug>
#include <QDir>
#include <QElapsedTimer>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

#include "fuck_intel.h"

#include "calibration.h"

#include <chrono>
#include <execution>
#include <iostream>

QList<Pixels> openDump(
    const QString &dumpPath)
{
    QString dirToRead{dumpPath};
    qDebug() << __func__ << "trying to open dump path:" << dirToRead;

    if (dirToRead.isEmpty()) {
        qDebug() << "dumpPath not specified. looking into" << dumpsRoot;

        QDir dumpsRootDir{dumpsRoot};

        const auto filter = QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable;
        // there is no battery in my rpi5 for now
        const auto sort = QDir::Name;
        const auto entries = dumpsRootDir.entryList(filter, sort);

        if (entries.isEmpty()) {
            qWarning() << "dumps root" << dumpsRoot << "contains no dumps. "
                       << "specify existing dump path";

            return {};
        }

        dirToRead = dumpsRoot + "/" + entries.last();
    }

    QDir dumpDir{dirToRead};

    // const QStringList nameFilters{"*.bin"};
    const QStringList nameFilters{};
    const auto filter = QDir::Files;
    const auto sort = QDir::Name;

    auto filenames = dumpDir.entryList(nameFilters, filter, sort);
    qDebug() << __func__ << "dump path" << dumpPath << "has" << filenames.size() << "files";

    if (filenames.isEmpty()) {
        qDebug() << "no filenames found in" << dumpDir.path();
        return {};
    }

    if (false) {
        filenames = filenames.first(1000);
    }

    using mc_t = decltype(Counters::measurementCounter);
    using ep_t = decltype(Counters::encoderPosition);
    using counters_tuple_t = std::tuple<mc_t, ep_t>;
    std::vector<counters_tuple_t> metaFilenames{static_cast<size_t>(filenames.size())};

    const auto fn2meta = [](const QString &filename) -> counters_tuple_t {
        const auto splitted = filename.split('_');
        const auto mc = splitted.at(3).toUInt();
        const auto ep = splitted.at(5).toUInt();
        return std::make_tuple(mc, ep);
    };

    const auto meta2fn = [](const counters_tuple_t &meta) {
        const auto &[mc, ep] = meta;
        const auto tmp = QStringLiteral("raw_profile_meas_%1_enc_%2").arg(mc).arg(ep);
        return tmp;
    };

    std::transform(filenames.cbegin(), filenames.cend(), metaFilenames.begin(), fn2meta);

    filenames.clear();
    filenames.squeeze();

    std::sort(metaFilenames.begin(), metaFilenames.end(), [](const auto &a, const auto &b) {
        const auto &[mca, epa] = a;
        const auto &[mcb, epb] = b;
        return mca < mcb;
    });

    // std::multimap<ep_t, mc_t> enc_meas;
    std::map<ep_t, std::vector<mc_t>> enc_meas;

    for (const auto &mf : metaFilenames) {
        const auto &[mc, ep] = mf;
        enc_meas[ep].push_back(mc);
    }

    metaFilenames.clear();
    metaFilenames.shrink_to_fit();

    QList<Pixels> result;
    result.reserve(static_cast<qsizetype>(enc_meas.size()));

    QElapsedTimer t;
    t.start();
    qDebug() << __func__ << "open real files";
    uint8_t lastPercent{std::numeric_limits<decltype(lastPercent)>::max()};
    auto lastPercentTime = std::chrono::system_clock::now();

    // for (const auto &[ep, mcl] : enc_meas) {
    for (auto em = enc_meas.cbegin(); em != enc_meas.cend(); ++em) {
        const auto &[ep, mcl] = *em;
        std::vector<Pixels> toFilter;
        toFilter.reserve(mcl.size());

        for (const auto &mc : mcl) {
            const auto &filename = meta2fn(std::make_tuple(mc, ep));
            const auto pixelsOpt = Pixels::load(dirToRead + '/' + filename);

            if (pixelsOpt.has_value()) {
                toFilter.push_back(*pixelsOpt);
            }
        };

        // const auto filtered = op::avgFilterAtPos(std::move(toFilter));
        const auto filtered = op::medianFilterAtPos(std::move(toFilter));

        if (filtered.has_value()) {
            result.push_back(*filtered);
        }

        const uint8_t percent{
            static_cast<uint8_t>(std::distance(enc_meas.cbegin(), em) * 100 / enc_meas.size())};

        if (percent != lastPercent) {
            lastPercent = percent;
            const auto now = std::chrono::system_clock::now();
            const auto diffMs = std::chrono::duration_cast<std::chrono::milliseconds>(
                                    now - lastPercentTime)
                                    .count();
            lastPercentTime = std::chrono::system_clock::now();
            qDebug().nospace() << Q_FUNC_INFO << ": " << lastPercent
                               << "%; count: " << result.size() << "; ms (1%): " << diffMs;
        }
    }

    // std::sort(filenames.begin(), filenames.end(), [](const auto &a, const auto &b) {
    //     const auto mca = a.split('_').at(3).toInt();
    //     const auto mcb = b.split('_').at(3).toInt();
    //     return mca < mcb;
    // });

    // for (size_t i{0}; i < metaFilenames.size(); ++i) {
    //     const auto &meta = metaFilenames.at(i);
    //     const auto filename = meta2fn(meta);
    //     auto rawProfile = Pixels::load(dirToRead + '/' + filename);

    //     if (rawProfile.has_value()) {
    //         result << *rawProfile;
    //     }
    //     const uint8_t percent{static_cast<uint8_t>(i * 100 / metaFilenames.size())};

    //     if (percent != lastPercent) {
    //         lastPercent = percent;
    //         qDebug().nospace() << Q_FUNC_INFO << ": " << lastPercent << '%';
    //     }
    // }

    qDebug() << Q_FUNC_INFO << "elapsed (ms)" << t.elapsed();

    return result;
}

std::optional<Pixels> openRawProfile(
    const QString &filePath)
{
    QFile f{filePath};

    if (!f.open(QFile::ReadOnly)) {
        qWarning() << "cannot open file for reading:" << f.fileName();
        qWarning() << "error string:" << f.errorString();

        return {};
    }

    // TODO: rewrite to remove manual serialization/deserialization
    const auto json = QJsonDocument::fromJson(f.readAll()).object();
    const auto jsonCounters = json["counters"].toObject();

    Pixels result;
    result.counters.timestampUs = jsonCounters["timestampUs"].toInteger();
    result.counters.measurementCounter = jsonCounters["measurementCounter"]
                                             .toInteger();
    result.counters.encoderPosition = jsonCounters["encoderPosition"].toInteger();

    const auto jsonPixels = json["pixels"].toArray();
    // TODO: check json pixels count
#ifdef FIRST_COLUMN_ONLY
    result.pixels[0] = jsonPixels.at(0).toDouble();
#else
    std::transform(
        // std::execution::par_unseq,
        jsonPixels.constBegin(),
        jsonPixels.constEnd(),
        result.pixels.begin(),
        [](const auto &jsonPixel) { return jsonPixel.toDouble(); });

// for (size_t i = 0; i < jsonPixels.count() && i < result.pixels.size();
// ++i)
// {
//     result.pixels[i] = jsonPixels[i].toDouble();
// }
#endif

    return result;
}