Debian Codegraph @

src/parsetext.f90

raw
1 !-----------------------------------------------------------------
2 !
3 ! This file is (or was) part of SPLASH, a visualisation tool
4 ! for Smoothed Particle Hydrodynamics written by Daniel Price:
5 !
6 ! http://users.monash.edu.au/~dprice/splash
7 !
8 ! SPLASH comes with ABSOLUTELY NO WARRANTY.
9 ! This is free software; and you are welcome to redistribute
10 ! it under the terms of the GNU General Public License
11 ! (see LICENSE file for details) and the provision that
12 ! this notice remains intact. If you modify this file, please
13 ! note section 2a) of the GPLv2 states that:
14 !
15 ! a) You must cause the modified files to carry prominent notices
16 ! stating that you changed the files and the date of any change.
17 !
18 ! Copyright (C) 2005-2025 Daniel Price. All rights reserved.
19 ! Contact: [email protected]
20 !
21 !-----------------------------------------------------------------
22
23 !-----------------------------------------------------------------
24 ! module containing routines to parse text strings containing
25 ! variables.
26 !
27 ! For example:
28 ! %(t + 10)
29 ! %(t*2)
30 ! t = %t
31 ! time = %t.5 ! specifying formatting to 5 sig-figs
32 ! %t:datetime ! formats as YYYY-MM-DD (rounded to days)
33 ! %(t + 2013-04-10):datetime ! formats as YYYY-MM-DD from base date (t in seconds)
34 ! %(t + 2013/04/10):datetime ! formats as YYYY/MM/DD from base date (t in seconds)
35 ! %(t + 2013-04-10 12:00):dt ! formats as YYYY-MM-DD HH:MM:SS from base date/time (t in seconds)
36 ! %(t + 2013/04/10 12:00):dt ! formats as YYYY/MM/DD HH:MM:SS from base date/time (t in seconds)
37 !
38 ! Uses the function parser module to evaluate the functions
39 ! once extracted from the text. Functions that cannot be
40 ! correctly evaluated are left intact in the text
41 !
42 ! Dependencies:
43 ! fparser module
44 ! plot_numb from the plotting library
45 !-----------------------------------------------------------------
46 module parsetext
47 use fparser, only:rn
48 implicit none
49
50 contains
51
52 subroutine parse_text(string,vars,vals)
53 use asciiutils, only:string_replace,string_sub,lcase
54 character(len=*), intent(inout) :: string
55 real(kind=rn), dimension(:), intent(in) :: vals
56 character(len=*), dimension(:), intent(in) :: vars
57 character(len=1) :: ch
58 character(len=len(string)+128) :: newstring
59 character(len=len(string)+128) :: temp_formula
60 integer :: ia,iz,i0,i9,lenstr,npar,i,istart,iend,ndecimal,ierr,i1,i2
61 logical :: in_variable,parse,is_datetime
62 real :: r
63 integer, parameter :: ndecimal_default = 3
64 character(len=32) :: varstring
65 !
66 !--look for strings of the form:
67 !
68 ! %var
69 ! %(var)
70 ! %var.n
71 ! %(var + 10).n
72 ! %(var1*var2 + 10)
73 ! %(var1*var2)
74 ! %(t + 2013-04-10):datetime
75 ! %(t + 2013-04-10 12:00):dt
76 ! %t:datetime
77 ! %t:dt
78 !
79 ia = iachar('a')
80 iz = iachar('z')
81 i0 = iachar('0')
82 i9 = iachar('9')
83 lenstr = len(newstring)
84 parse = .false.
85 in_variable = .false.
86 is_datetime = .false.
87 ! print*,'parsing ',trim(string)
88 newstring = string
89 npar = 0
90 ndecimal = ndecimal_default
91 i1 = 0
92 i2 = 0
93 !
94 ! In the following we extract two substrings:
95 !
96 ! string(istart:iend) is the string to replace, i.e. %(blah).5 or %(blah):datetime
97 ! string(i1:i2) is the variable/function to evaluate, i.e. blah
98 !
99 i = 0
100 do while (i < lenstr)
101 i = i + 1
102 ch = lcase(newstring(i:i))
103 select case(ch)
104 case('%')
105 in_variable = .true.
106 if (i > 1) then
107 if (newstring(i-1:i-1)=='\') in_variable = .false.
108 endif
109 if (in_variable) then
110 istart = i
111 iend = 0
112 i1 = i + 1
113 i2 = 0
114 is_datetime = .false.
115 endif
116 case('(')
117 if (in_variable) npar = npar + 1
118 case(')')
119 if (in_variable) then
120 npar = max(npar - 1,0)
121 if (i >= lenstr) then
122 iend = i
123 if (i2 < i1) i2 = iend
124 parse = .true.
125 elseif (npar==0) then
126 if (newstring(i+1:i+1) /= '.' .and. newstring(i+1:i+1) /= ':') then
127 iend = i
128 if (i2 <= i1) i2 = iend
129 parse = .true.
130 endif
131 endif
132 endif
133 case('.')
134 if (in_variable .and. npar <= 0 .and. i < lenstr) then
135 read(newstring(i+1:i+1),"(i1)",iostat=ierr) ndecimal
136 if (ierr /= 0) ndecimal = 3
137 iend = i+1
138 if (i2 < i1) i2 = i - 1
139 parse = .true.
140 endif
141 case(':')
142 if (in_variable .and. npar <= 0 .and. i < lenstr) then
143 ! check for datetime format
144 if (i+8 <= lenstr .and. lcase(newstring(i+1:i+8)) == 'datetime') then
145 is_datetime = .true.; iend = i+8
146 elseif (i+2 <= lenstr .and. lcase(newstring(i+1:i+2)) == 'dt') then
147 is_datetime = .true.; iend = i+2
148 else
149 ! not a datetime format, continue parsing as normal
150 is_datetime = .false.
151 endif
152 if (is_datetime) then
153 if (i2 < i1) i2 = i - 1
154 parse = .true.
155 endif
156 endif
157 case default
158 if ((.not.((iachar(ch) >= ia .and. iachar(ch) <= iz) &
159 .or.(iachar(ch) >= i0 .and. iachar(ch) <= i9)) &
160 .or. i==lenstr) .and. npar <= 0) then
161 if (in_variable) then
162 if (i==lenstr) then
163 iend = i
164 else
165 iend = i - 1
166 endif
167 if (i2 < i1) i2 = iend
168 parse = .true.
169 endif
170 endif
171 end select
172 if (parse) then
173 in_variable = .false.
174 if (is_datetime) then
175 call create_parseable_formula(newstring(i1:i2), temp_formula)
176 r = parse_formula(temp_formula,vars,vals,ierr)
177 if (ierr==0) then
178 call get_datetime_string(r, varstring, newstring(i1:i2))
179 else
180 varstring = 'ERROR'
181 endif
182 else
183 r = parse_formula(newstring(i1:i2),vars,vals,ierr)
184 if (ierr==0) then
185 call get_varstring(r,ndecimal,varstring)
186 else
187 varstring = 'ERROR'
188 endif
189 endif
190
191 call string_sub(newstring,istart,iend,trim(varstring))
192 i = i + (len_trim(varstring) - (iend - istart)) - 1
193 parse = .false.; ndecimal = ndecimal_default; is_datetime = .false.
194 endif
195 enddo
196 !
197 ! get rid of escape sequence on %
198 !
199 call string_replace(newstring,'\%','%')
200 !
201 ! replace original string (possibly truncated)
202 !
203 string = trim(newstring)
204 ! print*,' string: "',trim(newstring),'"'
205
206 end subroutine parse_text
207
208 !---------------------------------------------------------------------------
209 !
210 ! write the real number r to a string
211 ! with ndec decimal places
212 !
213 ! uses plot_numb to do the formatting
214 !
215 !---------------------------------------------------------------------------
216 subroutine get_varstring(r,ndec,string)
217 use plotlib, only:plot_numb
218 real, intent(in) :: r
219 integer, intent(in) :: ndec
220 character(len=*), intent(out) :: string
221 real :: rtmp
222 integer :: mm,pp,nc
223
224 if (abs(r) < tiny(r)) then
225 string = '0'
226 nc = 1
227 else
228 rtmp = abs(r)
229 mm = nint(r/10.**(int(log10(rtmp)-ndec)))
230 pp = int(log10(rtmp) - ndec)
231 call plot_numb(mm,pp,1,string,nc)
232 endif
233
234 end subroutine get_varstring
235
236 !---------------------------------------------------------------------------
237 !
238 ! write the real number r (time in seconds) to a datetime string
239 ! format can be 'datetime' or 'dt'
240 !
241 ! converts seconds since epoch to datetime format
242 ! base_date is optional and can be in format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM' or 'YYYY/MM/DD HH:MM'
243 ! If base_date has no time component, the output will be rounded to days
244 ! original_format preserves the separators and format from the input
245 !
246 !---------------------------------------------------------------------------
247 subroutine get_datetime_string(r,string,original_format)
248 real, intent(in) :: r
249 character(len=*), intent(out) :: string
250 character(len=*), intent(in), optional :: original_format
251 integer :: year, month, day, hour, minute, second
252 character(len=1) :: date_separator
253 integer :: seconds_since_epoch, total_seconds
254 logical :: is_datetime_format
255
256 ! convert real to integer seconds
257 seconds_since_epoch = nint(r)
258
259 ! determine separators and format from original format if provided
260 date_separator = '-'
261 is_datetime_format = .true.
262 if (present(original_format)) then
263 call determine_separator(original_format, date_separator)
264 is_datetime_format = index(original_format, ':') > 0 ! if has time component HH:MM
265 endif
266
267 ! convert seconds since Unix epoch to date components
268 year = 1970; month = 1; day = 1
269 total_seconds = seconds_since_epoch
270 day = day + total_seconds / 86400
271 total_seconds = mod(total_seconds, 86400)
272
273 ! handle negative remaining seconds
274 if (total_seconds < 0) then
275 total_seconds = total_seconds + 86400
276 day = day - 1
277 endif
278
279 ! convert remaining seconds to time components
280 hour = total_seconds / 3600
281 minute = (total_seconds - hour * 3600) / 60
282 second = total_seconds - hour * 3600 - minute * 60
283
284 ! normalize the date by working backwards from the epoch
285 do while (day > days_in_year(year))
286 day = day - days_in_year(year)
287 year = year + 1
288 enddo
289
290 do while (day > days_in_month(month, year))
291 day = day - days_in_month(month, year)
292 month = month + 1
293 if (month > 12) then
294 month = 1
295 year = year + 1
296 endif
297 enddo
298
299 ! format the date string
300 write(string,"(i4,a1,i2.2,a1,i2.2)") year, date_separator, month, date_separator, day
301
302 ! add time if datetime format is requested
303 if (is_datetime_format) then
304 write(string,"(a,1x,i2.2,':',i2.2)") trim(string), hour, minute
305 endif
306
307 end subroutine get_datetime_string
308
309 !---------------------------------------------------------------------------
310 !
311 ! Create a parseable formula by replacing datetime strings with time
312 ! since a reference epoch in seconds
313 ! For example: "t + 2013-04-10 12:00" becomes "t + 1365595200"
314 !
315 !---------------------------------------------------------------------------
316 subroutine create_parseable_formula(original_formula, parseable_formula)
317 use asciiutils, only:string_replace
318 character(len=*), intent(in) :: original_formula
319 character(len=*), intent(out) :: parseable_formula
320 integer :: i, len_formula
321 integer :: year, month, day, hour, minute, second
322 integer :: seconds_since_epoch
323 character(len=32) :: temp_str
324 character(len=32) :: datetime_str
325
326 parseable_formula = original_formula
327 len_formula = len_trim(parseable_formula)
328
329 i = 1
330 do while (i <= len_formula)
331 if (parse_datetime_pattern(original_formula,i,year,month,day,hour,minute,second,datetime_str)) then
332 ! convert to seconds since Unix epoch (1970-01-01)
333 seconds_since_epoch = datetime_to_seconds(year, month, day, hour, minute, second)
334
335 ! replace the datetime string with the value in seconds since 1970
336 write(temp_str, '(i0)') seconds_since_epoch
337 call string_replace(parseable_formula, trim(datetime_str), trim(temp_str))
338 len_formula = len_trim(parseable_formula)
339 endif
340 i = i + 1
341 enddo
342
343 end subroutine create_parseable_formula
344
345 !---------------------------------------------------------------------------
346 !
347 ! evaluate the variable or function via the function parser
348 !
349 ! i.e. (t + 10) or (t*10) etc.
350 !
351 ! OUTPUT: a real number
352 !
353 ! unknown variables or un-parsable syntax return an error and a zero value
354 !
355 !---------------------------------------------------------------------------
356 real function parse_formula(string,vars,vals,ierr)
357 use fparser, only:initf,evalf,endf,checkf,parsef
358 character(len=*), intent(in) :: string
359 character(len=*), dimension(:), intent(in) :: vars
360 real(kind=rn), dimension(:), intent(in) :: vals
361 integer, intent(out) :: ierr
362
363 call initf(1)
364 ierr = checkf(string,vars,verbose=.false.)
365 if (ierr==0) then
366 call parsef(1,string,vars)
367 parse_formula = real(evalf(1,vals))
368 else
369 parse_formula = 0.
370 endif
371 call endf
372
373 end function parse_formula
374
375 !---------------------------------------------------------------------------
376 !
377 ! Determine date separators from the original format string
378 !
379 !---------------------------------------------------------------------------
380 subroutine determine_separator(format_str, date_sep)
381 character(len=*), intent(in) :: format_str
382 character(len=1), intent(out) :: date_sep
383
384 date_sep = '-'
385 if (index(format_str, '/') > 0) date_sep = '/'
386
387 end subroutine determine_separator
388
389 !---------------------------------------------------------------------------
390 !
391 ! Convert datetime components to seconds since Unix epoch (1970-01-01 00:00:00)
392 !
393 !---------------------------------------------------------------------------
394 integer function datetime_to_seconds(year,month,day,hour,minute,second)
395 integer, intent(in) :: year,month,day,hour,minute,second
396 integer :: days_since_epoch,i
397
398 ! days since Unix epoch (1970-01-01)
399 days_since_epoch = 0
400
401 ! add days for each year from 1970 to year-1
402 do i = 1970, year - 1
403 days_since_epoch = days_since_epoch + days_in_year(i)
404 enddo
405
406 ! add days for months in current year (up to month-1)
407 do i = 1, month - 1
408 days_since_epoch = days_since_epoch + days_in_month(i, year)
409 enddo
410
411 ! add days in current month (day-1 because we start from day 1)
412 days_since_epoch = days_since_epoch + day - 1
413
414 ! convert to seconds and add time components
415 datetime_to_seconds = days_since_epoch * 86400 + hour * 3600 + minute * 60 + second
416
417 end function datetime_to_seconds
418
419 !---------------------------------------------------------------------------
420 !
421 ! Parse a datetime string and extract year, month, day, hour, minute, second
422 ! returns .true. if a valid datetime pattern is found
423 !
424 !---------------------------------------------------------------------------
425 logical function parse_datetime_pattern(str,start_pos,year,month,day,hour,minute,second,datetime_str)
426 character(len=*), intent(in) :: str
427 integer, intent(in) :: start_pos
428 integer, intent(out) :: year, month, day, hour, minute, second
429 character(len=*), intent(out) :: datetime_str
430 integer :: len_str,ierr
431 character(len=1) :: separator,sep2
432
433 parse_datetime_pattern = .false.
434 len_str = len_trim(str)
435
436 if (start_pos + 9 > len_str) return
437
438 ! Check for YYYY-MM-DD or YYYY/MM/DD pattern
439 separator = str(start_pos+4:start_pos+4)
440 sep2 = str(start_pos+7:start_pos+7)
441 if ((separator /= '-' .and. separator /= '/') .or. sep2 /= separator) return
442
443 ! parse date components using formatted read
444 read(str(start_pos:start_pos+9), '(i4,1x,i2,1x,i2)',iostat=ierr) year, month, day
445 if (ierr /= 0) return
446
447 ! Check if there's a time component
448 hour = 0; minute = 0; second = 0
449 datetime_str = str(start_pos:start_pos+9)
450
451 if (start_pos + 15 <= len_str .and. str(start_pos+10:start_pos+10) == ' ') then
452 if (str(start_pos+13:start_pos+13) == ':') then
453 ! parse time components HH:MM using formatted read
454 read(str(start_pos+11:start_pos+15), '(i2,1x,i2)', iostat=ierr) hour, minute
455 if (ierr /= 0) return
456 datetime_str = str(start_pos:start_pos+15)
457 ! read seconds if HH:MM:SS
458 if (str(start_pos+16:start_pos+16) == ':' .and. start_pos + 18 <= len_str) then
459 read(str(start_pos+17:start_pos+18), *, iostat=ierr) second
460 if (ierr /= 0) return
461 datetime_str = str(start_pos:start_pos+18)
462 endif
463 endif
464 endif
465
466 parse_datetime_pattern = .true.
467
468 end function parse_datetime_pattern
469
470 !---------------------------------------------------------------------------
471 !
472 ! check if a year is a leap year
473 !
474 !---------------------------------------------------------------------------
475 logical function is_leap_year(year)
476 integer, intent(in) :: year
477
478 is_leap_year = (mod(year, 4) == 0 .and. mod(year, 100) /= 0) .or. (mod(year, 400) == 0)
479
480 end function is_leap_year
481
482 !---------------------------------------------------------------------------
483 !
484 ! get number of days in a month (accounting for leap years)
485 !
486 !---------------------------------------------------------------------------
487 integer function days_in_month(month,year)
488 integer, intent(in) :: month, year
489 integer, parameter :: days_in_month_array(12) = &
490 (/31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31/)
491
492 days_in_month = days_in_month_array(month)
493 if (month == 2 .and. is_leap_year(year)) days_in_month = 29
494
495 end function days_in_month
496
497 !---------------------------------------------------------------------------
498 !
499 ! get number of days in a year (accounting for leap years)
500 !
501 !---------------------------------------------------------------------------
502 integer function days_in_year(year)
503 integer, intent(in) :: year
504
505 days_in_year = 365 + merge(1, 0, is_leap_year(year))
506
507 end function days_in_year
508
509 end module parsetext