-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataframe_index_date.f90
More file actions
1504 lines (1340 loc) · 47.2 KB
/
Copy pathdataframe_index_date.f90
File metadata and controls
1504 lines (1340 loc) · 47.2 KB
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
module dataframe_index_date_mod
use kind_mod, only: dp
use util_mod, only: default, split_string, seq, cbind
use iso_fortran_env, only: output_unit
use date_mod
use df_index_date_ops_mod, only: findloc_index, argsort_index, union_index, &
intersect_index, is_sorted_index_array, is_unique_index_array, &
bsearch_exact_index, bsearch_ffill_index, bsearch_bfill_index
use, intrinsic :: ieee_arithmetic, only: ieee_value, ieee_quiet_nan, ieee_is_nan
implicit none
private
public :: DataFrame_index_date, nrow, ncol, print_summary, random, operator(*), &
operator(/), operator(+), operator(-), display, allocate_df, &
operator(**), shape, subset_stride
integer, parameter :: nlen_columns = 100, nrows_print = 10 ! number of rows to print by default.
logical, save :: blank_line_before_display = .true.
interface display
module procedure display_data
end interface display
interface operator (*)
module procedure mult_x_df, mult_df_x, mult_n_df, mult_df_n
module procedure mult_df_df
end interface
interface operator (/)
module procedure div_df_x, div_df_n, div_x_df, div_n_df
module procedure div_df_df
end interface
interface operator (+)
module procedure add_x_df, add_df_x, add_n_df, add_df_n
module procedure add_df_df
end interface
interface operator (-)
module procedure subtract_x_df, subtract_df_x, &
subtract_n_df, subtract_df_n, subtract_df_df
end interface
interface operator (**)
module procedure power_df_n, power_df_x
end interface
type :: DataFrame_index_date
type(date), allocatable :: index(:)
character(len=nlen_columns), allocatable :: columns(:)
real(kind=dp), allocatable :: values(:,:)
contains
procedure :: read_csv, display=>display_data, write_csv, irow, icol, &
loc, append_col, append_cols, set_col, col_pos, row_pos, &
sort_index, is_sorted_index, is_unique_index, at, iat, &
set_at, set_iat, has_col, has_idx, drop_cols, drop_rows, &
rename_cols, where_cols, filter_cols, where, filter, iloc, &
select, add, subtract, multiply, divide, reindex, shift, &
pct_change, log_change, resample, keep_rows
end type DataFrame_index_date
contains
function resample(self) result(df_new)
! return a dataframe with rows sampled with replacement, keeping the original index
class(DataFrame_index_date), intent(in) :: self
type(DataFrame_index_date) :: df_new
integer :: i, n
real(kind=dp) :: u
integer, allocatable :: indices(:)
n = nrow(self)
allocate(indices(n))
do i = 1, n
call random_number(u)
indices(i) = int(u * n) + 1
end do
df_new = DataFrame_index_date(index=self%index, columns=self%columns, values=self%values(indices, :))
end function resample
function keep_rows(self, n, latest) result(df_new)
! Return a dataframe with at most n rows.
! If latest=.true. (default), keep the last n rows.
! If latest=.false., keep the first n rows.
! If n >= nrow(self) or n <= 0 the full dataframe is returned unchanged.
class(DataFrame_index_date), intent(in) :: self
integer, intent(in) :: n
logical, intent(in), optional :: latest
type(DataFrame_index_date) :: df_new
integer :: total, i0, i
logical :: from_end
integer, allocatable :: rows(:)
from_end = .true.
if (present(latest)) from_end = latest
total = nrow(self)
if (n <= 0 .or. n >= total) then
df_new = self%iloc()
return
end if
if (from_end) then
i0 = total - n + 1 ! first row to keep
else
i0 = 1
end if
rows = [(i0 + i - 1, i = 1, n)]
df_new = self%iloc(rows=rows)
end function keep_rows
pure function shape(df) result(ishape)
! return a 2-element array with the number of rows and columns of the dataframe
type(DataFrame_index_date), intent(in) :: df
integer :: ishape(2)
ishape = [nrow(df), ncol(df)]
end function shape
pure function icol(df, ivec) result(df_new)
! returns a dataframe with the subset of columns in ivec(:)
class(DataFrame_index_date), intent(in) :: df
integer, intent(in) :: ivec(:)
type(DataFrame_index_date) :: df_new
df_new = DataFrame_index_date(index=df%index, columns=df%columns(ivec), values=df%values(:, ivec))
end function icol
pure function loc(df, rows, columns) result(df_new)
! return a subset of a dataframe with the specified rows (index values) and columns
class(DataFrame_index_date), intent(in) :: df
type(date), intent(in), optional :: rows(:)
character (len=*), intent(in), optional :: columns(:)
type(DataFrame_index_date) :: df_new
type(date), allocatable :: rows_(:)
character (len=nlen_columns), allocatable :: columns_(:)
integer :: i
integer, allocatable :: jrow(:), jcol(:)
if (present(rows)) then
rows_ = rows
allocate (jrow(size(rows)))
do i=1,size(rows)
jrow(i) = findloc_index(df%index, rows(i))
end do
else
rows_ = df%index
jrow = seq(1, nrow(df))
end if
if (present(columns)) then
columns_ = columns
allocate(jcol(size(columns)))
do i=1,size(columns)
jcol(i) = findloc(df%columns, columns(i), dim=1)
end do
else
columns_ = df%columns
jcol = seq(1, ncol(df))
end if
df_new = DataFrame_index_date(index=rows_, columns=columns_, values=df%values(jrow, jcol))
end function loc
pure function row_pos(self, idx, assume_sorted, ascending) result(irow)
! return the row position (1..nrow) for index value idx
! if assume_sorted is true, use binary search assuming index is sorted
class(DataFrame_index_date), intent(in) :: self
type(date), intent(in) :: idx
logical, intent(in), optional :: assume_sorted, ascending
integer :: irow
logical :: do_sorted, asc
integer :: lo, hi, mid
do_sorted = default(.false., assume_sorted)
asc = default(.true., ascending)
if (.not. allocated(self%index)) error stop "in row_pos, index is not allocated"
if (do_sorted) then
! binary search for first occurrence (like findloc) in a sorted index
lo = 1
hi = size(self%index)
irow = 0
do while (lo <= hi)
mid = (lo + hi) / 2
if (asc) then
if (self%index(mid) < idx) then
lo = mid + 1
else
if (self%index(mid) == idx) irow = mid
hi = mid - 1
end if
else
if (self%index(mid) > idx) then
lo = mid + 1
else
if (self%index(mid) == idx) irow = mid
hi = mid - 1
end if
end if
end do
else
irow = findloc_index(self%index, idx)
end if
if (irow == 0) error stop "in row_pos, index not found"
end function row_pos
function is_sorted_index(self, ascending) result(is_sorted)
! return true if index is sorted (nondecreasing if ascending, nonincreasing otherwise)
class(DataFrame_index_date), intent(in) :: self
logical, intent(in), optional :: ascending
logical :: is_sorted
logical :: asc
integer :: i, n
asc = default(.true., ascending)
if (.not. allocated(self%index)) then
is_sorted = .true.
return
end if
n = size(self%index)
is_sorted = .true.
if (n <= 1) return
if (asc) then
do i=2,n
if (self%index(i) < self%index(i-1)) then
is_sorted = .false.
exit
end if
end do
else
do i=2,n
if (self%index(i) > self%index(i-1)) then
is_sorted = .false.
exit
end if
end do
end if
end function is_sorted_index
function is_unique_index(self) result(is_unique)
! return true if index has no duplicates
class(DataFrame_index_date), intent(in) :: self
logical :: is_unique
if (.not. allocated(self%index)) then
is_unique = .true.
return
end if
is_unique = is_unique_index_array(self%index)
end function is_unique_index
subroutine sort_index(self, ascending)
! sort rows by index, permuting values accordingly
class(DataFrame_index_date), intent(inout) :: self
logical, intent(in), optional :: ascending
logical :: asc
integer :: n
integer, allocatable :: perm(:)
real(kind=dp), allocatable :: vtmp(:,:)
asc = default(.true., ascending)
if (.not. allocated(self%index)) return
if (.not. allocated(self%values)) return
n = size(self%index)
if (n <= 1) return
call argsort_index(self%index, perm, ascending=asc)
! reorder index
self%index = self%index(perm)
! reorder values
allocate(vtmp(n, size(self%values,2)))
vtmp = self%values(perm, :)
self%values = vtmp
deallocate(vtmp, perm)
end subroutine sort_index
pure function col_pos(self, column) result(jcol)
! return the column position (1..ncol) for column name
class(DataFrame_index_date), intent(in) :: self
character(len=*), intent(in) :: column
integer :: jcol
jcol = findloc(self%columns, column, dim=1)
if (jcol == 0) error stop "in col_pos, column not found: " // trim(column)
end function col_pos
pure function iat(self, i, j) result(x)
! return a scalar element by 1-based row/column positions
class(DataFrame_index_date), intent(in) :: self
integer, intent(in) :: i, j
real(kind=dp) :: x
if (i < 1 .or. i > nrow(self)) error stop "in iat, row position out of range"
if (j < 1 .or. j > ncol(self)) error stop "in iat, column position out of range"
x = self%values(i, j)
end function iat
pure function at(self, idx, column) result(x)
! return a scalar element by index value and column name
class(DataFrame_index_date), intent(in) :: self
type(date), intent(in) :: idx
character(len=*), intent(in) :: column
real(kind=dp) :: x
integer :: i, j
i = self%row_pos(idx)
j = self%col_pos(column)
x = self%values(i, j)
end function at
pure subroutine set_iat(self, i, j, x)
! set a scalar element by 1-based row/column positions
class(DataFrame_index_date), intent(in out) :: self
integer, intent(in) :: i, j
real(kind=dp), intent(in) :: x
if (i < 1 .or. i > nrow(self)) error stop "in set_iat, row position out of range"
if (j < 1 .or. j > ncol(self)) error stop "in set_iat, column position out of range"
self%values(i, j) = x
end subroutine set_iat
pure subroutine set_at(self, idx, column, x)
! set a scalar element by index value and column name
class(DataFrame_index_date), intent(in out) :: self
type(date), intent(in) :: idx
character(len=*), intent(in) :: column
real(kind=dp), intent(in) :: x
integer :: i, j
i = self%row_pos(idx)
j = self%col_pos(column)
self%values(i, j) = x
end subroutine set_at
logical function has_col(self, name)
! return .true. if dataframe has a column with the given name
class(DataFrame_index_date), intent(in) :: self
character(len=*), intent(in) :: name
integer :: j
character(len=nlen_columns) :: key
key = trim(name)
j = findloc(self%columns, key, dim=1)
has_col = (j > 0)
end function has_col
logical function has_idx(self, idx)
! return .true. if dataframe has a row with the given index value
class(DataFrame_index_date), intent(in) :: self
type(date), intent(in) :: idx
integer :: i
i = findloc_index(self%index, idx)
has_idx = (i > 0)
end function has_idx
function drop_cols(self, names, missing) result(df_new)
! drop columns by name
class(DataFrame_index_date), intent(in) :: self
character(len=*), intent(in) :: names(:)
character(len=*), intent(in), optional :: missing
type(DataFrame_index_date) :: df_new
logical, allocatable :: keep(:)
integer, allocatable :: ivec_keep(:)
integer :: k, j, n
character(len=100) :: miss
character(len=nlen_columns) :: key
miss = trim(default("error", missing))
miss = str_lower(miss)
n = ncol(self)
allocate(keep(n))
keep = .true.
do k = 1, size(names)
key = trim(names(k))
j = findloc(self%columns, key, dim=1)
if (j <= 0) then
if (miss == "ignore") cycle
error stop "drop_cols: column not found: "//trim(names(k))
end if
keep(j) = .false.
end do
ivec_keep = pack(seq(1, n), keep)
df_new = self%icol(ivec_keep)
end function drop_cols
function drop_rows(self, idx, missing) result(df_new)
! drop rows by index value
class(DataFrame_index_date), intent(in) :: self
type(date), intent(in) :: idx(:)
character(len=*), intent(in), optional :: missing
type(DataFrame_index_date) :: df_new
logical, allocatable :: keep(:)
integer, allocatable :: ivec_keep(:)
integer :: k, i, n
character(len=100) :: miss
miss = trim(default("error", missing))
miss = str_lower(miss)
n = nrow(self)
allocate(keep(n))
keep = .true.
do k = 1, size(idx)
i = findloc_index(self%index, idx(k))
if (i <= 0) then
if (miss == "ignore") cycle
error stop "drop_rows: index not found"
end if
keep(i) = .false.
end do
ivec_keep = pack(seq(1, n), keep)
df_new = self%irow(ivec_keep)
end function drop_rows
subroutine rename_cols(self, old, new, missing)
! rename columns: replace each old(i) with new(i)
class(DataFrame_index_date), intent(in out) :: self
character(len=*), intent(in) :: old(:), new(:)
character(len=*), intent(in), optional :: missing
integer :: k, j
character(len=100) :: miss
character(len=nlen_columns) :: key
if (size(old) /= size(new)) error stop "rename_cols: size(old) /= size(new)"
miss = trim(default("error", missing))
miss = str_lower(miss)
do k = 1, size(old)
key = trim(old(k))
j = findloc(self%columns, key, dim=1)
if (j <= 0) then
if (miss == "ignore") cycle
error stop "rename_cols: column not found: "//trim(old(k))
end if
self%columns(j) = trim(new(k))
end do
end subroutine rename_cols
function where_cols(self, mask_cols) result(df_new)
! keep columns where mask_cols(j) is .true.
class(DataFrame_index_date), intent(in) :: self
logical, intent(in) :: mask_cols(:)
type(DataFrame_index_date) :: df_new
integer, allocatable :: j_keep(:)
if (size(mask_cols) /= ncol(self)) error stop "where_cols: size(mask_cols) /= ncol(self)"
j_keep = pack(seq(1, ncol(self)), mask_cols)
df_new = self%icol(j_keep)
end function where_cols
function filter_cols(self, mask_cols, drop) result(df_new)
! filter columns by mask; if drop=.true. then drop columns where mask is .true.
class(DataFrame_index_date), intent(in) :: self
logical, intent(in) :: mask_cols(:)
logical, intent(in), optional :: drop
type(DataFrame_index_date) :: df_new
logical :: drop_
logical, allocatable :: keep(:)
drop_ = default(.false., drop)
if (size(mask_cols) /= ncol(self)) error stop "filter_cols: size(mask_cols) /= ncol(self)"
allocate(keep(size(mask_cols)))
if (drop_) then
keep = .not. mask_cols
else
keep = mask_cols
end if
df_new = self%where_cols(keep)
end function filter_cols
function where(self, mask_rows, mask_cols) result(df_new)
! keep rows and columns where masks are .true.
class(DataFrame_index_date), intent(in) :: self
logical, intent(in) :: mask_rows(:)
logical, intent(in) :: mask_cols(:)
type(DataFrame_index_date) :: df_new
integer, allocatable :: i_keep(:), j_keep(:)
if (size(mask_rows) /= nrow(self)) error stop "where: size(mask_rows) /= nrow(self)"
if (size(mask_cols) /= ncol(self)) error stop "where: size(mask_cols) /= ncol(self)"
i_keep = pack(seq(1, nrow(self)), mask_rows)
j_keep = pack(seq(1, ncol(self)), mask_cols)
df_new = DataFrame_index_date(index=self%index(i_keep), columns=self%columns(j_keep), values=self%values(i_keep, j_keep))
end function where
function filter(self, mask_rows, mask_cols, drop_rows, drop_cols) result(df_new)
! filter rows and columns by masks; if drop_rows/drop_cols are .true. then drop where mask is .true.
class(DataFrame_index_date), intent(in) :: self
logical, intent(in) :: mask_rows(:)
logical, intent(in) :: mask_cols(:)
logical, intent(in), optional :: drop_rows, drop_cols
type(DataFrame_index_date) :: df_new
logical :: drop_r, drop_c
logical, allocatable :: keep_rows(:), keep_cols(:)
if (size(mask_rows) /= nrow(self)) error stop "filter: size(mask_rows) /= nrow(self)"
if (size(mask_cols) /= ncol(self)) error stop "filter: size(mask_cols) /= ncol(self)"
drop_r = default(.false., drop_rows)
drop_c = default(.false., drop_cols)
allocate(keep_rows(size(mask_rows)))
allocate(keep_cols(size(mask_cols)))
if (drop_r) then
keep_rows = .not. mask_rows
else
keep_rows = mask_rows
end if
if (drop_c) then
keep_cols = .not. mask_cols
else
keep_cols = mask_cols
end if
df_new = self%where(keep_rows, keep_cols)
end function filter
function iloc(self, rows, cols) result(df_new)
! positional selection by row/column positions (1-based)
class(DataFrame_index_date), intent(in) :: self
integer, intent(in), optional :: rows(:)
integer, intent(in), optional :: cols(:)
type(DataFrame_index_date) :: df_new
if (present(rows) .and. present(cols)) then
df_new = self%select(irows=rows, icols=cols)
else if (present(rows)) then
df_new = self%select(irows=rows)
else if (present(cols)) then
df_new = self%select(icols=cols)
else
df_new = self%select()
end if
end function iloc
function select(self, rows, columns, irows, icols) result(df_new)
! select a sub-dataframe using label- or position-based selectors on each axis.
! rules:
! - at most one of rows/irows may be present
! - at most one of columns/icols may be present
class(DataFrame_index_date), intent(in) :: self
type(date), intent(in), optional :: rows(:)
character(len=*), intent(in), optional :: columns(:)
integer, intent(in), optional :: irows(:)
integer, intent(in), optional :: icols(:)
type(DataFrame_index_date) :: df_new
integer, allocatable :: i_keep(:), j_keep(:)
integer :: k
if (present(rows) .and. present(irows)) error stop "select: both rows and irows are present"
if (present(columns) .and. present(icols)) error stop "select: both columns and icols are present"
if (present(rows)) then
allocate(i_keep(size(rows)))
do k = 1, size(rows)
i_keep(k) = self%row_pos(rows(k))
end do
else if (present(irows)) then
i_keep = irows
do k = 1, size(i_keep)
if (i_keep(k) < 1 .or. i_keep(k) > nrow(self)) error stop "select: row position out of range"
end do
else
i_keep = seq(1, nrow(self))
end if
if (present(columns)) then
allocate(j_keep(size(columns)))
do k = 1, size(columns)
j_keep(k) = self%col_pos(columns(k))
end do
else if (present(icols)) then
j_keep = icols
do k = 1, size(j_keep)
if (j_keep(k) < 1 .or. j_keep(k) > ncol(self)) error stop "select: column position out of range"
end do
else
j_keep = seq(1, ncol(self))
end if
df_new = DataFrame_index_date(index=self%index(i_keep), columns=self%columns(j_keep), values=self%values(i_keep, j_keep))
end function select
pure function str_lower(str) result(out)
! return str converted to lowercase (ASCII)
character(len=*), intent(in) :: str
character(len=len(str)) :: out
integer :: i, c
out = str
do i = 1, len(str)
c = iachar(out(i:i))
if (c >= iachar('A') .and. c <= iachar('Z')) out(i:i) = achar(c + 32)
end do
end function str_lower
pure function irow(df, ivec) result(df_new)
! returns a dataframe with the subset of columns in ivec(:)
class(DataFrame_index_date), intent(in) :: df
integer, intent(in) :: ivec(:)
type(DataFrame_index_date) :: df_new
df_new = DataFrame_index_date(index=df%index(ivec), columns=df%columns, values=df%values(ivec, :))
end function irow
pure subroutine set_col(df, column, values)
! append a column with specified values to DataFrame df if column is not in df,
! and set the values of that column if it is already present
class(DataFrame_index_date), intent(in out) :: df
character (len=*), intent(in) :: column
real(kind=dp), intent(in) :: values(:)
integer :: jcol
if (size(values) /= nrow(df)) error stop "in set_col, size(values) /= nrow(df)"
jcol = findloc(df%columns, column, dim=1)
if (jcol == 0) then
call append_col(df, column, values)
else
df%values(:,jcol) = values
end if
end subroutine set_col
pure subroutine append_col(df, column, values)
! append a column with specified values to DataFrame df
class(DataFrame_index_date), intent(in out) :: df
character (len=*), intent(in) :: column
real(kind=dp), intent(in) :: values(:)
character (len=nlen_columns) :: column_
if (size(values) /= nrow(df)) error stop "in append_col, size(values) /= nrow(df)"
column_ = column
df%columns = [df%columns, column_]
df%values = cbind(df%values, values)
end subroutine append_col
pure subroutine append_cols(df, columns, values)
! append a column with specified values to DataFrame df
class(DataFrame_index_date), intent(in out) :: df
character (len=*), intent(in) :: columns(:)
real(kind=dp), intent(in) :: values(:,:)
character (len=nlen_columns), allocatable :: columns_(:)
if (size(values, 1) /= nrow(df)) error stop "in append_cols, size(values) /= nrow(df)"
if (size(values, 2) /= size(columns)) error stop "in append_cols, size(values, 2) /= size(columns)"
columns_ = columns
df%columns = [df%columns, columns_]
df%values = cbind(df%values, values)
end subroutine append_cols
subroutine allocate_df(df, n1, n2, default_indices, default_columns)
type(DataFrame_index_date), intent(out) :: df
integer , intent(in) :: n1, n2
logical , intent(in), optional :: default_indices, default_columns
integer :: i
allocate (df%index(n1), df%columns(n2), df%values(n1, n2))
if (default(.true., default_indices)) then
do i=1,n1
df%index(i) = date(2000,1,1) + (i - 1)
end do
end if
if (default(.true., default_columns)) then
do i=1,n2
write (df%columns(i), "('x',i0)") i
end do
end if
end subroutine allocate_df
elemental function nrow(df) result(num_rows)
! return the # of rows
type(DataFrame_index_date), intent(in) :: df
integer :: num_rows
if (allocated(df%values)) then
num_rows = size(df%values, 1)
else
num_rows = -1
end if
end function nrow
elemental function ncol(df) result(num_col)
! return the # of columns
type(DataFrame_index_date), intent(in) :: df
integer :: num_col
if (allocated(df%values)) then
num_col = size(df%values, 2)
else
num_col = -1
end if
end function ncol
!------------------------------------------------------------------
! read_csv:
!
! Reads from a CSV file with the following format:
!
! ,Col1,Col2,...
! index1,val11,val12,...
! index2,val21,val22,...
!
! The header row begins with an empty token (before the first comma).
!------------------------------------------------------------------
subroutine read_csv(self, filename, max_col, max_rows)
class(DataFrame_index_date), intent(inout) :: self
character(len=*), intent(in) :: filename
integer, intent(in), optional :: max_col, max_rows
integer :: io, unit, i, j, nrows, ncols
character(len=1024) :: line
character(:), allocatable :: tokens(:)
type(date) :: idx
if (allocated(self%index)) deallocate(self%index)
if (allocated(self%columns)) deallocate(self%columns)
if (allocated(self%values)) deallocate(self%values)
open(newunit=unit, file=filename, status="old", action="read", iostat=io)
if (io /= 0) error stop "Error opening " // trim(filename) // " in read_csv"
read(unit, "(A)", iostat=io) line
if (io /= 0) error stop "Error reading header line in read_csv"
call split_string(line, ",", tokens)
ncols = size(tokens) - 1
if (present(max_col)) ncols = min(ncols, max_col)
if (ncols <= 0) error stop "No columns detected in header in read_csv"
allocate(self%columns(ncols))
do i = 1, ncols
self%columns(i) = tokens(i+1)
end do
nrows = 0
do
if (present(max_rows)) then
if (nrows >= max_rows) exit
end if
read(unit, "(A)", iostat=io) line
if (io /= 0 .or. trim(line) == "") exit
nrows = nrows + 1
end do
if (nrows == 0) error stop "No data lines detected in read_csv"
rewind(unit)
read(unit, "(A)")
allocate(self%index(nrows), self%values(nrows, ncols))
do i = 1, nrows
read(unit, "(A)", iostat=io) line
if (io /= 0) error stop "Error reading data row in read_csv"
if (trim(line) == "") exit
call split_string(line, ",", tokens)
idx = date_from_iso(trim(tokens(1)))
if (.not. valid(idx)) idx = date_from_basic(trim(tokens(1)))
if (.not. valid(idx)) error stop "Invalid date in first column in read_csv"
self%index(i) = idx
do j = 1, ncols
read(tokens(j+1), *) self%values(i,j)
end do
end do
close(unit)
end subroutine read_csv
!------------------------------------------------------------------
! display_data:
!
! Prints the DataFrame to the screen in a CSV-like format.
! If the DataFrame has more than nrows_print observations, by default only
! the first nrows_print/2 and the last (nrows_print - nrows_print/2) rows are
! printed with an indication of omitted rows.
!
! An optional logical argument "print_all" may be provided. If it is present
! and set to .true., then all rows are printed.
!------------------------------------------------------------------
impure elemental subroutine display_data(self, print_all, fmt_ir, fmt_header, fmt_trailer, title)
class(DataFrame_index_date), intent(in) :: self
logical, intent(in), optional :: print_all
character (len=*), intent(in), optional :: fmt_ir, fmt_header, fmt_trailer, title
integer :: total, i, n_top, n_bottom
logical :: print_all_
character (len=100) :: fmt_ir_, fmt_header_
fmt_ir_ = default("(*(1x,f10.4))", fmt_ir)
fmt_header_ = default("(a10,*(1x,a10))", fmt_header)
print_all_ = default(.false., print_all)
total = size(self%index)
if (blank_line_before_display) write(*,*)
if (present(title)) write(*,"(a)") title
write(*,fmt_header_) "index", (trim(self%columns(i)), i=1,size(self%columns))
if (print_all_) then
do i = 1, total
write(*,"(a10)", advance="no") self%index(i)%to_str()
write(*,fmt_ir_) self%values(i,:)
end do
else
if (total <= nrows_print) then
do i = 1, total
write(*,"(a10)", advance="no") self%index(i)%to_str()
write(*,fmt_ir_) self%values(i,:)
end do
else
n_top = nrows_print / 2
n_bottom = nrows_print - n_top
do i = 1, n_top
write(*,"(a10)", advance="no") self%index(i)%to_str()
write(*,fmt_ir_) self%values(i,:)
end do
write(*,*) " ... (", total - nrows_print, " rows omitted) ..."
do i = total - n_bottom + 1, total
write(*,"(a10)", advance="no") self%index(i)%to_str()
write(*,fmt_ir_) self%values(i,:)
end do
end if
end if
if (present(fmt_trailer)) write(*,fmt_trailer)
end subroutine display_data
!------------------------------------------------------------------
! write_csv:
!
! Writes the DataFrame to a CSV file in the same format as read_csv.
!------------------------------------------------------------------
subroutine write_csv(self, filename)
class(DataFrame_index_date), intent(in) :: self
character(len=*), intent(in) :: filename
integer :: i, j, unit, io
open(newunit=unit, file=filename, status="replace", action="write", iostat=io)
if (io /= 0) error stop "Error opening " // trim(filename) // " in write_csv"
write(unit,"(A)", advance="no") ""
do j = 1, size(self%columns)
write(unit,'(",", A)', advance='no') trim(self%columns(j))
end do
write(unit,*)
do i = 1, size(self%index)
write(unit,'(A)', advance='no') trim(self%index(i)%to_str())
do j = 1, size(self%columns)
write(unit,'(",", G0.12)', advance='no') self%values(i,j)
end do
write(unit,*)
end do
close(unit)
end subroutine write_csv
subroutine print_summary(self, outu, fmt_header, fmt_trailer)
type(DataFrame_index_date), intent(in) :: self
integer, intent(in), optional :: outu
character (len=*), intent(in), optional :: fmt_header, fmt_trailer
integer :: outu_, nr, nc
outu_ = default(output_unit, outu)
if (present(fmt_header)) write (outu_, fmt_header)
nr = nrow(self)
nc = ncol(self)
write(outu_, "('#rows, columns:', 2(1x,i0))") nr, nc
if (nr > 0) write(outu_, "('first, last indices:', 2(1x,a))") trim(self%index(1)%to_str()), trim(self%index(nr)%to_str())
if (nc > 0) write(outu_, "('first, last columns:', 2(1x,a))") trim(self%columns(1)), trim(self%columns(nc))
if (present(fmt_trailer)) write (outu_, fmt_trailer)
end subroutine print_summary
subroutine alloc(self, nr, nc)
type(DataFrame_index_date), intent(out) :: self
integer , intent(in) :: nr, nc
allocate (self%index(nr), self%values(nr, nc))
allocate (self%columns(nc))
end subroutine alloc
subroutine random(self, nr, nc)
type(DataFrame_index_date), intent(out) :: self
integer, intent(in) :: nr, nc
integer :: i
call alloc(self, nr, nc)
call random_number(self%values)
do i=1,nr
self%index(i) = date(2000,1,1) + (i - 1)
end do
do i=1,nc
write (self%columns(i), "('C',i0)") i
end do
end subroutine random
function mult_x_df(x, df) result(res)
! return x * df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = x*res%values
end function mult_x_df
function mult_df_x(df, x) result(res)
! return df * x
type(DataFrame_index_date), intent(in) :: df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = x*res%values
end function mult_df_x
function add_x_df(x, df) result(res)
! return x * df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = x + res%values
end function add_x_df
function add_df_x(df, x) result(res)
! return df * x
type(DataFrame_index_date), intent(in) :: df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = res%values + x
end function add_df_x
function subtract_x_df(x, df) result(res)
! return x - df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = x - res%values
end function subtract_x_df
function subtract_df_x(df, x) result(res)
! return df - x
type(DataFrame_index_date), intent(in) :: df
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = res%values - x
end function subtract_df_x
function div_df_x(df, x) result(res)
! return df / x
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = res%values/x
end function div_df_x
function div_x_df(x, df) result(res)
! return df / x
real(kind=dp) , intent(in) :: x
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = x/res%values
end function div_x_df
function div_n_df(n, df) result(res)
! return n / x
integer , intent(in) :: n
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = n/res%values
end function div_n_df
function mult_n_df(n, df) result(res)
! return n * df
integer , intent(in) :: n
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = n*res%values
end function mult_n_df
function mult_df_n(df, n) result(res)
! return df * n
type(DataFrame_index_date), intent(in) :: df
integer , intent(in) :: n
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = n*res%values
end function mult_df_n
function add_n_df(n, df) result(res)
! return n * df
integer , intent(in) :: n
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = n + res%values
end function add_n_df
function add_df_n(df, n) result(res)
! return df * n
type(DataFrame_index_date), intent(in) :: df
integer , intent(in) :: n
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = res%values + n
end function add_df_n
function subtract_n_df(n, df) result(res)
! return n - df
integer , intent(in) :: n
type(DataFrame_index_date), intent(in) :: df
type(DataFrame_index_date) :: res
res = df
if (allocated(res%values)) res%values = n - res%values
end function subtract_n_df