• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

graphia-app / graphia / 42502562509

08 Nov 2026 04:57PM UTC coverage: 71.457% (-0.05%) from 71.51%
42502562509

push

github

timangus
CLAUDE: Suppress cppcheck's duplInheritedMember check and drop NodePositions' second mutex

11725 of 17974 branches covered (65.23%)

Branch coverage included in aggregate %.

29934 of 40325 relevant lines covered (74.23%)

375397.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.51
/source/plugins/correlation/correlation.cpp
1
/* Copyright © 2013-2025 Tim Angus
2
 * Copyright © 2013-2025 Tom Freeman
3
 *
4
 * This file is part of Graphia.
5
 *
6
 * Graphia is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * Graphia is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with Graphia.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
#include "correlation.h"
21

22
#include "correlationdatavector.h"
23
#include "correlationtype.h"
24
#include "knnprotograph.h"
25

26
#include "shared/utils/cancellable.h"
27
#include "shared/utils/progressable.h"
28
#include "shared/utils/redirects.h"
29

30
#include "shared/graph/covariancematrix.h"
31
#include "shared/graph/edgelist.h"
32

33
#include <QObject>
34
#include <QString>
35
#include <QVariantMap>
36

37
#include <algorithm>
38
#include <atomic>
39
#include <cmath>
40
#include <cstddef>
41
#include <cstdint>
42
#include <iterator>
43
#include <memory>
44
#include <numeric>
45
#include <type_traits>
46
#include <utility>
47
#include <variant>
48
#include <vector>
49

50
using namespace Qt::Literals::StringLiterals;
51

52
template<typename DataVectors>
53
class ThresholdFilter
54
{
55
private:
56
    CorrelationPolarity _polarity = CorrelationPolarity::Positive;
57
    double _threshold = 0.0;
58

59
public:
60
    ThresholdFilter(const DataVectors&, const QVariantMap& parameters)
61
    {
448 ✔
62
        _threshold = parameters[u"minimumThreshold"_s].toDouble();
448 ✔
63
        _polarity = normaliseQmlEnum<CorrelationPolarity>(parameters[u"correlationPolarity"_s].toInt());
448 ✔
64
    }
448 ✔
65

66
    using Results = CorrelationVector<DataVectors>;
67

68
    void add(Results* results,
69
        typename DataVectors::const_iterator a,
70
        typename DataVectors::const_iterator b,
71
        double r)
72
    {
4,739 ✔
73
        if(correlationExceedsThreshold(_polarity, r, _threshold))
4,739 ✔
74
            results->push_back({a, b, r});
2,967 ✔
75
    }
4,739 ✔
76
};
77

78
template<typename DataVectors>
79
class KnnFilter
80
{
81
private:
82
    KnnProtoGraph<DataVectors> _protoGraph;
83

84
public:
85
    KnnFilter(const DataVectors& vectors, const QVariantMap& parameters) :
86
        _protoGraph(vectors, parameters)
52 ✔
87
    {}
52 ✔
88

89
    using Results = std::monostate;
90

91
    void add(Results*,
92
        typename DataVectors::const_iterator a,
93
        typename DataVectors::const_iterator b,
94
        double r)
95
    {
317 ✔
96
        _protoGraph.add(a, b, r);
317 ✔
97
    }
317 ✔
98

99
    KnnProtoGraph<DataVectors>&& results() { return std::move(_protoGraph); }
52 ✔
100
};
101

102
struct RequiresRanking {};
103

104
template<typename Algorithm, template<typename> class FilterMethod>
105
class CovarianceCorrelation : public ContinuousCorrelation
106
{
107
private:
108
    auto process(const ContinuousDataVectors& vectors, const QVariantMap& parameters,
109
        const Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const
110
    {
438 ✔
111
        size_t size = vectors.front().size();
438 ✔
112

113
        if(progressable != nullptr)
438 !
114
            progressable->setProgress(-1);
300 ✔
115

116
        uint64_t totalCost = 0;
438 ✔
117
        for(const auto& vector : vectors)
438 ✔
118
        {
2,080 ✔
119
            totalCost += vector.computeCostHint();
2,080 ✔
120

121
            if constexpr(std::is_base_of_v<RequiresRanking, Algorithm>)
122
                vector.generateRanking();
96 ✔
123
        }
2,080 ✔
124

125
        Algorithm algorithm;
438 ✔
126

127
        if constexpr(requires { algorithm.preprocess(0, {}); })
128
            algorithm.preprocess(size, vectors);
20 ✔
129

130
        using FM = FilterMethod<ContinuousDataVectors>;
438 ✔
131
        FM filterMethod(vectors, parameters);
438 ✔
132

133
        std::atomic<uint64_t> cost(0);
438 ✔
134

135
        auto results = threadPool().parallel_for(vectors.begin(), vectors.end(),
438 ✔
136
        [&](ContinuousDataVectors::const_iterator vectorAIt)
438 ✔
137
        {
2,030 ✔
138
            const auto* vectorA = &(*vectorAIt);
2,030 ✔
139

140
            if constexpr(std::is_base_of_v<RequiresRanking, Algorithm>)
141
                vectorA = vectorA->ranking();
96 ✔
142

143
            typename FM::Results threadResults;
2,030 ✔
144

145
            if(cancellable != nullptr && cancellable->cancelled())
2,030 !
146
                return threadResults;
30 ✔
147

148
            for(auto vectorBIt = vectorAIt + 1; vectorBIt != vectors.end(); ++vectorBIt)
6,555 ✔
149
            {
4,555 ✔
150
                const auto* vectorB = &(*vectorBIt);
4,555 ✔
151

152
                if constexpr(std::is_base_of_v<RequiresRanking, Algorithm>)
153
                    vectorB = vectorB->ranking();
145 ✔
154

155
                const double r = algorithm.evaluate(size, vectorA, vectorB);
4,555 ✔
156

157
                if(!std::isfinite(r))
4,555 !
158
                    continue;
4 ✔
159

160
                filterMethod.add(&threadResults, vectorAIt, vectorBIt, r);
4,551 ✔
161
            }
4,551 ✔
162

163
            cost += vectorA->computeCostHint();
2,000 ✔
164

165
            if(progressable != nullptr)
2,000 !
166
                progressable->setProgress(static_cast<int>((cost * 100) / totalCost));
1,525 ✔
167

168
            return threadResults;
2,000 ✔
169
        });
2,030 ✔
170

171
        if(progressable != nullptr)
438 !
172
        {
300 ✔
173
            // Returning the results might take time
174
            progressable->setProgress(-1);
300 ✔
175
        }
300 ✔
176

177
        if constexpr(requires { filterMethod.results(); })
178
            return filterMethod.results();
34 ✔
179
        else
180
            return results;
404 ✔
181
    }
438 ✔
182

183
public:
184
    EdgeList edgeList(const ContinuousDataVectors& vectors, const QVariantMap& parameters,
185
        Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const final
186
    {
408 ✔
187
        if(vectors.empty())
408 !
188
            return {};
4 ✔
189

190
        auto results = process(vectors, parameters, cancellable, progressable);
404 ✔
191

192
        if(cancellable != nullptr && cancellable->cancelled())
404 !
193
            return {};
4 ✔
194

195
        EdgeList edges;
400 ✔
196
        edges.reserve(static_cast<size_t>(std::distance(results.begin(), results.end())));
400 ✔
197

198
        std::transform(results.begin(), results.end(), std::back_inserter(edges),
400 ✔
199
        [](const auto& result)
400 ✔
200
        {
2,544 ✔
201
            return EdgeListEdge{result._a->nodeId(), result._b->nodeId(), result._r};
2,544 ✔
202
        });
2,544 ✔
203

204
        return edges;
400 ✔
205
    }
404 ✔
206

207
    CovarianceMatrix matrix(const ContinuousDataVectors& vectors, const QVariantMap& parameters,
208
        Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const final
209
    {
38 ✔
210
        if(vectors.empty())
38 !
211
            return {};
4 ✔
212

213
        auto results = process(vectors, parameters, cancellable, progressable);
34 ✔
214

215
        if(cancellable != nullptr && cancellable->cancelled())
34 !
216
            return {};
4 ✔
217

218
        CovarianceMatrix matrix(vectors.size());
30 ✔
219

220
        for(const auto& result : results)
30 ✔
221
        {
208 ✔
222
            auto a = static_cast<size_t>(std::distance(vectors.begin(), result._a));
208 ✔
223
            auto b = static_cast<size_t>(std::distance(vectors.begin(), result._b));
208 ✔
224
            matrix.setValueAt(a, b, result._r);
208 ✔
225
        }
208 ✔
226

227
        return matrix;
30 ✔
228
    }
34 ✔
229

230
    QString name() const override                   { return Algorithm::name(); }
322 ✔
231
    QString description() const override            { return Algorithm::description(); }
10 ✔
232

233
    QString attributeName() const override          { return Algorithm::attributeName(); }
840 ✔
234
    QString attributeDisplayName() const override   { return Algorithm::attributeDisplayName(); }
570 ✔
235
    QString attributeDescription() const override   { return Algorithm::attributeDescription(); }
340 ✔
236
};
237

238
class PearsonAlgorithm
239
{
240
public:
241
    double evaluate(size_t size, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const;
242

243
    static QString name() { return QObject::tr("Pearson"); }
296 ✔
244
    static QString description()
245
    {
2 ✔
246
        return QObject::tr("The Pearson Correlation Coefficient is an indication "
2 ✔
247
            "of the linear correlation between two variables.");
2 ✔
248
    }
2 ✔
249

250
    static QString attributeName() { return u"PearsonCorrelationValue"_s; }
430 ✔
251
    static QString attributeDisplayName() { return QObject::tr("Pearson Correlation Value"); }
376 ✔
252
    static QString attributeDescription()
253
    {
330 ✔
254
        return QObject::tr("The %1 is an indication of "
330 ✔
255
            "the linear relationship between two variables.")
330 ✔
256
            .arg(u::redirectLink("pearson", QObject::tr("Pearson Correlation Coefficient")));
330 ✔
257
    }
330 ✔
258
};
259

260
using PearsonCorrelation = CovarianceCorrelation<PearsonAlgorithm, ThresholdFilter>;
261
using PearsonCorrelationKnn = CovarianceCorrelation<PearsonAlgorithm, KnnFilter>;
262

263
class SpearmanRankAlgorithm : public PearsonAlgorithm, RequiresRanking
264
{
265
public:
266
    static QString name() { return QObject::tr("Spearman Rank"); }
8 ✔
267
    static QString description()
268
    {
2 ✔
269
        return QObject::tr("Spearman's rank correlation coefficient is a "
2 ✔
270
            "nonparametric measure of the statistical dependence between "
2 ✔
271
            "the rankings of two variables. It assesses how well the "
2 ✔
272
            "relationship between two variables can be described using a "
2 ✔
273
            "monotonic function.");
2 ✔
274
    }
2 ✔
275

276
    static QString attributeName() { return u"SpearmanRankCorrelationValue"_s; }
104 ✔
277
    static QString attributeDisplayName() { return QObject::tr("Spearman Rank Correlation Value"); }
50 ✔
278
    static QString attributeDescription()
279
    {
4 ✔
280
        return QObject::tr("The %1 is an indication of "
4 ✔
281
            "the monotonic relationship between two variables.")
4 ✔
282
            .arg(u::redirectLink("spearman", QObject::tr("Spearman Rank Correlation Coefficient")));
4 ✔
283
    }
4 ✔
284
};
285

286
using SpearmanRankCorrelation = CovarianceCorrelation<SpearmanRankAlgorithm, ThresholdFilter>;
287
using SpearmanRankCorrelationKnn = CovarianceCorrelation<SpearmanRankAlgorithm, KnnFilter>;
288

289
class EuclideanSimilarityAlgorithm
290
{
291
public:
292
    double evaluate(size_t, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const;
293

294
    static QString name() { return QObject::tr("Euclidean Similarity"); }
6 ✔
295
    static QString description()
296
    {
2 ✔
297
        return QObject::tr("Euclidean Similarity is essentially the inverse "
2 ✔
298
            "of the Euclidean distance between two vectors.");
2 ✔
299
    }
2 ✔
300

301
    static QString attributeName() { return u"EuclideanSimilarity"_s; }
102 ✔
302
    static QString attributeDisplayName() { return QObject::tr("Euclidean Similarity"); }
48 ✔
303
    static QString attributeDescription()
304
    {
2 ✔
305
        return QObject::tr("%1 is essentially the inverse "
2 ✔
306
            "of the Euclidean distance between two vectors.")
2 ✔
307
            .arg(u::redirectLink("euclidean", QObject::tr("Euclidean Similarity")));
2 ✔
308
    }
2 ✔
309
};
310

311
using EuclideanSimilarityCorrelation = CovarianceCorrelation<EuclideanSimilarityAlgorithm, ThresholdFilter>;
312
using EuclideanSimilarityCorrelationKnn = CovarianceCorrelation<EuclideanSimilarityAlgorithm, KnnFilter>;
313

314
class CosineSimilarityAlgorithm
315
{
316
public:
317
    double evaluate(size_t, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const;
318

319
    static QString name() { return QObject::tr("Cosine Similarity"); }
6 ✔
320
    static QString description()
321
    {
2 ✔
322
        return QObject::tr("Cosine Similarity is a measure of similarity between two "
2 ✔
323
            "non-zero vectors of an inner product space. It is defined to equal "
2 ✔
324
            "the cosine of the angle between them, which is also the same as the "
2 ✔
325
            "inner product of the same vectors normalized to both have length 1.");
2 ✔
326
    }
2 ✔
327

328
    static QString attributeName() { return u"CosineSimilarity"_s; }
102 ✔
329
    static QString attributeDisplayName() { return QObject::tr("Cosine Similarity"); }
48 ✔
330
    static QString attributeDescription()
331
    {
2 ✔
332
        return QObject::tr("%1 is a measure of similarity between two "
2 ✔
333
            "non-zero vectors of an inner product space.")
2 ✔
334
            .arg(u::redirectLink("cosine", QObject::tr("Cosine Similarity")));
2 ✔
335
    }
2 ✔
336
};
337

338
using CosineSimilarityCorrelation = CovarianceCorrelation<CosineSimilarityAlgorithm, ThresholdFilter>;
339
using CosineSimilarityCorrelationKnn = CovarianceCorrelation<CosineSimilarityAlgorithm, KnnFilter>;
340

341
class BicorAlgorithm
342
{
343
private:
344
    const ContinuousDataVector* _base = nullptr;
345
    ContinuousDataVectors _processedVectors;
346

347
public:
348
    void preprocess(size_t size, const ContinuousDataVectors& vectors);
349
    double evaluate(size_t, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const;
350

351
    static QString name() { return QObject::tr("Bicor"); }
6 ✔
352
    static QString description()
353
    {
2 ✔
354
        return QObject::tr("Biweight Midcorrelation (also called Bicor) is a "
2 ✔
355
            "measure of similarity between samples. It is median-based, rather "
2 ✔
356
            "than mean-based, thus is less sensitive to outliers.");
2 ✔
357
    }
2 ✔
358

359
    static QString attributeName() { return u"BicorCorrelationValue"_s; }
102 ✔
360
    static QString attributeDisplayName() { return QObject::tr("Bicor Correlation Value"); }
48 ✔
361
    static QString attributeDescription()
362
    {
2 ✔
363
        return QObject::tr("%1 is a median-based measure of similarity between samples.")
2 ✔
364
            .arg(u::redirectLink("bicor", QObject::tr("Bicor")));
2 ✔
365
    }
2 ✔
366
};
367

368
using BicorCorrelation = CovarianceCorrelation<BicorAlgorithm, ThresholdFilter>;
369
using BicorCorrelationKnn = CovarianceCorrelation<BicorAlgorithm, KnnFilter>;
370

371
template<int Denominator, typename AlgorithmInfo, template<typename> class FilterMethod>
372
class MatchingCorrelation : public DiscreteCorrelation
373
{
374
private:
375
    struct Fraction
376
    {
377
        int _numerator = 0;
378
        int _denominator = 0;
379

380
        Fraction& operator+=(const Fraction& other)
381
        {
1,789 ✔
382
            _numerator += other._numerator;
1,789 ✔
383
            _denominator += other._denominator;
1,789 ✔
384

385
            return *this;
1,789 ✔
386
        }
1,789 ✔
387

388
        // NOLINTNEXTLINE(google-explicit-constructor)
389
        operator double() const { return static_cast<double>(_numerator) / _denominator; }
524 ✔
390
    };
391

392
    auto process(const TokenisedDataVectors& vectors, const QVariantMap& parameters,
393
        const Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const
394
    {
62 ✔
395
        const size_t size = vectors.front().size();
62 ✔
396
        auto treatAsBinary = parameters[u"treatAsBinary"_s].toBool();
62 ✔
397

398
        if(progressable != nullptr)
62 !
399
            progressable->setProgress(-1);
14 ✔
400

401
        auto totalCost = std::accumulate(vectors.begin(), vectors.end(), uint64_t{0},
62 ✔
402
            [](uint64_t sum, const auto& vector) { return sum + vector.computeCostHint(); });
248 ✔
403

404
        using FM = FilterMethod<TokenisedDataVectors>;
62 ✔
405
        FM filterMethod(vectors, parameters);
62 ✔
406

407
        std::atomic<uint64_t> cost(0);
62 ✔
408

409
        auto results = threadPool().parallel_for(vectors.begin(), vectors.end(),
62 ✔
410
        [&](TokenisedDataVectors::const_iterator vectorAIt)
62 ✔
411
        {
245 ✔
412
            typename FM::Results threadResults;
245 ✔
413

414
            if(cancellable != nullptr && cancellable->cancelled())
245 !
415
                return threadResults;
4 ✔
416

417
            auto binary = [&](auto vectorAValue, auto vectorBValue) -> Fraction
241 ✔
418
            {
483 ✔
419
                return {vectorAValue && vectorBValue ? 1 : 0, 1};
483 ✔
420
            };
483 ✔
421

422
            auto nonBinary = [&](auto vectorAValue, auto vectorBValue) -> Fraction
241 ✔
423
            {
1,136 ✔
424
                return {vectorAValue == vectorBValue ? 1 : 0, 1};
1,136 ✔
425
            };
1,136 ✔
426

427
            auto createEdgesForVectorPairs = [&](auto&& f)
241 ✔
428
            {
241 ✔
429
                for(auto vectorBIt = vectorAIt + 1; vectorBIt != vectors.end(); ++vectorBIt)
766 ✔
430
                {
525 ✔
431
                    Fraction fraction;
525 ✔
432
                    for(size_t i = 0; i < size; i++)
2,316 ✔
433
                    {
1,791 ✔
434
                        const auto& vectorAValue = vectorAIt->valueAt(i);
1,791 ✔
435
                        const auto& vectorBValue = vectorBIt->valueAt(i);
1,791 ✔
436

437
                        // Mutual absence is ignored when Denominator is 0 (Jaccard),
438
                        // and counts as a match when it is 1 (SMC)
439
                        if(!vectorAValue && !vectorBValue)
1,791 ✔
440
                            fraction += {Denominator, Denominator};
168 ✔
441
                        else
1,623 ✔
442
                            fraction += f(vectorAValue, vectorBValue);
1,623 ✔
443
                    }
1,791 ✔
444

445
                    const double r = fraction;
525 ✔
446

447
                    if(!std::isfinite(r))
525 !
448
                        continue;
×
449

450
                    filterMethod.add(&threadResults, vectorAIt, vectorBIt, r);
525 ✔
451
                }
525 ✔
452
            };
241 ✔
453

454
            if(treatAsBinary)
241 ✔
455
                createEdgesForVectorPairs(binary);
82 ✔
456
            else
159 ✔
457
                createEdgesForVectorPairs(nonBinary);
159 ✔
458

459
            cost += vectorAIt->computeCostHint();
241 ✔
460

461
            if(progressable != nullptr)
241 !
462
                progressable->setProgress(static_cast<int>((cost * 100) / totalCost));
74 ✔
463

464
            return threadResults;
241 ✔
465
        });
245 ✔
466

467
        if(progressable != nullptr)
62 !
468
        {
14 ✔
469
            // Returning the results might take time
470
            progressable->setProgress(-1);
14 ✔
471
        }
14 ✔
472

473
        if constexpr(requires { filterMethod.results(); })
474
            return filterMethod.results();
18 ✔
475
        else
476
            return results;
44 ✔
477
    }
62 ✔
478

479
public:
480
    EdgeList edgeList(const DiscreteDataVectors& vectors, const QVariantMap& parameters,
481
        Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const final
482
    {
50 ✔
483
        if(vectors.empty())
50 !
484
            return {};
4 ✔
485

486
        const auto tokenisedVectors = tokeniseDataVectors(vectors);
46 ✔
487
        auto results = process(tokenisedVectors, parameters, cancellable, progressable);
46 ✔
488

489
        if(cancellable != nullptr && cancellable->cancelled())
46 !
490
            return {};
2 ✔
491

492
        EdgeList edges;
44 ✔
493
        edges.reserve(static_cast<size_t>(std::distance(results.begin(), results.end())));
44 ✔
494

495
        std::transform(results.begin(), results.end(), std::back_inserter(edges),
44 ✔
496
        [](const auto& result)
44 ✔
497
        {
398 ✔
498
            return EdgeListEdge{result._a->nodeId(), result._b->nodeId(), result._r};
398 ✔
499
        });
398 ✔
500

501
        return edges;
44 ✔
502
    }
46 ✔
503

504
    CovarianceMatrix matrix(const DiscreteDataVectors& vectors, const QVariantMap& parameters,
505
        Cancellable* cancellable = nullptr, Progressable* progressable = nullptr) const final
506
    {
20 ✔
507
        if(vectors.empty())
20 !
508
            return {};
4 ✔
509

510
        const auto tokenisedVectors = tokeniseDataVectors(vectors);
16 ✔
511
        auto results = process(tokenisedVectors, parameters, cancellable, progressable);
16 ✔
512

513
        if(cancellable != nullptr && cancellable->cancelled())
16 !
514
            return {};
×
515

516
        CovarianceMatrix matrix(tokenisedVectors.size());
16 ✔
517

518
        for(const auto& result : results)
16 ✔
519
        {
96 ✔
520
            auto a = static_cast<size_t>(std::distance(tokenisedVectors.begin(), result._a));
96 ✔
521
            auto b = static_cast<size_t>(std::distance(tokenisedVectors.begin(), result._b));
96 ✔
522
            matrix.setValueAt(a, b, result._r);
96 ✔
523
        }
96 ✔
524

525
        return matrix;
16 ✔
526
    }
16 ✔
527

528
    QString name() const override                   { return AlgorithmInfo::name(); }
34 ✔
529
    QString description() const override            { return AlgorithmInfo::description(); }
4 ✔
530

531
    QString attributeName() const override          { return AlgorithmInfo::attributeName(); }
228 ✔
532
    QString attributeDisplayName() const override   { return AlgorithmInfo::attributeDisplayName(); }
112 ✔
533
    QString attributeDescription() const override   { return AlgorithmInfo::attributeDescription(); }
20 ✔
534
};
535

536
struct JaccardCorrelationInfo
537
{
538
    static QString name() { return QObject::tr("Jaccard"); }
16 ✔
539
    static QString description()
540
    {
2 ✔
541
        return QObject::tr("The Jaccard Index is a statistic used for "
2 ✔
542
            "gauging the similarity and diversity of sample sets.");
2 ✔
543
    }
2 ✔
544

545
    static QString attributeName() { return u"JaccardCorrelationValue"_s; }
112 ✔
546
    static QString attributeDisplayName() { return QObject::tr("Jaccard Correlation Value"); }
54 ✔
547
    static QString attributeDescription()
548
    {
8 ✔
549
        return QObject::tr("The %1 is a statistic used for gauging "
8 ✔
550
            "the similarity and diversity of sample sets.")
8 ✔
551
            .arg(u::redirectLink("jaccard", QObject::tr("Jaccard Index")));
8 ✔
552
    }
8 ✔
553
};
554

555
using JaccardCorrelation = MatchingCorrelation<0, JaccardCorrelationInfo, ThresholdFilter>;
556
using JaccardCorrelationKnn = MatchingCorrelation<0, JaccardCorrelationInfo, KnnFilter>;
557

558
struct SMCCorrelationInfo
559
{
560
    static QString name() { return QObject::tr("Simple Matching Coefficient"); }
18 ✔
561
    static QString description()
562
    {
2 ✔
563
        return QObject::tr("The Simple Matching Coefficient is a statistic used for "
2 ✔
564
            "gauging the similarity and diversity of sample sets. It is identical "
2 ✔
565
            "to Jaccard, except that it counts mutual absence.");
2 ✔
566
    }
2 ✔
567

568
    static QString attributeName() { return u"SimpleMatchingCoefficient"_s; }
116 ✔
569
    static QString attributeDisplayName() { return QObject::tr("Simple Matching Coefficient"); }
58 ✔
570
    static QString attributeDescription()
571
    {
12 ✔
572
        return QObject::tr("The %1 is a statistic used for gauging "
12 ✔
573
            "the similarity and diversity of sample sets.")
12 ✔
574
            .arg(u::redirectLink("smc", QObject::tr("Simple Matching Coefficient (SMC)")));
12 ✔
575
    }
12 ✔
576
};
577

578
using SMCCorrelation = MatchingCorrelation<1, SMCCorrelationInfo, ThresholdFilter>;
579
using SMCCorrelationKnn = MatchingCorrelation<1, SMCCorrelationInfo, KnnFilter>;
580

581
class EuclideanDistanceAlgorithm
582
{
583
public:
584
    double evaluate(size_t size, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const;
585

586
    static QString name() { return {}; }
×
587
    static QString description() { return {}; }
×
588
    static QString attributeName() { return {}; }
×
589
    static QString attributeDisplayName() { return {}; }
×
590
    static QString attributeDescription() { return {}; }
×
591
};
592

593
using EuclideanDistanceCorrelation = CovarianceCorrelation<EuclideanDistanceAlgorithm, ThresholdFilter>;
594

595
std::unique_ptr<ContinuousCorrelation> ContinuousCorrelation::create(CorrelationType correlationType,
596
    CorrelationFilterType correlationFilterType)
597
{
1,376 ✔
598
    switch(correlationFilterType)
1,376 ✔
599
    {
1,376 ✔
600
    case CorrelationFilterType::Threshold:
1,344 ✔
601
        switch(correlationType)
1,344 ✔
602
        {
1,344 ✔
603
        case CorrelationType::Pearson:              return std::make_unique<PearsonCorrelation>();
984 ✔
604
        case CorrelationType::SpearmanRank:         return std::make_unique<SpearmanRankCorrelation>();
72 ✔
605
        case CorrelationType::EuclideanSimilarity:  return std::make_unique<EuclideanSimilarityCorrelation>();
64 ✔
606
        case CorrelationType::CosineSimilarity:     return std::make_unique<CosineSimilarityCorrelation>();
64 ✔
607
        case CorrelationType::Bicor:                return std::make_unique<BicorCorrelation>();
64 ✔
608
        default: break;
96 ✔
609
        }
1,344 ✔
610
        break;
96 ✔
611

612
    case CorrelationFilterType::Knn:
96 ✔
613
        switch(correlationType)
32 ✔
614
        {
32 ✔
615
        case CorrelationType::Pearson:              return std::make_unique<PearsonCorrelationKnn>();
24 ✔
616
        case CorrelationType::SpearmanRank:         return std::make_unique<SpearmanRankCorrelationKnn>();
2 ✔
617
        case CorrelationType::EuclideanSimilarity:  return std::make_unique<EuclideanSimilarityCorrelationKnn>();
2 ✔
618
        case CorrelationType::CosineSimilarity:     return std::make_unique<CosineSimilarityCorrelationKnn>();
2 ✔
619
        case CorrelationType::Bicor:                return std::make_unique<BicorCorrelationKnn>();
2 ✔
620
        default: break;
×
621
        }
32 ✔
622
        break;
×
623

624
    default: break;
×
625
    }
1,376 ✔
626

627
    return nullptr;
96 ✔
628
}
1,376 ✔
629

630
std::unique_ptr<DiscreteCorrelation> DiscreteCorrelation::create(CorrelationType correlationType,
631
    CorrelationFilterType correlationFilterType)
632
{
428 ✔
633
    switch(correlationFilterType)
428 ✔
634
    {
428 ✔
635
    case CorrelationFilterType::Threshold:
416 ✔
636
        switch(correlationType)
416 ✔
637
        {
416 ✔
638
        case CorrelationType::Jaccard:              return std::make_unique<JaccardCorrelation>();
80 ✔
639
        case CorrelationType::SMC:                  return std::make_unique<SMCCorrelation>();
86 ✔
640
        default: break;
250 ✔
641
        }
416 ✔
642
        break;
250 ✔
643

644
    case CorrelationFilterType::Knn:
250 ✔
645
        switch(correlationType)
12 ✔
646
        {
12 ✔
647
        case CorrelationType::Jaccard:              return std::make_unique<JaccardCorrelationKnn>();
8 ✔
648
        case CorrelationType::SMC:                  return std::make_unique<SMCCorrelationKnn>();
4 ✔
649
        default: break;
×
650
        }
12 ✔
651
        break;
×
652

653
    default: break;
×
654
    }
428 ✔
655

656
    return nullptr;
250 ✔
657
}
428 ✔
658

659
std::unique_ptr<ContinuousCorrelation> ContinuousCorrelation::createEuclideanDistance()
660
{
8 ✔
661
    return std::make_unique<EuclideanDistanceCorrelation>();
8 ✔
662
}
8 ✔
663

664
double PearsonAlgorithm::evaluate(size_t size, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const
665
{
4,133 ✔
666
    const double productSum = std::inner_product(vectorA->begin(), vectorA->end(), vectorB->begin(), 0.0);
4,133 ✔
667
    const double numerator = (static_cast<double>(size) * productSum) - (vectorA->sum() * vectorB->sum());
4,133 ✔
668
    const double denominator = vectorA->variability() * vectorB->variability();
4,133 ✔
669

670
    return numerator / denominator;
4,133 ✔
671
}
4,133 ✔
672

673
double EuclideanSimilarityAlgorithm::evaluate(size_t size, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const
674
{
120 ✔
675
    double sum = 0.0;
120 ✔
676

677
    for(size_t i = 0; i < size; i++)
718 ✔
678
    {
598 ✔
679
        auto diff = vectorA->valueAt(i) - vectorB->valueAt(i);
598 ✔
680
        auto diffSq = diff * diff;
598 ✔
681
        sum += diffSq;
598 ✔
682
    }
598 ✔
683

684
    auto sqrtSum = sum != 0.0 ? std::sqrt(sum) : 0.0;
120 !
685

686
    return 1.0 / (1.0 + sqrtSum);
120 ✔
687
}
120 ✔
688

689
double EuclideanDistanceAlgorithm::evaluate(size_t size, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const
690
{
96 ✔
691
    double sum = 0.0;
96 ✔
692

693
    for(size_t i = 0; i < size; i++)
551 ✔
694
    {
455 ✔
695
        auto diff = vectorA->valueAt(i) - vectorB->valueAt(i);
455 ✔
696
        auto diffSq = diff * diff;
455 ✔
697
        sum += diffSq;
455 ✔
698
    }
455 ✔
699

700
    return sum != 0.0 ? std::sqrt(sum) : 0.0;
96 !
701
}
96 ✔
702

703
double CosineSimilarityAlgorithm::evaluate(size_t, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const
704
{
120 ✔
705
    const double productSum = std::inner_product(vectorA->begin(), vectorA->end(), vectorB->begin(), 0.0);
120 ✔
706
    const double magnitudeProduct = vectorA->magnitude() * vectorB->magnitude();
120 ✔
707

708
    return magnitudeProduct > 0.0 ? productSum / magnitudeProduct : 0.0;
120 !
709
}
120 ✔
710

711
void BicorAlgorithm::preprocess(size_t size, const ContinuousDataVectors& vectors)
712
{
20 ✔
713
    _base = &vectors.front();
20 ✔
714
    _processedVectors.resize(vectors.size());
20 ✔
715

716
    for(size_t i = 0; const auto& vector : vectors)
20 ✔
717
    {
80 ✔
718
        auto median = u::medianOf(vector.data());
80 ✔
719

720
        std::vector<double> absDiffs(size);
80 ✔
721
        std::vector<double> intermediate(size);
80 ✔
722

723
        for(size_t j = 0; auto value : vector)
80 ✔
724
        {
400 ✔
725
            intermediate[j] = value - median;
400 ✔
726
            absDiffs[j] = std::abs(intermediate[j]);
400 ✔
727
            j++;
400 ✔
728
        }
400 ✔
729

730
        auto mad = u::medianOf(absDiffs);
80 ✔
731

732
        for(size_t j = 0; auto value : intermediate)
80 ✔
733
        {
400 ✔
734
            auto u = value / (9.0 * mad);
400 ✔
735
            auto v = 1 - (u * u);
400 ✔
736
            auto newValue = value * (v * v) * (v > 0.0 ? 1.0 : 0.0);
400 !
737

738
            intermediate[j++] = newValue;
400 ✔
739
        }
400 ✔
740

741
        auto& processedVector = _processedVectors.at(i++);
80 ✔
742
        processedVector = {intermediate, vector.nodeId(), vector.computeCostHint()};
80 ✔
743
        processedVector.update();
80 ✔
744
    }
80 ✔
745
}
20 ✔
746

747
double BicorAlgorithm::evaluate(size_t, const ContinuousDataVector* vectorA, const ContinuousDataVector* vectorB) const
748
{
120 ✔
749
    auto a = static_cast<size_t>(std::distance(_base, vectorA));
120 ✔
750
    auto b = static_cast<size_t>(std::distance(_base, vectorB));
120 ✔
751
    const auto& processedVectorA = _processedVectors.at(a);
120 ✔
752
    const auto& processedVectorB = _processedVectors.at(b);
120 ✔
753

754
    const double productSum = std::inner_product(processedVectorA.begin(), processedVectorA.end(),
120 ✔
755
        processedVectorB.begin(), 0.0);
120 ✔
756

757
    return productSum / (processedVectorA.magnitude() * processedVectorB.magnitude());
120 ✔
758
}
120 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc