-
Notifications
You must be signed in to change notification settings - Fork 147
/
burndown.go
1402 lines (1331 loc) · 46.1 KB
/
burndown.go
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
package leaves
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"sort"
"sync"
"unicode/utf8"
"github.com/gogo/protobuf/proto"
"github.com/sergi/go-diff/diffmatchpatch"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/utils/merkletrie"
"gopkg.in/src-d/hercules.v7/internal/burndown"
"gopkg.in/src-d/hercules.v7/internal/core"
"gopkg.in/src-d/hercules.v7/internal/pb"
items "gopkg.in/src-d/hercules.v7/internal/plumbing"
"gopkg.in/src-d/hercules.v7/internal/plumbing/identity"
"gopkg.in/src-d/hercules.v7/internal/rbtree"
"gopkg.in/src-d/hercules.v7/internal/yaml"
)
// BurndownAnalysis allows to gather the line burndown statistics for a Git repository.
// It is a LeafPipelineItem.
// Reference: https://erikbern.com/2016/12/05/the-half-life-of-code.html
type BurndownAnalysis struct {
// Granularity sets the size of each band - the number of days it spans.
// Smaller values provide better resolution but require more work and eat more
// memory. 30 days is usually enough.
Granularity int
// Sampling sets how detailed is the statistic - the size of the interval in
// days between consecutive measurements. It may not be greater than Granularity. Try 15 or 30.
Sampling int
// TrackFiles enables or disables the fine-grained per-file burndown analysis.
// It does not change the project level burndown results.
TrackFiles bool
// PeopleNumber is the number of developers for which to collect the burndown stats. 0 disables it.
PeopleNumber int
// HibernationThreshold sets the hibernation threshold for the underlying
// RBTree allocator. It is useful to trade CPU time for reduced peak memory consumption
// if there are many branches.
HibernationThreshold int
// HibernationToDisk specifies whether the hibernated RBTree allocator must be saved on disk
// rather than kept in memory.
HibernationToDisk bool
// HibernationDirectory is the name of the temporary directory to use for saving hibernated
// RBTree allocators.
HibernationDirectory string
// Debug activates the debugging mode. Analyse() runs slower in this mode
// but it accurately checks all the intermediate states for invariant
// violations.
Debug bool
// Repository points to the analysed Git repository struct from go-git.
repository *git.Repository
// globalHistory is the daily deltas of daily line counts.
// E.g. day 0: day 0 +50 lines
// day 10: day 0 -10 lines; day 10 +20 lines
// day 12: day 0 -5 lines; day 10 -3 lines; day 12 +10 lines
// map [0] [0] = 50
// map[10] [0] = -10
// map[10][10] = 20
// map[12] [0] = -5
// map[12][10] = -3
// map[12][12] = 10
globalHistory sparseHistory
// fileHistories is the daily deltas of each file's daily line counts.
fileHistories map[string]sparseHistory
// peopleHistories is the daily deltas of each person's daily line counts.
peopleHistories []sparseHistory
// files is the mapping <file path> -> *File.
files map[string]*burndown.File
// fileAllocator is the allocator for RBTree-s in `files`.
fileAllocator *rbtree.Allocator
// hibernatedFileName is the path to the serialized `fileAllocator`.
hibernatedFileName string
// mergedFiles is used during merges to record the real file hashes
mergedFiles map[string]bool
// mergedAuthor of the processed merge commit
mergedAuthor int
// renames is a quick and dirty solution for the "future branch renames" problem.
renames map[string]string
// matrix is the mutual deletions and self insertions.
matrix []map[int]int64
// day is the most recent day index processed.
day int
// previousDay is the day from the previous sample period -
// different from DaysSinceStart.previousDay.
previousDay int
// references IdentityDetector.ReversedPeopleDict
reversedPeopleDict []string
}
// BurndownResult carries the result of running BurndownAnalysis - it is returned by
// BurndownAnalysis.Finalize().
type BurndownResult struct {
// [number of samples][number of bands]
// The number of samples depends on Sampling: the less Sampling, the bigger the number.
// The number of bands depends on Granularity: the less Granularity, the bigger the number.
GlobalHistory DenseHistory
// The key is the path inside the Git repository. The value's dimensions are the same as
// in GlobalHistory.
FileHistories map[string]DenseHistory
// [number of people][number of samples][number of bands]
PeopleHistories []DenseHistory
// [number of people][number of people + 2]
// The first element is the total number of lines added by the author.
// The second element is the number of removals by unidentified authors (outside reversedPeopleDict).
// The rest of the elements are equal the number of line removals by the corresponding
// authors in reversedPeopleDict: 2 -> 0, 3 -> 1, etc.
PeopleMatrix DenseHistory
// The following members are private.
// reversedPeopleDict is borrowed from IdentityDetector and becomes available after
// Pipeline.Initialize(facts map[string]interface{}). Thus it can be obtained via
// facts[FactIdentityDetectorReversedPeopleDict].
reversedPeopleDict []string
// sampling and granularity are copied from BurndownAnalysis and stored for service purposes
// such as merging several results together.
sampling int
granularity int
}
const (
// ConfigBurndownGranularity is the name of the option to set BurndownAnalysis.Granularity.
ConfigBurndownGranularity = "Burndown.Granularity"
// ConfigBurndownSampling is the name of the option to set BurndownAnalysis.Sampling.
ConfigBurndownSampling = "Burndown.Sampling"
// ConfigBurndownTrackFiles enables burndown collection for files.
ConfigBurndownTrackFiles = "Burndown.TrackFiles"
// ConfigBurndownTrackPeople enables burndown collection for authors.
ConfigBurndownTrackPeople = "Burndown.TrackPeople"
// ConfigBurndownHibernationThreshold sets the hibernation threshold for the underlying
// RBTree allocator. It is useful to trade CPU time for reduced peak memory consumption
// if there are many branches.
ConfigBurndownHibernationThreshold = "Burndown.HibernationThreshold"
// ConfigBurndownHibernationToDisk sets whether the hibernated RBTree allocator must be saved
// on disk rather than kept in memory.
ConfigBurndownHibernationToDisk = "Burndown.HibernationOnDisk"
// ConfigBurndownHibernationDirectory sets the name of the temporary directory to use for
// saving hibernated RBTree allocators.
ConfigBurndownHibernationDirectory = "Burndown.HibernationDirectory"
// ConfigBurndownDebug enables some extra debug assertions.
ConfigBurndownDebug = "Burndown.Debug"
// DefaultBurndownGranularity is the default number of days for BurndownAnalysis.Granularity
// and BurndownAnalysis.Sampling.
DefaultBurndownGranularity = 30
// authorSelf is the internal author index which is used in BurndownAnalysis.Finalize() to
// format the author overwrites matrix.
authorSelf = (1 << (32 - burndown.TreeMaxBinPower)) - 2
)
type sparseHistory = map[int]map[int]int64
// DenseHistory is the matrix [number of samples][number of bands] -> number of lines.
type DenseHistory = [][]int64
// Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
func (analyser *BurndownAnalysis) Name() string {
return "Burndown"
}
// Provides returns the list of names of entities which are produced by this PipelineItem.
// Each produced entity will be inserted into `deps` of dependent Consume()-s according
// to this list. Also used by core.Registry to build the global map of providers.
func (analyser *BurndownAnalysis) Provides() []string {
return []string{}
}
// Requires returns the list of names of entities which are needed by this PipelineItem.
// Each requested entity will be inserted into `deps` of Consume(). In turn, those
// entities are Provides() upstream.
func (analyser *BurndownAnalysis) Requires() []string {
arr := [...]string{
items.DependencyFileDiff, items.DependencyTreeChanges, items.DependencyBlobCache,
items.DependencyDay, identity.DependencyAuthor}
return arr[:]
}
// ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
func (analyser *BurndownAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
options := [...]core.ConfigurationOption{{
Name: ConfigBurndownGranularity,
Description: "How many days there are in a single band.",
Flag: "granularity",
Type: core.IntConfigurationOption,
Default: DefaultBurndownGranularity}, {
Name: ConfigBurndownSampling,
Description: "How frequently to record the state in days.",
Flag: "sampling",
Type: core.IntConfigurationOption,
Default: DefaultBurndownGranularity}, {
Name: ConfigBurndownTrackFiles,
Description: "Record detailed statistics per each file.",
Flag: "burndown-files",
Type: core.BoolConfigurationOption,
Default: false}, {
Name: ConfigBurndownTrackPeople,
Description: "Record detailed statistics per each developer.",
Flag: "burndown-people",
Type: core.BoolConfigurationOption,
Default: false}, {
Name: ConfigBurndownHibernationThreshold,
Description: "The minimum size for the allocated memory in each branch to be compressed." +
"0 disables this optimization. Lower values trade CPU time more. Sane examples: Nx1000.",
Flag: "burndown-hibernation-threshold",
Type: core.IntConfigurationOption,
Default: 0}, {
Name: ConfigBurndownHibernationToDisk,
Description: "Save hibernated RBTree allocators to disk rather than keep it in memory; " +
"requires --burndown-hibernation-threshold to be greater than zero.",
Flag: "burndown-hibernation-disk",
Type: core.BoolConfigurationOption,
Default: false}, {
Name: ConfigBurndownHibernationDirectory,
Description: "Temporary directory where to save the hibernated RBTree allocators; " +
"requires --burndown-hibernation-disk.",
Flag: "burndown-hibernation-dir",
Type: core.PathConfigurationOption,
Default: ""}, {
Name: ConfigBurndownDebug,
Description: "Validate the trees on each step.",
Flag: "burndown-debug",
Type: core.BoolConfigurationOption,
Default: false},
}
return options[:]
}
// Configure sets the properties previously published by ListConfigurationOptions().
func (analyser *BurndownAnalysis) Configure(facts map[string]interface{}) error {
if val, exists := facts[ConfigBurndownGranularity].(int); exists {
analyser.Granularity = val
}
if val, exists := facts[ConfigBurndownSampling].(int); exists {
analyser.Sampling = val
}
if val, exists := facts[ConfigBurndownTrackFiles].(bool); exists {
analyser.TrackFiles = val
}
if people, exists := facts[ConfigBurndownTrackPeople].(bool); people {
if val, exists := facts[identity.FactIdentityDetectorPeopleCount].(int); exists {
if val < 0 {
return fmt.Errorf("PeopleNumber is negative: %d", val)
}
analyser.PeopleNumber = val
analyser.reversedPeopleDict = facts[identity.FactIdentityDetectorReversedPeopleDict].([]string)
}
} else if exists {
analyser.PeopleNumber = 0
}
if val, exists := facts[ConfigBurndownHibernationThreshold].(int); exists {
analyser.HibernationThreshold = val
}
if val, exists := facts[ConfigBurndownHibernationToDisk].(bool); exists {
analyser.HibernationToDisk = val
}
if val, exists := facts[ConfigBurndownHibernationDirectory].(string); exists {
analyser.HibernationDirectory = val
}
if val, exists := facts[ConfigBurndownDebug].(bool); exists {
analyser.Debug = val
}
return nil
}
// Flag for the command line switch which enables this analysis.
func (analyser *BurndownAnalysis) Flag() string {
return "burndown"
}
// Description returns the text which explains what the analysis is doing.
func (analyser *BurndownAnalysis) Description() string {
return "Line burndown stats indicate the numbers of lines which were last edited within " +
"specific time intervals through time. Search for \"git-of-theseus\" in the internet."
}
// Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
// calls. The repository which is going to be analysed is supplied as an argument.
func (analyser *BurndownAnalysis) Initialize(repository *git.Repository) error {
if analyser.Granularity <= 0 {
log.Printf("Warning: adjusted the granularity to %d days\n",
DefaultBurndownGranularity)
analyser.Granularity = DefaultBurndownGranularity
}
if analyser.Sampling <= 0 {
log.Printf("Warning: adjusted the sampling to %d days\n",
DefaultBurndownGranularity)
analyser.Sampling = DefaultBurndownGranularity
}
if analyser.Sampling > analyser.Granularity {
log.Printf("Warning: granularity may not be less than sampling, adjusted to %d\n",
analyser.Granularity)
analyser.Sampling = analyser.Granularity
}
analyser.repository = repository
analyser.globalHistory = sparseHistory{}
analyser.fileHistories = map[string]sparseHistory{}
if analyser.PeopleNumber < 0 {
return fmt.Errorf("PeopleNumber is negative: %d", analyser.PeopleNumber)
}
analyser.peopleHistories = make([]sparseHistory, analyser.PeopleNumber)
analyser.files = map[string]*burndown.File{}
analyser.fileAllocator = rbtree.NewAllocator()
analyser.fileAllocator.HibernationThreshold = analyser.HibernationThreshold
analyser.mergedFiles = map[string]bool{}
analyser.mergedAuthor = identity.AuthorMissing
analyser.renames = map[string]string{}
analyser.matrix = make([]map[int]int64, analyser.PeopleNumber)
analyser.day = 0
analyser.previousDay = 0
return nil
}
// Consume runs this PipelineItem on the next commit's data.
// `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
// Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
// This function returns the mapping with analysis results. The keys must be the same as
// in Provides(). If there was an error, nil is returned.
func (analyser *BurndownAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
if analyser.fileAllocator.Size() == 0 && len(analyser.files) > 0 {
panic("BurndownAnalysis.Consume() was called on a hibernated instance")
}
author := deps[identity.DependencyAuthor].(int)
day := deps[items.DependencyDay].(int)
if !deps[core.DependencyIsMerge].(bool) {
analyser.day = day
analyser.onNewDay()
} else {
// effectively disables the status updates if the commit is a merge
// we will analyse the conflicts resolution in Merge()
analyser.day = burndown.TreeMergeMark
analyser.mergedFiles = map[string]bool{}
analyser.mergedAuthor = author
}
cache := deps[items.DependencyBlobCache].(map[plumbing.Hash]*items.CachedBlob)
treeDiffs := deps[items.DependencyTreeChanges].(object.Changes)
fileDiffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
for _, change := range treeDiffs {
action, _ := change.Action()
var err error
switch action {
case merkletrie.Insert:
err = analyser.handleInsertion(change, author, cache)
case merkletrie.Delete:
err = analyser.handleDeletion(change, author, cache)
case merkletrie.Modify:
err = analyser.handleModification(change, author, cache, fileDiffs)
}
if err != nil {
return nil, err
}
}
// in case there is a merge analyser.day equals to TreeMergeMark
analyser.day = day
return nil, nil
}
// Fork clones this item. Everything is copied by reference except the files
// which are copied by value.
func (analyser *BurndownAnalysis) Fork(n int) []core.PipelineItem {
result := make([]core.PipelineItem, n)
for i := range result {
clone := *analyser
clone.files = map[string]*burndown.File{}
clone.fileAllocator = clone.fileAllocator.Clone()
for key, file := range analyser.files {
clone.files[key] = file.CloneShallow(clone.fileAllocator)
}
result[i] = &clone
}
return result
}
// Merge combines several items together. We apply the special file merging logic here.
func (analyser *BurndownAnalysis) Merge(branches []core.PipelineItem) {
all := make([]*BurndownAnalysis, len(branches)+1)
all[0] = analyser
for i, branch := range branches {
all[i+1] = branch.(*BurndownAnalysis)
}
keys := map[string]bool{}
for _, burn := range all {
for key, val := range burn.mergedFiles {
// (*)
// there can be contradicting flags,
// e.g. item was renamed and a new item written on its place
// this may be not exactly accurate
keys[key] = keys[key] || val
}
}
for key, val := range keys {
if !val {
for _, burn := range all {
if f, exists := burn.files[key]; exists {
f.Delete()
}
delete(burn.files, key)
}
continue
}
files := make([]*burndown.File, 0, len(all))
for _, burn := range all {
file := burn.files[key]
if file != nil {
// file can be nil if it is considered binary in this branch
files = append(files, file)
}
}
if len(files) == 0 {
// so we could be wrong in (*) and there is no such file eventually
// it could be also removed in the merge commit itself
continue
}
files[0].Merge(analyser.packPersonWithDay(analyser.mergedAuthor, analyser.day), files[1:]...)
for _, burn := range all {
if burn.files[key] != files[0] {
if burn.files[key] != nil {
burn.files[key].Delete()
}
burn.files[key] = files[0].CloneDeep(burn.fileAllocator)
}
}
}
analyser.onNewDay()
}
// Hibernate compresses the bound RBTree memory with the files.
func (analyser *BurndownAnalysis) Hibernate() error {
analyser.fileAllocator.Hibernate()
if analyser.HibernationToDisk {
file, err := ioutil.TempFile(analyser.HibernationDirectory, "*-hercules.bin")
if err != nil {
return err
}
analyser.hibernatedFileName = file.Name()
err = file.Close()
if err != nil {
analyser.hibernatedFileName = ""
return err
}
err = analyser.fileAllocator.Serialize(analyser.hibernatedFileName)
if err != nil {
analyser.hibernatedFileName = ""
return err
}
}
return nil
}
// Boot decompresses the bound RBTree memory with the files.
func (analyser *BurndownAnalysis) Boot() error {
if analyser.hibernatedFileName != "" {
err := analyser.fileAllocator.Deserialize(analyser.hibernatedFileName)
if err != nil {
return err
}
err = os.Remove(analyser.hibernatedFileName)
if err != nil {
return err
}
analyser.hibernatedFileName = ""
}
analyser.fileAllocator.Boot()
return nil
}
// Finalize returns the result of the analysis. Further Consume() calls are not expected.
func (analyser *BurndownAnalysis) Finalize() interface{} {
globalHistory, lastDay := analyser.groupSparseHistory(analyser.globalHistory, -1)
fileHistories := map[string]DenseHistory{}
for key, history := range analyser.fileHistories {
if len(history) > 0 {
fileHistories[key], _ = analyser.groupSparseHistory(history, lastDay)
}
}
peopleHistories := make([]DenseHistory, analyser.PeopleNumber)
for i, history := range analyser.peopleHistories {
if len(history) > 0 {
// there can be people with only trivial merge commits and without own lines
peopleHistories[i], _ = analyser.groupSparseHistory(history, lastDay)
} else {
peopleHistories[i] = make(DenseHistory, len(globalHistory))
for j, gh := range globalHistory {
peopleHistories[i][j] = make([]int64, len(gh))
}
}
}
peopleMatrix := make(DenseHistory, analyser.PeopleNumber)
for i, row := range analyser.matrix {
mrow := make([]int64, analyser.PeopleNumber+2)
peopleMatrix[i] = mrow
for key, val := range row {
if key == identity.AuthorMissing {
key = -1
} else if key == authorSelf {
key = -2
}
mrow[key+2] = val
}
}
return BurndownResult{
GlobalHistory: globalHistory,
FileHistories: fileHistories,
PeopleHistories: peopleHistories,
PeopleMatrix: peopleMatrix,
reversedPeopleDict: analyser.reversedPeopleDict,
sampling: analyser.Sampling,
granularity: analyser.Granularity,
}
}
// Serialize converts the analysis result as returned by Finalize() to text or bytes.
// The text format is YAML and the bytes format is Protocol Buffers.
func (analyser *BurndownAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
burndownResult := result.(BurndownResult)
if binary {
return analyser.serializeBinary(&burndownResult, writer)
}
analyser.serializeText(&burndownResult, writer)
return nil
}
// Deserialize converts the specified protobuf bytes to BurndownResult.
func (analyser *BurndownAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
msg := pb.BurndownAnalysisResults{}
err := proto.Unmarshal(pbmessage, &msg)
if err != nil {
return nil, err
}
result := BurndownResult{}
convertCSR := func(mat *pb.BurndownSparseMatrix) DenseHistory {
res := make(DenseHistory, mat.NumberOfRows)
for i := 0; i < int(mat.NumberOfRows); i++ {
res[i] = make([]int64, mat.NumberOfColumns)
for j := 0; j < len(mat.Rows[i].Columns); j++ {
res[i][j] = int64(mat.Rows[i].Columns[j])
}
}
return res
}
result.GlobalHistory = convertCSR(msg.Project)
result.FileHistories = map[string]DenseHistory{}
for _, mat := range msg.Files {
result.FileHistories[mat.Name] = convertCSR(mat)
}
result.reversedPeopleDict = make([]string, len(msg.People))
result.PeopleHistories = make([]DenseHistory, len(msg.People))
for i, mat := range msg.People {
result.PeopleHistories[i] = convertCSR(mat)
result.reversedPeopleDict[i] = mat.Name
}
if msg.PeopleInteraction != nil {
result.PeopleMatrix = make(DenseHistory, msg.PeopleInteraction.NumberOfRows)
}
for i := 0; i < len(result.PeopleMatrix); i++ {
result.PeopleMatrix[i] = make([]int64, msg.PeopleInteraction.NumberOfColumns)
for j := int(msg.PeopleInteraction.Indptr[i]); j < int(msg.PeopleInteraction.Indptr[i+1]); j++ {
result.PeopleMatrix[i][msg.PeopleInteraction.Indices[j]] = msg.PeopleInteraction.Data[j]
}
}
result.sampling = int(msg.Sampling)
result.granularity = int(msg.Granularity)
return result, nil
}
// MergeResults combines two BurndownResult-s together.
func (analyser *BurndownAnalysis) MergeResults(
r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
bar1 := r1.(BurndownResult)
bar2 := r2.(BurndownResult)
merged := BurndownResult{}
if bar1.sampling < bar2.sampling {
merged.sampling = bar1.sampling
} else {
merged.sampling = bar2.sampling
}
if bar1.granularity < bar2.granularity {
merged.granularity = bar1.granularity
} else {
merged.granularity = bar2.granularity
}
var people map[string][3]int
people, merged.reversedPeopleDict = identity.Detector{}.MergeReversedDicts(
bar1.reversedPeopleDict, bar2.reversedPeopleDict)
var wg sync.WaitGroup
if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
merged.GlobalHistory = mergeMatrices(
bar1.GlobalHistory, bar2.GlobalHistory,
bar1.granularity, bar1.sampling,
bar2.granularity, bar2.sampling,
c1, c2)
}()
}
if len(bar1.FileHistories) > 0 || len(bar2.FileHistories) > 0 {
merged.FileHistories = map[string]DenseHistory{}
historyMutex := sync.Mutex{}
for key, fh1 := range bar1.FileHistories {
if fh2, exists := bar2.FileHistories[key]; exists {
wg.Add(1)
go func(fh1, fh2 DenseHistory, key string) {
defer wg.Done()
historyMutex.Lock()
defer historyMutex.Unlock()
merged.FileHistories[key] = mergeMatrices(
fh1, fh2, bar1.granularity, bar1.sampling, bar2.granularity, bar2.sampling, c1, c2)
}(fh1, fh2, key)
} else {
historyMutex.Lock()
merged.FileHistories[key] = fh1
historyMutex.Unlock()
}
}
for key, fh2 := range bar2.FileHistories {
if _, exists := bar1.FileHistories[key]; !exists {
historyMutex.Lock()
merged.FileHistories[key] = fh2
historyMutex.Unlock()
}
}
}
if len(merged.reversedPeopleDict) > 0 {
merged.PeopleHistories = make([]DenseHistory, len(merged.reversedPeopleDict))
for i, key := range merged.reversedPeopleDict {
ptrs := people[key]
if ptrs[1] < 0 {
if len(bar2.PeopleHistories) > 0 {
merged.PeopleHistories[i] = bar2.PeopleHistories[ptrs[2]]
}
} else if ptrs[2] < 0 {
if len(bar1.PeopleHistories) > 0 {
merged.PeopleHistories[i] = bar1.PeopleHistories[ptrs[1]]
}
} else {
wg.Add(1)
go func(i int) {
defer wg.Done()
var m1, m2 DenseHistory
if len(bar1.PeopleHistories) > 0 {
m1 = bar1.PeopleHistories[ptrs[1]]
}
if len(bar2.PeopleHistories) > 0 {
m2 = bar2.PeopleHistories[ptrs[2]]
}
merged.PeopleHistories[i] = mergeMatrices(
m1, m2,
bar1.granularity, bar1.sampling,
bar2.granularity, bar2.sampling,
c1, c2,
)
}(i)
}
}
wg.Add(1)
go func() {
defer wg.Done()
if len(bar2.PeopleMatrix) == 0 {
merged.PeopleMatrix = bar1.PeopleMatrix
// extend the matrix in both directions
for i := 0; i < len(merged.PeopleMatrix); i++ {
for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
}
}
for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
merged.PeopleMatrix = append(
merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
}
} else {
merged.PeopleMatrix = make(DenseHistory, len(merged.reversedPeopleDict))
for i := range merged.PeopleMatrix {
merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
}
for i, key := range bar1.reversedPeopleDict {
mi := people[key][0] // index in merged.reversedPeopleDict
copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
for j, val := range bar1.PeopleMatrix[i][2:] {
merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
}
}
for i, key := range bar2.reversedPeopleDict {
mi := people[key][0] // index in merged.reversedPeopleDict
merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
for j, val := range bar2.PeopleMatrix[i][2:] {
merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
}
}
}
}()
}
wg.Wait()
return merged
}
// mergeMatrices takes two [number of samples][number of bands] matrices,
// resamples them to days so that they become square, sums and resamples back to the
// least of (sampling1, sampling2) and (granularity1, granularity2).
func mergeMatrices(m1, m2 DenseHistory, granularity1, sampling1, granularity2, sampling2 int,
c1, c2 *core.CommonAnalysisResult) DenseHistory {
commonMerged := c1.Copy()
commonMerged.Merge(c2)
var granularity, sampling int
if sampling1 < sampling2 {
sampling = sampling1
} else {
sampling = sampling2
}
if granularity1 < granularity2 {
granularity = granularity1
} else {
granularity = granularity2
}
size := int((commonMerged.EndTime - commonMerged.BeginTime) / (3600 * 24))
daily := make([][]float32, size+granularity+1)
for i := range daily {
daily[i] = make([]float32, size+sampling+1)
}
if len(m1) > 0 {
addBurndownMatrix(m1, granularity1, sampling1, daily,
int(c1.BeginTime-commonMerged.BeginTime)/(3600*24))
}
if len(m2) > 0 {
addBurndownMatrix(m2, granularity2, sampling2, daily,
int(c2.BeginTime-commonMerged.BeginTime)/(3600*24))
}
// convert daily to [][]int64
result := make(DenseHistory, (size+sampling-1)/sampling)
for i := range result {
result[i] = make([]int64, (size+granularity-1)/granularity)
sampledIndex := i * sampling
if i == len(result)-1 {
sampledIndex = size - 1
}
for j := 0; j < len(result[i]); j++ {
accum := float32(0)
for k := j * granularity; k < (j+1)*granularity && k < size; k++ {
accum += daily[sampledIndex][k]
}
result[i][j] = int64(accum)
}
}
return result
}
// Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` days
// and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
// the caller.
// Rows: *at least* len(matrix) * sampling + offset
// Columns: *at least* len(matrix[...]) * granularity + offset
// `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
func addBurndownMatrix(matrix DenseHistory, granularity, sampling int, daily [][]float32, offset int) {
// Determine the maximum number of bands; the actual one may be larger but we do not care
maxCols := 0
for _, row := range matrix {
if maxCols < len(row) {
maxCols = len(row)
}
}
neededRows := len(matrix)*sampling + offset
if len(daily) < neededRows {
log.Panicf("merge bug: too few daily rows: required %d, have %d",
neededRows, len(daily))
}
if len(daily[0]) < maxCols {
log.Panicf("merge bug: too few daily cols: required %d, have %d",
maxCols, len(daily[0]))
}
for x := 0; x < maxCols; x++ {
for y := 0; y < len(matrix); y++ {
if x*granularity > (y+1)*sampling {
// the future is zeros
continue
}
decay := func(startIndex int, startVal float32) {
if startVal == 0 {
return
}
k := float32(matrix[y][x]) / startVal // <= 1
scale := float32((y+1)*sampling - startIndex)
for i := x * granularity; i < (x+1)*granularity; i++ {
initial := daily[startIndex-1+offset][i+offset]
for j := startIndex; j < (y+1)*sampling; j++ {
daily[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
}
}
}
raise := func(finishIndex int, finishVal float32) {
var initial float32
if y > 0 {
initial = float32(matrix[y-1][x])
}
startIndex := y * sampling
if startIndex < x*granularity {
startIndex = x * granularity
}
if startIndex == finishIndex {
return
}
avg := (finishVal - initial) / float32(finishIndex-startIndex)
for j := y * sampling; j < finishIndex; j++ {
for i := startIndex; i <= j; i++ {
daily[j+offset][i+offset] = avg
}
}
// copy [x*g..y*s)
for j := y * sampling; j < finishIndex; j++ {
for i := x * granularity; i < y*sampling; i++ {
daily[j+offset][i+offset] = daily[j-1+offset][i+offset]
}
}
}
if (x+1)*granularity >= (y+1)*sampling {
// x*granularity <= (y+1)*sampling
// 1. x*granularity <= y*sampling
// y*sampling..(y+1)sampling
//
// x+1
// /
// /
// / y+1 -|
// / |
// / y -|
// /
// / x
//
// 2. x*granularity > y*sampling
// x*granularity..(y+1)sampling
//
// x+1
// /
// /
// / y+1 -|
// / |
// / x -|
// /
// / y
if x*granularity <= y*sampling {
raise((y+1)*sampling, float32(matrix[y][x]))
} else if (y+1)*sampling > x*granularity {
raise((y+1)*sampling, float32(matrix[y][x]))
avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
for j := x * granularity; j < (y+1)*sampling; j++ {
for i := x * granularity; i <= j; i++ {
daily[j+offset][i+offset] = avg
}
}
}
} else if (x+1)*granularity >= y*sampling {
// y*sampling <= (x+1)*granularity < (y+1)sampling
// y*sampling..(x+1)*granularity
// (x+1)*granularity..(y+1)sampling
// x+1
// /\
// / \
// / \
// / y+1
// /
// y
v1 := float32(matrix[y-1][x])
v2 := float32(matrix[y][x])
var peak float32
delta := float32((x+1)*granularity - y*sampling)
var scale float32
var previous float32
if y > 0 && (y-1)*sampling >= x*granularity {
// x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
// |________|.......^
if y > 1 {
previous = float32(matrix[y-2][x])
}
scale = float32(sampling)
} else {
// (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
// |______|.......^
if y == 0 {
scale = float32(sampling)
} else {
scale = float32(y*sampling - x*granularity)
}
}
peak = v1 + (v1-previous)/scale*delta
if v2 > peak {
// we need to adjust the peak, it may not be less than the decayed value
if y < len(matrix)-1 {
// y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
// ^.........|_________|
k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
// peak > v2 > v1
} else {
peak = v2
// not enough data to interpolate; this is at least not restricted
}
}
raise((x+1)*granularity, peak)
decay((x+1)*granularity, peak)
} else {
// (x+1)*granularity < y*sampling
// y*sampling..(y+1)sampling
decay(y*sampling, float32(matrix[y-1][x]))
}
}
}
}
func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
fmt.Fprintln(writer, " granularity:", result.granularity)
fmt.Fprintln(writer, " sampling:", result.sampling)
yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
if len(result.FileHistories) > 0 {
fmt.Fprintln(writer, " files:")
keys := sortedKeys(result.FileHistories)
for _, key := range keys {
yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
}
}
if len(result.PeopleHistories) > 0 {
fmt.Fprintln(writer, " people_sequence:")
for key := range result.PeopleHistories {
fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
}
fmt.Fprintln(writer, " people:")
for key, val := range result.PeopleHistories {
yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
}
fmt.Fprintln(writer, " people_interaction: |-")
yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
}
}
func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
message := pb.BurndownAnalysisResults{
Granularity: int32(result.granularity),
Sampling: int32(result.sampling),
}
if len(result.GlobalHistory) > 0 {
message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
}
if len(result.FileHistories) > 0 {
message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
keys := sortedKeys(result.FileHistories)
i := 0
for _, key := range keys {
message.Files[i] = pb.ToBurndownSparseMatrix(
result.FileHistories[key], key)
i++
}
}
if len(result.PeopleHistories) > 0 {
message.People = make(
[]*pb.BurndownSparseMatrix, len(result.PeopleHistories))
for key, val := range result.PeopleHistories {
if len(val) > 0 {
message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
}
}
message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
}
serialized, err := proto.Marshal(&message)
if err != nil {
return err
}
_, err = writer.Write(serialized)
return err
}
func sortedKeys(m map[string]DenseHistory) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func checkClose(c io.Closer) {
if err := c.Close(); err != nil {
panic(err)