forked from se-sic/coronet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util-split.R
1180 lines (1036 loc) · 55.2 KB
/
util-split.R
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
## This file is part of coronet, which is free software: you
## can redistribute it and/or modify it under the terms of the GNU General
## Public License as published by the Free Software Foundation, version 2.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
##
## Copyright 2017-2018 by Claus Hunsen <[email protected]>
## Copyright 2017 by Sofie Kemper <[email protected]>
## Copyright 2017 by Raphael Nömmer <[email protected]>
## Copyright 2017-2018 by Christian Hechtl <[email protected]>
## Copyright 2020 by Christian Hechtl <[email protected]>
## Copyright 2017 by Felix Prasse <[email protected]>
## Copyright 2017-2018 by Thomas Bock <[email protected]>
## Copyright 2020 by Thomas Bock <[email protected]>
## Copyright 2021 by Niklas Schneider <[email protected]>
## Copyright 2021 by Johannes Hostert <[email protected]>
## Copyright 2022 by Jonathan Baumann <[email protected]>
## All Rights Reserved.
## / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
## Libraries ---------------------------------------------------------------
requireNamespace("igraph") # networks
requireNamespace("logging") # for logging
requireNamespace("parallel") # for parallel computation
requireNamespace("lubridate") # for date conversion
## / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
## Split data --------------------------------------------------------------
#' Split project data in time-based ranges as specified
#'
#' Important: For given 'time.period' parameters (e.g., 3-month windows), the last bin may be a lot smaller
#' than the specified time period.
#'
#' @param project.data the *Data object from which the data is retrieved
#' @param time.period the time period describing the length of the ranges, a character string,
#' e.g., "3 mins" or "15 days" [default: "3 months"]
#' @param bins the date objects defining the start of ranges (the last date defines the end of the last range, in an
#' *exclusive* manner). If set, the \code{time.period} parameter is ignored; consequently, \code{split.basis} and
#' \code{sliding.window} do not make sense then either. [default: NULL]
#' @param number.windows the number of consecutive data objects to get from this function, implying equally
#' time-sized windows for all ranges. If set, the \code{time.period} and \code{bins} parameters are ignored;
#' consequently, \code{sliding.window} does not make sense then either.
#' [default: NULL]
#' @param split.basis the data name to use as the basis for split bins, either 'commits', 'mails', or 'issues'
#' [default: "commits"]
#' @param sliding.window logical indicating whether the splitting should be performed using a sliding-window approach
#' [default: FALSE]
#' @param project.conf.new the new project config to construct the \code{RangeData} objects.
#' If \code{NULL}, a clone of \code{project.data$get.project.conf()} will be used.
#' [default: NULL]
#'
#' @return the list of RangeData objects, each referring to one time period
split.data.time.based = function(project.data, time.period = "3 months", bins = NULL,
number.windows = NULL, split.basis = c("commits", "mails", "issues"),
sliding.window = FALSE, project.conf.new = NULL) {
## get basis for splitting process
split.basis = match.arg(split.basis)
## if the data used by the split basis is not present, load it automatically
if (!(split.basis %in% project.data$get.cached.data.sources("only.unfiltered"))) {
function.name = DATASOURCE.TO.UNFILTERED.ARTIFACT.FUNCTION[[split.basis]]
project.data[[function.name]]()
}
## get actual raw data
data.to.split = project.data$get.cached.data.sources("only.unfiltered")
data = lapply(data.to.split, function(ds) {
## build the name of the respective getter and call it
function.name = DATASOURCE.TO.UNFILTERED.ARTIFACT.FUNCTION[[ds]]
return(project.data[[function.name]]())
})
names(data) = data.to.split
## load available additional data sources
additional.data.sources = project.data$get.cached.data.sources("only.additional")
additional.data = lapply(additional.data.sources, function(ds) {
## build the name of the respective getter and call it
function.name = DATASOURCE.TO.ADDITIONAL.ARTIFACT.FUNCTION[[ds]]
return(project.data[[function.name]]())
})
names(additional.data) = additional.data.sources
## number of windows given (ignoring time period and bins)
if (!is.null(number.windows)) {
## reset bins for the later algorithm
bins = NULL
## remove sliding windows
sliding.window = FALSE
}
## if bins are NOT given explicitly
if (is.null(bins)) {
## get bins based on split.basis
bins = split.get.bins.time.based(data[[split.basis]][["date"]], time.period, number.windows)$bins
bins.labels = head(bins, -1)
split.by.bins = FALSE
## logging
logging::loginfo("Splitting data '%s' into time ranges of %s based on '%s' data.",
project.data$get.class.name(), time.period, split.basis)
}
## when bins are given explicitly
else {
## remove sliding windows
sliding.window = FALSE
## get bins based on parameter
split.basis = NULL
bins = get.date.from.string(bins)
bins = get.date.string(bins)
bins.labels = head(bins, -1)
split.by.bins = TRUE
## logging
logging::loginfo("Splitting data '%s' into time ranges [%s].",
project.data$get.class.name(), paste(bins, collapse = ", "))
}
bins.date = get.date.from.string(bins)
## construct ranges
bins.ranges = construct.ranges(bins)
names(bins.ranges) = bins.ranges
if ((length(bins.ranges) <= 1) && sliding.window) {
logging::logwarn("Sliding-window approach does not apply for one range or less.")
sliding.window = FALSE
}
if (is.null(project.conf.new)) {
## Clone the project configuration, so that splitting repeatedly does not interfere
## with the same configuration.
project.conf.new = project.data$get.project.conf()$clone()
}
if (!sliding.window) {
## split data
data.split = parallel::mclapply(data.to.split, function(df.name) {
logging::logdebug("Splitting %s.", df.name)
## identify bins for data
df = data[[df.name]]
df.bins = findInterval(df[["date"]], bins.date, all.inside = FALSE)
## split data according to df.bins
df.split = split(df, df.bins)
## add proper labels/names
names(df.split) = sapply(as.integer(names(df.split)), function(bin) bins[bin])
return(df.split)
})
## set the names to the data sources obtained earlier
names(data.split) = data.to.split
## re-arrange data to get the proper list of data per range
logging::logdebug("Re-arranging data.")
data.split = parallel::mclapply(bins.labels, function(bin) lapply(data.split, `[[`, bin))
names(data.split) = bins.ranges
## adapt project configuration
project.conf.new$set.revisions(bins, bins.date)
## construct RangeData objects
logging::logdebug("Constructing RangeData objects.")
cf.data = parallel::mclapply(bins.ranges, function(range) {
logging::logdebug("Constructing data for range %s.", range)
## construct object for current range
cf.range.data = RangeData$new(project.conf.new, range)
## get data for current range
df.list = data.split[[range]]
## set main data sources: commits, mails, issues
for (data.source in data.to.split) {
setter.name = sprintf("set.%s", data.source)
cf.range.data[[setter.name]](df.list[[data.source]])
}
## set additional data sources: authors, commit.messages, pasta, synchronicity
for (data.source in additional.data.sources) {
setter.name = sprintf("set.%s", data.source)
cf.range.data[[setter.name]](additional.data[[data.source]])
}
return(cf.range.data)
})
} else {
## perform different steps for sliding-window approach
ranges = construct.overlapping.ranges(start = min(bins.date), end = max(bins.date),
time.period = time.period, overlap = 0.5, raw = FALSE,
include.end.date = FALSE) # bins have already been prepared correctly
bins.info = construct.overlapping.ranges(start = min(bins.date), end = max(bins.date),
time.period = time.period, overlap = 0.5, raw = TRUE,
include.end.date = FALSE) # bins have already been prepared correctly
bins.date = sort(unname(unique(get.date.from.unix.timestamp(unlist(bins.info)))))
bins = get.date.string(bins.date)
logging::loginfo("Splitting data '%s' into time ranges using sliding windows [%s].",
project.data$get.class.name(), ranges)
cf.data = split.data.time.based.by.ranges(project.data, ranges)
## update project configuration
project.conf.new$set.revisions(bins, bins.date, sliding.window = TRUE)
for (cf in cf.data) {
## re-set project configuration due to object duplication
cf.conf = cf$set.project.conf(project.conf.new)
}
}
## add splitting information to project configuration
project.conf.new$set.splitting.info(
type = "time-based",
length = if (split.by.bins) {
bins
}
else {
if (!is.null(number.windows)) {
as.character(lubridate::as.period(
get.time.period.by.amount(
min(data[[split.basis]][["date"]]),
max(data[[split.basis]][["date"]]),
number.windows
)
))
}
else time.period
},
basis = split.basis,
sliding.window = sliding.window,
revisions = bins,
revisions.dates = bins.date
)
## set bin attribute
attr(cf.data, "bins") = bins.date
## return list of RangeData objects
return(cf.data)
}
#' Split project data by timestamps
#'
#' Splits project data into ranges, where the first range starts with the first timestamp
#' and the last range ends with the last timestamp.
#'
#' If timestamps are not provided, the custom event timestamps in \code{project.data} are
#' used instead.
#'
#' @param project.data the *Data object from which the data is retrieved
#' @param bins a vector of timestamps [default: NULL]
#' @param project.conf.new the new project config to construct the \code{RangeData} objects.
#' If \code{NULL}, a clone of \code{project.data$get.project.conf()} will be used.
#' [default: NULL]
#'
#' @return the list of RangeData objects, each referring to one time period
split.data.time.based.by.timestamps = function(project.data, bins = NULL, project.conf.new = NULL) {
if (is.null(bins)) { # bins were not provided, use custom timestamps from project
bins = unlist(project.data$get.custom.event.timestamps())
}
return (split.data.time.based(project.data, bins = bins, project.conf.new));
}
#' Split project data in activity-based ranges as specified
#'
#' Important: For a given amount of activity, the last set of data may be a lot smaller
#' than the specified amount.
#'
#' @param project.data the *Data object from which the data is retrieved
#' @param activity.type the type of activity used for splitting, either 'commits', 'mails', or 'issues'
#' [default: "commits"]
#' @param activity.amount the amount of activity describing the size of the ranges, a numeric, further
#' specified by 'activity.type' [default: 5000]
#' @param number.windows the number of consecutive data objects to get from this function
#' (implying an equally distributed amount of data in each range and
#' 'sliding.window = FALSE') [default: NULL]
#' @param sliding.window logical indicating whether the splitting should be performed using a sliding-window approach
#' [default: FALSE]
#' @param project.conf.new the new project config to construct the \code{RangeData} objects.
#' If \code{NULL}, a clone of \code{project.data$get.project.conf()} will be used.
#' [default: NULL]
#'
#' @return the list of RangeData objects, each referring to one time period
split.data.activity.based = function(project.data, activity.type = c("commits", "mails", "issues"),
activity.amount = 5000, number.windows = NULL,
sliding.window = FALSE, project.conf.new = NULL) {
## get basis for splitting process
activity.type = match.arg(activity.type)
## get actual raw data
data.sources = project.data$get.cached.data.sources("only.unfiltered")
data = lapply(data.sources, function(ds) {
## build the name of the respective getter and call it
function.name = DATASOURCE.TO.UNFILTERED.ARTIFACT.FUNCTION[[ds]]
return(project.data[[function.name]]())
})
names(data) = data.sources
## if the data used by the split basis is not present, load it automatically
if (!(activity.type %in% project.data$get.cached.data.sources("only.unfiltered"))) {
function.name = DATASOURCE.TO.UNFILTERED.ARTIFACT.FUNCTION[[activity.type]]
project.data[[function.name]]()
}
## define ID columns for mails and commits
id.column = list(
commits = "hash",
mails = "message.id",
issues = "event.id"
)
## get amount of available activity
activity = length(unique(data[[activity.type]][[ id.column[[activity.type]] ]]))
if (is.null(project.conf.new)) {
## Clone the project configuration, so that splitting repeatedly does not interfere
## with the same configuration.
project.conf.new = project.data$get.project.conf()$clone()
}
## activity amount given (number of windows NOT given)
if (is.null(number.windows)) {
if (activity < 1) {
logging::logerror("The given amount of activity has to be strictly positive (given: %s).", activity)
stop("Stopping due to missing data.")
}
## compute the number of time windows according to the activity amount
number.windows = ceiling(activity / activity.amount)
if (activity < activity.amount) {
activity.type.pretty = list(
commits = "commits",
mails = "mails",
issues = "issue events"
)[[activity.type]]
logging::logwarn("Can not form bins of %s %s for splitting data %s, as there are only %s %s.",
activity.amount, activity.type.pretty, project.data$get.class.name(), activity, activity.type.pretty)
}
}
## number of windows given (ignoring amount of activity)
else {
## check the breaking case
if (number.windows < 1 || number.windows > activity) {
logging::logerror("The given number of windows is not suitable for this
data object (given: %s).", number.windows)
stop("Stopping due to illegally specified amount of windows to create.")
}
## compute the amount of activity according to the number of specified windows
activity.amount = ceiling(activity / number.windows)
## remove sliding windows as they do not make sense here
sliding.window = FALSE
}
logging::loginfo("Splitting data '%s' into activity ranges of %s %s (%s windows).",
project.data$get.class.name(), activity.amount, activity.type, number.windows)
## get bins based on split.basis
logging::logdebug("Getting activity-based bins.")
bins.data = split.get.bins.activity.based(data[[activity.type]], id.column[[activity.type]],
activity.amount, remove.duplicate.bins = TRUE)
bins = bins.data[["bins"]]
bins.date = get.date.from.string(bins)
## split the data based on the extracted timestamps
logging::logdebug("Splitting data based on time windows arising from activity bins.")
cf.data = split.data.time.based(project.data, bins = bins.date, split.basis = activity.type,
project.conf.new = project.conf.new)
## perform additional steps for sliding-window approach:
## for activity-based sliding-window bins to work, we need to crop the data appropriately and,
## then, compute bins on the cropped data
## (only if there is more than one range until here)
if (sliding.window && length(bins.date) <= 2) {
logging::logwarn("Sliding-window approach does not apply for one range or less.")
} else if (sliding.window) {
## get the list of unique items that are used for the bin computation and, thus, also the
## cropping of data
items.unique = unique(data[[activity.type]][[ id.column[[activity.type]] ]])
items.unique.count = length(items.unique)
## offsets used for cropping (half the first/last bin)
offset.start = floor(activity.amount / 2)
offset.end = (items.unique.count - offset.start) %% activity.amount
## cut the data appropriately
if (offset.end > 0) {
items.cut = c(
items.unique[seq_len(offset.start)],
items.unique[seq(from = (items.unique.count - offset.end + 1), to = items.unique.count)]
)
} else {
items.cut = items.unique[seq_len(offset.start)]
}
## determine end bin of last sliding-window range
end.event.id = items.unique[(items.unique.count - offset.end + 1)]
end.event.logical = (data[[activity.type]][[ id.column[[activity.type]] ]] == end.event.id)
end.event.date = unique(data[[activity.type]][end.event.logical, ][["date"]])
## store the data again
data.to.cut = data[[activity.type]][[ id.column[[activity.type]] ]] %in% items.cut
data[[activity.type]] = data[[activity.type]][ !data.to.cut, ]
## clone the project data and update raw data to split it again
project.data.clone = project.data$clone()
project.data.clone$set.commits(data[["commits"]])
project.data.clone$set.mails(data[["mails"]])
project.data.clone$set.issues(data[["issues"]])
## split data for sliding windows
cf.data.sliding = split.data.activity.based(project.data.clone, activity.type = activity.type,
activity.amount = activity.amount, sliding.window = FALSE,
project.conf.new = project.conf.new)
## append data to normally-split data
cf.data = append(cf.data, cf.data.sliding)
## compute bins for sliding windows: pairwise middle between dates
bins.date.middle = attr(cf.data.sliding, "bins")
## sort data object properly by bin starts
bins.ranges.start = c(head(bins.date, -1), head(bins.date.middle, -1))
cf.data = cf.data[ order(bins.ranges.start) ]
## construct proper bin vectors for configuration
bins.date = sort(c(bins.date, bins.date.middle))
bins = get.date.string(bins.date)
## if the last regular range and the last sliding-window range end at the same time
## and the data of the last regular range is contained in the last sliding-window range, then:
## remove the last regular range as it is not complete and we don't loose data when removing it
last.regular.range = cf.data[[length(cf.data)]]
last.sliding.range = cf.data[[length(cf.data) - 1]]
get.activity.data = DATASOURCE.TO.UNFILTERED.ARTIFACT.FUNCTION[[activity.type]]
last.regular.range.ids = (last.regular.range[[get.activity.data]]())[[ id.column[[activity.type]] ]]
last.sliding.range.ids = (last.sliding.range[[get.activity.data]]())[[ id.column[[activity.type]] ]]
if (bins.date[length(bins.date)] == bins.date.middle[length(bins.date.middle)]
&& all(last.regular.range.ids %in% last.sliding.range.ids) ) {
cf.data = cf.data[-length(cf.data)]
bins.date = bins.date[-length(bins.date)]
bins = bins[-length(bins)]
} else if (bins.date[length(bins.date)] != bins.date.middle[length(bins.date.middle)]) {
## adjust the end date of the last sliding-window range, as it might be shorter than it should be:
## The end of the last range usually is one second after the last event (as end dates are exclusive).
## In case of sliding windows, the end of the last sliding range needs to be extended to the date of the
## next event after that range (as end dates are exclusive) to get a full range as for all the previous
## ranges which end at the beginning of the next range, which is the date of the first event after the
## actual range.
## When we have sliding windows, there are, at least, three ranges (two regular ranges and one
## sliding-window range. Hence, there are always more than three elements in the bins vector, so accessing
## bins[length(bins) - 3] cannot throw errors in this case.
name.last.sliding.window = construct.ranges(c(bins[length(bins) - 3], get.date.string(end.event.date)))
names(cf.data)[length(cf.data) - 1] = name.last.sliding.window
bins.date[length(bins.date) - 1] = end.event.date
bins[length(bins) - 1] = get.date.string(end.event.date)
}
## update project configuration
project.conf.new$set.revisions(bins, bins.date, sliding.window = TRUE)
for (cf in cf.data) {
## re-set project configuration due to object duplication
cf.conf = cf$set.project.conf(project.conf.new, reset.environment = FALSE)
}
}
## add splitting information to project configuration
project.conf.new$set.splitting.info(
type = "activity-based",
length = activity.amount,
basis = activity.type,
sliding.window = sliding.window,
revisions = bins,
revisions.dates = bins.date
)
## set bin attribute
attr(cf.data, "bins") = bins.date
return(cf.data)
}
#' Map a list of networks to their corresponding range data, after splitting the
#' given project data (\code{project.data}) to the time ranges given by the networks'
#' names. The splitting can be more specifically configured with the parameter
#' \code{aggregation.level}, see below for more details.
#'
#' For this function to work properly, the list of networks needs to be named with
#' timestamp-ranges, which can be splitted using \code{get.range.bounds}. The easiest
#' way to achieve this is to use one of the \code{split.*} functions in this very file.
#' For example, the time ranges have a format like this:
#' "2017-01-01 23:57:01-2017-02-15 12:19:37", which can be split by the utility
#' function \code{get.range.bounds}, obtaining the range bounds as timestamps.
#'
#' Using different aggregation levels given by the parameter \code{aggregation.level},
#' it is possible to configure the exact treatment of range bounds and, thus, the
#' splitting of the given project data. The various aggregation levels work as follows:
#' - \code{"range"}: The project data will be split exactly to the time ranges specified
#' by the networks' names.
#' - \code{"cumulative"}: The project data will be split exactly to the time ranges
#' specified by the networks' names, but in a cumulative manner.
#' - \code{"all.ranges"}: The project data will be split exactly to the time range
#' specified by the start of the first network and end of the last
#' network. All data instances will contain the same data.
#' - \code{"project.cumulative"}: The same splitting as for \code{"cumulative"}, but all
#' data will start at the beginning of the project data and *not* at
#' the beginning of the first network.
#' - \code{"project.all.ranges"}: The same splitting as for \code{"all.ranges"}, but all
#' data will start at the beginning of the project data and *not* at
#' the beginning of the first network. All data instances will contain
#' the same data.
#' - \code{"complete"}: The same splitting as for \code{"all.ranges"}, but all data will
#' start at the beginning of the project data and end at the end of
#' the project data. All data instances will contain the same data.
#'
#' @param list.of.networks The network list
#' @param project.data The entire project data
#' @param aggregation.level One of \code{"range"}, \code{"cumulative"}, \code{"all.ranges"},
#' \code{"project.cumulative"}, \code{"project.all.ranges"}, and
#' \code{"complete"}. See above for more details. [default: "range"]
#'
#' @return A list containing tuples with the keys "network" and "data", where, under "network", are
#' the respective networks passed via \code{list.of.networks} and, under "data", are the
#' split data instances of type \code{RangeData}.
#'
#' @seealso \code{aggregate.ranges}
split.data.by.networks = function(list.of.networks, project.data,
aggregation.level = c("range", "cumulative", "all.ranges",
"project.cumulative", "project.all.ranges",
"complete")) {
## get the chosen aggregation level
aggregation.level = match.arg.or.default(aggregation.level, default = "range")
## get the timestamp data from the project data (needed for some aggr. levels)
project.timestamps = project.data$get.data.timestamps(outermost = TRUE)
## get the list of ranges
list.of.ranges = names(list.of.networks)
## aggregate ranges
ranges.bounds = aggregate.ranges(
list.of.ranges, project.start = project.timestamps[["start"]], project.end = project.timestamps[["end"]],
aggregation.level = aggregation.level, raw = TRUE
)
## split the data by the computed (and aggregated) ranges
list.of.data = split.data.time.based.by.ranges(project.data, ranges.bounds)
## zip networks and range data
net.to.range.list = mapply(
list.of.networks, list.of.data, SIMPLIFY = FALSE,
FUN = function(net, range.data) {
net.to.range.entry = list(
"network" = net,
"data" = range.data
)
return(net.to.range.entry)
}
)
## properly set names for the result list
names(net.to.range.list) = list.of.ranges
return(net.to.range.list)
}
#' Split the given data to the given ranges and return the resulting list.
#'
#' Note: You may want to use any function \code{construct.*.ranges} to obtain
#' an appropriate sequence of ranges to pass to this function.
#'
#' @param project.data the \code{ProjectData} instance to be split
#' @param ranges the ranges to be used for splitting
#'
#' @return a list of \code{RangeData} instances, each representing one of the
#' given ranges; the ranges are used as names for the list
split.data.time.based.by.ranges = function(project.data, ranges) {
## check whether all ranges are identical (then we only need to split the data once)
if (length(ranges) > 1 && length(unique(ranges)) == 1) {
## aggregate range
range.bounds = get.range.bounds(ranges[[1]])
## split data accordingly
range.data = split.data.time.based(project.data, bins = range.bounds, sliding.window = FALSE)[[1]]
## clone range data objects (as all ranges are identical)
data.split = lapply(ranges, function(x) range.data$clone())
} else {
## aggregate ranges
ranges.bounds = lapply(ranges, get.range.bounds)
## loop over all ranges and split the data accordingly:
data.split = mapply(ranges, ranges.bounds, SIMPLIFY = FALSE, FUN = function(range, start.end) {
## 1) split the data to the current range
range.data = split.data.time.based(project.data, bins = start.end, sliding.window = FALSE)[[1]]
## 2) return the data
return (range.data)
})
}
return(data.split)
}
## / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
## Split networks ----------------------------------------------------------
#' Discretizes a network (using the edge attribute "date") according to the given 'time.period',
#' to the given hard 'bins', or the given number of windows ('number.windows').
#'
#' Important: For given 'time.period' parameters (e.g., 3-month windows), the last bin may be a lot smaller
#' than the specified time period.
#'
#' Important notice: This function only works for unsimplified networks, where no edges have been
#' contracted, which would combine edge attributes, especially the "date" attribute.
#'
#' @param network the igraph network to split, needs to have an edge attribute named "date"
#' @param time.period the time period describing the length of the ranges, a character string,
#' e.g., "3 mins" or "15 days" [default: "3 months"]
#' @param bins the date objects defining the start of ranges (the last date defines the end of the last range, in an
#' *exclusive* manner). If set, the 'time.period' and 'sliding.window' parameters are ignored.
#' [default: NULL]
#' @param number.windows the number of consecutive networks to get from this function, implying equally
#' time-sized windows for all ranges. If set, the 'time.period' and 'bins' parameters are ignored;
#' consequently, 'sliding.window' does not make sense then either.
#' [default: NULL]
#' @param sliding.window logical indicating whether the splitting should be performed using a sliding-window approach
#' [default: FALSE]
#' @param remove.isolates whether to remove isolates in the resulting split networks [default: TRUE]
#'
#' @return a list of igraph networks, each referring to one time period
split.network.time.based = function(network, time.period = "3 months", bins = NULL,
number.windows = NULL, sliding.window = FALSE,
remove.isolates = TRUE) {
## extract date attributes from edges
dates = get.date.from.unix.timestamp(igraph::get.edge.attribute(network, "date"))
## number of windows given (ignoring time period and bins)
if (!is.null(number.windows)) {
## reset bins for the later algorithm
bins = NULL
## ignore sliding windows
sliding.window = FALSE
}
## get bin information for all edges
if (is.null(bins)) {
## get bins
bins.info = split.get.bins.time.based(dates, time.period, number.windows)
bins.vector = bins.info[["vector"]]
bins.date = get.date.from.string(bins.info[["bins"]])
bins = head(bins.info[["bins"]], -1)
} else {
## specific bins are given, do not use sliding windows
sliding.window = FALSE
## find bins for dates
bins.date = get.date.from.string(bins)
bins.vector = findInterval(dates, bins.date, all.inside = FALSE)
bins = seq_len(length(bins.date) - 1) # the last item just closes the last bin
}
## perform additional steps for sliding-window approach
if (sliding.window) {
ranges = construct.overlapping.ranges(start = min(bins.date), end = max(bins.date),
time.period = time.period, overlap = 0.5, raw = FALSE,
include.end.date = FALSE) # bins have already been prepared correctly
bins.info = construct.overlapping.ranges(start = min(bins.date), end = max(bins.date),
time.period = time.period, overlap = 0.5, raw = TRUE,
include.end.date = FALSE) # bins have already been prepared correctly
bins.date = sort(unname(unique(get.date.from.unix.timestamp(unlist(bins.info)))))
logging::loginfo("Splitting network into time ranges [%s].",
paste(ranges, collapse = ", "))
nets = split.network.time.based.by.ranges(network, ranges, remove.isolates)
} else {
logging::loginfo("Splitting network into bins [%s].",
paste(bins.date, collapse = ", "))
nets = split.network.by.bins(network, bins, bins.vector, remove.isolates)
}
## set bin attribute
attr(nets, "bins") = bins.date
## set ranges as names
revs = get.date.string(bins.date)
names(nets) = construct.ranges(revs, sliding.window = sliding.window)
return(nets)
}
#' Discretizes a list of networks (using the edge attribute "date") according to the given 'time.period',
#' using the very same bins for all networks. The procedure is as follows:
#' 1) Use the earliest timestamp of all networks and the latest timestamp of all networks
#' to compute the bins for splitting.
#' 2) All networks are then split using the computed and, thus, very same bins using the
#' function \code{split.network.time.based}.
#' 3) The list of split networks is returned.
#'
#' For further information, see the documentation of \code{split.network.time.based}.
#'
#' Important notice: This function only works for unsimplified networks, where no edges have been
#' contracted, which would combine edge attributes, especially the "date" attribute.
#'
#' @param networks the igraph networks to split, needs to have an edge attribute named "date"
#' @param time.period the time period describing the length of the ranges, a character string,
#' e.g., "3 mins" or "15 days" [default: "3 months"]
#' @param bins the date objects defining the start of ranges (the last date defines the end of the last range, in an
#' *exclusive* manner). If set, the 'time.period' and 'sliding.window' parameters are ignored.
#' [default: NULL]
#' @param number.windows the number of consecutive networks to get for each network, implying equally
#' time-sized windows for all ranges. If set, the 'time.period' and 'bins' parameters are ignored;
#' consequently, 'sliding.window' does not make sense then either.
#' [default: NULL]
#' @param sliding.window logical indicating whether the splitting should be performed using a sliding-window approach
#' [default: FALSE]
#' @param remove.isolates whether to remove isolates in the resulting split networks [default: TRUE]
#'
#' @return a list of network-splitting results (of length \code{length(networks)}), each item referring to a list
#' of networks, each itself referring to one time period
split.networks.time.based = function(networks, time.period = "3 months", bins = NULL,
number.windows = NULL, sliding.window = FALSE,
remove.isolates = TRUE) {
## number of windows given (ignoring time period and bins)
if (!is.null(number.windows)) {
## reset bins for the later algorithm
bins = NULL
## ignore sliding windows
sliding.window = FALSE
}
if (is.null(bins)) {
## get base network and obtain splitting information:
## 1) extract date attributes from edges
networks.dates = lapply(networks, function(net) {
dates = igraph::E(net)$date
return(dates)
})
dates = unlist(networks.dates, recursive = FALSE)
dates = get.date.from.unix.timestamp(dates)
## 2) get bin information
if (sliding.window) {
ranges = construct.overlapping.ranges(start = min(dates), end = max(dates),
time.period = time.period, overlap = 0.5, raw = FALSE,
include.end.date = TRUE)
bins.info = construct.overlapping.ranges(start = min(dates), end = max(dates),
time.period = time.period, overlap = 0.5, raw = TRUE,
include.end.date = TRUE)
bins.date = sort(unname(unique(get.date.from.unix.timestamp(unlist(bins.info)))))
} else {
bins.info = split.get.bins.time.based(dates, time.period, number.windows)
bins.date = get.date.from.string(bins.info[["bins"]])
}
} else {
## specific bins are given, do not use sliding windows
sliding.window = FALSE
## set the bins to use
bins.date = bins
}
## split all networks to the extracted bins
networks.split = lapply(networks, function(net) {
if (sliding.window) {
nets = split.network.time.based.by.ranges(network = net, ranges = ranges,
remove.isolates = remove.isolates)
attr(nets, "bins") = bins.date
} else {
nets = split.network.time.based(network = net, bins = bins.date, sliding.window = sliding.window,
remove.isolates = remove.isolates)
}
return(nets)
})
## return the split networks
return(networks.split)
}
#' Discretizes a network according to the given 'number.edges' or by a predefined 'number.windows'.
#'
#' Important: For a given amount of edges, the last set of data may be a lot smaller
#' than the specified amount.
#'
#' Important notice: This function only works for unsimplified networks, where no edges have been
#' contracted, which would combine edge attributes, especially the "date" attribute.
#'
#' @param network the igraph network to split
#' @param number.edges the amount of edges describing the size of the ranges
#' (implying an open number of resulting ranges) [default: 5000]
#' @param number.windows the number of consecutive networks to get from this function
#' (implying an equally distributed amount of edges in each range and
#' 'sliding.window = FALSE) [default: NULL]
#' @param sliding.window logical indicating whether the splitting should be performed using
#' a sliding-window approach [default: FALSE]
#' @param remove.isolates whether to remove isolates in the resulting split networks [default: TRUE]
#'
#' @return a list of igraph networks, each referring to one period of activity
split.network.activity.based = function(network, number.edges = 5000, number.windows = NULL,
sliding.window = FALSE, remove.isolates = TRUE) {
## get total edge count
edge.count = igraph::ecount(network)
## number of edges given (number of windows NOT given)
if (is.null(number.windows)) {
if (edge.count < 1) {
logging::logerror("The number of edges in the given network has to be
strictly positive (given: %s).", edge.count)
stop("Stopping due to missing edges in given network.")
}
## compute the number of time windows according to the number of edges per network
number.windows = ceiling(edge.count / number.edges)
}
## number of windows given (ignoring number of edges)
else {
## check the breaking case
if (number.windows < 1 || number.windows > edge.count) {
logging::logerror("The given number of windows is not suitable for this
network (given: %s).", number.windows)
stop("Stopping due to illegally specified amount of windows to create.")
}
## compute the amount of activity according to the number of specified windows
number.edges = ceiling(edge.count / number.windows)
## remove sliding windows as they do not make sense here
sliding.window = FALSE
}
logging::loginfo("Splitting network into activity ranges of %s edges, yielding %s windows.",
number.edges, number.windows)
## get dates in a data.frame for splitting purposes
df = data.frame(
date = get.date.from.unix.timestamp(igraph::get.edge.attribute(network, "date")),
my.unique.id = seq_len(edge.count) # as a unique identifier only
)
## sort by date
df = df[ with(df, order(date)), ]
## identify bins
logging::logdebug("Getting bins for activity-based splitting based on amount of edges.")
bins.data = split.get.bins.activity.based(df, "my.unique.id", activity.amount = number.edges,
remove.duplicate.bins = FALSE)
bins.date = bins.data[["bins"]]
bins.vector = bins.data[["vector"]]
bins.vector = bins.vector[ with(df, order(my.unique.id)) ] # re-order to get igraph ordering
bins = sort(unique(bins.vector))
## split network by bins
networks = split.network.by.bins(network, bins, bins.vector, remove.isolates)
if (number.edges >= edge.count) {
logging::logwarn("Sliding-window approach does not apply: not enough edges (%s) for number of edges %s",
edge.count, number.edges)
sliding.window = FALSE
}
## perform additional steps for sliding-window approach
## for activity-based sliding-window bins to work, we need to crop edges appropriately and,
## then, compute bins on the cropped networks
if (sliding.window) {
## get edge ids ordered by date
edges.by.date = df[["my.unique.id"]]
## offsets used for cropping (half the first/last bin)
offset.start = floor(number.edges / 2)
offset.end = (edge.count - offset.start) %% number.edges
## cut the data appropriately
if (offset.end > 0) {
edges.cut = c(
edges.by.date[seq_len(offset.start)],
edges.by.date[seq(from = (edge.count - offset.end + 1), to = edge.count)]
)
} else {
edges.cut = edges.by.date[seq_len(offset.start)]
}
## delete edges from the network and create a new network
network.cut = igraph::delete.edges(network, igraph::E(network)[edges.cut])
## split network for sliding windows
networks.sliding = split.network.activity.based(network.cut, number.edges = number.edges,
sliding.window = FALSE)
## append data to normally-split data
networks = append(networks, networks.sliding)
## compute bins for sliding windows: pairwise middle between dates
bins.date.middle = attr(networks.sliding, "bins")
## sort data object properly by bin starts
bins.ranges.start = c(head(bins.date, -1), head(bins.date.middle, -1))
networks = networks[ order(bins.ranges.start) ]
## construct proper bin vectors for configuration
bins.date = sort(c(bins.date, bins.date.middle))
## if the last regular range and the last sliding-window range end at the same time
## and the latter contains the former's edges, then:
## remove the last regular range as it is not complete and we don't loose data when removing it
edges.last.regular = igraph::E(networks[[length(networks)]])
edges.last.sliding = igraph::E(networks[[length(networks) - 1]])
if (bins.date[length(bins.date)] == bins.date.middle[length(bins.date.middle)]
&& all(edges.last.regular %in% edges.last.sliding)
&& table(edges.last.regular$date) %in% table(edges.last.sliding$date) ) {
networks = networks[-length(networks)]
bins.date = bins.date[-length(bins.date)]
bins = bins[-length(bins)]
}
}
## set bin attribute
attr(networks, "bins") = bins.date
## set ranges as names
revs = get.date.string(bins.date)
names(networks) = construct.ranges(revs, sliding.window = sliding.window)
## issue warning if ranges are not unique
if (any(duplicated(names(networks)))) {
logging::logwarn(
paste("Due to the splitting, there are duplicated range names.",
"You can correct these by calling the function 'split.unify.range.names()'",
"and providing the range names.")
)
}
return(networks)
}
#' Split the given network to the given ranges and return the resulting list.
#'
#' Note: You may want to use any function \code{construct.*.ranges} to obtain
#' an appropriate sequence of ranges to pass to this function.
#'
#' @param network the network to be split
#' @param ranges the ranges to be used for splitting
#' @param remove.isolates whether to remove isolates in the resulting split networks [default: TRUE]
#'
#' @return a list of networks, each representing one of the given ranges; the
#' ranges are used as names for the list
split.network.time.based.by.ranges = function(network, ranges, remove.isolates = TRUE) {
## aggregate ranges
ranges.bounds = lapply(ranges, get.range.bounds)
## loop over all ranges and split the network accordingly:
nets.split = mapply(
ranges, ranges.bounds, SIMPLIFY = FALSE,
FUN = function(range, start.end) {
## 1) split the network to the current range
range.net = split.network.time.based(network, bins = start.end, sliding.window = FALSE,
remove.isolates = remove.isolates)[[1]]
## 2) return the network
return (range.net)
}
)
return(nets.split)
}
## / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
## Split raw data ----------------------------------------------------------
#' Split the given data by the given bins.
#'
#' @param df a data.frame to be split
#' @param bins a vector with the length of 'nrow(df)' assigning a bin for each row of 'df'
#'
#' @return a list of data.frames, with the length of 'unique(bins)'
split.data.by.bins = function(df, bins) {
logging::logdebug("split.data.by.bins: starting.")
df.split = split(df, bins)
logging::logdebug("split.data.by.bins: finished.")
return(df.split)
}
#' Split the given data by the given bins, in increasing order of the bin identifiers.
#'
#' @param network a network
#' @param bins a vector with the unique bin identifiers, describing the order in which the bins are created
#' @param bins.vector a vector of length 'ecount(network)' assigning a bin for each edge of 'network'
#' @param remove.isolates whether to remove isolates in the resulting split networks [default: TRUE]
#'
#' @return a list of networks, with the length of 'unique(bins.vector)'
split.network.by.bins = function(network, bins, bins.vector, remove.isolates = TRUE) {
logging::logdebug("split.network.by.bins: starting.")
## create a network for each bin of edges
nets = parallel::mclapply(bins, function(bin) {