-
Notifications
You must be signed in to change notification settings - Fork 4
/
timescalecalculus.py
1950 lines (1486 loc) · 81.7 KB
/
timescalecalculus.py
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
import operator
from functools import reduce # Added this because in python 3.* they changed the location of the reduce() method to the functools module
from scipy import integrate
from scipy.misc import derivative
import numpy as np
import matplotlib.pyplot as plt
import symengine
#import jitcdde
import mpmath
#
#
# Product function from
# https://stackoverflow.com/questions/595374/whats-the-python-function-like-sum-but-for-multiplication-product
#
def product(factors):
return reduce(operator.mul, factors, 1)
#
#
# Time scale class
#
#
class timescale:
def __init__(self,ts,name='none'):
self.ts = ts
self.name = name
# The following two dictionary data members are used for the memoization of the g_k and h_k functions of this class.
self.memo_g_k = {}
self.memo_h_k = {}
# The following data member allows users to access the functions of the matplotlib.pyplot interface.
# This means that a user has more control over the plotting functionality of this class.
# For instance, the xlabel and ylabel functions of the pyplot interface can be set via this data member.
# Then, whenever the plot() or scatter() functions of this class are called and displayed (via plt.show()), the xlabel and ylabel will display whatever the user set them to.
# See this resource for a list of available functionality: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html
self.plt = plt
#
# The following code validates the user-specified timescale to ensure that there are no overlaps such as:
# - a point given more than once
# - a point that is included in an interval
# - a point that is the starting value or ending value of an interval
# - an interval given more than once
# - overlapping intervals
#
# If a timescale is detected as invalid an Exception will be generated with a corresponding message that describes the cause of the invalidity.
#
for listItem in ts:
if isinstance(listItem, list):
if len(listItem) > 2:
raise Exception("Invalid timescale declaration: you cannot have an interval with more than one starting and one ending value.")
if len(listItem) < 2:
raise Exception("Invalid timescale declaration: an interval must have a starting value and an ending value.")
if listItem[0] > listItem[1]:
raise Exception("Invalid timescale declaration: you cannot have an interval in which the ending value is smaller than the starting value.")
if listItem[0] == listItem[1]:
raise Exception("Invalid timescale declaration: you cannot have an interval in which the starting value and ending value are equal (such an interval should be declared as a point).")
for listItemToCompare in ts:
if listItem == listItemToCompare and listItem is not listItemToCompare:
raise Exception("Invalid timescale declaration: you cannot include the same point or interval more than once.")
if listItem is not listItemToCompare:
if isinstance(listItem, list) and isinstance(listItemToCompare, list):
if (listItem[0] >= listItemToCompare[0] and listItem[0] <= listItemToCompare[1]) or (listItem[1] >= listItemToCompare[0] and listItem[1] <= listItemToCompare[1]):
raise Exception("Invalid timescale declaration: you cannot have overlapping intervals.")
if isinstance(listItem, list) and not isinstance(listItemToCompare, list):
if listItemToCompare >= listItem[0] and listItemToCompare <= listItem[1]:
raise Exception("Invalid timescale declaration: you cannot declare a point that is included in an interval (you cannot declare a value more than once).")
if not isinstance(listItem, list) and isinstance(listItemToCompare, list):
if listItem >= listItemToCompare[0] and listItem <= listItemToCompare[1]:
raise Exception("Invalid timescale declaration: you cannot declare a point that is included in an interval (you cannot declare a value more than once).")
print("Timescale successfully constructed:")
print("Timescale:", self.ts)
print("Timescale name:", self.name)
#
#
# forward jump
#
#
def sigma(self,t):
tIndex = 0
tNext = None
iterations = 0
for x in self.ts:
if (not isinstance(x, list) and t == x) or (isinstance(x, list) and t >= x[0] and t <= x[1]):
tIndex = iterations
break
iterations = iterations + 1
if (tIndex + 1) == len(self.ts):
return t
elif isinstance(self.ts[tIndex], list):
if (t != self.ts[tIndex][1]):
return t
else:
if (isinstance(self.ts[tIndex + 1], list)):
return self.ts[tIndex + 1][0]
else:
return self.ts[tIndex + 1]
else:
tNext = self.ts[tIndex + 1]
if isinstance(tNext, list):
return tNext[0]
else:
return tNext
#
#
# backwards jump
#
#
def rho(self,t):
if t==min(self.ts):
return t
else:
return max([x for x in self.ts if x<t])
#
#
# graininess
#
#
def mu(self,t):
for x in self.ts:
if isinstance(x, list) and t >= x[0] and t < x[1]:
return 0
return self.sigma(t)-t
#
#
# backward graininess
#
#
def nu(self,t):
return t-self.rho(t)
#
#
# delta derivative
#
#
def dderivative(self,f,t):
if self.sigma(t) == t:
return derivative(f, t, dx=(1.0/2**16))
else:
return (f(self.sigma(t))-f(t))/self.mu(t)
#
#
# nabla derivative
#
#
def nderivative(self,f,t):
return (f(t)-f(self.rho(t)))/self.nu(t)
#
#
# delta integral
#
#
def dintegral(self, f, t, s, throwExceptions = True):
# The following code checks that t and s are elements of the timescale
tIsAnElement = False
sIsAnElement = False
for x in self.ts:
if not isinstance(x, list) and x == t:
tIsAnElement = True
if not isinstance(x, list) and x == s:
sIsAnElement = True
if isinstance(x, list) and (t >= x[0] and t <= x[1]):
tIsAnElement = True
if isinstance(x, list) and (s >= x[0] and s <= x[1]):
sIsAnElement = True
if tIsAnElement and sIsAnElement:
break
errorOccurred = False
message = ""
if not tIsAnElement and not sIsAnElement:
message = "The bounds of the dintegral function, t = " + str(t) + " and s = " + str(s) + ", are not elements of the timescale."
errorOccurred = True
elif not tIsAnElement:
message = "The upper bound of dintegral function, t = " + str(t) + ", is not an element of timescale."
errorOccurred = True
elif not sIsAnElement:
message = "The lower bound of dintegral function, s = " + str(s) + ", is not an element of timescale."
errorOccurred = True
if errorOccurred:
if throwExceptions:
raise Exception(message)
else:
print("Warning: " + message)
# Validation code ends
points = []
intervals = []
for x in self.ts:
if not isinstance(x, list) and s <= x and t > x:
points.append(x)
elif isinstance(x, list) and s <= x[0] and t > x[1]:
points.append(x[1])
intervals.append(x)
elif isinstance(x, list) and s <= x[0] and t == x[1]:
intervals.append(x)
elif isinstance(x, list) and (s >= x[0] and s <= x[1]) and (t > x[1]):
points.append(x[1])
intervals.append([s, x[1]])
elif isinstance(x, list) and (s >= x[0] and s <= x[1]) and (t == x[1]):
intervals.append([s, x[1]])
elif isinstance(x, list) and (s >= x[0] and s < x[1]) and (t < x[1]):
intervals.append([s, t])
elif isinstance(x, list) and (s < x[0]) and (t >= x[0] and t < x[1]):
intervals.append([x[0], t])
# print(points)
# print(intervals)
sumOfIntegratedPoints = sum([self.mu(x)*f(x) for x in points])
sumOfIntegratedIntervals = sum([self.integrate_complex(f, x[0], x[1]) for x in intervals])
return sum([sumOfIntegratedPoints, sumOfIntegratedIntervals])
#
#
# Utility function to integrate potentially infinite timescale sections of points and intervals.
#
#
def compute_potentially_infinite_timescale(self, f, ts_generator_function, ts_generator_arguments):
print("ts_generator_arguments =", ts_generator_arguments)
print()
# The following argument "ts_gen_arg_mpf" has "mpf" on the end because the mpmath package passes "mpf" objects to this function as part of the nsum() function's design.
# These objects are converted to floats via the line: ts_gen_arg = float(mpmath.nstr(ts_gen_arg_mpf, n=15)).
# This conversion enables us to integrate/solve as usual for the generated points/intervals.
def wrapper_function(ts_gen_arg_mpf):
ts_gen_arg = float(mpmath.nstr(ts_gen_arg_mpf, n=15))
ts_item = ts_generator_function(ts_gen_arg)
next_ts_item = ts_generator_function(ts_gen_arg + 1)
self.validate_generated_timescale_value_pair(ts_item, next_ts_item, ts_generator_function)
print("wrapper_function: ts_gen_arg =", ts_gen_arg)
print("wrapper_function: ts_generator_arguments =", ts_generator_arguments)
print("wrapper_function: ts_item =", ts_item)
print("wrapper_function: next_ts_item =", next_ts_item)
if isinstance(ts_item, list):
print("wrapper_function: integrating over interval")
interval_result = self.integrate_complex(f, ts_item[0], ts_item[1])
step_after_interval = 0.0
if ts_generator_arguments[1] > ts_gen_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
step_after_interval = (next_ts_item - ts_item[1]) * f(ts_item[1])
print("interval_result =", interval_result)
print("step_after_interval =", step_after_interval)
print("*****wrapper_function: RETURNING interval_result + step_after_interval =", interval_result + step_after_interval)
print()
return interval_result + step_after_interval
else:
print("wrapper_function: calculating discrete value")
discrete_result = 0.0
if ts_generator_arguments[1] > ts_gen_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
discrete_result = (next_ts_item - ts_item) * f(ts_item)
print("*****wrapper_function: RETURNING discrete result value =", discrete_result)
print()
return discrete_result
result = mpmath.nsum(wrapper_function, ts_generator_arguments)
print("----RESULT----")
print()
return result
#
#
# Utility function to integrate a generated timescale section of points and intervals for t.
# Arguments:
# f: The function with which to solve the timescale for a particular target value = t.
#
# t_0: The timescale value from which to begin solving.
#
# t_target: The timescale value for which to solve.
#
# ts_generator_function: The function that, when it is fed values where, for any value n, ts_generator_arguments[0] <= n <= ts_generator_arguments[1] is True AND (n_(m+1) - n_m) = 1.
# In other words: the difference between two consecutive n-values is always 1.
#
# ts_generator_arguments: A list of two numbers of the form [start, end] where start is the first value fed to the ts_generator_function and end is the last value fed to that same function.
# As mentioned before, the different between any two consecutive numbers between start and end is always 1 -- this is purely a method for generating the timescale.
# As an example: if ts_generator_arguments = [1, 4], then ts_generator_function will be fed the following values in the listed order: 1, 2, 3, 4.
# That ts_generator_function will then return, for each value fed to it, a particular timescale section.
# compute_potentially_infinite_timescale_for_t() will then solve over these sections.
#
# signif_count: How many previously calcuated values (that are obtained from solving integrals or discrete points) to check the "significance" of -- see "signif_threshold" for more information.
#
# signif_threshold: The value that a particular calculated value (from solving an integral or discrete point) must be below to be considered "insignificant".
# If m=signif_count previously calculated values are all below this signif_threshold, then the compute_potentially_infinite_timescale_for_t() function will
# return the current result sum with a warning message.
#
# increasing_always_signif: If this boolean is True: when insignificant_prior_results() detects that result values seem to be increasing (when they were decreasing before),
# it will not consider them to be insignificant even if all are below the signif_threshold.
#
#
def compute_potentially_infinite_timescale_for_t(self, f, t_target, t_0, ts_generator_function, ts_generator_arguments, signif_count = 10, signif_threshold = 0.0000001, increasing_always_signif = True):
print("ts_generator_arguments =", ts_generator_arguments)
print()
def wrapper_function(ts_gen_arg):
ts_item = ts_generator_function(ts_gen_arg)
next_ts_item = ts_generator_function(ts_gen_arg + 1)
self.validate_generated_timescale_value_pair(ts_item, next_ts_item, ts_generator_function)
print("wrapper_function: ts_gen_arg =", ts_gen_arg)
print("wrapper_function: ts_generator_arguments =", ts_generator_arguments)
print("wrapper_function: t_target =", t_target)
print("wrapper_function: ts_item =", ts_item)
print("wrapper_function: next_ts_item =", next_ts_item)
if isinstance(ts_item, list):
print("wrapper_function: integrating over interval")
if ts_item[0] > t_target:
raise Exception("ts_item[0] = " + str(ts_item[0]) + " was greater than t_target = " + str(t_target) + " -- the timescale does not contain t_target")
if t_target > ts_item[1]:
interval_result = self.integrate_complex(f, ts_item[0], ts_item[1])
else:
interval_result = self.integrate_complex(f, ts_item[0], t_target)
print("*****wrapper_function: t_target <= ts_item[1] -> RETURNING interval_result =", interval_result)
return {"result" : interval_result, "found_t_target" : True}
step_after_interval = 0.0
if ts_generator_arguments[1] > ts_gen_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
step_after_interval = (next_ts_item - ts_item[1]) * f(ts_item[1])
print("interval_result =", interval_result)
print("step_after_interval =", step_after_interval)
print("*****wrapper_function: RETURNING interval_result + step_after_interval =", interval_result + step_after_interval)
print()
if t_target == next_ts_item:
return {"result" : interval_result + step_after_interval, "found_t_target" : True}
else:
return {"result" : interval_result + step_after_interval, "found_t_target" : False}
else:
print("wrapper_function: calculating discrete value")
if ts_item > t_target:
raise Exception("ts_item = " + str(ts_item) + " was greater than t_target = " + str(t_target) + " -- the timescale does not contain t_target")
discrete_result = 0.0
if ts_generator_arguments[1] > ts_gen_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
discrete_result = (next_ts_item - ts_item) * f(ts_item)
print("*****wrapper_function: RETURNING discrete result value =", discrete_result)
print()
if t_target == ts_item:
return {"result" : discrete_result, "found_t_target" : True}
else:
return {"result" : discrete_result, "found_t_target" : False}
result = self.special_sum_function(f, t_target, t_0, wrapper_function, ts_generator_function, ts_generator_arguments, prior_results_significance_count = signif_count, significance_limit = signif_threshold, increasing_always_signif = increasing_always_signif)
print()
print("----RESULT----")
print()
return result
#
#
# This function is used by the compute_potentially_infinite_timescale_for_t() function of this class.
# It is responsible for summing the results obtained from solving discrete points and intervals in a generated timescale.
# It is a "special" function because, in addition to summing, it also checks -- via the insignificant_prior_results() function -- the values of the previous n=prior_results_significance_count calculated values.
# Calculated values that are below the significance_limit are considered "insignificant" -- if all n previously
# calculated values are "insignificant", the special_sum_function() return the current result along with a warning message.
# The reasoning behind having a significance_limit is so that an overflow is less likely to occur -- if result values are allowed to indefinitely become smaller, then it is likely that the precision limit on the float
# data type is reached which results in an overflow error.
# See the description of the insignificant_prior_results() function for more information.
#
#
def special_sum_function(self, f, t_target, t_0, wrapper_function, ts_generator_function, ts_generator_arguments, prior_results_significance_count, significance_limit, increasing_always_signif):
result = 0.0
iteration = 0
ts_generator_arg = ts_generator_arguments[0]
iterations_limit = ts_generator_arguments[1] - ts_generator_arguments[0]
found_t_target = False
print("iterations_limit =", iterations_limit)
print("prior_results_significance_count =", prior_results_significance_count)
print("significance_limit =", significance_limit)
# Initializing prior results list.
prior_results = []
i = 0
while i < prior_results_significance_count:
prior_results.append(0.0)
i = i + 1
# Finding t_0 in generated timescale.
while iteration < iterations_limit:
print()
print("iteration =", iteration)
print("ts_generator_arg =", ts_generator_arg)
find_t_0_dictionary_result = self.special_sum_function_find_t_0(f, t_target, t_0, wrapper_function, ts_generator_function, ts_generator_arg, ts_generator_arguments,)
iteration = iteration + 1
ts_generator_arg = ts_generator_arg + 1
if find_t_0_dictionary_result["found_t_0"] is True:
if find_t_0_dictionary_result["found_t_target"] is True:
found_t_target = True
prior_results[iteration % prior_results_significance_count] = find_t_0_dictionary_result["result"]
result = result + find_t_0_dictionary_result["result"]
break
# Solving over generated timescale sections for t_target if t_target has not already been found.
if found_t_target is False:
while iteration < iterations_limit:
print()
print("iteration =", iteration)
print("ts_generator_arg =", ts_generator_arg)
dictionary_result = wrapper_function(ts_generator_arg)
prior_results[iteration % prior_results_significance_count] = dictionary_result["result"]
result = result + dictionary_result["result"]
if dictionary_result["found_t_target"] is True:
print("special_sum_function: found_t_target -> returning result")
break
if iteration >= prior_results_significance_count:
print("special_sum_function: checking significance of the last " + str(prior_results_significance_count) + " results:")
if self.insignificant_prior_results(iteration, prior_results, prior_results_significance_count, significance_limit, increasing_always_signif) is True:
print("special_sum_function: ***WARNING***: insignificant results detected: returning result before t_target was found")
break
iteration = iteration + 1
ts_generator_arg = ts_generator_arg + 1
print("special_sum_function: before result")
print("iteration =", iteration)
print("iterations_limit =", iterations_limit)
print("ts_generator_arg =", ts_generator_arg)
if iteration == iterations_limit:
print("special_sum_function: iterations_limit reached -- t_target may not have been found")
return result
#
#
# Utility function used by the special_sum_function() function of this class.
# This function finds t_0 (the starting value from which to begin solving) in the generated timescale.
# This function also handles cases where t_0 == t_target and throws and exception when ts_item > t_0 (which indicates that t_0 is not in the timescale).
#
#
def special_sum_function_find_t_0(self, f, t_target, t_0, wrapper_function, ts_generator_function, ts_generator_arg, ts_generator_arguments):
if t_0 > t_target:
raise Exception("t_0 > t_target")
print("find_t_0: t_0 =", t_0)
print("find_t_0: t_target =", t_target)
print("find_t_0: ts_generator_arg =", ts_generator_arg)
ts_item = ts_generator_function(ts_generator_arg)
next_ts_item = ts_generator_function(ts_generator_arg + 1)
self.validate_generated_timescale_value_pair(ts_item, next_ts_item, ts_generator_function)
print("find_t_0: ts_item =", ts_item)
print("find_t_0: next_ts_item =", next_ts_item)
if isinstance(ts_item, list):
if ts_item[0] <= t_0 <= ts_item[1]:
if t_target > ts_item[1]:
interval_result = self.integrate_complex(f, t_0, ts_item[1])
step_after_interval = 0.0
if ts_generator_arguments[1] > ts_generator_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
step_after_interval = (next_ts_item - ts_item[1]) * f(ts_item[1])
print("interval_result =", interval_result)
print("step_after_interval =", step_after_interval)
print("*****find_t_0: RETURNING interval_result + step_after_interval =", interval_result + step_after_interval)
print()
if t_target == next_ts_item:
return {"result" : interval_result + step_after_interval, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : True}
else:
return {"result" : interval_result + step_after_interval, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : False}
else:
interval_result = self.integrate_complex(f, t_0, t_target)
print("*****special_sum_function_find_t_0: t_target <= ts_item[1] -> RETURNING interval_result =", interval_result)
return {"result" : interval_result, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : True}
elif ts_item[0] > t_0:
raise Exception("ts_item[0] > t_0 -- t_0 was not in the timescale")
else:
if t_0 == ts_item:
if t_0 != t_target:
if ts_item > t_target:
raise Exception("ts_item = " + str(ts_item) + " was greater than t_target = " + str(t_target) + " -- the timescale does not contain t_target")
discrete_result = 0.0
if ts_generator_arguments[1] > ts_generator_arg:
if isinstance(next_ts_item, list):
next_ts_item = next_ts_item[0]
discrete_result = (next_ts_item - ts_item) * f(ts_item)
print("*****find_t_0: RETURNING discrete result value =", discrete_result)
print()
if t_target == ts_item:
print("t_target == ts_item")
return {"result" : discrete_result, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : True}
else:
print("t_target != ts_item")
return {"result" : discrete_result, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : False}
else:
return {"result" : 0.0, "ts_generator_arg" : ts_generator_arg, "found_t_0" : True, "found_t_target" : True}
elif ts_item > t_0:
raise Exception("ts_item > t_0 -- t_0 was not in the timescale")
return {"result" : None, "ts_generator_arg" : ts_generator_arg, "found_t_0" : False, "found_t_target" : False}
#
#
# Utility function for the special sum function -- it checks the last n=prior_results_significance_count prior_results to see if they are below the significance_limit.
# If all n prior_results are below that limit, this function will return True.
# Else it will return False.
#
# The argument "increasing_always_signif" is used to check whether the most recently obtained result is greater than ANY of the previous n=prior_results_significance_count results.
# If this condition holds, then -- regardless of whether all results are below the significance_limit -- this function will consider the results to be significant.
# The reasoning for this is that, since the results seem to be increasing, they may climb above the significance_limit at some point.
#
#
def insignificant_prior_results(self, iteration, prior_results, prior_results_significance_count, significance_limit, increasing_always_signif):
i = 0
insignificant = True
last_obtained_result_abs_val = abs(prior_results[(iteration) % prior_results_significance_count])
while i < prior_results_significance_count:
# print("abs(prior_results[((" + str(iteration) + " + " + str(i) + ") % " + str(prior_results_significance_count) + ") = " + str((iteration + i) % prior_results_significance_count) + "]) =", abs(prior_results[(iteration + i) % prior_results_significance_count]))
print("abs(prior_results[" + str((iteration + i) % prior_results_significance_count) + "]) =", abs(prior_results[(iteration + i) % prior_results_significance_count]))
obtained_result_abs_val = abs(prior_results[(iteration + i) % prior_results_significance_count])
if obtained_result_abs_val > significance_limit:
insignificant = False
if increasing_always_signif is True:
if last_obtained_result_abs_val > obtained_result_abs_val:
insignificant = False
i = i + 1
if insignificant:
return True
else:
return False
#
#
# Utility function to check if a pair of generated timescale values are valid.
# "Valid" in this case means that, for any ts_item, the condition (next_ts_item > ts_item) holds.
# This should be true regardless of whether ts_item or next_ts_item are intervals or discrete points.
#
#
def validate_generated_timescale_value_pair(self, ts_item, next_ts_item, ts_generator_function):
description = "The given function " + str(locals().get("ts_generator_function")) + " did not generate a strictly increasing timescale."
if isinstance(ts_item, list):
if isinstance(next_ts_item, list):
if ts_item[1] >= next_ts_item[0]:
raise Exception("(ts_item[1] = " + str(ts_item[1]) + ") >= (next_ts_item[0] = " + str(next_ts_item[0]) + ")\n" + description)
else:
if ts_item[1] >= next_ts_item:
raise Exception("(ts_item[1] = " + str(ts_item[1]) + ") >= (next_ts_item = " + str(next_ts_item) + ")\n" + description)
else:
if isinstance(next_ts_item, list):
if ts_item >= next_ts_item[0]:
raise Exception("(ts_item = " + str(ts_item) + ") >= (next_ts_item[0] = " + str(next_ts_item[0]) + ")\n" + description)
else:
if ts_item >= next_ts_item:
raise Exception("(ts_item = " + str(ts_item) + ") >= (next_ts_item = " + str(next_ts_item) + ")\n" + description)
#
#
# Utility function to get n values of a generated timescale where the starting values is 0.
#
#
def get_n_ts_gen_values(self, ts_gen_function, n):
i = 0
generated_timescale = []
while i < n:
generated_timescale.append(ts_gen_function(i))
i = i + 1
return generated_timescale
#
#
# Utility function to print n values of a generated timescale where the starting value is 0.
#
#
def print_n_ts_gen_values(self, ts_gen_function, n):
i = 0
generated_timescale = []
while i < n:
generated_timescale.append(ts_gen_function(i))
i = i + 1
print("Generated timescale:")
print(generated_timescale)
print()
#
#
# Utility function to get the values of a generated timescale based on a starting value and ending value.
#
#
def get_ts_gen_values(self, ts_gen_function, start, end):
i = start
generated_timescale = []
while i < end:
generated_timescale.append(ts_gen_function(i))
i = i + 1
return generated_timescale
#
#
# Utility function to print the values of a generated timescale based on a starting value and ending value.
#
#
def print_ts_gen_values(self, ts_gen_function, start, end):
i = start
generated_timescale = []
while i < end:
generated_timescale.append(ts_gen_function(i))
i = i + 1
print("Generated timescale:")
print(generated_timescale)
print()
#
#
# Utility function to integrate potentially complex functions.
#
#
def integrate_complex(self, f, s, t, **kwargs):
def real_component(t):
return np.real(f(t))
def imaginary_component(t):
return np.imag(f(t))
real_result = float(mpmath.nstr(mpmath.quad(real_component, [s, t], **kwargs), n=15))
imaginary_result = float(mpmath.nstr(mpmath.quad(imaginary_component, [s, t], **kwargs), n=15))
if imaginary_result == 0:
return real_result
else:
return real_result + 1j*imaginary_result
#
#
# Generalized g_k polynomial from page 38 with memoization.
#
#
def g_k(self, k, t, s):
if (k < 0):
raise Exception("g_k(): k should never be less than 0!")
elif (k != 0):
currentKey = str(k) + ":" + str(t) + ":" + str(s)
if currentKey in self.memo_g_k:
return self.memo_g_k[currentKey]
else:
def g(x):
return self.g_k(k - 1, self.sigma(x), s)
integralResult = self.dintegral(g, t, s, throwExceptions = False)
self.memo_g_k[currentKey] = integralResult
return integralResult
elif (k == 0):
return 1
#
#
# Generalized h_k polynomial from page 38 with memoization.
#
#
def h_k(self, k, t, s):
if (k < 0):
raise Exception("h_k(): k should never be less than 0!")
elif (k != 0):
currentKey = str(k) + ":" + str(t) + ":" + str(s)
if currentKey in self.memo_h_k:
return self.memo_h_k[currentKey]
else:
def h(x):
return self.h_k(k - 1, x, s)
# print("h_k: t =", t)
integralResult = self.dintegral(h, t, s, throwExceptions = False)
self.memo_h_k[currentKey] = integralResult
return integralResult
elif (k == 0):
return 1
#
#
# Cylinder transformation from definition 2.21
#
#
def cyl(self, t, z):
if (self.mu(t) == 0):
return z
else:
return 1/self.mu(t) * np.log(1 + z*self.mu(t))
#
#
# Delta exponential based on definition 2.30
#
#
def dexp_p(self, p, t, s):
def f(t):
if(t>s):
return self.cyl(t, p(t))
elif(t==s):
return 1.0
else:
return self.dexp_p(p, s, t)
return np.exp(self.dintegral(f, t, s))
#
#
# forward circle minus
#
#
def mucircleminus(self,f,t):
return -f(t)/(1+f(t)*self.mu(t))
#
#
# The forward-derivative cosine trigonometric function.
#
#
def dcos_p(self, p, t, s):
dexp_p1 = self.dexp_p(lambda x: p(x) * 1j, t, s)
dexp_p2 = self.dexp_p(lambda x: p(x) * -1j, t, s)
result = ((dexp_p1 + dexp_p2) / 2)
if np.imag(result) == 0:
return np.real(result)
else:
return result
#
#
# The forward-derivative sine trigonometric function.
#
#
def dsin_p(self, p, t, s):
dexp_p1 = self.dexp_p(lambda x: p(x) * 1j, t, s)
dexp_p2 = self.dexp_p(lambda x: p(x) * -1j, t, s)
result = ((dexp_p1 - dexp_p2) / 2j)
if np.imag(result) == 0:
return np.real(result)
else:
return result
#
#
# The Laplace transform function.
#
#
def laplace_transform(self, f, z, s):
def g(t):
return f(t) * self.dexp_p(lambda t: self.mucircleminus(z, t), self.sigma(t), s)
return self.dintegral(g, max(self.ts), s)
#
#
# Ordinary Differential Equation solver for equations of the form
#
# y'(t) = p(t)*y(t)
#
# where t_0 is the starting value in the timescale and
#
# y_0 = y(t_0)
#
# is the initial value provided by the user.
#
# Arguments:
# "y_0" is the initial value assigned to y(t_0) that is used as a starting point to evaluate the ODE.
#
# "t_0" is the initial value that is considered the starting point in the timescale from which to solve subsequent points.
# t_0 is the value that is plugged into y to determine y_0 via: y_0 = y(t_0).
#
# "t_target" is the timescale value for which y should be evaluated and returned.
#
# "y_prime" is the function y'(t) of the ODE y'(t) = p(t)*y(t).
# NOTE: "y_prime" MUST be defined such that the arguments ("t" and "y") appear in this order: y_prime(t, y).
# If this particular order is not used, then the solve_ode_for_t() function will plug in the wrong values for t and y when solving.
# This means that the solve_ode_for_t() function will (except in specific cases like when t = y) return an incorrect result.
#
# Other Variables:
# "t_current" is the current value of t. t must be a value in the timescale.
#
# "y_current" holds the value obtained from y(t_current).
#
# The function will solve for the next t value until the value of y(t_target) is obtained.
# y(t_target) is then returned.
# Currently, t_target > t_0 is a requirement -- solving for a t_target < t_0 is not supported.
#
#
def solve_ode_for_t(self, y_0, t_0, t_target, y_prime): # Note: y(t_0) = y_0
# print("solve_ode_for_t arguments:")
# print("y_0 =", y_0)
# print("t_0 =", t_0)
# print("t_target =", t_target)
# print("")
# The following is more validation code -- this is very similar to the validation code in the dIntegral function.
#----------------------------------------------------------------------------#
t_in_ts = False
t_0_in_ts = False
discretePoint = False
for x in self.ts:
if not isinstance(x, list) and t_target == x:
t_in_ts = True
if not isinstance(x, list) and t_0 == x:
discretePoint = True
t_0_in_ts = True
if isinstance(x, list) and t_target <= x[1] and t_target >= x[0]:
t_in_ts = True
if isinstance(x, list) and t_0 < x[1] and t_0 >= x[0]:
discretePoint = False
t_0_in_ts = True
if isinstance(x, list) and t_0 == x[1]:
discretePoint = True
t_0_in_ts = True
if t_in_ts and t_0_in_ts:
break
if t_in_ts and not t_0_in_ts:
raise Exception("solve_ode_for_t: t_0 is not a value in the timescale.")
if not t_in_ts and t_0_in_ts:
raise Exception("solve_ode_for_t: t_target is not a value in the timescale.")
if not t_in_ts and not t_0_in_ts:
raise Exception("solve_ode_for_t: t_0 and t_target are not values in the timescale.")
if t_0 == t_target:
return y_0
elif t_0 > t_target:
raise Exception("solve_ode_for_t: t_0 cannot be greater than t_target.")