-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgsgraduatedsymbolrendererv2.cpp
1538 lines (1309 loc) · 43.7 KB
/
qgsgraduatedsymbolrendererv2.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
/***************************************************************************
qgsgraduatedsymbolrendererv2.cpp
---------------------
begin : November 2009
copyright : (C) 2009 by Martin Dobias
email : wonder dot sk at gmail dot com
***************************************************************************
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsgraduatedsymbolrendererv2.h"
#include "qgssymbolv2.h"
#include "qgssymbollayerv2utils.h"
#include "qgsvectorcolorrampv2.h"
#include "qgspointdisplacementrenderer.h"
#include "qgsinvertedpolygonrenderer.h"
#include "qgsfeature.h"
#include "qgsvectorlayer.h"
#include "qgslogger.h"
#include "qgsvectordataprovider.h"
#include "qgsexpression.h"
#include <QDomDocument>
#include <QDomElement>
#include <QSettings> // for legend
#include <limits> // for jenks classification
#include <cmath> // for pretty classification
#include <ctime>
QgsRendererRangeV2::QgsRendererRangeV2()
: mLowerValue( 0 )
, mUpperValue( 0 )
, mSymbol( 0 )
, mLabel()
{
}
QgsRendererRangeV2::QgsRendererRangeV2( double lowerValue, double upperValue, QgsSymbolV2* symbol, QString label, bool render )
: mLowerValue( lowerValue )
, mUpperValue( upperValue )
, mSymbol( symbol )
, mLabel( label )
, mRender( render )
{
}
QgsRendererRangeV2::QgsRendererRangeV2( const QgsRendererRangeV2& range )
: mLowerValue( range.mLowerValue )
, mUpperValue( range.mUpperValue )
, mSymbol( range.mSymbol.data() ? range.mSymbol->clone() : NULL )
, mLabel( range.mLabel )
, mRender( range.mRender )
{
}
// cpy and swap idiom, note that the cpy is done with 'pass by value'
QgsRendererRangeV2& QgsRendererRangeV2::operator=( QgsRendererRangeV2 range )
{
swap( range );
return *this;
}
bool QgsRendererRangeV2::operator<( const QgsRendererRangeV2 &other ) const
{
return
lowerValue() < other.lowerValue() ||
( lowerValue() == other.lowerValue() && upperValue() < other.upperValue() );
}
void QgsRendererRangeV2::swap( QgsRendererRangeV2 & other )
{
qSwap( mLowerValue, other.mLowerValue );
qSwap( mUpperValue, other.mUpperValue );
qSwap( mSymbol, other.mSymbol );
std::swap( mLabel, other.mLabel );
}
double QgsRendererRangeV2::lowerValue() const
{
return mLowerValue;
}
double QgsRendererRangeV2::upperValue() const
{
return mUpperValue;
}
QgsSymbolV2* QgsRendererRangeV2::symbol() const
{
return mSymbol.data();
}
QString QgsRendererRangeV2::label() const
{
return mLabel;
}
void QgsRendererRangeV2::setSymbol( QgsSymbolV2* s )
{
if ( mSymbol.data() != s ) mSymbol.reset( s );
}
void QgsRendererRangeV2::setLabel( QString label )
{
mLabel = label;
}
void QgsRendererRangeV2::setUpperValue( double upperValue )
{
mUpperValue = upperValue;
}
void QgsRendererRangeV2::setLowerValue( double lowerValue )
{
mLowerValue = lowerValue;
}
bool QgsRendererRangeV2::renderState() const
{
return mRender;
}
void QgsRendererRangeV2::setRenderState( bool render )
{
mRender = render;
}
QString QgsRendererRangeV2::dump() const
{
return QString( "%1 - %2::%3::%4\n" ).arg( mLowerValue ).arg( mUpperValue ).arg( mLabel ).arg( mSymbol->dump() );
}
void QgsRendererRangeV2::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props ) const
{
if ( !mSymbol.data() || props.value( "attribute", "" ).isEmpty() )
return;
QString attrName = props[ "attribute" ];
QDomElement ruleElem = doc.createElement( "se:Rule" );
element.appendChild( ruleElem );
QDomElement nameElem = doc.createElement( "se:Name" );
nameElem.appendChild( doc.createTextNode( mLabel ) );
ruleElem.appendChild( nameElem );
QDomElement descrElem = doc.createElement( "se:Description" );
QDomElement titleElem = doc.createElement( "se:Title" );
QString descrStr = QString( "range: %1 - %2" ).arg( mLowerValue ).arg( mUpperValue );
titleElem.appendChild( doc.createTextNode( !mLabel.isEmpty() ? mLabel : descrStr ) );
descrElem.appendChild( titleElem );
ruleElem.appendChild( descrElem );
// create the ogc:Filter for the range
QString filterFunc = QString( "%1 > %2 AND %1 <= %3" )
.arg( attrName.replace( "\"", "\"\"" ) )
.arg( mLowerValue ).arg( mUpperValue );
QgsSymbolLayerV2Utils::createFunctionElement( doc, ruleElem, filterFunc );
mSymbol->toSld( doc, ruleElem, props );
}
///////////
QgsRendererRangeV2LabelFormat::QgsRendererRangeV2LabelFormat():
mFormat( " %1 - %2 " ),
mDecimalPlaces( 4 ),
mTrimTrailingZeroes( false ),
mReTrailingZeroes( "\\.?0*$" )
{
}
QgsRendererRangeV2LabelFormat::QgsRendererRangeV2LabelFormat( QString format, int decimalPlaces, bool trimTrailingZeroes ):
mReTrailingZeroes( "\\.?0*$" )
{
setFormat( format );
setDecimalPlaces( decimalPlaces );
setTrimTrailingZeroes( trimTrailingZeroes );
}
bool QgsRendererRangeV2LabelFormat::operator==( const QgsRendererRangeV2LabelFormat &other ) const
{
return
format() == other.format() &&
decimalPlaces() == other.decimalPlaces() &&
trimTrailingZeroes() == other.trimTrailingZeroes();
}
bool QgsRendererRangeV2LabelFormat::operator!=( const QgsRendererRangeV2LabelFormat &other ) const
{
return !( *this == other );
}
void QgsRendererRangeV2LabelFormat::setDecimalPlaces( int decimalPlaces )
{
// Limit the range of decimal places to a reasonable range
if ( decimalPlaces < 0 ) decimalPlaces = 0;
if ( decimalPlaces > 15 ) decimalPlaces = 15;
mDecimalPlaces = decimalPlaces;
}
QString QgsRendererRangeV2LabelFormat::labelForRange( const QgsRendererRangeV2 &range ) const
{
return labelForRange( range.lowerValue(), range.upperValue() );
}
QString QgsRendererRangeV2LabelFormat::labelForRange( double lower, double upper ) const
{
QString lowerStr = QString::number( lower, 'f', mDecimalPlaces );
QString upperStr = QString::number( upper, 'f', mDecimalPlaces );
if ( mTrimTrailingZeroes )
{
if ( lowerStr.contains( '.' ) ) lowerStr = lowerStr.replace( mReTrailingZeroes, "" );
if ( upperStr.contains( '.' ) ) upperStr = upperStr.replace( mReTrailingZeroes, "" );
}
return mFormat.arg( lowerStr, upperStr );
}
void QgsRendererRangeV2LabelFormat::setFromDomElement( QDomElement &element )
{
mFormat = element.attribute( "format",
element.attribute( "prefix", " " ) + "%1" +
element.attribute( "separator", " - " ) + "%2" +
element.attribute( "suffix", " " )
);
mDecimalPlaces = element.attribute( "decimalplaces", "4" ).toInt();
mTrimTrailingZeroes = element.attribute( "trimtrailingzeroes", "false" ) == "true";
}
void QgsRendererRangeV2LabelFormat::saveToDomElement( QDomElement &element )
{
element.setAttribute( "format", mFormat );
element.setAttribute( "decimalplaces", mDecimalPlaces );
element.setAttribute( "trimtrailingzeroes", mTrimTrailingZeroes ? "true" : "false" );
}
///////////
QgsGraduatedSymbolRendererV2::QgsGraduatedSymbolRendererV2( QString attrName, QgsRangeList ranges )
: QgsFeatureRendererV2( "graduatedSymbol" ),
mAttrName( attrName ),
mRanges( ranges ),
mMode( Custom ),
mInvertedColorRamp( false ),
mScaleMethod( DEFAULT_SCALE_METHOD )
{
// TODO: check ranges for sanity (NULL symbols, invalid ranges)
}
QgsGraduatedSymbolRendererV2::~QgsGraduatedSymbolRendererV2()
{
mRanges.clear(); // should delete all the symbols
}
QgsSymbolV2* QgsGraduatedSymbolRendererV2::symbolForValue( double value )
{
for ( QgsRangeList::iterator it = mRanges.begin(); it != mRanges.end(); ++it )
{
if ( it->lowerValue() <= value && it->upperValue() >= value )
{
if ( it->renderState() || mCounting )
return it->symbol();
else
return NULL;
}
}
// the value is out of the range: return NULL instead of symbol
return NULL;
}
QgsSymbolV2* QgsGraduatedSymbolRendererV2::symbolForFeature( QgsFeature& feature )
{
QgsSymbolV2* symbol = originalSymbolForFeature( feature );
if ( symbol == NULL )
return NULL;
if ( !mRotation.data() && !mSizeScale.data() )
return symbol; // no data-defined rotation/scaling - just return the symbol
// find out rotation, size scale
const double rotation = mRotation.data() ? mRotation->evaluate( feature ).toDouble() : 0;
const double sizeScale = mSizeScale.data() ? mSizeScale->evaluate( feature ).toDouble() : 1.;
// take a temporary symbol (or create it if doesn't exist)
QgsSymbolV2* tempSymbol = mTempSymbols[symbol];
// modify the temporary symbol and return it
if ( tempSymbol->type() == QgsSymbolV2::Marker )
{
QgsMarkerSymbolV2* markerSymbol = static_cast<QgsMarkerSymbolV2*>( tempSymbol );
if ( mRotation.data() ) markerSymbol->setAngle( rotation );
markerSymbol->setSize( sizeScale * static_cast<QgsMarkerSymbolV2*>( symbol )->size() );
markerSymbol->setScaleMethod( mScaleMethod );
}
else if ( tempSymbol->type() == QgsSymbolV2::Line )
{
QgsLineSymbolV2* lineSymbol = static_cast<QgsLineSymbolV2*>( tempSymbol );
lineSymbol->setWidth( sizeScale * static_cast<QgsLineSymbolV2*>( symbol )->width() );
}
return tempSymbol;
}
QgsSymbolV2* QgsGraduatedSymbolRendererV2::originalSymbolForFeature( QgsFeature& feature )
{
const QgsAttributes& attrs = feature.attributes();
QVariant value;
if ( mAttrNum < 0 || mAttrNum >= attrs.count() )
{
value = mExpression->evaluate( &feature );
}
else
{
value = attrs[mAttrNum];
}
// Null values should not be categorized
if ( value.isNull() )
return NULL;
// find the right category
return symbolForValue( value.toDouble() );
}
void QgsGraduatedSymbolRendererV2::startRender( QgsRenderContext& context, const QgsFields& fields )
{
mCounting = context.rendererScale() == 0.0;
// find out classification attribute index from name
mAttrNum = fields.fieldNameIndex( mAttrName );
if ( mAttrNum == -1 )
{
mExpression.reset( new QgsExpression( mAttrName ) );
mExpression->prepare( fields );
}
QgsRangeList::iterator it = mRanges.begin();
for ( ; it != mRanges.end(); ++it )
{
it->symbol()->startRender( context, &fields );
if ( mRotation.data() || mSizeScale.data() )
{
QgsSymbolV2* tempSymbol = it->symbol()->clone();
tempSymbol->setRenderHints(( mRotation.data() ? QgsSymbolV2::DataDefinedRotation : 0 ) |
( mSizeScale.data() ? QgsSymbolV2::DataDefinedSizeScale : 0 ) );
tempSymbol->startRender( context, &fields );
mTempSymbols[ it->symbol()] = tempSymbol;
}
}
}
void QgsGraduatedSymbolRendererV2::stopRender( QgsRenderContext& context )
{
QgsRangeList::iterator it = mRanges.begin();
for ( ; it != mRanges.end(); ++it )
it->symbol()->stopRender( context );
// cleanup mTempSymbols
QHash<QgsSymbolV2*, QgsSymbolV2*>::iterator it2 = mTempSymbols.begin();
for ( ; it2 != mTempSymbols.end(); ++it2 )
{
it2.value()->stopRender( context );
delete it2.value();
}
mTempSymbols.clear();
}
QList<QString> QgsGraduatedSymbolRendererV2::usedAttributes()
{
QSet<QString> attributes;
// mAttrName can contain either attribute name or an expression.
// Sometimes it is not possible to distinguish between those two,
// e.g. "a - b" can be both a valid attribute name or expression.
// Since we do not have access to fields here, try both options.
attributes << mAttrName;
QgsExpression testExpr( mAttrName );
if ( !testExpr.hasParserError() )
attributes.unite( testExpr.referencedColumns().toSet() );
if ( mRotation.data() ) attributes.unite( mRotation->referencedColumns().toSet() );
if ( mSizeScale.data() ) attributes.unite( mSizeScale->referencedColumns().toSet() );
QgsRangeList::const_iterator range_it = mRanges.constBegin();
for ( ; range_it != mRanges.constEnd(); ++range_it )
{
QgsSymbolV2* symbol = range_it->symbol();
if ( symbol )
{
attributes.unite( symbol->usedAttributes() );
}
}
return attributes.toList();
}
bool QgsGraduatedSymbolRendererV2::updateRangeSymbol( int rangeIndex, QgsSymbolV2* symbol )
{
if ( rangeIndex < 0 || rangeIndex >= mRanges.size() )
return false;
mRanges[rangeIndex].setSymbol( symbol );
return true;
}
bool QgsGraduatedSymbolRendererV2::updateRangeLabel( int rangeIndex, QString label )
{
if ( rangeIndex < 0 || rangeIndex >= mRanges.size() )
return false;
mRanges[rangeIndex].setLabel( label );
return true;
}
bool QgsGraduatedSymbolRendererV2::updateRangeUpperValue( int rangeIndex, double value )
{
if ( rangeIndex < 0 || rangeIndex >= mRanges.size() )
return false;
QgsRendererRangeV2 &range = mRanges[rangeIndex];
bool isDefaultLabel = range.label() == mLabelFormat.labelForRange( range );
range.setUpperValue( value );
if ( isDefaultLabel ) range.setLabel( mLabelFormat.labelForRange( range ) );
return true;
}
bool QgsGraduatedSymbolRendererV2::updateRangeLowerValue( int rangeIndex, double value )
{
if ( rangeIndex < 0 || rangeIndex >= mRanges.size() )
return false;
QgsRendererRangeV2 &range = mRanges[rangeIndex];
bool isDefaultLabel = range.label() == mLabelFormat.labelForRange( range );
range.setLowerValue( value );
if ( isDefaultLabel ) range.setLabel( mLabelFormat.labelForRange( range ) );
return true;
}
bool QgsGraduatedSymbolRendererV2::updateRangeRenderState( int rangeIndex, bool value )
{
if ( rangeIndex < 0 || rangeIndex >= mRanges.size() )
return false;
mRanges[rangeIndex].setRenderState( value );
return true;
}
QString QgsGraduatedSymbolRendererV2::dump() const
{
QString s = QString( "GRADUATED: attr %1\n" ).arg( mAttrName );
for ( int i = 0; i < mRanges.count(); i++ )
s += mRanges[i].dump();
return s;
}
QgsFeatureRendererV2* QgsGraduatedSymbolRendererV2::clone() const
{
QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( mAttrName, mRanges );
r->setMode( mMode );
if ( mSourceSymbol.data() )
r->setSourceSymbol( mSourceSymbol->clone() );
if ( mSourceColorRamp.data() )
{
r->setSourceColorRamp( mSourceColorRamp->clone() );
r->setInvertedColorRamp( mInvertedColorRamp );
}
r->setUsingSymbolLevels( usingSymbolLevels() );
r->setRotationField( rotationField() );
r->setSizeScaleField( sizeScaleField() );
r->setScaleMethod( scaleMethod() );
r->setLabelFormat( labelFormat() );
return r;
}
void QgsGraduatedSymbolRendererV2::toSld( QDomDocument& doc, QDomElement &element ) const
{
QgsStringMap props;
props[ "attribute" ] = mAttrName;
if ( mRotation.data() )
props[ "angle" ] = mRotation->expression();
if ( mSizeScale.data() )
props[ "scale" ] = mSizeScale->expression();
// create a Rule for each range
for ( QgsRangeList::const_iterator it = mRanges.constBegin(); it != mRanges.constEnd(); ++it )
{
QgsStringMap catProps( props );
it->toSld( doc, element, catProps );
}
}
QgsSymbolV2List QgsGraduatedSymbolRendererV2::symbols()
{
QgsSymbolV2List lst;
for ( int i = 0; i < mRanges.count(); i++ )
lst.append( mRanges[i].symbol() );
return lst;
}
static QList<double> _calcEqualIntervalBreaks( double minimum, double maximum, int classes )
{
// Equal interval algorithm
//
// Returns breaks based on dividing the range ('minimum' to 'maximum')
// into 'classes' parts.
double step = ( maximum - minimum ) / classes;
QList<double> breaks;
double value = minimum;
for ( int i = 0; i < classes; i++ )
{
value += step;
breaks.append( value );
}
// floating point arithmetics is not precise:
// set the last break to be exactly maximum so we do not miss it
breaks[classes-1] = maximum;
return breaks;
}
static QList<double> _calcQuantileBreaks( QList<double> values, int classes )
{
// q-th quantile of a data set:
// value where q fraction of data is below and (1-q) fraction is above this value
// Xq = (1 - r) * X_NI1 + r * X_NI2
// NI1 = (int) (q * (n+1))
// NI2 = NI1 + 1
// r = q * (n+1) - (int) (q * (n+1))
// (indices of X: 1...n)
// sort the values first
qSort( values );
QList<double> breaks;
// If there are no values to process: bail out
if ( !values.count() )
return breaks;
int n = values.count();
double Xq = n > 0 ? values[0] : 0.0;
for ( int i = 1; i < classes; i++ )
{
if ( n > 1 )
{
double q = i / ( double ) classes;
double a = q * ( n - 1 );
int aa = ( int )( a );
double r = a - aa;
Xq = ( 1 - r ) * values[aa] + r * values[aa+1];
}
breaks.append( Xq );
}
breaks.append( values[ n-1 ] );
return breaks;
}
static QList<double> _calcPrettyBreaks( double minimum, double maximum, int classes )
{
// C++ implementation of R's pretty algorithm
// Based on code for determining optimal tick placement for statistical graphics
// from the R statistical programming language.
// Code ported from R implementation from 'labeling' R package
//
// Computes a sequence of about 'classes' equally spaced round values
// which cover the range of values from 'minimum' to 'maximum'.
// The values are chosen so that they are 1, 2 or 5 times a power of 10.
QList<double> breaks;
if ( classes < 1 )
{
breaks.append( maximum );
return breaks;
}
int minimumCount = ( int ) classes / 3;
double shrink = 0.75;
double highBias = 1.5;
double adjustBias = 0.5 + 1.5 * highBias;
int divisions = classes;
double h = highBias;
double cell;
int U;
bool small = false;
double dx = maximum - minimum;
if ( dx == 0 && maximum == 0 )
{
cell = 1.0;
small = true;
U = 1;
}
else
{
cell = qMax( qAbs( minimum ), qAbs( maximum ) );
if ( adjustBias >= 1.5 * h + 0.5 )
{
U = 1 + ( 1.0 / ( 1 + h ) );
}
else
{
U = 1 + ( 1.5 / ( 1 + adjustBias ) );
}
small = dx < ( cell * U * qMax( 1, divisions ) * 1e-07 * 3.0 );
}
if ( small )
{
if ( cell > 10 )
{
cell = 9 + cell / 10;
cell = cell * shrink;
}
if ( minimumCount > 1 )
{
cell = cell / minimumCount;
}
}
else
{
cell = dx;
if ( divisions > 1 )
{
cell = cell / divisions;
}
}
if ( cell < 20 * 1e-07 )
{
cell = 20 * 1e-07;
}
double base = pow( 10.0, floor( log10( cell ) ) );
double unit = base;
if (( 2 * base ) - cell < h *( cell - unit ) )
{
unit = 2.0 * base;
if (( 5 * base ) - cell < adjustBias *( cell - unit ) )
{
unit = 5.0 * base;
if (( 10.0 * base ) - cell < h *( cell - unit ) )
{
unit = 10.0 * base;
}
}
}
// Maybe used to correct for the epsilon here??
int start = floor( minimum / unit + 1e-07 );
int end = ceil( maximum / unit - 1e-07 );
// Extend the range out beyond the data. Does this ever happen??
while ( start * unit > minimum + ( 1e-07 * unit ) )
{
start = start - 1;
}
while ( end * unit < maximum - ( 1e-07 * unit ) )
{
end = end + 1;
}
QgsDebugMsg( QString( "pretty classes: %1" ).arg( end ) );
// If we don't have quite enough labels, extend the range out
// to make more (these labels are beyond the data :( )
int k = floor( 0.5 + end - start );
if ( k < minimumCount )
{
k = minimumCount - k;
if ( start >= 0 )
{
end = end + k / 2;
start = start - k / 2 + k % 2;
}
else
{
start = start - k / 2;
end = end + k / 2 + k % 2;
}
}
double minimumBreak = start * unit;
//double maximumBreak = end * unit;
int count = end - start;
for ( int i = 1; i < count + 1; i++ )
{
breaks.append( minimumBreak + i * unit );
}
if ( breaks.isEmpty() )
return breaks;
if ( breaks.first() < minimum )
{
breaks[0] = minimum;
}
if ( breaks.last() > maximum )
{
breaks[breaks.count()-1] = maximum;
}
return breaks;
} // _calcPrettyBreaks
static QList<double> _calcStdDevBreaks( QList<double> values, int classes, QList<double> &labels )
{
// C++ implementation of the standard deviation class interval algorithm
// as implemented in the 'classInt' package available for the R statistical
// prgramming language.
// Returns breaks based on '_calcPrettyBreaks' of the centred and scaled
// values of 'values', and may have a number of classes different from 'classes'.
// If there are no values to process: bail out
if ( !values.count() )
return QList<double>();
double mean = 0.0;
double stdDev = 0.0;
int n = values.count();
double minimum = values[0];
double maximum = values[0];
for ( int i = 0; i < n; i++ )
{
mean += values[i];
minimum = qMin( values[i], minimum ); // could use precomputed max and min
maximum = qMax( values[i], maximum ); // but have to go through entire list anyway
}
mean = mean / ( double ) n;
double sd = 0.0;
for ( int i = 0; i < n; i++ )
{
sd = values[i] - mean;
stdDev += sd * sd;
}
stdDev = sqrt( stdDev / n );
QList<double> breaks = _calcPrettyBreaks(( minimum - mean ) / stdDev, ( maximum - mean ) / stdDev, classes );
for ( int i = 0; i < breaks.count(); i++ )
{
labels.append( breaks[i] );
breaks[i] = ( breaks[i] * stdDev ) + mean;
}
return breaks;
} // _calcStdDevBreaks
static QList<double> _calcJenksBreaks( QList<double> values, int classes,
double minimum, double maximum,
int maximumSize = 1000 )
{
// Jenks Optimal (Natural Breaks) algorithm
// Based on the Jenks algorithm from the 'classInt' package available for
// the R statistical prgramming language, and from Python code from here:
// http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
// and is based on a JAVA and Fortran code available here:
// https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html
// Returns class breaks such that classes are internally homogeneous while
// assuring heterogeneity among classes.
if ( !values.count() )
return QList<double>();
if ( classes <= 1 )
{
return QList<double>() << maximum;
}
if ( classes >= values.size() )
{
return values;
}
QVector<double> sample;
// if we have lots of values, we need to take a random sample
if ( values.size() > maximumSize )
{
// for now, sample at least maximumSize values or a 10% sample, whichever
// is larger. This will produce a more representative sample for very large
// layers, but could end up being computationally intensive...
qsrand( time( 0 ) );
sample.resize( qMax( maximumSize, values.size() / 10 ) );
QgsDebugMsg( QString( "natural breaks (jenks) sample size: %1" ).arg( sample.size() ) );
QgsDebugMsg( QString( "values:%1" ).arg( values.size() ) );
sample[ 0 ] = minimum;
sample[ 1 ] = maximum;;
for ( int i = 2; i < sample.size(); i++ )
{
// pick a random integer from 0 to n
double r = qrand();
int j = floor( r / RAND_MAX * ( values.size() - 1 ) );
sample[ i ] = values[ j ];
}
}
else
{
sample = values.toVector();
}
int n = sample.size();
// sort the sample values
qSort( sample );
QVector< QVector<int> > matrixOne( n + 1 );
QVector< QVector<double> > matrixTwo( n + 1 );
for ( int i = 0; i <= n; i++ )
{
matrixOne[i].resize( classes + 1 );
matrixTwo[i].resize( classes + 1 );
}
for ( int i = 1; i <= classes; i++ )
{
matrixOne[0][i] = 1;
matrixOne[1][i] = 1;
matrixTwo[0][i] = 0.0;
for ( int j = 2; j <= n; j++ )
{
matrixTwo[j][i] = std::numeric_limits<double>::max();
}
}
for ( int l = 2; l <= n; l++ )
{
double s1 = 0.0;
double s2 = 0.0;
int w = 0;
double v = 0.0;
for ( int m = 1; m <= l; m++ )
{
int i3 = l - m + 1;
double val = sample[ i3 - 1 ];
s2 += val * val;
s1 += val;
w++;
v = s2 - ( s1 * s1 ) / ( double ) w;
int i4 = i3 - 1;
if ( i4 != 0 )
{
for ( int j = 2; j <= classes; j++ )
{
if ( matrixTwo[l][j] >= v + matrixTwo[i4][j - 1] )
{
matrixOne[l][j] = i4;
matrixTwo[l][j] = v + matrixTwo[i4][j - 1];
}
}
}
}
matrixOne[l][1] = 1;
matrixTwo[l][1] = v;
}
QVector<double> breaks( classes );
breaks[classes-1] = sample[n-1];
for ( int j = classes, k = n; j >= 2; j-- )
{
int id = matrixOne[k][j] - 1;
breaks[j - 2] = sample[id];
k = matrixOne[k][j] - 1;
}
return breaks.toList();
} //_calcJenksBreaks
QgsGraduatedSymbolRendererV2* QgsGraduatedSymbolRendererV2::createRenderer(
QgsVectorLayer* vlayer,
QString attrName,
int classes,
Mode mode,
QgsSymbolV2* symbol,
QgsVectorColorRampV2* ramp,
bool inverted,
QgsRendererRangeV2LabelFormat labelFormat
)
{
QgsRangeList ranges;
QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges );
r->setSourceSymbol( symbol->clone() );
r->setSourceColorRamp( ramp->clone() );
r->setInvertedColorRamp( inverted );
r->setMode( mode );
r->setLabelFormat( labelFormat, false );
r->updateClasses( vlayer, mode, classes );
return r;
}
QList<double> QgsGraduatedSymbolRendererV2::getDataValues( QgsVectorLayer *vlayer )
{
QList<double> values;
QScopedPointer<QgsExpression> expression;
int attrNum = vlayer->fieldNameIndex( mAttrName );
if ( attrNum == -1 )
{
// try to use expression
expression.reset( new QgsExpression( mAttrName ) );
if ( expression->hasParserError() || !expression->prepare( vlayer->pendingFields() ) )
return values; // should have a means to report errors
}
QgsFeature f;
QStringList lst;
if ( expression.isNull() )
lst.append( mAttrName );
else
lst = expression->referencedColumns();
QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( lst, vlayer->pendingFields() ) );
// create list of non-null attribute values
while ( fit.nextFeature( f ) )
{
QVariant v = expression.isNull() ? f.attribute( attrNum ) : expression->evaluate( f );
if ( !v.isNull() )
values.append( v.toDouble() );
}
return values;
}
void QgsGraduatedSymbolRendererV2::updateClasses( QgsVectorLayer *vlayer, Mode mode, int nclasses )
{
if ( mAttrName.isEmpty() ) return;
setMode( mode );
// Custom classes are not recalculated
if ( mode == Custom ) return;
if ( nclasses < 1 ) nclasses = 1;
QList<double> values;
bool valuesLoaded = false;
double minimum;
double maximum;
int attrNum = vlayer->fieldNameIndex( mAttrName );
if ( attrNum == -1 )
{
values = getDataValues( vlayer );
qSort( values );
minimum = values.first();
maximum = values.last();
valuesLoaded = true;
}
else
{
minimum = vlayer->minimumValue( attrNum ).toDouble();
maximum = vlayer->maximumValue( attrNum ).toDouble();
}
QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) );
QList<double> breaks;
QList<double> labels;
if ( mode == EqualInterval )
{
breaks = _calcEqualIntervalBreaks( minimum, maximum, nclasses );
}
else if ( mode == Pretty )
{
breaks = _calcPrettyBreaks( minimum, maximum, nclasses );
}
else if ( mode == Quantile || mode == Jenks || mode == StdDev )
{
// get values from layer
if ( ! valuesLoaded )