-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmat.f90
More file actions
2052 lines (1853 loc) · 81.1 KB
/
mat.f90
File metadata and controls
2052 lines (1853 loc) · 81.1 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 interpret_mod
use kind_mod, only: dp
use stats_mod, only: mean, sd, cor, cov, cumsum, diff, standardize, &
print_stats, skew, kurtosis
use util_mod, only: matched_brackets, matched_parentheses, arange, &
head, tail, grid, print_real, is_alphanumeric, &
is_numeral, is_letter, zeros, ones, replace, rep
use random_mod, only: random_normal, runif
use qsort_mod, only: sorted, indexx, rank, median
use iso_fortran_env, only: compiler_options, compiler_version
use plot_mod, only: plot, plot_to_label
implicit none
private
public :: eval_print, tunit, code_transcript_file, vars, write_code, &
echo_code
integer, parameter :: max_vars = 100, len_name = 32
integer, parameter :: max_print = 15 ! for arrays larger than this, summary stats printed instead of elements
type :: var_t
character(len=len_name) :: name = ""
real(kind=dp), allocatable :: val(:)
end type var_t
type(var_t) :: vars(max_vars)
integer :: n_vars = 0, tunit
logical, save :: write_code = .true., eval_error = .false., &
echo_code = .true.
character(len=1) :: curr_char
character(len=*), parameter :: code_transcript_file = "code.fi" ! stores the commands issued
character(len=*), parameter :: comment_char = "!"
logical, parameter :: stop_if_error = .false.
real(kind=dp), parameter :: bad_value = -999.0_dp, tol = 1.0e-6_dp
logical, parameter :: mutable = .true. ! when .false., no reassignments allowed
logical, save :: print_array_as_int_if_possible = .true.
character(len=:), allocatable :: line_cp
logical, save :: in_loop_execute = .false. ! TRUE only inside run_loop_body
logical, save :: exit_loop = .false., cycle_loop = .false.
!––– support for DO … END DO loops –––––––––––––––––––––––––––––––––
!── Maximum nesting and a fixed buffer for every loop level
integer, parameter :: max_loop_depth = 8
character(len=4096), save :: loop_body(max_loop_depth) = "" ! collected lines
character(len=len_name), save :: loop_var(max_loop_depth) = "" ! i , j , ...
integer, save :: loop_start(max_loop_depth) = 0
integer, save :: loop_end(max_loop_depth) = 0
integer, save :: loop_step(max_loop_depth) = 1
integer, save :: loop_depth = 0 ! current level
!––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
contains
subroutine slice_array(name, idxs, result)
! Return a 1-D section of variable NAME described by the text
! in IDXS (e.g. "2:11:3", "5:", ":7:-2",).
character(len=*), intent(in) :: name
character(len=*), intent(in) :: idxs
real(kind=dp), allocatable, intent(out) :: result(:)
real(kind=dp), allocatable :: v(:), larr(:), uarr(:), sarr(:)
integer :: c1, c2 ! locations of ':' in IDXS
integer :: i1, i2, step
integer :: n ! array size
! evaluate the variable itself
v = evaluate(name)
if (eval_error) return
n = size(v)
! locate first and (optional) second ':' in the text
c1 = index(idxs, ":")
if (c1 == 0) then
print *, "Error: bad slice syntax in '", trim(idxs), "'"
eval_error = .true.
allocate (result(0)); return
end if
c2 = index(idxs(c1 + 1:), ":")
if (c2 > 0) c2 = c1 + c2 ! absolute position, or 0 if none
! lower bound
if (c1 > 1) then
call parse_index(idxs(:c1 - 1), larr, i1)
else
i1 = 1
end if
! upper bound & stride
if (c2 == 0) then ! only one ':'
step = 1
if (c1 < len_trim(idxs)) then
call parse_index(idxs(c1 + 1:), uarr, i2)
else
i2 = n
end if
else ! two ':' stride present
if (c2 - c1 > 1) then ! strictly > 1 is the right check
call parse_index(idxs(c1 + 1:c2 - 1), uarr, i2)
else
i2 = n ! omitted upper bound
end if
call parse_index(idxs(c2 + 1:), sarr, step)
end if
! sanity checks
if (step == 0) then
print *, "Error: slice stride cannot be zero"
eval_error = .true.; allocate (result(0)); return
end if
if (i1 < 1 .or. i1 > n .or. i2 < 0 .or. i2 > n) then
print *, "Error: slice indices out of range"
eval_error = .true.; allocate (result(0)); return
end if
! empty slice situations that are nevertheless valid
if ((step > 0 .and. i1 > i2) .or. &
(step < 0 .and. i1 < i2)) then
allocate (result(0))
return
end if
! finally deliver the section
result = v(i1:i2:step)
contains
subroutine parse_index(str, arr, idx)
! Parse a slice index string str into its evaluated array arr and
! integer index idx.
character(len=*), intent(in) :: str
real(kind=dp), allocatable, intent(out) :: arr(:)
integer, intent(out) :: idx
arr = evaluate(str)
if (eval_error) then
idx = -1
else
idx = int(arr(1))
end if
end subroutine parse_index
end subroutine slice_array
subroutine clear()
! delete all variables
integer :: i
do i = 1, min(n_vars, max_vars)
vars(i)%name = ""
if (allocated(vars(i)%val)) deallocate (vars(i)%val)
end do
n_vars = 0
end subroutine clear
subroutine set_variable(name, val)
! Store or replace a variable
character(len=*), intent(in) :: name
real(kind=dp), intent(in) :: val(:)
integer :: i
character(len=len_name) :: nm
nm = adjustl(name)
do i = 1, n_vars
if (vars(i)%name == nm) then
if (.not. mutable) then
print *, "Error: cannot reassign '"//trim(nm)//"' if mutable is .false."
eval_error = .true.
return
end if
vars(i)%val = val
return
end if
end do
if (n_vars < max_vars) then
n_vars = n_vars + 1
vars(n_vars)%name = nm
vars(n_vars)%val = val
else
print *, "Error: too many variables."
eval_error = .true.
end if
end subroutine set_variable
function apply_scalar_func(fname, arr) result(r)
! Apply a scalar-returning function: sum, minval, maxval, etc.
character(len=*), intent(in) :: fname
real(kind=dp), intent(in) :: arr(:)
real(kind=dp) :: r
select case (trim(fname))
case ("size"); r = size(arr)
case ("sum"); r = sum(arr)
case ("product"); r = product(arr)
case ("norm1"); r = sum(abs(arr))
case ("norm2"); r = norm2(arr)
case ("minval"); r = minval(arr)
case ("maxval"); r = maxval(arr)
case ("minloc"); r = minloc(arr, dim=1)
case ("maxloc"); r = maxloc(arr, dim=1)
case ("count"); r = real(count(arr /= 0.0_dp), dp)
case ("median"); r = median(arr)
case ("mean"); r = mean(arr)
case ("sd"); r = sd(arr)
case ("skew"); r = skew(arr)
case ("kurt"); r = kurtosis(arr)
case ("print_stats"); call print_stats(arr); r = 0
case default
print *, "Error in apply_scalar_func: function '", trim(fname), "' not defined"
eval_error = .true.
r = bad_value
end select
end function apply_scalar_func
function apply_vec_func(fname, arr) result(res)
! Apply a function that takes an array and returns an array
character(len=*), intent(in) :: fname
real(kind=dp), intent(in) :: arr(:)
real(kind=dp), allocatable :: res(:)
select case (trim(fname))
case ("abs"); res = abs(arr)
case ("acos"); res = acos(arr)
case ("acosh"); res = acosh(arr)
case ("asin"); res = asin(arr)
case ("asinh"); res = asinh(arr)
case ("atan"); res = atan(arr)
case ("atanh"); res = atanh(arr)
case ("cos"); res = cos(arr)
case ("cosh"); res = cosh(arr)
case ("exp"); res = exp(arr)
case ("log"); res = log(arr)
case ("log10"); res = log10(arr)
case ("sin"); res = sin(arr)
case ("sinh"); res = sinh(arr)
case ("sqrt"); res = sqrt(arr)
case ("tan"); res = tan(arr)
case ("tanh"); res = tanh(arr)
case ("bessel_j0"); res = bessel_j0(arr)
case ("bessel_j1"); res = bessel_j1(arr)
case ("bessel_y0"); res = bessel_y0(arr)
case ("bessel_y1"); res = bessel_y1(arr)
case ("gamma"); res = gamma(arr)
case ("log_gamma"); res = log_gamma(arr)
case ("cosd"); res = cosd(arr)
case ("sind"); res = sind(arr)
case ("tand"); res = tand(arr)
case ("acosd"); res = acosd(arr)
case ("asind"); res = asind(arr)
case ("atand"); res = atand(arr)
case ("spacing"); res = spacing(arr)
case ("cumsum"); res = cumsum(arr)
case ("diff"); res = diff(arr)
case ("head"); res = head(arr)
case ("tail"); res = tail(arr)
case ("sort"); res = sorted(arr)
case ("indexx"); res = indexx(arr)
case ("rank"); res = rank(arr)
case ("stdz"); res = standardize(arr)
case default
print *, "Error in apply_vec_func: function '", trim(fname), "' not defined"
eval_error = .true.
res = [bad_value]
end select
end function apply_vec_func
recursive function evaluate(str) result(res)
! Evaluate the input string str as an expression or assignment
! and return its result array res
character(len=*), intent(in) :: str
real(kind=dp), allocatable :: res(:)
!- local to this outer shell ----------------------------------
character(len=:), allocatable :: expr, lhs, rhs
integer :: pos, lenstr ! parser cursor & length
integer :: i, eqpos ! scan index & "=" position
integer :: depth_b, depth_p
!------------------------------------------------------------------
! prepare the string for parsing
call init_evaluator(trim(str), expr, lenstr, pos)
! look for an *assignment* = that is **not** part of >= <= == <=
!------------------------------------------------------------------
! find a top‑level “=” that is **not** part of >= <= == /= etc.
!------------------------------------------------------------------
eqpos = 0
depth_p = 0 ! nesting level ()
depth_b = 0 ! nesting level []
do i = 1, lenstr
select case (expr(i:i))
case ("("); depth_p = depth_p + 1
case (")"); if (depth_p > 0) depth_p = depth_p - 1
case ("["); depth_b = depth_b + 1
case ("]"); if (depth_b > 0) depth_b = depth_b - 1
case ("=")
if (depth_p == 0 .and. depth_b == 0) then
if (i > 1) then
if (any(expr(i - 1:i - 1) == [">", "<", "!", "=", "/"])) cycle
end if
if (i < lenstr .and. expr(i + 1:i + 1) == "=") cycle
eqpos = i
exit ! first *top‑level* “=” wins
end if
end select
end do
! eqpos = 0
! do i = 1, lenstr
! if (expr(i:i) == "=") then
! if (i > 1 .and. any(expr(i - 1:i - 1) == [">", "<", "!", "=", "/"])) cycle
! if (i < lenstr .and. expr(i + 1:i + 1) == "=") cycle
! eqpos = i
! exit ! first qualifying = wins
! end if
! end do
! assignment found evaluate RHS then store
if (eqpos > 0) then
lhs = adjustl(expr(1:eqpos - 1))
rhs = expr(eqpos + 1:)
res = evaluate(rhs) ! recursive call
if (.not. eval_error) then
if (index(lhs, "(") > 0 .and. index(lhs, ")") > index(lhs, "(")) then
call assign_element(lhs, res) ! element assignment a(i)=
else
call set_variable(lhs, res) ! wholevariable assignment
end if
end if
return
end if
! no = treat the whole string as an expression
res = parse_expression()
! detect any extraneous characters left on the line
call skip_spaces()
if (curr_char /= char(0)) then
print *, "Error: unexpected input after valid expression: '", &
trim(expr(pos - 1:lenstr)), "'"
eval_error = .true.
! return an empty result to signal failure
res = [real(kind=dp) ::]
end if
contains
!--------------------------------------------------
subroutine init_evaluator(str_in, expr, lenstr, pos)
! Prepare parser state: copy str_in into expr and set lenstr
! and reset pos for evaluation
character(len=*), intent(in) :: str_in
character(len=:), allocatable, intent(out) :: expr
integer, intent(out) :: lenstr, pos
expr = str_in
lenstr = len_trim(expr)
pos = 1
eval_error = .false.
call next_char()
end subroutine init_evaluator
subroutine next_char()
! Advance the parser cursor to the next character in expr
! updating curr_char and pos
if (pos > lenstr) then
curr_char = char(0)
else
curr_char = expr(pos:pos)
end if
pos = pos + 1
end subroutine next_char
subroutine skip_spaces()
! Advance pos until non-space is found
do while (curr_char == " ")
call next_char()
end do
end subroutine skip_spaces
!---------------------------------------------------------------
logical function at_token(tok) ! TRUE if
character(len=*), intent(in) :: tok ! the
integer :: l ! text
l = len_trim(tok) ! TOK
if (pos - 1 + l - 1 > lenstr) then ! starts
at_token = .false. ! at the
else ! current
at_token = (expr(pos - 1:pos - 2 + l) == tok) ! cursor
end if
end function at_token
subroutine advance_token(n) ! skip the
integer, intent(in) :: n ! next N
integer :: k ! letters
do k = 1, n ! (calls
call next_char() ! next_char)
end do
end subroutine advance_token
!---------------------------------------------------------------
function parse_number() result(num)
! Read a numeric literal starting at the current cursor
! and return it as a one-element array num
real(kind=dp), allocatable :: num(:)
character(len=64) :: buf
integer :: i
real(kind=dp) :: tmp
call skip_spaces()
i = 0
do while (is_numeral(curr_char) .or. curr_char == ".")
i = i + 1
buf(i:i) = curr_char
call next_char()
end do
read (buf(1:i), *) tmp
num = [tmp]
end function parse_number
function parse_identifier() result(name_out)
! Read an alphanumeric identifier from the current cursor
! and return it as name_out
character(len=len_name) :: name_out
integer :: i
call skip_spaces()
i = 0
do while (is_alphanumeric(curr_char) .or. curr_char == "_")
i = i + 1
name_out(i:i) = curr_char
call next_char()
end do
name_out = adjustl(name_out(1:i))
end function parse_identifier
function get_variable(name) result(v)
! Look up variable name in storage and return its value array v
! or signal an undefined-variable error
character(len=*), intent(in) :: name
real(kind=dp), allocatable :: v(:)
integer :: i
do i = 1, n_vars
if (vars(i)%name == name) then
v = vars(i)%val
return
end if
end do
print *, "Error: undefined variable '", trim(name), "'"
eval_error = .true.
v = [bad_value]
end function get_variable
recursive function parse_array() result(arr)
! Parse a bracketed array literal (e.g. '[1,2,3]') and return its elements
! as a 1-D real(kind=dp) allocatable array.
real(kind=dp), allocatable :: arr(:), tmp(:), elem(:)
integer :: total, ne
! consume the '['
call next_char()
call skip_spaces()
! empty array literal []
if (curr_char == "]") then
allocate (arr(0))
call next_char()
return
end if
total = 0
allocate (arr(0))
do
! parse one element (may itself be an array)
elem = parse_expression()
if (eval_error) return
ne = size(elem)
! append elem to arr
if (allocated(tmp)) deallocate (tmp)
allocate (tmp(total + ne))
if (total > 0) tmp(1:total) = arr
tmp(total + 1:total + ne) = elem
arr = tmp
total = total + ne
! now skip any spaces, then decide what to do
call skip_spaces()
select case (curr_char)
case (",") ! explicit comma
call next_char()
case ("]") ! end of array
call next_char()
exit
end select
end do
end function parse_array
recursive function parse_factor() result(f)
! Parse a single factor in an expression, handling:
! - numeric literals
! - parenthesized sub‑expressions
! - array literals
! - identifiers (variable lookup, function calls, slicing)
! - unary +/– and exponentiation.
real(kind=dp), allocatable :: f(:) ! result
!=================== locals =====================================
real(kind=dp), allocatable :: arg1(:), arg2(:), arg3(:)
real(kind=dp), allocatable :: exponent(:), vvar(:)
integer, allocatable :: idxv(:)
character(len=len_name) :: id
character(len=:), allocatable :: idxs
integer :: nsize, pstart, pend, depth, n1, n2, dim_val
logical :: is_neg, have_second
logical :: toplevel_colon, toplevel_comma, have_dim
character(len=len_name) :: look_name ! NEW
have_dim = .false.
dim_val = 1
call skip_spaces()
!-------------- logical NOT ---------------------------------
if (at_token('.not.')) then
call advance_token(5) ! consume ".not."
f = parse_factor() ! recurse on the operand
if (.not. eval_error) then
f = merge(1.0_dp, 0.0_dp, f == 0.0_dp) ! element-wise .not.
else
f = [bad_value]
end if
return
end if
!---------------- unary -----------------------------------------
if (curr_char == "+" .or. curr_char == "-") then
is_neg = (curr_char == "-")
call next_char()
f = parse_factor()
if (.not. eval_error .and. is_neg) f = -f
return
end if
select case (curr_char)
case ("(") ! parenthesised expr.
call next_char()
f = parse_expression()
if (curr_char == ")") call next_char()
case ("[") ! array literal
f = parse_array()
case default
if (is_numeral(curr_char) .or. curr_char == ".") then
f = parse_number()
else if (is_letter(curr_char)) then
id = parse_identifier()
call skip_spaces()
!-----------------------------------------------------------------
if (curr_char == "(") then ! id()
call next_char() ! consume "("
call skip_spaces()
!============ ZERO-ARGUMENT SPECIAL CASE ======================
if (curr_char == ")") then ! e.g. runif()
call next_char() ! consume ")"
select case (trim(id))
case ("runif")
allocate (f(1))
call random_number(f(1))
case ("rnorm")
f = random_normal(1)
case default
print *, "Error: function '"//trim(id)//"' needs arguments"
eval_error = .true.
f = [bad_value]
end select
return
end if
!========== end zero-argument special case ====================
!--- examine the whole parenthesised chunk --------------------
pstart = pos - 1 ! first char _inside_ '('
depth = 1
toplevel_colon = .false.
toplevel_comma = .false.
pend = pstart - 1
do while (pend < lenstr .and. depth > 0)
pend = pend + 1
select case (expr(pend:pend))
case ("("); depth = depth + 1
case (")"); depth = depth - 1
case (":")
if (depth == 1) toplevel_colon = .true.
case (",")
if (depth == 1) toplevel_comma = .true.
end select
end do
if (depth /= 0) then
print *, "Error: mismatched parentheses"
eval_error = .true.; f = [bad_value]; return
end if
!---------------- slice? -------------------------------------
if (toplevel_colon .and. .not. toplevel_comma) then
idxs = expr(pstart:pend - 1)
call slice_array(id, idxs, f)
! advance cursor just past ")"
pos = pend + 1
if (pos > lenstr) then
curr_char = char(0)
else
curr_char = expr(pos:pos); pos = pos + 1
end if
return
end if
!------------- first argument -----------------------------------
arg1 = parse_expression()
if (eval_error) then
f = [bad_value]; return
end if
! after ARG1 has been parsed
call skip_spaces()
have_second = .false.
if (curr_char == ",") then
if (any(trim(id) == [character(len=len_name) :: &
"sum", "product", "minval", "maxval"])) then
!------------------------------------------------------------
! 2nd *token* can be either
! • a positional DIM value → sum(x , 1)
! • a named argument → sum(x , mask = …)
!------------------------------------------------------------
block
integer :: save_pos
logical :: is_name_eq
real(kind=dp), allocatable :: tmp(:)
save_pos = pos ! index **after** the comma
call next_char() ! step over ‘,’
call skip_spaces()
!–– look ahead: identifier followed by '=' ? ––
is_name_eq = .false.
if (is_letter(curr_char)) then
look_name = parse_identifier()
call skip_spaces()
if (curr_char == "=") is_name_eq = .true.
end if
if (is_name_eq) then
!–– restore → named‑argument loop will handle it ––
pos = save_pos
curr_char = ","
else
!–––––––––––––––––––––––––––––––––––––––––––––––––––
! **Positional DIM value**
!–––––––––––––––––––––––––––––––––––––––––––––––––––
pos = save_pos ! we already skipped the comma
call next_char()
call skip_spaces()
tmp = parse_expression() ! DIM expression
if (eval_error) then
f = [bad_value]; return
end if
if (size(tmp) /= 1) then
print *, "Error: dim argument must be scalar"
eval_error = .true.; f = [bad_value]; return
end if
dim_val = nint(tmp(1))
have_dim = .true.
call skip_spaces()
end if
end block
else
!------------------------------------------------------------
! Any other routine – 2‑nd positional argument as before
!------------------------------------------------------------
call next_char() ! consume ','
call skip_spaces()
arg2 = parse_expression()
have_second = .true.
if (eval_error) then
f = [bad_value]; return
end if
end if
end if
if (curr_char == ")") call next_char()
!------------- dispatch -----------------------------------------
select case (trim(id))
!================================================================
! SUM / PRODUCT / MINVAL / MAXVAL
! – optional named arguments in any order
! dim = 1 and/or mask = logical array
!================================================================
case ("sum", "product", "minval", "maxval")
block
!---- local to this block only ---------------------------
logical :: have_mask
real(dp), allocatable :: mask_arr(:)
logical, allocatable :: lmask(:)
real(dp), allocatable :: tmp(:)
character(len=len_name) :: name_tok
have_mask = .false.
!---------------------------------------------------------
! first positional argument already parsed → ARG1
! now parse any , name = expr pairs
do
call skip_spaces()
if (curr_char /= ",") exit
call next_char(); call skip_spaces()
if (.not. is_letter(curr_char)) then
print *, "Error: expected named argument after ','"
eval_error = .true.; f = [bad_value]; return
end if
name_tok = parse_identifier()
call skip_spaces()
if (curr_char /= "=") then
print *, "Error: expected '=' after '"//trim(name_tok)//"'"
eval_error = .true.; f = [bad_value]; return
end if
call next_char(); call skip_spaces()
tmp = parse_expression()
if (eval_error) then
f = [bad_value]; return
end if
select case (trim(name_tok))
case ("mask")
if (have_mask) then
print *, "Error: duplicate mask= argument"
eval_error = .true.; f = [bad_value]; return
end if
mask_arr = tmp
have_mask = .true.
case ("dim")
if (have_dim) then
print *, "Error: duplicate dim= argument"
eval_error = .true.; f = [bad_value]; return
end if
if (size(tmp) /= 1) then
print *, "Error: dim= must be scalar"
eval_error = .true.; f = [bad_value]; return
end if
dim_val = nint(tmp(1))
have_dim = .true.
case default
print *, "Error: unknown named argument '"//trim(name_tok)//"'"
eval_error = .true.; f = [bad_value]; return
end select
end do
! -- eat any white-space and the final right-parenthesis -----------------
call skip_spaces()
if (curr_char == ")") then ! make absolutely sure the ')' itself
call next_char() ! is consumed (curr_char -> next char)
end if
if (have_dim .and. dim_val /= 1) then
print *, "Error: only dim=1 is allowed for 1D argument, dim_val =",dim_val
eval_error = .true.; f = [bad_value]; return
end if
!---- build logical mask ---------------------------------
if (have_mask) then
if (size(mask_arr) == 1) then
allocate (lmask(size(arg1)))
lmask = mask_arr(1) /= 0.0_dp
else if (size(mask_arr) == size(arg1)) then
allocate (lmask(size(arg1)))
lmask = mask_arr /= 0.0_dp
else
print "(a,i0,1x,i0)", "Error: mask size mismatch in "//trim(id) &
//", sizes of arg1 and mask are ", size(arg1), size(mask_arr)
eval_error = .true.; f = [bad_value]; return
end if
if (size(lmask) /= size(arg1)) then
print *, "Error: mask must match array size in "//trim(id)
eval_error = .true.; f = [bad_value]; return
end if
end if
!---- intrinsic call -------------------------------------
select case (trim(id))
case ("sum")
if (have_mask) then
f = [sum(arg1, mask=lmask)]
else
f = [sum(arg1)]
end if
case ("product")
if (have_mask) then
! PRODUCT(mask=…) is F2003; use PACK for portability
f = [product(pack(arg1, lmask))]
else
f = [product(arg1)]
end if
case ("minval")
if (have_mask) then
f = [minval(arg1, mask=lmask)]
else
f = [minval(arg1)]
end if
case ("maxval")
if (have_mask) then
f = [maxval(arg1, mask=lmask)]
else
f = [maxval(arg1)]
end if
end select
end block
case ("cor", "cov", "dot") ! correlation, covariance, dot product
if (.not. have_second) then
print *, "Error: function needs two arguments"
eval_error = .true.; f = [bad_value]
else if (size(arg1) /= size(arg2)) then
print "(a,i0,1x,i0,a)", "Error: function array arguments have sizes ", &
size(arg1), size(arg2), " must be equal"
eval_error = .true.; f = [bad_value]
else if ((id == "cor" .or. id == "cov") .and. size(arg1) < 2) then
print *, "Error: function array arguments must have sizes > 1, sizes are ", size(arg1), size(arg2)
eval_error = .true.; f = [bad_value]
else if (id == "dot") then
f = [dot_product(arg1, arg2)]
else
if (id == "cor") then
f = [cor(arg1, arg2)]
else if (id == "cov") then
f = [cov(arg1, arg2)]
end if
end if
case ("min", "max") ! two-arg intrinsics
if (.not. have_second) then
print *, "Error: ", trim(id), "() needs two arguments"
eval_error = .true.; f = [bad_value]
else
n1 = size(arg1); n2 = size(arg2)
if (n1 == n2) then
if (trim(id) == "min") then
f = min(arg1, arg2)
else
f = max(arg1, arg2)
end if
else if (n1 == 1) then
if (trim(id) == "min") then
f = min(arg1(1), arg2)
else
f = max(arg1(1), arg2)
end if
else if (n2 == 1) then
if (trim(id) == "min") then
f = min(arg1, arg2(1))
else
f = max(arg1, arg2(1))
end if
else
print *, "Error: argument size mismatch in ", trim(id), "()"
eval_error = .true.; f = [bad_value]
end if
end if
case ("pack")
if (.not. have_second) then
print *, "Error: pack() needs two arguments"
eval_error = .true.
f = [bad_value]
else if (size(arg1) /= size(arg2)) then
print *, "Error: pack() arguments must have same size"
eval_error = .true.
f = [bad_value]
else
! intrinsic PACK(source, mask) returns a 1-D array of those source(i)
! for which mask(i) is .true. Here we treat nonzero arg2 as .true.
f = pack(arg1, arg2 /= 0.0_dp)
end if
!---------------------------------------------------------------
case ("rep")
! rep(v , n) = v repeated n times
if (.not. have_second) then
print *, "Error: rep() needs two arguments"
eval_error = .true.
f = [bad_value]
else ! we already have arg1 and arg2
if (size(arg2) /= 1) then
print *, "Error: second argument of rep() must be scalar"
eval_error = .true.
f = [bad_value]
else
f = rep(arg1, nint(arg2(1)))
end if
end if
!---------------------------------------------------------------
case ("runif", "rnorm", "arange", "zeros", "ones") ! one-arg
if (have_second) then
print *, "Error: function takes one argument"
eval_error = .true.; f = [bad_value]
else
nsize = nint(arg1(1))
select case (id)
case ("runif"); f = runif(nsize)
case ("rnorm"); f = random_normal(nsize)
case ("arange"); f = arange(nsize)
case ("zeros"); f = zeros(nsize)
case ("ones"); f = ones(nsize)
end select
end if
case ("grid") ! grid(n,x0,xh)
if (.not. have_second) then
! we have only one argument so far need two more
print *, "Error: grid(n,x0,xh) needs three arguments"
eval_error = .true.; f = [bad_value]
else
! arg1 and arg2 have already been parsed --> read arg3
call skip_spaces()
if (curr_char /= ",") then
print *, "Error: grid(n,x0,xh) needs three arguments"
eval_error = .true.; f = [bad_value]
else
call next_char()
call skip_spaces()
! ---------------- third argument ----------------
arg3 = parse_expression()
if (eval_error) then
f = [bad_value]
else
! ---- scalar-checks and the actual call -------
if (size(arg1) /= 1 .or. size(arg2) /= 1 .or. size(arg3) /= 1) then
print *, "Error: grid arguments must be scalars"
eval_error = .true.; f = [bad_value]
else
f = grid(nint(arg1(1)), arg2(1), arg3(1))
end if
call skip_spaces()
if (curr_char == ")") call next_char()
end if
end if
end if
case ("abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "cos", "cosh", &
"exp", "log", "log10", "sin", "sinh", "sqrt", "tan", "tanh", "size", &
"norm1", "norm2", "minloc", &
"maxloc", "count", "mean", "sd", "cumsum", "diff", "sort", "indexx", "rank", &
"stdz", "median", "head", "tail", "bessel_j0", "bessel_j1", &
"bessel_y0", "bessel_y1", "gamma", "log_gamma", "cosd", "sind", "tand", &
"acosd", "asind", "atand", "spacing", "skew", "kurt", "print_stats")
if (have_second) then
print "(a)", "Error: function '"//trim(id)//"' takes one argument"
eval_error = .true.; f = [bad_value]
else
if (index("size sum product norm1 norm2 minval maxval minloc "// &
"maxloc count mean sd median print_stats skew kurt", trim(id)) > 0) then
f = [apply_scalar_func(id, arg1)] ! functions that take array and return scalar
else
f = apply_vec_func(id, arg1)
end if
end if
case ("merge")
if (.not. have_second) then
print *, "Error: merge() needs three arguments"
eval_error = .true.; f = [bad_value]
else
! arg1 and arg2 have already been parsed
call skip_spaces()
if (curr_char /= ",") then
print *, "Error: merge() needs three arguments"
eval_error = .true.; f = [bad_value]
else
call next_char() ! skip the comma
call skip_spaces()
arg3 = parse_expression() ! ----- third argument -----
if (.not. eval_error) then
f = merge_array(arg1, arg2, arg3)
call skip_spaces()
if (curr_char == ")") call next_char()
else
f = [bad_value]
end if
end if
end if
case ("plot")