-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutil.cpp
2795 lines (2490 loc) · 103 KB
/
util.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
#include "util.h"
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>
#include <QLayoutItem>
#include <QLayout>
#include <QWidget>
#include <QPlainTextEdit>
#include <QTextCursor>
#include <QScreen>
#include <QApplication>
#include <QFrame>
#include <QPushButton>
#include <cassert>
#include <stdint.h>
#include <chrono>
#include "exceptions/invalidgslibdatafileexception.h"
#include "domain/application.h"
#include "domain/cartesiangrid.h"
#include "domain/attribute.h"
#include "domain/project.h"
#include "domain/categorydefinition.h"
#include "domain/pointset.h"
#include "domain/variogrammodel.h"
#include "domain/segmentset.h"
#include "domain/auxiliary/faciestransitionmatrixmaker.h"
#include "gslib/gslibparameterfiles/gslibparameterfile.h"
#include "gslib/gslibparameterfiles/gslibparamtypes.h"
#include "gslib/gslibparams/gslibparinputdata.h"
#include "gslib/gslib.h"
#include "graphviz/graphviz.h"
#include "dialogs/displayplotdialog.h"
#include "dialogs/distributioncolumnrolesdialog.h"
#include <QDir>
#include <QFileInfo>
#include <QInputDialog>
#include <QSettings>
#include <cmath>
#include <vtkSmartPointer.h>
#include <vtkImageData.h>
#include <vtkImageFFT.h>
#include <vtkImageRFFT.h>
#include <vtkLookupTable.h>
#include <QProgressDialog>
#include "spectral/spectral.h"
#include <QStringBuilder>
#include <QMessageBox>
#include <algorithm>
//includes for getPhysicalRAMusage()
#ifdef Q_OS_WIN
#include <windows.h>
#include <psapi.h>
#endif
#ifdef Q_OS_LINUX
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#endif
#ifdef Q_OS_MAC
#include <mach/mach.h>
#endif
//TODO: define constants for other GSLib program NDVs and checke whether this is being
// actually used.
/*static*/const QString Util::VARMAP_NDV("-999.00000");
/*static*/const long double Util::PI( 3.141592653589793238L );
/*static*/const long double Util::PI_OVER_180( Util::PI / 180.0L );
//TODO: move this to geostatsutils.h, or transfer its PI_OVER_180 constant here
#define C_180_OVER_PI (180.0 / 3.14159265)
Util::Util()
{
}
QStringList Util::getFieldNames(const QString gslib_data_file_path)
{
QStringList list;
QFile file( gslib_data_file_path );
file.open( QFile::ReadOnly | QFile::Text );
QTextStream in(&file);
int n_vars = 0;
int var_count = 0;
for (int i = 0; !in.atEnd(); ++i)
{
//read file line by line
QString line = in.readLine();
//second line is the number of variables
if( i == 1 ){
n_vars = Util::getFirstNumber( line );
} else if ( i > 1 && var_count < n_vars ){
list << line;
++var_count;
if( var_count == n_vars )
break;
}
}
file.close();
return list;
}
std::pair<QStringList, QString> Util::parseTagsAndDescription( const QString gslib_param_file_template_line )
{
QStringList tags;
QString description;
QRegularExpression re_tags("(<.*?>)");
QRegularExpression re_description(".*>\\s*-(.*)");
//finding the individual tags
QRegularExpressionMatchIterator i = re_tags.globalMatch(gslib_param_file_template_line);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
tags.append( match.captured(1) );
}
}
//finding the description
QRegularExpressionMatch match = re_description.match( gslib_param_file_template_line );
if( match.hasMatch() ){
description = match.captured(1);
}
return std::pair<QStringList, QString>(tags, description);
}
uint Util::getIndentation(const QString gslib_param_file_template_line)
{
uint indent = 0;
QRegularExpression re_name("(\\s*)<.*");
//finding the leading spaces
QRegularExpressionMatch match = re_name.match( gslib_param_file_template_line );
if( match.hasMatch() ){
indent = match.captured(1).length();
}
return indent;
}
QString Util::getNameFromTag(const QString tag)
{
QString name;
QRegularExpression re_name("<(.*?)[\\+\\s>]+.*");
//finding the type name
QRegularExpressionMatch match = re_name.match( tag );
if( match.hasMatch() ){
name = match.captured(1);
}
return name;
}
bool Util::hasPlusSign(const QString tag)
{
QRegularExpression re_name("<.*\\+.*>");
//finding the plus sign (if any)
QRegularExpressionMatch match = re_name.match( tag );
return match.hasMatch();
}
QString Util::getRefNameFromTag(const QString tag)
{
QString name;
QRegularExpression re_name("\\((.*)\\)");
//finding the reference name
QRegularExpressionMatch match = re_name.match( tag );
if( match.hasMatch() ){
name = match.captured(1);
}
return name;
}
std::vector< std::pair<QString, QString> > Util::getTagOptions(const QString tag)
{
std::vector< std::pair<QString, QString> > options;
QRegularExpression re_option("\\[(.*?):(.*?)\\]");
//finding the individual options
QRegularExpressionMatchIterator i = re_option.globalMatch( tag );
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
options.push_back( std::pair<QString, QString>(match.captured(1), match.captured(2)) );
}
}
return options;
}
QString Util::getReferenceName(const QString tag)
{
QString ref_name;
QRegularExpression re_name("\\[(\\w*)\\]");
//finding the reference tag name
QRegularExpressionMatch match = re_name.match( tag );
if( match.hasMatch() ){
ref_name = match.captured(1);
}
return ref_name;
}
bool Util::almostEqual2sComplement(float A, float B, int maxUlps)
{
// Make sure maxUlps is non-negative and small enough that the
// default NAN won't compare as equal to anything.
assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}
void Util::clearChildWidgets(QWidget *widget)
{
QLayoutItem* item;
while ( ( item = widget->layout()->takeAt( 0 ) ) )
{
delete item->widget();
delete item;
}
}
void Util::readFileSample(QPlainTextEdit *text_field, QString file_path)
{
//read file content sample
QFile file( file_path );
file.open( QFile::ReadOnly | QFile::Text );
QTextStream in(&file);
//read up to 100 first lines
for (int i = 0; !in.atEnd() && i < 100; ++i)
{
QString line = in.readLine();
text_field->appendPlainText( line );
}
file.close();
//send text cursor to home
QTextCursor tmpCursor = text_field->textCursor();
tmpCursor.movePosition(QTextCursor::Start);
text_field->setTextCursor(tmpCursor);
}
void Util::addTrailingHiphens(const QString par_file_path)
{
//open a new file for output
QFile outputFile( QString(par_file_path).append(".new") );
outputFile.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&outputFile);
//open the current file for reading
QFile inputFile( par_file_path );
if ( inputFile.open(QIODevice::ReadOnly | QFile::Text ) ) {
QTextStream in(&inputFile);
bool in_header = true; //flags whether file read is still in header
while ( !in.atEnd() ){
QString line = in.readLine();
if( in_header ){
out << line << "\n"; //write header lines without change.
if( line.trimmed().startsWith( "START OF PARAMETERS", Qt::CaseInsensitive ) )
in_header = false;
} else {
//replaces end line characters with spaces and appens the trailing hiphen
line.replace('\n', ' ');
line.replace('\r', ' ');
line.append(" - \n");
//writes the modified line to output file
out << line;
}
}
inputFile.close();
//closes the output file
outputFile.close();
//deletes current file
inputFile.remove();
//renames the new file
outputFile.rename( QFile( par_file_path ).fileName() );
}
}
uint Util::getFirstNumber(const QString line)
{
uint result = 0;
QRegularExpression re("(\\d+).*");
QRegularExpressionMatch match = re.match( line );
if( match.hasMatch() ){
result = match.captured(1).toInt( );
}
return result;
}
QString Util::getValuesFromParFileLine(const QString line)
{
QString result;
QRegularExpression re("((?:(?:-[\\d.])?[^-]*)+)(?:-?.*)");
QRegularExpressionMatch match = re.match( line );
if( match.hasMatch() ){
result = match.captured(1).trimmed();
}
return result;
}
void Util::fixVarmapBug(const QString varmap_grid_file_path)
{
//open a new file for output
QFile outputFile( QString(varmap_grid_file_path).append(".new") );
outputFile.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&outputFile);
//open the current file for reading
QFile inputFile( varmap_grid_file_path );
if ( inputFile.open(QIODevice::ReadOnly | QFile::Text ) ) {
QTextStream in(&inputFile);
while ( !in.atEnd() ){
QString line = in.readLine();
//replaces sequences of asterisks with the varmap standard no-data value
line.replace(QRegularExpression("\\*+"), Util::VARMAP_NDV);
//writes the fixed line to the new file
out << line << '\n';
}
inputFile.close();
//closes the output file
outputFile.close();
//deletes current file
inputFile.remove();
//renames the new file
outputFile.rename( QFile( varmap_grid_file_path ).fileName() );
}
}
void Util::renameGEOEASvariable(const QString file_path, const QString old_name, const QString new_name)
{
//open a new file for output
QFile outputFile( QString(file_path).append(".new") );
outputFile.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&outputFile);
//open the current file for reading
QFile inputFile( file_path );
int n_vars = 0;
if ( inputFile.open(QIODevice::ReadOnly | QFile::Text ) ) {
QTextStream in(&inputFile);
int i_line = 1;
int var_count = 0;
while ( !in.atEnd() ){
QString line = in.readLine();
//first number of second line holds the variable count
if( i_line == 2 ){
n_vars = Util::getFirstNumber( line );
//try a replacement only on lines corresponding to variable names.
} else if ( i_line > 1 && var_count < n_vars ){
if(line.trimmed() == old_name.trimmed())
line = new_name;
else
line = line.trimmed();
++var_count;
}
out << line << '\n';
++i_line;
}
inputFile.close();
//closes the output file
outputFile.close();
//deletes current file
inputFile.remove();
//renames the new file
outputFile.rename( QFile( file_path ).fileName() );
}
}
void Util::copyFile(const QString from_path, const QString to_path)
{
//removes destination if it exists.
QFile destination( to_path );
if( destination.exists() )
if( ! destination.remove() ){
Application::instance()->logError("Util::copyFile: old file removal failed.");
return;
}
//performs the copy
QFile origin( from_path );
if( ! origin.copy( to_path ) )
Application::instance()->logError("Util::copyFile: file copy failed.");
}
QString Util::copyFileToDir(const QString from_path, const QString path_to_directory)
{
//get information on the original file
QFileInfo info_origin( from_path );
//get file name and extension of original file
QString origin_file_name = info_origin.fileName();
//get destination directory
QDir dest_dir( path_to_directory );
//make path by joining the destination directory path and the original file name
QString to_path = dest_dir.absoluteFilePath( origin_file_name );
//perfoms the copy
Util::copyFile( from_path, to_path);
//returns the new complete path to the copied file
return to_path;
}
void Util::createGEOEAScheckerboardGrid(GridFile * gf, QString path)
{
//open file for writing
QFile file( path );
file.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&file);
//write out the GEO-EAS grid geader
out << "Grid file\n";
out << "1\n";
out << "checkerboard pattern\n";
//flags to help in creating a checkerboard pattern.
bool isNXeven = ( gf->getNI() % 2 ) == 0;
bool isNYeven = ( gf->getNJ() % 2 ) == 0;
QProgressDialog progressDialog;
progressDialog.setRange(0,0);
progressDialog.show();
progressDialog.setLabelText("Creating grid...");
//loop to output the binary values
ulong count = 0;
int counter = 0;
for( uint ir = 0; ir < gf->getNumberOfRealizations(); ++ir)
for( uint iz = 0; iz < gf->getNK(); ++iz){
for( uint iy = 0; iy < gf->getNJ(); ++iy, ++counter){
for( uint ix = 0; ix < gf->getNI(); ++ix, ++count)
out << (count % 2) << '\n';
if( isNXeven )
++count;
if( ! ( counter % 1000) )
QCoreApplication::processEvents(); //let Qt repaint widgets
}
if( isNYeven )
++count;
}
//close file
file.close();
}
void Util::createGEOEASGrid(const QString columnNameForRealPart,
const QString columnNameForImaginaryPart,
std::vector<std::complex<double> > &array, QString path)
{
//open file for writing
QFile file( path );
file.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&file);
//determine the number of columns
int nColumns = 0;
if( ! columnNameForRealPart.isEmpty() )
nColumns++;
if( ! columnNameForImaginaryPart.isEmpty() )
nColumns++;
if( nColumns == 0)
return;
//write out the GEO-EAS grid header
out << "Grid file\n";
out << nColumns << '\n';
if( ! columnNameForRealPart.isEmpty() )
out << columnNameForRealPart << '\n';
if( ! columnNameForImaginaryPart.isEmpty() )
out << columnNameForImaginaryPart << '\n';
QProgressDialog progressDialog;
progressDialog.setRange(0,0);
progressDialog.show();
progressDialog.setLabelText("Creating grid...");
//loop to output the values
std::vector< std::complex<double> >::iterator it = array.begin();
int counter = 0;
for( ; it != array.end(); ++it, ++counter ){
if( ! columnNameForRealPart.isEmpty() ){
out << (*it).real() ;
if( ! columnNameForImaginaryPart.isEmpty() )
out << '\t';
}
if( ! columnNameForImaginaryPart.isEmpty() )
out << (*it).imag() ;
out << '\n';
if( ! ( counter % 1000) )
QCoreApplication::processEvents(); //let Qt repaint widgets
}
//close file
file.close();
}
void Util::createGEOEASGrid(const QString columnName, std::vector<double> &values, QString path)
{
//open file for writing
QFile file( path );
file.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&file);
//write out the GEO-EAS grid header
out << "Grid file\n";
out << "1\n";
out << columnName << '\n';
QProgressDialog progressDialog;
progressDialog.setRange(0,0);
progressDialog.show();
progressDialog.setLabelText("Creating grid...");
//loop to output the values
std::vector< double >::iterator it = values.begin();
int counter = 0;
for( ; it != values.end(); ++it, ++counter ){
out << (*it) << '\n';
if( ! ( counter % 1000) )
QCoreApplication::processEvents(); //let Qt repaint widgets
}
//close file
file.close();
}
void Util::createGEOEASGrid(const QString columnName,
const spectral::array &values,
QString path,
bool silent,
const CartesianGrid *cg_to_print_definitions_from )
{
//open file for writing
QFile file( path );
file.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&file);
//write out the GEO-EAS grid header
out << "Grid file";
if( cg_to_print_definitions_from ){
const CartesianGrid* cg = cg_to_print_definitions_from;
out << " X0,Y0,Z0=" << cg->getX0() << "," << cg->getY0() << "," << cg->getZ0();
out << " NI,NJ,NK=" << cg->getNI() << "," << cg->getNJ() << "," << cg->getNK();
out << " dX,dY,dZ=" << cg->getDX() << "," << cg->getDY() << "," << cg->getDZ();
}
out << '\n';
out << "1\n";
out << columnName << '\n';
//show a progress bar if client code opted for non-silent execution
QProgressDialog* progressDialog = nullptr;
if( ! silent ){
progressDialog = new QProgressDialog;
progressDialog->setRange(0,0);
progressDialog->show();
progressDialog->setLabelText("Creating grid...");
}
//loop to output the values
int nI = values.M();
int nJ = values.N();
int nK = values.K();
int counter = 0;
for( int k = 0; k < nK; ++k )
for( int j = 0; j < nJ; ++j )
for( int i = 0; i < nI; ++i, ++counter ){
out << values( i, j, k ) << '\n';
if( !silent && !( counter % 1000) )
QCoreApplication::processEvents(); //let Qt repaint widgets if client code opted
//for non-silent execution
}
//hide the progress bar if client code opted for non-silent execution
if( ! silent )
delete progressDialog;
//close file
file.close();
}
void Util::createGEOEASGridFile(const QString gridDescription,
std::vector<QString> columnNames,
std::vector<std::vector<double> > &array,
QString path)
{
//open file for writing
QFile file( path );
file.open( QFile::WriteOnly | QFile::Text );
QTextStream out(&file);
//determine the number of columns
int nColumns = columnNames.size();
//write out the GEO-EAS grid header
out << gridDescription << '\n';
out << nColumns << '\n';
std::vector<QString>::iterator itColNames = columnNames.begin();
for(; itColNames != columnNames.end(); ++itColNames){
out << *itColNames << '\n';
}
QProgressDialog progressDialog;
progressDialog.setRange(0,0);
progressDialog.show();
progressDialog.setLabelText("Creating grid...");
//loop to output the values
std::vector< std::vector<double> >::iterator it = array.begin();
int counter = 0;
for( ; it != array.end(); ++it, ++counter ){
std::vector<double> dataLine = *it;
std::vector<double>::iterator itData = dataLine.begin();
for(; itData != dataLine.end(); ++itData){
out << *itData << '\t'; //TODO: it would be nice to not leave a useless trailing tab char
}
out << '\n';
if( ! ( counter % 1000) )
QCoreApplication::processEvents(); //let Qt repaint widgets
}
//close file
file.close();
}
bool Util::viewGrid(Attribute *variable, QWidget* parent = 0, bool modal, CategoryDefinition *cd)
{
//get input data file
//the parent component of an attribute is a file
//assumes the file is a Cartesian Grid, since the user is calling pixelplt
CartesianGrid* input_data_file = (CartesianGrid*)variable->getContainingFile();
//loads data in file, because it's necessary.
input_data_file->loadData();
//get the variable index in parent data file
uint var_index = input_data_file->getFieldGEOEASIndex( variable->getName() );
//make plot/window title
QString title = variable->getContainingFile()->getName();
title.append("/");
title.append(variable->getName());
title.append(" grid");
//Construct an object composition based on the parameter file template for the pixelplt program.
GSLibParameterFile gpf( "pixelplt" );
//Set default values so we need to change less parameters and let
//the user change the others as one may see fit.
gpf.setDefaultValues();
//get the max and min of the selected variable
double data_min = input_data_file->min( var_index-1 );
double data_max = input_data_file->max( var_index-1 );
//----------------set the minimum required pixelplt paramaters-----------------------
//input data parameters: data file, trimming limits and var,weight indexes
GSLibParInputData* par0;
par0 = gpf.getParameter<GSLibParInputData*>(0);
par0->_file_with_data._path = input_data_file->getPath();
par0->_var_wgt_pairs.first()->_var_index = var_index;
par0->_trimming_limits._min = data_min - fabs( data_min/100.0 );
par0->_trimming_limits._max = data_max + fabs( data_max/100.0 );
//postscript file
gpf.getParameter<GSLibParFile*>(1)->_path = Application::instance()->getProject()->generateUniqueTmpFilePath("ps");
//grid definition parameters
GSLibParGrid* par3 = gpf.getParameter<GSLibParGrid*>(3);
par3->_specs_x->getParameter<GSLibParUInt*>(0)->_value = input_data_file->getNX(); //nx
par3->_specs_x->getParameter<GSLibParDouble*>(1)->_value = input_data_file->getX0(); //min x
par3->_specs_x->getParameter<GSLibParDouble*>(2)->_value = input_data_file->getDX(); //cell size x
par3->_specs_y->getParameter<GSLibParUInt*>(0)->_value = input_data_file->getNY(); //ny
par3->_specs_y->getParameter<GSLibParDouble*>(1)->_value = input_data_file->getY0(); //min y
par3->_specs_y->getParameter<GSLibParDouble*>(2)->_value = input_data_file->getDY(); //cell size y
par3->_specs_z->getParameter<GSLibParUInt*>(0)->_value = input_data_file->getNZ(); //nz
par3->_specs_z->getParameter<GSLibParDouble*>(1)->_value = input_data_file->getZ0(); //min z
par3->_specs_z->getParameter<GSLibParDouble*>(2)->_value = input_data_file->getDZ(); //cell size z
//plot title
gpf.getParameter<GSLibParString*>(6)->_value = title;
//horizontal axis (normally X) label
gpf.getParameter<GSLibParString*>(7)->_value = "longitude";
//vertical axis (normally Y) label
gpf.getParameter<GSLibParString*>(8)->_value = "latitude";
//min, max, resolution for color scale
GSLibParMultiValuedFixed* par12 = gpf.getParameter<GSLibParMultiValuedFixed*>(12);
Util::assureNonZeroWindow( par12->getParameter<GSLibParDouble*>(0)->_value,
par12->getParameter<GSLibParDouble*>(1)->_value,
data_min, data_max);
par12->getParameter<GSLibParDouble*>(2)->_value = (par12->getParameter<GSLibParDouble*>(1)->_value -
par12->getParameter<GSLibParDouble*>(0)->_value)/10.0;
//enable categorical display, if a category definition is passed
if( cd ){
//make sure the category definition info is loaded from the file
cd->loadQuintuplets();
//set category mode on
GSLibParOption* par11 = gpf.getParameter<GSLibParOption*>(11);
par11->_selected_value = 1;
//set the number of categories
GSLibParUInt* par13 = gpf.getParameter<GSLibParUInt*>(13);
par13->_value = cd->getCategoryCount();
//set the category display parameters
GSLibParRepeat* par14 = gpf.getParameter<GSLibParRepeat*>(14);
par14->setCount( par13->_value );
for( uint iCat = 0; iCat < par13->_value; ++iCat){
//The category code, color code and name are in a row of three paramaters
GSLibParMultiValuedFixed *parMV = par14->getParameter<GSLibParMultiValuedFixed*>( iCat, 0 );
//set the category code
GSLibParUInt* par14_0 = parMV->getParameter<GSLibParUInt*>( 0 );
par14_0->_value = cd->getCategoryCode( iCat );
//set the category color
GSLibParColor* par14_1 = parMV->getParameter<GSLibParColor*>( 1 );
par14_1->_color_code = cd->getColorCode( iCat );
//set the category name
GSLibParString* par14_2 = parMV->getParameter<GSLibParString*>( 2 );
par14_2->_value = cd->getCategoryName( iCat );
//the other two values in the category definition are not relevant for GSLib
}
}
//----------------------------------------------------------------------------------
//Generate the parameter file
QString par_file_path = Application::instance()->getProject()->generateUniqueTmpFilePath("par");
gpf.save( par_file_path );
//run pixelplt program
Application::instance()->logInfo("Starting pixelplt program...");
GSLib::instance()->runProgram( "pixelplt", par_file_path );
//display the plot output
DisplayPlotDialog *dpd = new DisplayPlotDialog(gpf.getParameter<GSLibParFile*>(1)->_path, title, gpf, parent);
if( modal ){
int response = dpd->exec();
return response == QDialog::Accepted;
}
dpd->show();
return false;
}
bool Util::viewPointSet(Attribute *variable, QWidget *parent, bool modal)
{
//get input data file
//the parent component of an attribute is a file
//assumes the file is a Point Set, since the user is calling locmap
PointSet* input_data_file = (PointSet*)variable->getContainingFile();
//loads data in file, because it's necessary.
input_data_file->loadData();
//get the variable index in parent data file
uint var_index = input_data_file->getFieldGEOEASIndex( variable->getName() );
//make plot/window title
QString title = variable->getContainingFile()->getName();
title.append("/");
title.append(variable->getName());
title.append(" map");
//Construct an object composition based on the parameter file template for the locmap program.
GSLibParameterFile gpf( "locmap" );
//Set default values so we need to change less parameters and let
//the user change the others as one may see fit.
gpf.setDefaultValues();
//get the max and min of the selected variable
double data_min = input_data_file->min( var_index-1 );
double data_max = input_data_file->max( var_index-1 );
//----------------set the minimum required locmap paramaters-----------------------
//input file
gpf.getParameter<GSLibParFile*>(0)->_path = input_data_file->getPath();
//X, Y and variable
GSLibParMultiValuedFixed* par1 = gpf.getParameter<GSLibParMultiValuedFixed*>(1);
par1->getParameter<GSLibParUInt*>(0)->_value = input_data_file->getXindex();
par1->getParameter<GSLibParUInt*>(1)->_value = input_data_file->getYindex();
par1->getParameter<GSLibParUInt*>(2)->_value = var_index;
//trimming limits
GSLibParMultiValuedFixed* par2 = gpf.getParameter<GSLibParMultiValuedFixed*>(2);
par2->getParameter<GSLibParDouble*>(0)->_value = data_min - fabs( data_min/100.0 );
par2->getParameter<GSLibParDouble*>(1)->_value = data_max + fabs( data_max/100.0 );
//postscript file
gpf.getParameter<GSLibParFile*>(3)->_path = Application::instance()->getProject()->generateUniqueTmpFilePath("ps");
//X limits
GSLibParMultiValuedFixed* par4 = gpf.getParameter<GSLibParMultiValuedFixed*>(4);
Util::assureNonZeroWindow( par4->getParameter<GSLibParDouble*>(0)->_value,
par4->getParameter<GSLibParDouble*>(1)->_value,
input_data_file->min( input_data_file->getXindex()-1 ),
input_data_file->max( input_data_file->getXindex()-1 ));
//Y limits
GSLibParMultiValuedFixed* par5 = gpf.getParameter<GSLibParMultiValuedFixed*>(5);
Util::assureNonZeroWindow( par5->getParameter<GSLibParDouble*>(0)->_value,
par5->getParameter<GSLibParDouble*>(1)->_value,
input_data_file->min( input_data_file->getYindex()-1 ),
input_data_file->max( input_data_file->getYindex()-1 ));
//color scale details
GSLibParMultiValuedFixed* par10 = gpf.getParameter<GSLibParMultiValuedFixed*>(10);
Util::assureNonZeroWindow( par10->getParameter<GSLibParDouble*>(0)->_value,
par10->getParameter<GSLibParDouble*>(1)->_value,
data_min, data_max);
par10->getParameter<GSLibParDouble*>(2)->_value = (par10->getParameter<GSLibParDouble*>(1)->_value -
par10->getParameter<GSLibParDouble*>(0)->_value)/10.0; //color scale ticks in 10 steps
//plot title
gpf.getParameter<GSLibParString*>(12)->_value = title;
//----------------------------------------------------------------------------------
//Generate the parameter file
QString par_file_path = Application::instance()->getProject()->generateUniqueTmpFilePath("par");
gpf.save( par_file_path );
//run locmap program
Application::instance()->logInfo("Starting locmap program...");
GSLib::instance()->runProgram( "locmap", par_file_path );
//display the plot output
DisplayPlotDialog *dpd = new DisplayPlotDialog(gpf.getParameter<GSLibParFile*>(3)->_path, title, gpf, parent);
if( modal ){
int response = dpd->exec();
return response == QDialog::Accepted;
}
dpd->show();
return false;
}
void Util::viewXPlot(Attribute *xVariable, Attribute *yVariable, QWidget *parent, Attribute *zVariable)
{
//get the selected attributes
Attribute* var1 = xVariable;
Attribute* var2 = yVariable;
Attribute* var3 = zVariable;
//assumes their parent are a data file and they refer to the same one.
DataFile* data_file = static_cast<DataFile*>( var1->getContainingFile() );
//loads data in file, because it's necessary to compute some stats.
data_file->loadData();
//get the variables indexes in the parent data file
uint var1_index = data_file->getFieldGEOEASIndex( var1->getName() );
uint var2_index = data_file->getFieldGEOEASIndex( var2->getName() );
uint var3_index = 0;
if( var3 ){
var3_index = data_file->getFieldGEOEASIndex( var3->getName() );
}
//make plot/window title
QString title = "Crossplot ";
title.append(data_file->getName());
title.append(": ");
title.append(var1->getName());
title.append(" x ");
title.append(var2->getName());
if( var3 ){
title.append(" x ");
title.append(var3->getName());
}
//Construct an object composition based on the parameter file template for the scatplot program.
GSLibParameterFile gpf( "scatplt" );
//Set default values so we need to change less parameters and let
//the user change the others as one may see fit.
gpf.setDefaultValues();
//----------------set the minimum required scatplot paramaters---------------------
//input data parameters: data file, trimming limits and var1,var2,weight and 3rd var indexes
GSLibParInputData* par0;
par0 = gpf.getParameter<GSLibParInputData*>(0);
par0->_file_with_data._path = data_file->getPath();
par0->_var_wgt_pairs.first()->_var_index = var1_index;
par0->_var_wgt_pairs.last()->_var_index = var2_index;
if( var3 ){
//scatplt expects the third variable index as the fourth value
//instead of the usual weight for the second variable. figures...
par0->_var_wgt_pairs.last()->_wgt_index = var3_index;
}
//path to postscript file
gpf.getParameter<GSLibParFile*>(1)->_path = Application::instance()->getProject()->generateUniqueTmpFilePath("ps");
//min,max and scale type for X variable
GSLibParMultiValuedFixed* par2 = gpf.getParameter<GSLibParMultiValuedFixed*>(2);
par2->getParameter<GSLibParDouble*>(0)->_value = data_file->min( var1_index-1 );
par2->getParameter<GSLibParDouble*>(1)->_value = data_file->max( var1_index-1 );
//min,max and scale type for Y variable
GSLibParMultiValuedFixed* par3 = gpf.getParameter<GSLibParMultiValuedFixed*>(3);
par3->getParameter<GSLibParDouble*>(0)->_value = data_file->min( var2_index-1 );
par3->getParameter<GSLibParDouble*>(1)->_value = data_file->max( var2_index-1 );
if( var3 ){
//min,max and scale type for 3rd variable (grayscale)
GSLibParLimitsDouble* par6 = gpf.getParameter<GSLibParLimitsDouble*>(6);
par6->_min = data_file->min( var3_index-1 );
par6->_max = data_file->max( var3_index-1 );
}
gpf.getParameter<GSLibParString*>(7)->_value = title;
//---------------------------------------------------------------------------------
//Generate the parameter file
QString par_file_path = Application::instance()->getProject()->generateUniqueTmpFilePath("par");
gpf.save( par_file_path );
//run scatplt program
Application::instance()->logInfo("Starting scatplt program...");
GSLib::instance()->runProgram( "scatplt", par_file_path );
//display the plot output
DisplayPlotDialog *dpd = new DisplayPlotDialog(gpf.getParameter<GSLibParFile*>(1)->_path, title, gpf, parent);
dpd->show(); //show() makes dialog modalless
}
qint64 Util::getDirectorySize(const QString path)
{
quint64 sizex = 0;
QFileInfo str_info( path );
if (str_info.isDir())
{
QDir dir(path);
QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot);
for (int i = 0; i < list.size(); ++i){
QFileInfo fileInfo = list.at(i);
if(fileInfo.isDir()){
sizex += getDirectorySize(fileInfo.absoluteFilePath());
}else
sizex += fileInfo.size();
}
}
return sizex;
}
void Util::clearDirectory(const QString path)
{
QDir dir(path);
dir.setNameFilters(QStringList() << "*");
dir.setFilter(QDir::Files);
foreach(QString dirFile, dir.entryList()) //foreach is a Qt macro
{
dir.remove(dirFile);
}
}
QString Util::renameFile(const QString path, const QString newName)
{
QFileInfo original( path );
QString newPath = original.canonicalPath() + QDir::separator() + newName;
QFile::rename( path, newPath );
return newPath;
}
void Util::importUnivariateDistribution(Attribute *at, const QString path_from, QWidget *dialogs_owner)
{
//propose a name for the file
QString proposed_name( at->getName() );
proposed_name = proposed_name.append("_SMOOTH_DISTR");
//open file rename dialog
bool ok;
QString new_dist_model_name = QInputDialog::getText(dialogs_owner, "Name the new file",
"New univariate distribution model file name:", QLineEdit::Normal,
proposed_name, &ok);
if (ok && !new_dist_model_name.isEmpty()){
QString tmpPathOfDistr = path_from;
//asks the user to set the roles for each of the distribution file columns.
DistributionColumnRolesDialog dcrd( tmpPathOfDistr, dialogs_owner );
dcrd.adjustSize();
int result = dcrd.exec(); //show modally
if( result == QDialog::Accepted )
Application::instance()->getProject()->importUnivariateDistribution( tmpPathOfDistr,
new_dist_model_name.append(".dst"),
dcrd.getRoles() );
else
Application::instance()->getProject()->importUnivariateDistribution( tmpPathOfDistr,
new_dist_model_name.append(".dst"),
QMap<uint, Roles::DistributionColumnRole>() ); //empty list
}
}
void Util::makeGSLibColorsList(QList<QColor> &colors)
{