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

graphia-app / graphia / 42111753990

05 Nov 2026 08:51PM UTC coverage: 71.459% (+0.02%) from 71.439%
42111753990

push

github

timangus
Fix flaky test

11816 of 18088 branches covered (65.33%)

Branch coverage included in aggregate %.

30012 of 40446 relevant lines covered (74.2%)

639624.28 hits per line

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

81.86
/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,774 ✔
73
        if(correlationExceedsThreshold(_polarity, r, _threshold))
4,774 ✔
74
            results->push_back({a, b, r});
2,976 ✔
75
    }
4,774 ✔
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
    {
320 ✔
96
        _protoGraph.add(a, b, r);
320 ✔
97
    }
320 ✔
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
        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,033 ✔
138
            const auto* vectorA = &(*vectorAIt);
2,033 ✔
139

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

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

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

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

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

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

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

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

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

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

168
            return threadResults;
2,001 ✔
169
        });
2,033 ✔
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,794 ✔
382
            _numerator += other._numerator;
1,794 ✔
383
            _denominator += other._denominator;
1,794 ✔
384

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

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

392
    auto process(const TokenisedDataVectors& vectors, const QVariantMap& parameters,
393
        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
        uint64_t totalCost = 0;
62 ✔
402
        for(const auto& vector : vectors)
62 ✔
403
            totalCost += vector.computeCostHint();
248 ✔
404

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

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

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

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

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

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

428
            auto createEdgesForVectorPairs = [&](auto&& f)
242 ✔
429
            {
242 ✔
430
                for(auto vectorBIt = vectorAIt + 1; vectorBIt != vectors.end(); ++vectorBIt)
769 ✔
431
                {
528 ✔
432
                    Fraction fraction;
528 ✔
433
                    for(size_t i = 0; i < size; i++)
2,309 ✔
434
                    {
1,781 ✔
435
                        const auto& vectorAValue = vectorAIt->valueAt(i);
1,781 ✔
436
                        const auto& vectorBValue = vectorBIt->valueAt(i);
1,781 ✔
437

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

446
                    const double r = fraction;
528 ✔
447

448
                    if(!std::isfinite(r))
528 !
449
                        continue;
×
450

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

455
            if(treatAsBinary)
242 ✔
456
                createEdgesForVectorPairs(binary);
82 ✔
457
            else
160 ✔
458
                createEdgesForVectorPairs(nonBinary);
160 ✔
459

460
            cost += vectorAIt->computeCostHint();
242 ✔
461

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

465
            return threadResults;
242 ✔
466
        });
246 ✔
467

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

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

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

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

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

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

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

502
        return edges;
44 ✔
503
    }
46 ✔
504

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

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

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

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

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

526
        return matrix;
16 ✔
527
    }
16 ✔
528

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

654
    default: break;
×
655
    }
428 ✔
656

657
    return nullptr;
250 ✔
658
}
428 ✔
659

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

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

671
    return numerator / denominator;
4,124 ✔
672
}
4,124 ✔
673

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

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

685
    auto sqrtSum = sum != 0.0 ? std::sqrt(sum) : 0.0;
2,147,483,647 ✔
686

687
    return 1.0 / (1.0 + sqrtSum);
119 ✔
688
}
119 ✔
689

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

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

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

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

709
    return magnitudeProduct > 0.0 ? productSum / magnitudeProduct : 0.0;
2,147,483,647 ✔
710
}
119 ✔
711

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

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

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

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

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

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

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

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

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

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

758
    return productSum / (processedVectorA.magnitude() * processedVectorB.magnitude());
120 ✔
759
}
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