burndown.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. package leaves
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "log"
  7. "sort"
  8. "sync"
  9. "unicode/utf8"
  10. "github.com/gogo/protobuf/proto"
  11. "github.com/sergi/go-diff/diffmatchpatch"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  16. "gopkg.in/src-d/hercules.v4/internal/burndown"
  17. "gopkg.in/src-d/hercules.v4/internal/core"
  18. "gopkg.in/src-d/hercules.v4/internal/pb"
  19. items "gopkg.in/src-d/hercules.v4/internal/plumbing"
  20. "gopkg.in/src-d/hercules.v4/internal/plumbing/identity"
  21. "gopkg.in/src-d/hercules.v4/yaml"
  22. )
  23. // BurndownAnalysis allows to gather the line burndown statistics for a Git repository.
  24. // It is a LeafPipelineItem.
  25. // Reference: https://erikbern.com/2016/12/05/the-half-life-of-code.html
  26. type BurndownAnalysis struct {
  27. // Granularity sets the size of each band - the number of days it spans.
  28. // Smaller values provide better resolution but require more work and eat more
  29. // memory. 30 days is usually enough.
  30. Granularity int
  31. // Sampling sets how detailed is the statistic - the size of the interval in
  32. // days between consecutive measurements. It may not be greater than Granularity. Try 15 or 30.
  33. Sampling int
  34. // TrackFiles enables or disables the fine-grained per-file burndown analysis.
  35. // It does not change the project level burndown results.
  36. TrackFiles bool
  37. // The number of developers for which to collect the burndown stats. 0 disables it.
  38. PeopleNumber int
  39. // Debug activates the debugging mode. Analyse() runs slower in this mode
  40. // but it accurately checks all the intermediate states for invariant
  41. // violations.
  42. Debug bool
  43. // Repository points to the analysed Git repository struct from go-git.
  44. repository *git.Repository
  45. // globalHistory is the daily deltas of daily line counts.
  46. // E.g. day 0: day 0 +50 lines
  47. // day 10: day 0 -10 lines; day 10 +20 lines
  48. // day 12: day 0 -5 lines; day 10 -3 lines; day 12 +10 lines
  49. // map [0] [0] = 50
  50. // map[10] [0] = -10
  51. // map[10][10] = 20
  52. // map[12] [0] = -5
  53. // map[12][10] = -3
  54. // map[12][12] = 10
  55. globalHistory sparseHistory
  56. // fileHistories is the daily deltas of each file's daily line counts.
  57. fileHistories map[string]sparseHistory
  58. // peopleHistories is the daily deltas of each person's daily line counts.
  59. peopleHistories []sparseHistory
  60. // files is the mapping <file path> -> *File.
  61. files map[string]*burndown.File
  62. // matrix is the mutual deletions and self insertions.
  63. matrix []map[int]int64
  64. // day is the most recent day index processed.
  65. day int
  66. // previousDay is the day from the previous sample period -
  67. // different from DaysSinceStart.previousDay.
  68. previousDay int
  69. // references IdentityDetector.ReversedPeopleDict
  70. reversedPeopleDict []string
  71. }
  72. // BurndownResult carries the result of running BurndownAnalysis - it is returned by
  73. // BurndownAnalysis.Finalize().
  74. type BurndownResult struct {
  75. // [number of samples][number of bands]
  76. // The number of samples depends on Sampling: the less Sampling, the bigger the number.
  77. // The number of bands depends on Granularity: the less Granularity, the bigger the number.
  78. GlobalHistory DenseHistory
  79. // The key is the path inside the Git repository. The value's dimensions are the same as
  80. // in GlobalHistory.
  81. FileHistories map[string]DenseHistory
  82. // [number of people][number of samples][number of bands]
  83. PeopleHistories []DenseHistory
  84. // [number of people][number of people + 2]
  85. // The first element is the total number of lines added by the author.
  86. // The second element is the number of removals by unidentified authors (outside reversedPeopleDict).
  87. // The rest of the elements are equal the number of line removals by the corresponding
  88. // authors in reversedPeopleDict: 2 -> 0, 3 -> 1, etc.
  89. PeopleMatrix DenseHistory
  90. // The following members are private.
  91. // reversedPeopleDict is borrowed from IdentityDetector and becomes available after
  92. // Pipeline.Initialize(facts map[string]interface{}). Thus it can be obtained via
  93. // facts[FactIdentityDetectorReversedPeopleDict].
  94. reversedPeopleDict []string
  95. // sampling and granularity are copied from BurndownAnalysis and stored for service purposes
  96. // such as merging several results together.
  97. sampling int
  98. granularity int
  99. }
  100. const (
  101. // ConfigBurndownGranularity is the name of the option to set BurndownAnalysis.Granularity.
  102. ConfigBurndownGranularity = "Burndown.Granularity"
  103. // ConfigBurndownSampling is the name of the option to set BurndownAnalysis.Sampling.
  104. ConfigBurndownSampling = "Burndown.Sampling"
  105. // ConfigBurndownTrackFiles enables burndown collection for files.
  106. ConfigBurndownTrackFiles = "Burndown.TrackFiles"
  107. // ConfigBurndownTrackPeople enables burndown collection for authors.
  108. ConfigBurndownTrackPeople = "Burndown.TrackPeople"
  109. // ConfigBurndownDebug enables some extra debug assertions.
  110. ConfigBurndownDebug = "Burndown.Debug"
  111. // DefaultBurndownGranularity is the default number of days for BurndownAnalysis.Granularity
  112. // and BurndownAnalysis.Sampling.
  113. DefaultBurndownGranularity = 30
  114. // authorSelf is the internal author index which is used in BurndownAnalysis.Finalize() to
  115. // format the author overwrites matrix.
  116. authorSelf = (1 << (32 - burndown.TreeMaxBinPower)) - 2
  117. )
  118. type sparseHistory = map[int]map[int]int64
  119. // DenseHistory is the matrix [number of samples][number of bands] -> number of lines.
  120. type DenseHistory = [][]int64
  121. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  122. func (analyser *BurndownAnalysis) Name() string {
  123. return "Burndown"
  124. }
  125. // Provides returns the list of names of entities which are produced by this PipelineItem.
  126. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  127. // to this list. Also used by core.Registry to build the global map of providers.
  128. func (analyser *BurndownAnalysis) Provides() []string {
  129. return []string{}
  130. }
  131. // Requires returns the list of names of entities which are needed by this PipelineItem.
  132. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  133. // entities are Provides() upstream.
  134. func (analyser *BurndownAnalysis) Requires() []string {
  135. arr := [...]string{
  136. items.DependencyFileDiff, items.DependencyTreeChanges, items.DependencyBlobCache,
  137. items.DependencyDay, identity.DependencyAuthor}
  138. return arr[:]
  139. }
  140. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  141. func (analyser *BurndownAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  142. options := [...]core.ConfigurationOption{{
  143. Name: ConfigBurndownGranularity,
  144. Description: "How many days there are in a single band.",
  145. Flag: "granularity",
  146. Type: core.IntConfigurationOption,
  147. Default: DefaultBurndownGranularity}, {
  148. Name: ConfigBurndownSampling,
  149. Description: "How frequently to record the state in days.",
  150. Flag: "sampling",
  151. Type: core.IntConfigurationOption,
  152. Default: DefaultBurndownGranularity}, {
  153. Name: ConfigBurndownTrackFiles,
  154. Description: "Record detailed statistics per each file.",
  155. Flag: "burndown-files",
  156. Type: core.BoolConfigurationOption,
  157. Default: false}, {
  158. Name: ConfigBurndownTrackPeople,
  159. Description: "Record detailed statistics per each developer.",
  160. Flag: "burndown-people",
  161. Type: core.BoolConfigurationOption,
  162. Default: false}, {
  163. Name: ConfigBurndownDebug,
  164. Description: "Validate the trees on each step.",
  165. Flag: "burndown-debug",
  166. Type: core.BoolConfigurationOption,
  167. Default: false},
  168. }
  169. return options[:]
  170. }
  171. // Configure sets the properties previously published by ListConfigurationOptions().
  172. func (analyser *BurndownAnalysis) Configure(facts map[string]interface{}) {
  173. if val, exists := facts[ConfigBurndownGranularity].(int); exists {
  174. analyser.Granularity = val
  175. }
  176. if val, exists := facts[ConfigBurndownSampling].(int); exists {
  177. analyser.Sampling = val
  178. }
  179. if val, exists := facts[ConfigBurndownTrackFiles].(bool); exists {
  180. analyser.TrackFiles = val
  181. }
  182. if people, exists := facts[ConfigBurndownTrackPeople].(bool); people {
  183. if val, exists := facts[identity.FactIdentityDetectorPeopleCount].(int); exists {
  184. analyser.PeopleNumber = val
  185. analyser.reversedPeopleDict = facts[identity.FactIdentityDetectorReversedPeopleDict].([]string)
  186. }
  187. } else if exists {
  188. analyser.PeopleNumber = 0
  189. }
  190. if val, exists := facts[ConfigBurndownDebug].(bool); exists {
  191. analyser.Debug = val
  192. }
  193. }
  194. // Flag for the command line switch which enables this analysis.
  195. func (analyser *BurndownAnalysis) Flag() string {
  196. return "burndown"
  197. }
  198. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  199. // calls. The repository which is going to be analysed is supplied as an argument.
  200. func (analyser *BurndownAnalysis) Initialize(repository *git.Repository) {
  201. if analyser.Granularity <= 0 {
  202. log.Printf("Warning: adjusted the granularity to %d days\n",
  203. DefaultBurndownGranularity)
  204. analyser.Granularity = DefaultBurndownGranularity
  205. }
  206. if analyser.Sampling <= 0 {
  207. log.Printf("Warning: adjusted the sampling to %d days\n",
  208. DefaultBurndownGranularity)
  209. analyser.Sampling = DefaultBurndownGranularity
  210. }
  211. if analyser.Sampling > analyser.Granularity {
  212. log.Printf("Warning: granularity may not be less than sampling, adjusted to %d\n",
  213. analyser.Granularity)
  214. analyser.Sampling = analyser.Granularity
  215. }
  216. analyser.repository = repository
  217. analyser.globalHistory = sparseHistory{}
  218. analyser.fileHistories = map[string]sparseHistory{}
  219. analyser.peopleHistories = make([]sparseHistory, analyser.PeopleNumber)
  220. analyser.files = map[string]*burndown.File{}
  221. analyser.matrix = make([]map[int]int64, analyser.PeopleNumber)
  222. analyser.day = 0
  223. analyser.previousDay = 0
  224. }
  225. // Consume runs this PipelineItem on the next commit's data.
  226. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  227. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  228. // This function returns the mapping with analysis results. The keys must be the same as
  229. // in Provides(). If there was an error, nil is returned.
  230. func (analyser *BurndownAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  231. author := deps[identity.DependencyAuthor].(int)
  232. day := deps[items.DependencyDay].(int)
  233. if !core.IsMergeCommit(deps) {
  234. analyser.day = day
  235. analyser.onNewDay()
  236. } else {
  237. // effectively disables the status updates if the commit is a merge
  238. // we will analyse the conflicts resolution in Merge()
  239. analyser.day = burndown.TreeMergeMark
  240. }
  241. cache := deps[items.DependencyBlobCache].(map[plumbing.Hash]*object.Blob)
  242. treeDiffs := deps[items.DependencyTreeChanges].(object.Changes)
  243. fileDiffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
  244. for _, change := range treeDiffs {
  245. action, _ := change.Action()
  246. var err error
  247. switch action {
  248. case merkletrie.Insert:
  249. err = analyser.handleInsertion(change, author, cache)
  250. case merkletrie.Delete:
  251. err = analyser.handleDeletion(change, author, cache)
  252. case merkletrie.Modify:
  253. err = analyser.handleModification(change, author, cache, fileDiffs)
  254. }
  255. if err != nil {
  256. return nil, err
  257. }
  258. }
  259. // in case there is a merge analyser.day equals to TreeMergeMark
  260. analyser.day = day
  261. return nil, nil
  262. }
  263. // Fork clones this item. Everything is copied by reference except the files
  264. // which are copied by value.
  265. func (analyser *BurndownAnalysis) Fork(n int) []core.PipelineItem {
  266. result := make([]core.PipelineItem, n)
  267. for i := range result {
  268. clone := *analyser
  269. clone.files = map[string]*burndown.File{}
  270. for key, file := range analyser.files {
  271. clone.files[key] = file.Clone(false)
  272. }
  273. result[i] = &clone
  274. }
  275. return result
  276. }
  277. // Merge combines several items together. We apply the special file merging logic here.
  278. func (analyser *BurndownAnalysis) Merge(branches []core.PipelineItem) {
  279. for key, file := range analyser.files {
  280. others := make([]*burndown.File, len(branches))
  281. for i, branch := range branches {
  282. others[i] = branch.(*BurndownAnalysis).files[key]
  283. }
  284. // don't worry, we compare the hashes first before heavy-lifting
  285. if file.Merge(analyser.day, others...) {
  286. for _, branch := range branches {
  287. branch.(*BurndownAnalysis).files[key] = file.Clone(false)
  288. }
  289. }
  290. }
  291. analyser.onNewDay()
  292. }
  293. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  294. func (analyser *BurndownAnalysis) Finalize() interface{} {
  295. fileHistories := map[string]DenseHistory{}
  296. for key, history := range analyser.fileHistories {
  297. fileHistories[key] = analyser.groupSparseHistory(history)
  298. }
  299. peopleHistories := make([]DenseHistory, analyser.PeopleNumber)
  300. for i, history := range analyser.peopleHistories {
  301. peopleHistories[i] = analyser.groupSparseHistory(history)
  302. }
  303. peopleMatrix := make(DenseHistory, analyser.PeopleNumber)
  304. for i, row := range analyser.matrix {
  305. mrow := make([]int64, analyser.PeopleNumber+2)
  306. peopleMatrix[i] = mrow
  307. for key, val := range row {
  308. if key == identity.AuthorMissing {
  309. key = -1
  310. } else if key == authorSelf {
  311. key = -2
  312. }
  313. mrow[key+2] = val
  314. }
  315. }
  316. return BurndownResult{
  317. GlobalHistory: analyser.groupSparseHistory(analyser.globalHistory),
  318. FileHistories: fileHistories,
  319. PeopleHistories: peopleHistories,
  320. PeopleMatrix: peopleMatrix,
  321. reversedPeopleDict: analyser.reversedPeopleDict,
  322. sampling: analyser.Sampling,
  323. granularity: analyser.Granularity,
  324. }
  325. }
  326. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  327. // The text format is YAML and the bytes format is Protocol Buffers.
  328. func (analyser *BurndownAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  329. burndownResult := result.(BurndownResult)
  330. if binary {
  331. return analyser.serializeBinary(&burndownResult, writer)
  332. }
  333. analyser.serializeText(&burndownResult, writer)
  334. return nil
  335. }
  336. // Deserialize converts the specified protobuf bytes to BurndownResult.
  337. func (analyser *BurndownAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  338. msg := pb.BurndownAnalysisResults{}
  339. err := proto.Unmarshal(pbmessage, &msg)
  340. if err != nil {
  341. return nil, err
  342. }
  343. result := BurndownResult{}
  344. convertCSR := func(mat *pb.BurndownSparseMatrix) DenseHistory {
  345. res := make(DenseHistory, mat.NumberOfRows)
  346. for i := 0; i < int(mat.NumberOfRows); i++ {
  347. res[i] = make([]int64, mat.NumberOfColumns)
  348. for j := 0; j < len(mat.Rows[i].Columns); j++ {
  349. res[i][j] = int64(mat.Rows[i].Columns[j])
  350. }
  351. }
  352. return res
  353. }
  354. result.GlobalHistory = convertCSR(msg.Project)
  355. result.FileHistories = map[string]DenseHistory{}
  356. for _, mat := range msg.Files {
  357. result.FileHistories[mat.Name] = convertCSR(mat)
  358. }
  359. result.reversedPeopleDict = make([]string, len(msg.People))
  360. result.PeopleHistories = make([]DenseHistory, len(msg.People))
  361. for i, mat := range msg.People {
  362. result.PeopleHistories[i] = convertCSR(mat)
  363. result.reversedPeopleDict[i] = mat.Name
  364. }
  365. if msg.PeopleInteraction != nil {
  366. result.PeopleMatrix = make(DenseHistory, msg.PeopleInteraction.NumberOfRows)
  367. }
  368. for i := 0; i < len(result.PeopleMatrix); i++ {
  369. result.PeopleMatrix[i] = make([]int64, msg.PeopleInteraction.NumberOfColumns)
  370. for j := int(msg.PeopleInteraction.Indptr[i]); j < int(msg.PeopleInteraction.Indptr[i+1]); j++ {
  371. result.PeopleMatrix[i][msg.PeopleInteraction.Indices[j]] = msg.PeopleInteraction.Data[j]
  372. }
  373. }
  374. result.sampling = int(msg.Sampling)
  375. result.granularity = int(msg.Granularity)
  376. return result, nil
  377. }
  378. // MergeResults combines two BurndownResult-s together.
  379. func (analyser *BurndownAnalysis) MergeResults(
  380. r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
  381. bar1 := r1.(BurndownResult)
  382. bar2 := r2.(BurndownResult)
  383. merged := BurndownResult{}
  384. if bar1.sampling < bar2.sampling {
  385. merged.sampling = bar1.sampling
  386. } else {
  387. merged.sampling = bar2.sampling
  388. }
  389. if bar1.granularity < bar2.granularity {
  390. merged.granularity = bar1.granularity
  391. } else {
  392. merged.granularity = bar2.granularity
  393. }
  394. var people map[string][3]int
  395. people, merged.reversedPeopleDict = identity.Detector{}.MergeReversedDicts(
  396. bar1.reversedPeopleDict, bar2.reversedPeopleDict)
  397. var wg sync.WaitGroup
  398. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  399. wg.Add(1)
  400. go func() {
  401. defer wg.Done()
  402. merged.GlobalHistory = mergeMatrices(
  403. bar1.GlobalHistory, bar2.GlobalHistory,
  404. bar1.granularity, bar1.sampling,
  405. bar2.granularity, bar2.sampling,
  406. c1, c2)
  407. }()
  408. }
  409. if len(bar1.FileHistories) > 0 || len(bar2.FileHistories) > 0 {
  410. merged.FileHistories = map[string]DenseHistory{}
  411. historyMutex := sync.Mutex{}
  412. for key, fh1 := range bar1.FileHistories {
  413. if fh2, exists := bar2.FileHistories[key]; exists {
  414. wg.Add(1)
  415. go func(fh1, fh2 DenseHistory, key string) {
  416. defer wg.Done()
  417. historyMutex.Lock()
  418. defer historyMutex.Unlock()
  419. merged.FileHistories[key] = mergeMatrices(
  420. fh1, fh2, bar1.granularity, bar1.sampling, bar2.granularity, bar2.sampling, c1, c2)
  421. }(fh1, fh2, key)
  422. } else {
  423. historyMutex.Lock()
  424. merged.FileHistories[key] = fh1
  425. historyMutex.Unlock()
  426. }
  427. }
  428. for key, fh2 := range bar2.FileHistories {
  429. if _, exists := bar1.FileHistories[key]; !exists {
  430. historyMutex.Lock()
  431. merged.FileHistories[key] = fh2
  432. historyMutex.Unlock()
  433. }
  434. }
  435. }
  436. if len(merged.reversedPeopleDict) > 0 {
  437. merged.PeopleHistories = make([]DenseHistory, len(merged.reversedPeopleDict))
  438. for i, key := range merged.reversedPeopleDict {
  439. ptrs := people[key]
  440. if ptrs[1] < 0 {
  441. if len(bar2.PeopleHistories) > 0 {
  442. merged.PeopleHistories[i] = bar2.PeopleHistories[ptrs[2]]
  443. }
  444. } else if ptrs[2] < 0 {
  445. if len(bar1.PeopleHistories) > 0 {
  446. merged.PeopleHistories[i] = bar1.PeopleHistories[ptrs[1]]
  447. }
  448. } else {
  449. wg.Add(1)
  450. go func(i int) {
  451. defer wg.Done()
  452. var m1, m2 DenseHistory
  453. if len(bar1.PeopleHistories) > 0 {
  454. m1 = bar1.PeopleHistories[ptrs[1]]
  455. }
  456. if len(bar2.PeopleHistories) > 0 {
  457. m2 = bar2.PeopleHistories[ptrs[2]]
  458. }
  459. merged.PeopleHistories[i] = mergeMatrices(
  460. m1, m2,
  461. bar1.granularity, bar1.sampling,
  462. bar2.granularity, bar2.sampling,
  463. c1, c2,
  464. )
  465. }(i)
  466. }
  467. }
  468. wg.Add(1)
  469. go func() {
  470. defer wg.Done()
  471. if len(bar2.PeopleMatrix) == 0 {
  472. merged.PeopleMatrix = bar1.PeopleMatrix
  473. // extend the matrix in both directions
  474. for i := 0; i < len(merged.PeopleMatrix); i++ {
  475. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  476. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  477. }
  478. }
  479. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  480. merged.PeopleMatrix = append(
  481. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  482. }
  483. } else {
  484. merged.PeopleMatrix = make(DenseHistory, len(merged.reversedPeopleDict))
  485. for i := range merged.PeopleMatrix {
  486. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  487. }
  488. for i, key := range bar1.reversedPeopleDict {
  489. mi := people[key][0] // index in merged.reversedPeopleDict
  490. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  491. for j, val := range bar1.PeopleMatrix[i][2:] {
  492. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
  493. }
  494. }
  495. for i, key := range bar2.reversedPeopleDict {
  496. mi := people[key][0] // index in merged.reversedPeopleDict
  497. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  498. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  499. for j, val := range bar2.PeopleMatrix[i][2:] {
  500. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
  501. }
  502. }
  503. }
  504. }()
  505. }
  506. wg.Wait()
  507. return merged
  508. }
  509. // mergeMatrices takes two [number of samples][number of bands] matrices,
  510. // resamples them to days so that they become square, sums and resamples back to the
  511. // least of (sampling1, sampling2) and (granularity1, granularity2).
  512. func mergeMatrices(m1, m2 DenseHistory, granularity1, sampling1, granularity2, sampling2 int,
  513. c1, c2 *core.CommonAnalysisResult) DenseHistory {
  514. commonMerged := *c1
  515. commonMerged.Merge(c2)
  516. var granularity, sampling int
  517. if sampling1 < sampling2 {
  518. sampling = sampling1
  519. } else {
  520. sampling = sampling2
  521. }
  522. if granularity1 < granularity2 {
  523. granularity = granularity1
  524. } else {
  525. granularity = granularity2
  526. }
  527. size := int((commonMerged.EndTime - commonMerged.BeginTime) / (3600 * 24))
  528. daily := make([][]float32, size+granularity)
  529. for i := range daily {
  530. daily[i] = make([]float32, size+sampling)
  531. }
  532. if len(m1) > 0 {
  533. addBurndownMatrix(m1, granularity1, sampling1, daily,
  534. int(c1.BeginTime-commonMerged.BeginTime)/(3600*24))
  535. }
  536. if len(m2) > 0 {
  537. addBurndownMatrix(m2, granularity2, sampling2, daily,
  538. int(c2.BeginTime-commonMerged.BeginTime)/(3600*24))
  539. }
  540. // convert daily to [][]int64
  541. result := make(DenseHistory, (size+sampling-1)/sampling)
  542. for i := range result {
  543. result[i] = make([]int64, (size+granularity-1)/granularity)
  544. sampledIndex := i * sampling
  545. if i == len(result)-1 {
  546. sampledIndex = size - 1
  547. }
  548. for j := 0; j < len(result[i]); j++ {
  549. accum := float32(0)
  550. for k := j * granularity; k < (j+1)*granularity && k < size; k++ {
  551. accum += daily[sampledIndex][k]
  552. }
  553. result[i][j] = int64(accum)
  554. }
  555. }
  556. return result
  557. }
  558. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` days
  559. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  560. // the caller.
  561. // Rows: *at least* len(matrix) * sampling + offset
  562. // Columns: *at least* len(matrix[...]) * granularity + offset
  563. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  564. func addBurndownMatrix(matrix DenseHistory, granularity, sampling int, daily [][]float32, offset int) {
  565. // Determine the maximum number of bands; the actual one may be larger but we do not care
  566. maxCols := 0
  567. for _, row := range matrix {
  568. if maxCols < len(row) {
  569. maxCols = len(row)
  570. }
  571. }
  572. neededRows := len(matrix)*sampling + offset
  573. if len(daily) < neededRows {
  574. panic(fmt.Sprintf("merge bug: too few daily rows: required %d, have %d",
  575. neededRows, len(daily)))
  576. }
  577. if len(daily[0]) < maxCols {
  578. panic(fmt.Sprintf("merge bug: too few daily cols: required %d, have %d",
  579. maxCols, len(daily[0])))
  580. }
  581. for x := 0; x < maxCols; x++ {
  582. for y := 0; y < len(matrix); y++ {
  583. if x*granularity > (y+1)*sampling {
  584. // the future is zeros
  585. continue
  586. }
  587. decay := func(startIndex int, startVal float32) {
  588. if startVal == 0 {
  589. return
  590. }
  591. k := float32(matrix[y][x]) / startVal // <= 1
  592. scale := float32((y+1)*sampling - startIndex)
  593. for i := x * granularity; i < (x+1)*granularity; i++ {
  594. initial := daily[startIndex-1+offset][i+offset]
  595. for j := startIndex; j < (y+1)*sampling; j++ {
  596. daily[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  597. }
  598. }
  599. }
  600. raise := func(finishIndex int, finishVal float32) {
  601. var initial float32
  602. if y > 0 {
  603. initial = float32(matrix[y-1][x])
  604. }
  605. startIndex := y * sampling
  606. if startIndex < x*granularity {
  607. startIndex = x * granularity
  608. }
  609. if startIndex == finishIndex {
  610. return
  611. }
  612. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  613. for j := y * sampling; j < finishIndex; j++ {
  614. for i := startIndex; i <= j; i++ {
  615. daily[j+offset][i+offset] = avg
  616. }
  617. }
  618. // copy [x*g..y*s)
  619. for j := y * sampling; j < finishIndex; j++ {
  620. for i := x * granularity; i < y*sampling; i++ {
  621. daily[j+offset][i+offset] = daily[j-1+offset][i+offset]
  622. }
  623. }
  624. }
  625. if (x+1)*granularity >= (y+1)*sampling {
  626. // x*granularity <= (y+1)*sampling
  627. // 1. x*granularity <= y*sampling
  628. // y*sampling..(y+1)sampling
  629. //
  630. // x+1
  631. // /
  632. // /
  633. // / y+1 -|
  634. // / |
  635. // / y -|
  636. // /
  637. // / x
  638. //
  639. // 2. x*granularity > y*sampling
  640. // x*granularity..(y+1)sampling
  641. //
  642. // x+1
  643. // /
  644. // /
  645. // / y+1 -|
  646. // / |
  647. // / x -|
  648. // /
  649. // / y
  650. if x*granularity <= y*sampling {
  651. raise((y+1)*sampling, float32(matrix[y][x]))
  652. } else if (y+1)*sampling > x*granularity {
  653. raise((y+1)*sampling, float32(matrix[y][x]))
  654. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  655. for j := x * granularity; j < (y+1)*sampling; j++ {
  656. for i := x * granularity; i <= j; i++ {
  657. daily[j+offset][i+offset] = avg
  658. }
  659. }
  660. }
  661. } else if (x+1)*granularity >= y*sampling {
  662. // y*sampling <= (x+1)*granularity < (y+1)sampling
  663. // y*sampling..(x+1)*granularity
  664. // (x+1)*granularity..(y+1)sampling
  665. // x+1
  666. // /\
  667. // / \
  668. // / \
  669. // / y+1
  670. // /
  671. // y
  672. v1 := float32(matrix[y-1][x])
  673. v2 := float32(matrix[y][x])
  674. var peak float32
  675. delta := float32((x+1)*granularity - y*sampling)
  676. var scale float32
  677. var previous float32
  678. if y > 0 && (y-1)*sampling >= x*granularity {
  679. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  680. // |________|.......^
  681. if y > 1 {
  682. previous = float32(matrix[y-2][x])
  683. }
  684. scale = float32(sampling)
  685. } else {
  686. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  687. // |______|.......^
  688. if y == 0 {
  689. scale = float32(sampling)
  690. } else {
  691. scale = float32(y*sampling - x*granularity)
  692. }
  693. }
  694. peak = v1 + (v1-previous)/scale*delta
  695. if v2 > peak {
  696. // we need to adjust the peak, it may not be less than the decayed value
  697. if y < len(matrix)-1 {
  698. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  699. // ^.........|_________|
  700. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  701. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  702. // peak > v2 > v1
  703. } else {
  704. peak = v2
  705. // not enough data to interpolate; this is at least not restricted
  706. }
  707. }
  708. raise((x+1)*granularity, peak)
  709. decay((x+1)*granularity, peak)
  710. } else {
  711. // (x+1)*granularity < y*sampling
  712. // y*sampling..(y+1)sampling
  713. decay(y*sampling, float32(matrix[y-1][x]))
  714. }
  715. }
  716. }
  717. }
  718. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  719. fmt.Fprintln(writer, " granularity:", result.granularity)
  720. fmt.Fprintln(writer, " sampling:", result.sampling)
  721. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  722. if len(result.FileHistories) > 0 {
  723. fmt.Fprintln(writer, " files:")
  724. keys := sortedKeys(result.FileHistories)
  725. for _, key := range keys {
  726. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  727. }
  728. }
  729. if len(result.PeopleHistories) > 0 {
  730. fmt.Fprintln(writer, " people_sequence:")
  731. for key := range result.PeopleHistories {
  732. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  733. }
  734. fmt.Fprintln(writer, " people:")
  735. for key, val := range result.PeopleHistories {
  736. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  737. }
  738. fmt.Fprintln(writer, " people_interaction: |-")
  739. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  740. }
  741. }
  742. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  743. message := pb.BurndownAnalysisResults{
  744. Granularity: int32(result.granularity),
  745. Sampling: int32(result.sampling),
  746. }
  747. if len(result.GlobalHistory) > 0 {
  748. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  749. }
  750. if len(result.FileHistories) > 0 {
  751. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  752. keys := sortedKeys(result.FileHistories)
  753. i := 0
  754. for _, key := range keys {
  755. message.Files[i] = pb.ToBurndownSparseMatrix(
  756. result.FileHistories[key], key)
  757. i++
  758. }
  759. }
  760. if len(result.PeopleHistories) > 0 {
  761. message.People = make(
  762. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  763. for key, val := range result.PeopleHistories {
  764. if len(val) > 0 {
  765. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  766. }
  767. }
  768. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  769. }
  770. serialized, err := proto.Marshal(&message)
  771. if err != nil {
  772. return err
  773. }
  774. writer.Write(serialized)
  775. return nil
  776. }
  777. func sortedKeys(m map[string]DenseHistory) []string {
  778. keys := make([]string, 0, len(m))
  779. for k := range m {
  780. keys = append(keys, k)
  781. }
  782. sort.Strings(keys)
  783. return keys
  784. }
  785. func checkClose(c io.Closer) {
  786. if err := c.Close(); err != nil {
  787. panic(err)
  788. }
  789. }
  790. // We do a hack and store the day in the first 14 bits and the author index in the last 18.
  791. // Strictly speaking, int can be 64-bit and then the author index occupies 32+18 bits.
  792. // This hack is needed to simplify the values storage inside File-s. We can compare
  793. // different values together and they are compared as days for the same author.
  794. func (analyser *BurndownAnalysis) packPersonWithDay(person int, day int) int {
  795. if analyser.PeopleNumber == 0 {
  796. return day
  797. }
  798. result := day & burndown.TreeMergeMark
  799. result |= person << burndown.TreeMaxBinPower
  800. // This effectively means max (16383 - 1) days (>44 years) and (131072 - 2) devs.
  801. // One day less because burndown.TreeMergeMark = ((1 << 14) - 1) is a special day.
  802. return result
  803. }
  804. func (analyser *BurndownAnalysis) unpackPersonWithDay(value int) (int, int) {
  805. if analyser.PeopleNumber == 0 {
  806. return identity.AuthorMissing, value
  807. }
  808. return value >> burndown.TreeMaxBinPower, value & burndown.TreeMergeMark
  809. }
  810. func (analyser *BurndownAnalysis) onNewDay() {
  811. if analyser.day > analyser.previousDay {
  812. analyser.previousDay = analyser.day
  813. }
  814. }
  815. func (analyser *BurndownAnalysis) updateGlobal(currentTime, previousTime, delta int) {
  816. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  817. _, previousDay := analyser.unpackPersonWithDay(previousTime)
  818. currentHistory := analyser.globalHistory[currentDay]
  819. if currentHistory == nil {
  820. currentHistory = map[int]int64{}
  821. analyser.globalHistory[currentDay] = currentHistory
  822. }
  823. currentHistory[previousDay] += int64(delta)
  824. }
  825. // updateFile is bound to the specific `history` in the closure.
  826. func (analyser *BurndownAnalysis) updateFile(
  827. history sparseHistory, currentTime, previousTime, delta int) {
  828. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  829. _, previousDay := analyser.unpackPersonWithDay(previousTime)
  830. currentHistory := history[currentDay]
  831. if currentHistory == nil {
  832. currentHistory = map[int]int64{}
  833. history[currentDay] = currentHistory
  834. }
  835. currentHistory[previousDay] += int64(delta)
  836. }
  837. func (analyser *BurndownAnalysis) updateAuthor(currentTime, previousTime, delta int) {
  838. previousAuthor, previousDay := analyser.unpackPersonWithDay(previousTime)
  839. if previousAuthor == identity.AuthorMissing {
  840. return
  841. }
  842. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  843. history := analyser.peopleHistories[previousAuthor]
  844. if history == nil {
  845. history = sparseHistory{}
  846. analyser.peopleHistories[previousAuthor] = history
  847. }
  848. currentHistory := history[currentDay]
  849. if currentHistory == nil {
  850. currentHistory = map[int]int64{}
  851. history[currentDay] = currentHistory
  852. }
  853. currentHistory[previousDay] += int64(delta)
  854. }
  855. func (analyser *BurndownAnalysis) updateMatrix(currentTime, previousTime, delta int) {
  856. newAuthor, _ := analyser.unpackPersonWithDay(currentTime)
  857. oldAuthor, _ := analyser.unpackPersonWithDay(previousTime)
  858. if oldAuthor == identity.AuthorMissing {
  859. return
  860. }
  861. if newAuthor == oldAuthor && delta > 0 {
  862. newAuthor = authorSelf
  863. }
  864. row := analyser.matrix[oldAuthor]
  865. if row == nil {
  866. row = map[int]int64{}
  867. analyser.matrix[oldAuthor] = row
  868. }
  869. cell, exists := row[newAuthor]
  870. if !exists {
  871. row[newAuthor] = 0
  872. cell = 0
  873. }
  874. row[newAuthor] = cell + int64(delta)
  875. }
  876. func (analyser *BurndownAnalysis) newFile(
  877. hash plumbing.Hash, name string, author int, day int, size int) (*burndown.File, error) {
  878. statuses := make([]burndown.Updater, 1)
  879. statuses[0] = analyser.updateGlobal
  880. if analyser.TrackFiles {
  881. if _, exists := analyser.fileHistories[name]; exists {
  882. return nil, fmt.Errorf("file %s already exists", name)
  883. }
  884. history := sparseHistory{}
  885. analyser.fileHistories[name] = history
  886. statuses = append(statuses, func(currentTime, previousTime, delta int) {
  887. analyser.updateFile(history, currentTime, previousTime, delta)
  888. })
  889. }
  890. if analyser.PeopleNumber > 0 {
  891. statuses = append(statuses, analyser.updateAuthor)
  892. statuses = append(statuses, analyser.updateMatrix)
  893. day = analyser.packPersonWithDay(author, day)
  894. }
  895. return burndown.NewFile(hash, day, size, statuses...), nil
  896. }
  897. func (analyser *BurndownAnalysis) handleInsertion(
  898. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  899. blob := cache[change.To.TreeEntry.Hash]
  900. lines, err := items.CountLines(blob)
  901. if err != nil {
  902. if err.Error() == "binary" {
  903. return nil
  904. }
  905. return err
  906. }
  907. name := change.To.Name
  908. file, exists := analyser.files[name]
  909. if exists {
  910. return fmt.Errorf("file %s already exists", name)
  911. }
  912. file, err = analyser.newFile(blob.Hash, name, author, analyser.day, lines)
  913. analyser.files[name] = file
  914. return err
  915. }
  916. func (analyser *BurndownAnalysis) handleDeletion(
  917. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  918. blob := cache[change.From.TreeEntry.Hash]
  919. lines, err := items.CountLines(blob)
  920. if err != nil {
  921. if err.Error() == "binary" {
  922. return nil
  923. }
  924. return err
  925. }
  926. name := change.From.Name
  927. file := analyser.files[name]
  928. file.Update(analyser.packPersonWithDay(author, analyser.day), 0, 0, lines)
  929. file.Hash = plumbing.ZeroHash
  930. delete(analyser.files, name)
  931. delete(analyser.fileHistories, name)
  932. return nil
  933. }
  934. func (analyser *BurndownAnalysis) handleModification(
  935. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob,
  936. diffs map[string]items.FileDiffData) error {
  937. file, exists := analyser.files[change.From.Name]
  938. if !exists {
  939. // this indeed may happen
  940. return analyser.handleInsertion(change, author, cache)
  941. }
  942. file.Hash = change.To.TreeEntry.Hash
  943. // possible rename
  944. if change.To.Name != change.From.Name {
  945. err := analyser.handleRename(change.From.Name, change.To.Name)
  946. if err != nil {
  947. return err
  948. }
  949. }
  950. thisDiffs := diffs[change.To.Name]
  951. if file.Len() != thisDiffs.OldLinesOfCode {
  952. log.Printf("====TREE====\n%s", file.Dump())
  953. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  954. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  955. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  956. }
  957. // we do not call RunesToDiffLines so the number of lines equals
  958. // to the rune count
  959. position := 0
  960. pending := diffmatchpatch.Diff{Text: ""}
  961. apply := func(edit diffmatchpatch.Diff) {
  962. length := utf8.RuneCountInString(edit.Text)
  963. if edit.Type == diffmatchpatch.DiffInsert {
  964. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length, 0)
  965. position += length
  966. } else {
  967. file.Update(analyser.packPersonWithDay(author, analyser.day), position, 0, length)
  968. }
  969. if analyser.Debug {
  970. file.Validate()
  971. }
  972. }
  973. for _, edit := range thisDiffs.Diffs {
  974. dumpBefore := ""
  975. if analyser.Debug {
  976. dumpBefore = file.Dump()
  977. }
  978. length := utf8.RuneCountInString(edit.Text)
  979. debugError := func() {
  980. log.Printf("%s: internal diff error\n", change.To.Name)
  981. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.day, position,
  982. length, utf8.RuneCountInString(pending.Text))
  983. if dumpBefore != "" {
  984. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  985. }
  986. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  987. }
  988. switch edit.Type {
  989. case diffmatchpatch.DiffEqual:
  990. if pending.Text != "" {
  991. apply(pending)
  992. pending.Text = ""
  993. }
  994. position += length
  995. case diffmatchpatch.DiffInsert:
  996. if pending.Text != "" {
  997. if pending.Type == diffmatchpatch.DiffInsert {
  998. debugError()
  999. return errors.New("DiffInsert may not appear after DiffInsert")
  1000. }
  1001. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length,
  1002. utf8.RuneCountInString(pending.Text))
  1003. if analyser.Debug {
  1004. file.Validate()
  1005. }
  1006. position += length
  1007. pending.Text = ""
  1008. } else {
  1009. pending = edit
  1010. }
  1011. case diffmatchpatch.DiffDelete:
  1012. if pending.Text != "" {
  1013. debugError()
  1014. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1015. }
  1016. pending = edit
  1017. default:
  1018. debugError()
  1019. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1020. }
  1021. }
  1022. if pending.Text != "" {
  1023. apply(pending)
  1024. pending.Text = ""
  1025. }
  1026. if file.Len() != thisDiffs.NewLinesOfCode {
  1027. return fmt.Errorf("%s: internal integrity error dst %d != %d",
  1028. change.To.Name, thisDiffs.NewLinesOfCode, file.Len())
  1029. }
  1030. return nil
  1031. }
  1032. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1033. if from == to {
  1034. return nil
  1035. }
  1036. file, exists := analyser.files[from]
  1037. if !exists {
  1038. return fmt.Errorf("file %s does not exist", from)
  1039. }
  1040. analyser.files[to] = file
  1041. delete(analyser.files, from)
  1042. history, exists := analyser.fileHistories[from]
  1043. if !exists {
  1044. return fmt.Errorf("file %s does not exist", from)
  1045. }
  1046. analyser.fileHistories[to] = history
  1047. delete(analyser.fileHistories, from)
  1048. return nil
  1049. }
  1050. func (analyser *BurndownAnalysis) groupSparseHistory(history sparseHistory) DenseHistory {
  1051. var days []int
  1052. for day := range history {
  1053. days = append(days, day)
  1054. }
  1055. sort.Ints(days)
  1056. // [y][x]
  1057. // y - sampling
  1058. // x - granularity
  1059. maxDay := days[len(days)-1]
  1060. samples := maxDay / analyser.Sampling
  1061. if (samples + 1) * analyser.Sampling - 1 != maxDay {
  1062. samples++
  1063. }
  1064. bands := maxDay / analyser.Granularity
  1065. if (bands + 1) * analyser.Granularity - 1 != maxDay {
  1066. bands++
  1067. }
  1068. result := make(DenseHistory, samples)
  1069. for i := 0; i < bands; i++ {
  1070. result[i] = make([]int64, bands)
  1071. }
  1072. prevsi := 0
  1073. for _, day := range days {
  1074. si := day / analyser.Sampling
  1075. if si > prevsi {
  1076. state := result[prevsi]
  1077. for i := prevsi + 1; i <= si; i++ {
  1078. copy(result[i], state)
  1079. }
  1080. prevsi = si
  1081. }
  1082. sample := result[si]
  1083. for bday, value := range history[day] {
  1084. sample[bday / analyser.Granularity] += value
  1085. }
  1086. }
  1087. return result
  1088. }
  1089. func init() {
  1090. core.Registry.Register(&BurndownAnalysis{})
  1091. }