forked from dgirardeau/q3DMASC
/
q3DMASCTools.cpp
1537 lines (1400 loc) · 43.1 KB
/
q3DMASCTools.cpp
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: q3DMASC #
//# #
//# 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; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: Dimitri Lague / CNRS / UEB #
//# #
//##########################################################################
#include "q3DMASCTools.h"
//Local
#include "PointFeature.h"
#include "NeighborhoodFeature.h"
#include "DualCloudFeature.h"
#include "ContextBasedFeature.h"
#include "ccMainAppInterface.h"
//qCC_io
#include <FileIOFilter.h>
//qCC_db
#include <ccScalarField.h>
#include <ccPointCloud.h>
//qPDALIO
#include "../../../core/IO/qPDALIO/include/LASFields.h"
//Qt
#include <QTextStream>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QMutex>
#include <QCoreApplication>
//system
#include <assert.h>
#if defined(_OPENMP)
#include <omp.h>
#endif
using namespace masc;
bool Tools::SaveClassifier( QString filename,
const Feature::Set& features,
const QString corePointsRole,
const masc::Classifier& classifier,
QWidget* parent/*=nullptr*/)
{
//first save the classifier data (same base filename but with the yaml extension)
QFileInfo fi(filename);
QString yamlFilename = fi.baseName() + ".yaml";
QString yamlAbsoluteFilename = fi.absoluteDir().absoluteFilePath(yamlFilename);
if (!classifier.toFile(yamlAbsoluteFilename, parent))
{
ccLog::Error("Failed to save the classifier data");
return false;
}
QFile file(filename);
if (!file.open(QFile::Text | QFile::WriteOnly))
{
ccLog::Warning(QString("Can't open file '%1' for writing").arg(filename));
return false;
}
QTextStream stream(&file);
stream << "# 3DMASC classifier file" << endl;
stream << "classifier: " << yamlFilename << endl;
//look for all clouds (labels)
QList<QString> cloudLabels;
for (Feature::Shared f : features)
{
if (f->cloud1 && !cloudLabels.contains(f->cloud1Label))
cloudLabels.push_back(f->cloud1Label);
if (f->cloud2 && !cloudLabels.contains(f->cloud2Label))
cloudLabels.push_back(f->cloud2Label);
}
if (!corePointsRole.isEmpty() && !cloudLabels.contains(corePointsRole))
{
cloudLabels.push_back(corePointsRole);
}
stream << "# Clouds (roles)" << endl;
for (const QString& label : cloudLabels)
{
stream << "cloud: " << label << endl;
}
if (!corePointsRole.isEmpty())
{
stream << "# Core points (classified role)" << endl;
stream << "core_points: " << corePointsRole << endl;
}
stream << "# Features" << endl;
for (Feature::Shared f : features)
{
stream << "feature: " << f->toString() << endl;
}
return true;
}
bool Tools::LoadClassifierCloudLabels(QString filename, QList<QString>& labels, QString& corePointsLabel, bool& filenamesSpecified, QMap<QString, QString>& rolesAndNames)
{
//just in case
corePointsLabel.clear();
labels.clear();
rolesAndNames.clear();
QFile file(filename);
if (!file.open(QFile::Text | QFile::ReadOnly))
{
ccLog::Warning(QString("Can't open file '%1'").arg(filename));
return false;
}
QTextStream stream(&file);
int filenameCount = 0;
for (int lineNumber = 0; ; ++lineNumber)
{
QString line = stream.readLine();
if (line.isNull())
{
//eof
break;
}
++lineNumber;
line = line.toUpper();
if (line.startsWith("CLOUD:"))
{
QString command = line.mid(6).trimmed();
QStringList tokens = command.split('=');
if (tokens.size() == 0)
{
ccLog::Warning("Malformed file: expecting some tokens after 'cloud:' on line #" + QString::number(lineNumber));
return false;
}
QString label = tokens.front();
if (labels.contains(label))
{
ccLog::Warning(QString("Malformed file: role '%1:' is already defined/used on line #%2").arg(label).arg(lineNumber));
return false;
}
labels.push_back(label);
rolesAndNames[label] = tokens.back();
if (tokens.size() > 1)
++filenameCount;
}
else if (line.startsWith("CORE_POINTS:"))
{
if (!corePointsLabel.isEmpty())
{
//core points defined multiple times?!
continue;
}
QString command = line.mid(12);
QStringList tokens = command.split('_');
if (tokens.empty())
{
ccLog::Warning("Malformed file: expecting tokens after 'core_points:' on line #" + QString::number(lineNumber));
return false;
}
corePointsLabel = tokens[0].trimmed();
}
}
filenamesSpecified = (filenameCount > 0 && filenameCount == labels.size());
return true;
}
bool CheckFeatureUnicity(std::vector<Feature::Shared>& rawFeatures, Feature::Shared feature)
{
if (!feature)
return false;
// check that the feature does not exists already!
for (const auto &feat : rawFeatures)
{
if (feat->toString() == feature->toString())
{
return false;
}
}
return true;
}
static bool CreateFeaturesFromCommand(const QString& command, QString corePointsRole, int lineNumber, const Tools::NamedClouds& clouds, std::vector<Feature::Shared>& rawFeatures, std::vector<double>& scales)
{
QStringList tokens = command.split('_');
if (tokens.empty())
{
ccLog::Warning("Malformed file: expecting at least one token after 'feature:' on line #" + QString::number(lineNumber));
return false;
}
Feature::Shared feature;
//read the type
QString typeStr = tokens[0].trimmed().toUpper();
{
for (int iteration = 0; iteration < 1; ++iteration) //fake loop for easy break
{
PointFeature::PointFeatureType pointFeatureType = PointFeature::FromUpperString(typeStr);
if (pointFeatureType != PointFeature::Invalid)
{
//we have a point feature
PointFeature* pointFeature = new PointFeature(pointFeatureType);
//specific case: 'SF'
if (pointFeatureType == PointFeature::SF)
{
QString sfIndexStr = typeStr.mid(2);
bool ok = true;
int sfIndex = sfIndexStr.toInt(&ok);
if (!ok)
{
ccLog::Warning(QString("Malformed file: expecting a valid integer value after 'SF' on line #%1").arg(lineNumber));
delete pointFeature;
return false;
}
pointFeature->sourceSFIndex = sfIndex;
}
feature.reset(pointFeature);
break;
}
NeighborhoodFeature::NeighborhoodFeatureType neighborhoodFeatureType = NeighborhoodFeature::FromUpperString(typeStr);
if (neighborhoodFeatureType != NeighborhoodFeature::Invalid)
{
//we have a neighborhood feature
feature = NeighborhoodFeature::Shared(new NeighborhoodFeature(neighborhoodFeatureType));
break;
}
ContextBasedFeature::ContextBasedFeatureType contextBasedFeatureType = ContextBasedFeature::FromUpperString(typeStr);
if (contextBasedFeatureType != ContextBasedFeature::Invalid)
{
//we have a context-based feature
QString featureStr = ContextBasedFeature::ToString(contextBasedFeatureType);
int kNN = 1;
if (featureStr.length() < typeStr.length())
{
bool ok = false;
kNN = typeStr.mid(featureStr.length()).toInt(&ok);
if (!ok || kNN <= 0)
{
ccLog::Warning(QString("Malformed file: expecting a valid and positive number after '%1' on line #%2").arg(featureStr).arg(lineNumber));
return false;
}
}
feature = ContextBasedFeature::Shared(new ContextBasedFeature(contextBasedFeatureType, kNN));
break;
}
DualCloudFeature::DualCloudFeatureType dualCloudFeatureType = DualCloudFeature::FromUpperString(typeStr);
if (dualCloudFeatureType != DualCloudFeature::Invalid)
{
//we have a dual cloud feature
feature = DualCloudFeature::Shared(new DualCloudFeature(dualCloudFeatureType));
break;
}
if (!feature)
{
ccLog::Warning(QString("Malformed file: unrecognized token '%1' after 'feature:' on line #%2").arg(typeStr).arg(lineNumber));
return false;
}
}
}
assert(feature);
//read the scales
bool useAllScales = false;
{
QString scaleStr = tokens[1].toUpper();
if (!scaleStr.startsWith("SC"))
{
ccLog::Warning(QString("Malformed file: unrecognized token '%1' (expecting the scale descriptor 'SC...' on line #%2").arg(typeStr).arg(lineNumber));
return false;
}
if (scaleStr == "SC0")
{
//no scale
}
else if (scaleStr == "SCX")
{
//all scales
useAllScales = true;
}
else
{
//read the specific scale value
bool ok = true;
feature->scale = scaleStr.mid(2).toDouble(&ok);
if (!ok)
{
ccLog::Warning(QString("Malformed file: expecting a valid number after 'SC:' on line #%1").arg(lineNumber));
return false;
}
}
}
//process the next tokens (may not be ordered)
int cloudCount = 0;
bool statDefined = false;
bool mathDefined = false;
bool contextBasedFeatureDeprecatedSyntax = false;
for (int i = 2; i < tokens.size(); ++i)
{
QString token = tokens[i].trimmed().toUpper();
//is the token a 'stat' one?
if (!statDefined)
{
if (token == "MEAN")
{
feature->stat = Feature::MEAN;
statDefined = true;
}
else if (token == "MODE")
{
feature->stat = Feature::MODE;
statDefined = true;
}
else if (token == "MEDIAN")
{
feature->stat = Feature::MEDIAN;
statDefined = true;
}
else if (token == "STD")
{
feature->stat = Feature::STD;
statDefined = true;
}
else if (token == "RANGE")
{
feature->stat = Feature::RANGE;
statDefined = true;
}
else if (token == "SKEW")
{
feature->stat = Feature::SKEW;
statDefined = true;
}
if (statDefined)
{
continue;
}
}
//is the token a cloud name?
if (cloudCount < 2)
{
bool cloudNameMatches = false;
for (QMap<QString, ccPointCloud* >::const_iterator it = clouds.begin(); it != clouds.end(); ++it)
{
QString key = it.key().toUpper();
if (key == token)
{
if (cloudCount == 0)
{
feature->cloud1 = it.value();
feature->cloud1Label = key;
if (feature && feature->getType() == Feature::Type::ContextBasedFeature)
{
// only one cloud is necessary for context based features
// the class should be just after the cloud name in the regular syntax
if (i + 1 < tokens.size())
{
bool ok = false;
int classLabel = tokens[i + 1].toInt(&ok);
if (!ok)
{
contextBasedFeatureDeprecatedSyntax = true; // let's try the deprecated syntax
}
else
{
qSharedPointerCast<ContextBasedFeature>(feature)->ctxClassLabel = classLabel;
++i;
}
}
else
{
ccLog::Warning(QString("Malformed context based features at line %1").arg(lineNumber));
return false;
}
}
}
else if (cloudCount == 1)
{
if (contextBasedFeatureDeprecatedSyntax)
{
feature->cloud1 = it.value();
feature->cloud1Label = key;
}
else
{
feature->cloud2 = it.value();
feature->cloud2Label = key;
}
if (feature && feature->getType() == Feature::Type::ContextBasedFeature)
{
// this is the DEPRECATED syntax for the context based feature
// the class is just after the cloud name
if (i + 1 < tokens.size())
{
bool ok = false;
int classLabel = tokens[i + 1].toInt(&ok);
if (!ok)
{
ccLog::Warning(QString("ContextBasedFeature: expecting a class number after the context cloud '%1' on line #%2").arg(token).arg(lineNumber));
return false;
}
else
{
ccLog::Warning("ContextBasedFeature: you are using the DEPRECATED syntax, the feature should contain only one cloud, as in DZ1_SC0_CTX_10)");
qSharedPointerCast<ContextBasedFeature>(feature)->ctxClassLabel = classLabel;
++i;
}
}
else
{
ccLog::Warning(QString("Malformed context based features at line %1").arg(lineNumber));
return false;
}
}
}
else
{
//we can't fall here
assert(false);
}
++cloudCount;
cloudNameMatches = true;
break;
}
}
if (cloudNameMatches)
{
continue;
}
}
//is the token a 'math' one?
if (!mathDefined)
{
if (token == "MINUS")
{
feature->op = Feature::MINUS;
mathDefined = true;
}
else if (token == "PLUS")
{
feature->op = Feature::PLUS;
mathDefined = true;
}
else if (token == "DIVIDE")
{
feature->op = Feature::DIVIDE;
mathDefined = true;
}
else if (token == "MULTIPLY")
{
feature->op = Feature::MULTIPLY;
mathDefined = true;
}
if (mathDefined)
{
continue;
}
}
//is the token a 'context' descriptor?
//if (feature->getType() == Feature::Type::ContextBasedFeature && token.startsWith("CTX"))
//{
// //read the context label
// QString ctxLabelStr = token.mid(3);
// bool ok = true;
// int ctxLabel = ctxLabelStr.toInt(&ok);
// if (!ok)
// {
// ccLog::Warning(QString("Malformed file: expecting a valid integer value after 'CTX' on line #%1").arg(lineNumber));
// return false;
// }
// static_cast<ContextBasedFeature*>(feature.data())->ctxClassLabel = ctxLabel;
// continue;
//}
//if we are here, it means we couldn't find a correspondance for the current token
ccLog::Warning(QString("Malformed file: unrecognized or unexpected token '%1' on line #%2").arg(token).arg(lineNumber));
return false;
}
//now create the various versions of rules (if any)
if (useAllScales)
{
if (scales.empty())
{
ccLog::Warning("Malformed file: 'SCx' token used while no scale is defined" + QString(" (line %1)").arg(lineNumber));
return false;
}
feature->scale = scales.front();
//we will duplicate the original feature AFTER having checked its consistency!
}
//now check the consistency of the rule
QString errorMessage;
if (!feature->checkValidity(corePointsRole, errorMessage))
{
ccLog::Warning("Malformed feature: " + errorMessage + QString(" (line %1)").arg(lineNumber));
return false;
}
if (!CheckFeatureUnicity(rawFeatures, feature)) // check that the feature does not exists already!
{
ccLog::Warning("[3DMASC] duplicated feature " + feature->toString() + ", check your parameter file");
return false;
}
else
{
//save the feature
rawFeatures.push_back(feature);
}
if (useAllScales)
{
for (size_t i = 1; i < scales.size(); ++i)
{
//copy the original rule
Feature::Shared newFeature = feature->clone();
newFeature->scale = scales.at(i);
//as we only change the scale value, all the duplicated features should be valid
assert(newFeature->checkValidity(corePointsRole, errorMessage));
if (!CheckFeatureUnicity(rawFeatures, newFeature)) // check that the feature does not exists already!
{
ccLog::Warning("[3DMASC] duplicated feature " + newFeature->toString() + ", check your parameter file");
return false;
}
else
{
//save the feature
rawFeatures.push_back(newFeature);
}
}
}
return true;
}
static bool ReadScales(const QString& command, std::vector<double>& scales, int lineNumber)
{
assert(scales.empty());
QStringList tokens = command.split(';');
if (tokens.empty())
{
ccLog::Warning("Malformed file: expecting at least one token after 'scales:' on line #" + QString::number(lineNumber));
return false;
}
for (const QString& token : tokens)
{
if (token.contains(':'))
{
//it's probably a range
QStringList subTokens = token.trimmed().split(':');
if (subTokens.size() != 3)
{
ccLog::Warning(QString("Malformed file: expecting 3 tokens for a range of scales (%1)").arg(token));
return false;
}
bool ok[3] = { true, true, true };
double start = subTokens[0].trimmed().toDouble(ok);
double step = subTokens[1].toDouble(ok + 1);
double stop = subTokens[2].toDouble(ok + 2);
if (!ok[0] || !ok[1] || !ok[2])
{
ccLog::Warning(QString("Malformed file: invalid values in scales range (%1) on line #%2").arg(token).arg(lineNumber));
return false;
}
if (stop < start || step <= 1.0 - 6)
{
ccLog::Warning(QString("Malformed file: invalid range (%1) on line #%2").arg(token).arg(lineNumber));
return false;
}
for (double v = start; v <= stop + 1.0e-6; v += step)
{
scales.push_back(v);
}
}
else
{
bool ok = true;
double v = token.trimmed().toDouble(&ok);
if (!ok)
{
ccLog::Warning(QString("Malformed file: invalid scale value (%1) on line #%2").arg(token).arg(lineNumber));
return false;
}
scales.push_back(v);
}
}
scales.shrink_to_fit();
return true;
}
static bool ReadCorePoints(const QString& command, const Tools::NamedClouds& clouds, masc::CorePoints& corePoints, int lineNumber)
{
QStringList tokens = command.split('_');
if (tokens.empty())
{
ccLog::Warning("Malformed file: expecting tokens after 'core_points:' on line #" + QString::number(lineNumber));
return false;
}
QString pcName = tokens[0].trimmed();
if (!clouds.contains(pcName))
{
ccLog::Warning(QString("Malformed file: unknown cloud '%1' on line #%2 (make sure it is declared before the core points)").arg(pcName).arg(lineNumber));
return false;
}
corePoints.origin = clouds[pcName];
corePoints.role = pcName;
//should we sub-sample the origin cloud?
if (tokens.size() > 1)
{
if (tokens[1].toUpper() == "SS")
{
if (tokens.size() < 3)
{
ccLog::Warning("Malformed file: missing token after 'SS' on line #" + QString::number(lineNumber));
return false;
}
QString options = tokens[2];
if (options.startsWith('R'))
{
corePoints.selectionMethod = CorePoints::RANDOM;
}
else if (options.startsWith('S'))
{
corePoints.selectionMethod = CorePoints::SPATIAL;
}
else
{
ccLog::Warning("Malformed file: unknown option after 'SS' on line #" + QString::number(lineNumber));
return false;
}
//read the subsampling parameter (ignore the first character)
bool ok = false;
corePoints.selectionParam = options.mid(1).toDouble(&ok);
if (!ok)
{
ccLog::Warning("Malformed file: expecting a number after 'SS_X' on line #" + QString::number(lineNumber));
return false;
}
} //end of subsampling options
}
return true;
}
static bool ReadCloud(const QString& command, Tools::NamedClouds& clouds, const QDir& defaultDir, int lineNumber, FileIOFilter::LoadParameters& loadParameters)
{
QStringList tokens = command.split('=');
if (tokens.size() != 2)
{
ccLog::Warning("Malformed file: expecting 2 tokens after 'cloud:' on line #" + QString::number(lineNumber));
return false;
}
QString pcName = tokens[0].trimmed();
QString pcFilename = defaultDir.absoluteFilePath(tokens[1].trimmed());
//try to open the cloud
{
CC_FILE_ERROR error = CC_FERR_NO_ERROR;
ccHObject* object = FileIOFilter::LoadFromFile(pcFilename, loadParameters, error);
if (error != CC_FERR_NO_ERROR || !object)
{
//error message already issued
if (object)
delete object;
return false;
}
ccHObject::Container cloudsInFile;
object->filterChildren(cloudsInFile, false, CC_TYPES::POINT_CLOUD, true);
if (cloudsInFile.empty())
{
ccLog::Warning("File doesn't contain a single cloud");
delete object;
return false;
}
else if (cloudsInFile.size() > 1)
{
ccLog::Warning("File contains more than one cloud, only the first one will be kept");
}
ccPointCloud* pc = static_cast<ccPointCloud*>(cloudsInFile.front());
for (size_t i = 1; i < cloudsInFile.size(); ++i)
{
delete cloudsInFile[i];
}
if (pc->getParent())
pc->getParent()->detachChild(pc);
pc->setName(pcName); //DGM: warning, may not be acceptable in the GUI version?
clouds.insert(pcName, pc);
}
return true;
}
bool Tools::LoadFile( const QString& filename,
Tools::NamedClouds* clouds,
bool cloudsAreProvided,
std::vector<Feature::Shared>* rawFeatures/*=nullptr*/, //requires 'clouds'
std::vector<double>* rawScales/*=nullptr*/,
masc::CorePoints* corePoints/*=nullptr*/, //requires 'clouds'
masc::Classifier* classifier/*=nullptr*/,
TrainParameters* parameters/*=nullptr*/,
QWidget* parent/*=nullptr*/)
{
QFileInfo fi(filename);
if (!fi.exists())
{
ccLog::Warning(QString("Can't find file '%1'").arg(filename));
return false;
}
QFile file(filename);
if (!file.open(QFile::Text | QFile::ReadOnly))
{
ccLog::Warning(QString("Can't open file '%1'").arg(filename));
return false;
}
//to use the same 'global shift' for multiple files
CCVector3d loadCoordinatesShift(0, 0, 0);
bool loadCoordinatesTransEnabled = false;
FileIOFilter::LoadParameters loadParameters;
if (!cloudsAreProvided)
{
loadParameters.alwaysDisplayLoadDialog = true;
loadParameters.shiftHandlingMode = ccGlobalShiftManager::DIALOG_IF_NECESSARY;
loadParameters._coordinatesShift = &loadCoordinatesShift;
loadParameters._coordinatesShiftEnabled = &loadCoordinatesTransEnabled;
loadParameters.parentWidget = parent;
FileIOFilter::ResetSesionCounter();
}
try
{
assert(!rawFeatures || rawFeatures->empty());
std::vector<double> scales;
QTextStream stream(&file);
bool badFeatures = false;
for (int lineNumber = 1; ; ++lineNumber)
{
if (stream.atEnd())
break;
QString line = stream.readLine();
if (line.isEmpty())
{
continue;
}
if (line.startsWith("#"))
{
//comment
continue;
}
//strip out the potential comment at the end of the line as well
int commentIndex = line.indexOf('#');
if (commentIndex >= 0)
line = line.left(commentIndex);
QString upperLine = line.toUpper();
if (upperLine.startsWith("CLASSIFIER:")) //classifier
{
if (!classifier)
{
//no need to load the classifier
continue;
}
if (classifier->isValid())
{
ccLog::Warning("Malformed file: can't declare the classifier file twice! (line #" + QString::number(lineNumber) + ")");
return false;
}
QString yamlFilename = line.mid(11).trimmed();
QString yamlAbsoluteFilename = fi.absoluteDir().absoluteFilePath(yamlFilename);
if (!classifier->fromFile(yamlAbsoluteFilename, parent))
{
ccLog::Warning("Failed to load the classifier file from " + yamlAbsoluteFilename);
return false;
}
ccLog::Print("[3DMASC] Classifier data loaded from " + yamlAbsoluteFilename);
}
else if (upperLine.startsWith("CLOUD:")) //clouds
{
if (!clouds || cloudsAreProvided)
{
//no need to load the clouds in this case
continue;
}
QString command = line.mid(6);
if (!ReadCloud(command, *clouds, fi.absoluteDir(), lineNumber, loadParameters))
{
return false;
}
}
else if (upperLine.startsWith("TEST:")) //test cloud
{
if (!clouds || cloudsAreProvided)
{
//no need to load the clouds in this case
continue;
}
QString command = line.mid(5);
if (!ReadCloud("TEST=" + command, *clouds, fi.absoluteDir(), lineNumber, loadParameters)) //add the TEST keyword so that the cloud will be loaded as the TEST cloud
{
return false;
}
}
else if (upperLine.startsWith("CORE_POINTS:")) //core points
{
if (!corePoints)
{
//no need to load the core points
continue;
}
if (corePoints->origin)
{
ccLog::Warning("Core points already defined (those declared on line #" + QString::number(lineNumber) + " will be ignored)");
}
else
{
QString command = line.mid(12);
if (clouds && !ReadCorePoints(command, *clouds, *corePoints, lineNumber))
{
return false;
}
}
}
else if (upperLine.startsWith("SCALES:")) //scales
{
if (!scales.empty())
{
ccLog::Warning("Malformed file: scales defined twice (line #" + QString::number(lineNumber) + ")");
return false;
}
QString command = line.mid(7);
if (!ReadScales(command, scales, lineNumber))
{
return false;
}
else
{
if (rawScales)
for (auto scale : scales)
rawScales->push_back(scale);
}
}
else if (upperLine.startsWith("FEATURE:")) //feature
{
QString command = line.mid(8);
if (rawFeatures && clouds)
{
if (!CreateFeaturesFromCommand(command, corePoints ? corePoints->role : QString(), lineNumber, *clouds, *rawFeatures, scales))
{
//error message already issued
//return false;
badFeatures = true; //we continue as we want to get ALL the errors
}
}
}
else if (upperLine.startsWith("PARAM_")) //parameter
{
if (parameters) //no need to actually read the parameters if the caller didn't requested them
{
QStringList tokens = upperLine.split("=");
if (tokens.size() != 2)
{
ccLog::Warning(QString("Line #%1: malformed parameter command (expecting param_XXX=Y)").arg(lineNumber));
return false;
}
bool ok = false;
if (tokens[0] == "PARAM_MAX_DEPTH")
{
parameters->rt.maxDepth = tokens[1].toInt(&ok);
}
else if (tokens[0] == "PARAM_MAX_TREE_COUNT")
{
parameters->rt.maxTreeCount = tokens[1].toInt(&ok);
}
else if (tokens[0] == "PARAM_ACTIVE_VAR_COUNT")
{
parameters->rt.activeVarCount = tokens[1].toInt(&ok);
}
else if (tokens[0] == "PARAM_MIN_SAMPLE_COUNT")
{
parameters->rt.minSampleCount = tokens[1].toInt(&ok);
}
else if (tokens[0] == "PARAM_TEST_DATA_RATIO")
{
parameters->testDataRatio = tokens[1].toFloat(&ok);
}
else
{
ccLog::Warning(QString("Line #%1: unrecognized parameter: ").arg(lineNumber) + tokens[0]);
}
if (!ok)
{
ccLog::Warning(QString("Line #%1: invalid value for parameter ").arg(lineNumber) + tokens[0]);
}
}
}
else
{
ccLog::Warning(QString("Line #%1: unrecognized token/command: ").arg(lineNumber) + (line.length() < 10 ? line : line.left(10) + "..."));
return false;
}
}
if (badFeatures)
{
return false;
}
}
catch (const std::bad_alloc&)
{
ccLog::Warning("Not enough memory");
return false;
}
if (rawFeatures)
rawFeatures->shrink_to_fit();
return true;
}
bool Tools::LoadClassifier(QString filename, NamedClouds& clouds, Feature::Set& rawFeatures, masc::Classifier& classifier, QWidget* parent/*=nullptr*/)
{
return LoadFile(filename, &clouds, true, &rawFeatures, nullptr, nullptr, &classifier, nullptr, parent);
}
bool Tools::LoadTrainingFile( QString filename,
Feature::Set& rawFeatures,
std::vector<double>& rawScales,
NamedClouds& loadedClouds,
TrainParameters& parameters,
CorePoints* corePoints/*=nullptr*/,
QWidget* parentWidget/*=nullptr*/)
{
bool cloudsWereProvided = !loadedClouds.empty();
if (LoadFile(filename, &loadedClouds, cloudsWereProvided, &rawFeatures, &rawScales, corePoints, nullptr, ¶meters, parentWidget))
{
return true;
}
else
{
if (!cloudsWereProvided)
{
//delete the already loaded clouds (if any)
for (NamedClouds::iterator it = loadedClouds.begin(); it != loadedClouds.end(); ++it)
delete it.value();
}
return false;