Repository navigation
Expand file tree
/
Copy pathtest_function.py
More file actions
2262 lines (1897 loc) · 75.9 KB
/
Copy pathtest_function.py
File metadata and controls
2262 lines (1897 loc) · 75.9 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
"""Unit tests for the Function class. Each method in tis module tests an
individual method of the Function class. The tests are made on both the
expected behaviour and the return instances."""
import weakref
import matplotlib as plt
import numpy as np
import pytest
from rocketpy import Function
from rocketpy.mathutils._calc.polation_nd import LinearNDPolation
from rocketpy.mathutils.function import SourceType
plt.rcParams.update({"figure.max_open_warning": 0})
@pytest.mark.parametrize("a", [-1, 0, 0.5, 1, 2, 2.5, 3.5, 4, 5])
@pytest.mark.parametrize("b", [-1, 0, 0.5, 1, 2, 2.5, 3.5, 4, 5])
def test_integral_linear_interpolation(linearly_interpolated_func, a, b):
"""Test the integral method of the Function class.
Parameters
----------
linear_func : rocketpy.Function
A Function object created from a list of values.
"""
# Test integral
assert isinstance(linearly_interpolated_func.integral(a, b, numerical=True), float)
assert np.isclose(
linearly_interpolated_func.integral(a, b, numerical=False),
linearly_interpolated_func.integral(a, b, numerical=True),
atol=1e-3,
)
@pytest.mark.parametrize("func", ["linear_func", "spline_interpolated_func"])
@pytest.mark.parametrize("a", [-1, -0.5, 0, 0.5, 1, 2, 2.5, 3.5, 4, 5])
@pytest.mark.parametrize("b", [-1, -0.5, 0, 0.5, 1, 2, 2.5, 3.5, 4, 5])
def test_integral_spline_interpolation(request, func, a, b):
"""Test the integral method of the Function class.
Parameters
----------
spline_func : rocketpy.Function
A Function object created from a list of values.
a : float
Lower limit of the integral.
b : float
Upper limit of the integral.
"""
# Test integral
# Get the function from the fixture
func = request.getfixturevalue(func)
assert np.isclose(
func.integral(a, b, numerical=False),
func.integral(a, b, numerical=True),
atol=1e-3,
)
@pytest.mark.parametrize(
"func_input, derivative_input, expected_derivative",
[
(1, 0, 0), # Test case 1: Function(1)
(lambda x: x, 0, 1), # Test case 2: Function(lambda x: x)
(lambda x: x**2, 1, 2), # Test case 3: Function(lambda x: x**2)
],
)
def test_differentiate(func_input, derivative_input, expected_derivative):
"""Test the differentiate method of the Function class.
Parameters
----------
func_input : function
A function object created from a list of values.
derivative_input : int
Point at which to differentiate.
expected_derivative : float
Expected value of the derivative.
"""
func = Function(func_input)
assert isinstance(func.differentiate(derivative_input), float)
assert np.isclose(func.differentiate(derivative_input), expected_derivative)
@pytest.mark.parametrize(
"func_input, derivative_input, expected_first_derivative",
[
(1, 0, 0), # Test case 1: Function(1)
(lambda x: x, 0, 1), # Test case 2: Function(lambda x: x)
(lambda x: x**2, 1, 2), # Test case 3: Function(lambda x: x**2)
(lambda x: -(x**3), 2, -12), # Test case 4: Function(lambda x: -x**3)
],
)
def test_differentiate_complex_step(
func_input, derivative_input, expected_first_derivative
):
"""Test the differentiate_complex_step method of the Function class.
Parameters
----------
func_input : function
A function object created from a list of values.
derivative_input : int
Point at which to differentiate.
expected_derivative : float
Expected value of the derivative.
"""
func = Function(func_input)
assert isinstance(func.differentiate_complex_step(x=derivative_input), float)
assert np.isclose(
func.differentiate_complex_step(x=derivative_input, order=1),
expected_first_derivative,
)
@pytest.mark.parametrize(
"interpolation", ["linear", "polynomial", "spline", "akima", "pchip"]
)
def test_differentiate_complex_step_1d_array_source(interpolation):
"""Complex-step differentiation supports every 1-D interpolator."""
# Arrange
source = np.column_stack((np.arange(4.0), np.arange(4.0) ** 2))
func = Function(source, interpolation=interpolation, extrapolation="natural")
point = 1.5
expected_derivative = func._evaluator.derivative(point)
# Act
derivative = func.differentiate_complex_step(point)
# Assert
assert derivative == pytest.approx(expected_derivative)
def test_get_value():
"""Tests the get_value method of the Function class.
Both with respect to return instances and expected behaviour.
"""
func = Function(lambda x: 2 * x)
assert isinstance(func.get_value(1), (int, float))
@pytest.mark.parametrize("vectorized_callable", [False, True])
def test_get_value_1d_callable_preserves_batched_complex_values(
vectorized_callable,
):
"""Complex batches retain their imaginary component for 1-D callables."""
# Arrange
func = Function(lambda x: x**2, vectorized_callable=vectorized_callable)
points = np.array([1 + 2j, 2 + 3j])
# Act
values = func.get_value(points)
# Assert
assert np.iscomplexobj(values)
assert values == pytest.approx(points**2)
@pytest.mark.parametrize("vectorized_callable", [False, True])
def test_get_value_nd_callable_preserves_batched_complex_values(
vectorized_callable,
):
"""Complex batches retain their imaginary component for N-D callables."""
# Arrange
func = Function(
lambda x, y: x**2 + y,
inputs=["x", "y"],
vectorized_callable=vectorized_callable,
)
x_points = np.array([1 + 2j, 2 + 3j])
y_points = np.array([3.0, 4.0])
# Act
values = func.get_value(x_points, y_points)
# Assert
assert np.iscomplexobj(values)
assert values == pytest.approx(x_points**2 + y_points)
@pytest.mark.parametrize(
"interpolation", ["linear", "polynomial", "spline", "akima", "pchip"]
)
@pytest.mark.parametrize("point_count", [2, 10])
def test_get_value_1d_array_preserves_batched_complex_step(interpolation, point_count):
"""All 1-D interpolators preserve short and vectorized complex batches."""
# Arrange
source = np.column_stack((np.arange(4.0), np.arange(4.0) ** 2))
func = Function(source, interpolation=interpolation, extrapolation="natural")
real_points = np.linspace(1.1, 1.9, point_count)
step = 1e-100
complex_points = real_points + step * 1j
expected_derivatives = func._evaluator.derivative(real_points)
# Act
values = func.get_value(complex_points)
# Assert
assert np.iscomplexobj(values)
assert np.imag(values) / step == pytest.approx(expected_derivatives)
def test_get_value_1d_array_complex_batch_uses_real_part_for_interval_lookup():
"""Scalar and vector complex queries select the same interval at a knot."""
# Arrange
func = Function(
[(0.0, 0.0), (1.0, 1.0), (2.0, 4.0)],
interpolation="linear",
extrapolation="natural",
)
step = 1e-100
points = np.full(10, 1.0 + step * 1j)
# Act
derivatives = np.imag(func.get_value(points)) / step
# Assert
assert derivatives == pytest.approx(np.ones(10))
@pytest.mark.parametrize("interpolation", ["linear", "shepard", "rbf"])
def test_get_value_scattered_nd_array_rejects_complex_coordinates(interpolation):
"""Scattered N-D interpolators reject scalar and batched complex inputs."""
# Arrange
source = np.array(
[
[0.0, 0.0, 0.0],
[0.0, 1.0, 1.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 2.0],
]
)
func = Function(source, interpolation=interpolation, extrapolation="natural")
error_message = "Complex coordinates are not supported"
# Act / Assert
with pytest.raises(TypeError, match=error_message):
func.get_value(0.25 + 1e-100j, 0.25)
with pytest.raises(TypeError, match=error_message):
func.get_value(np.array([0.25 + 1e-100j]), np.array([0.25]))
@pytest.mark.parametrize("extrapolation", ["natural", "constant", "zero"])
def test_get_value_regular_grid_rejects_complex_coordinates(extrapolation):
"""Regular-grid interpolation rejects scalar and batched complex inputs."""
# Arrange
axes = [np.array([0.0, 1.0]), np.array([0.0, 1.0])]
grid_data = np.array([[0.0, 1.0], [1.0, 2.0]])
func = Function(
(axes, grid_data),
interpolation="regular_grid",
extrapolation=extrapolation,
)
error_message = "Complex coordinates are not supported"
# Act / Assert
with pytest.raises(TypeError, match=error_message):
func.get_value(0.25 + 1e-100j, 0.25)
with pytest.raises(TypeError, match=error_message):
func.get_value(np.array([0.25 + 1e-100j]), np.array([0.25]))
def test_get_value_complex_constant_preserves_scalar_and_batched_values():
"""Complex constant sources construct and evaluate without losing dtype."""
# Arrange
func = Function(1 + 2j)
points = np.array([0.0, 1.0])
# Act
scalar_value = func.get_value(0.0)
batch_values = func.get_value(points)
# Assert
assert scalar_value == 1 + 2j
assert np.iscomplexobj(batch_values)
assert batch_values == pytest.approx(np.array([1 + 2j, 1 + 2j]))
def test_get_value_treats_zero_dimensional_numpy_arrays_as_scalars():
"""NumPy 0-D arrays expose __iter__, but Function should treat them as scalars."""
func = Function([(0, 0), (1, 2), (2, 4)], interpolation="linear")
scalar_arg = np.array(1.0)
assert np.isclose(func.get_value(scalar_arg), 2.0)
assert np.isclose(func.get_value_opt(scalar_arg), 2.0)
assert Function(3.0).get_value(scalar_arg) == 3.0
@pytest.mark.parametrize("shape", [(2, 2), (2, 5)])
def test_get_value_1d_array_preserves_multidimensional_batch_shape(shape):
"""Sampled 1-D evaluation preserves batch shape on both threshold paths."""
# Arrange
func = Function([(0.0, 1.0), (1.0, 3.0), (2.0, 5.0)], interpolation="linear")
points = np.linspace(0.0, 2.0, np.prod(shape)).reshape(shape)
expected = 2.0 * points + 1.0
# Act
values = func.get_value(points)
optimized_values = func.get_value_opt(points)
# Assert
assert values.shape == shape
assert optimized_values.shape == shape
assert values == pytest.approx(expected)
assert optimized_values == pytest.approx(expected)
def test_get_value_1d_nonvectorized_callable_flattens_and_restores_batch_shape():
"""Plain 1-D callables receive scalar values from multidimensional batches."""
# Arrange
def scalar_source(x):
assert np.ndim(x) == 0
return 2.0 * x + 1.0
func = Function(scalar_source)
points = np.arange(6.0).reshape(2, 3)
# Act
values = func.get_value(points)
# Assert
assert values.shape == points.shape
assert values == pytest.approx(2.0 * points + 1.0)
@pytest.mark.parametrize("source_type", ["callable", "scattered", "regular_grid"])
def test_get_value_nd_preserves_broadcast_shape(source_type):
"""N-D callable and sampled Functions restore the broadcast input shape."""
# Arrange
if source_type == "callable":
func = Function(lambda x, y: x + 2.0 * y, inputs=["x", "y"])
elif source_type == "scattered":
source = np.array(
[
[0.0, 0.0, 0.0],
[0.0, 1.0, 2.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 3.0],
]
)
func = Function(source, interpolation="linear", extrapolation="constant")
else:
axes = [np.array([0.0, 1.0]), np.array([0.0, 1.0])]
grid_data = np.array([[0.0, 2.0], [1.0, 3.0]])
func = Function((axes, grid_data), interpolation="regular_grid")
x_points = np.array([[0.2], [0.8]])
y_points = np.array([[0.1, 0.4, 0.7]])
expected = x_points + 2.0 * y_points
# Act
values = func.get_value(x_points, y_points)
optimized_values = func.get_value_opt(x_points, y_points)
# Assert
assert values.shape == expected.shape
assert optimized_values.shape == expected.shape
assert values == pytest.approx(expected)
assert optimized_values == pytest.approx(expected)
def test_evaluator_exposes_cached_dispatch_closures():
"""Function construction reuses the evaluator's cached dispatch closures."""
# Arrange
func = Function([(0.0, 0.0), (1.0, 1.0)], interpolation="linear")
# Act / Assert
assert func._array_evaluate is func._evaluator.expose()
assert func._array_evaluate_scalar is func._evaluator.expose_scalar()
assert func._array_evaluate_vector is func._evaluator.expose_vector()
def test_get_value_opt_does_not_keep_function_alive():
"""The optimized dispatch closure does not create a Function reference cycle."""
# Arrange
func = Function([(0.0, 0.0), (1.0, 1.0)], interpolation="linear")
function_reference = weakref.ref(func)
# Act
del func
# Assert
assert function_reference() is None
def test_vectorized_callable_opt_in_and_arithmetic_propagation():
"""Callable vectorization is opt-in and propagates through safe arithmetic."""
calls = {"count": 0}
def vectorized_source(x):
calls["count"] += 1
return np.asarray(x) * 2
vectorized = Function(vectorized_source, vectorized_callable=True)
plain = Function(lambda x: x * 2)
points = np.array([1.0, 2.0, 3.0])
assert np.array_equal(vectorized.get_value(points), np.array([2.0, 4.0, 6.0]))
assert calls["count"] == 1
calls["count"] = 0
assert np.array_equal((vectorized + 1).get_value(points), np.array([3.0, 5.0, 7.0]))
assert calls["count"] == 1
calls["count"] = 0
assert np.array_equal(
(vectorized + plain).get_value(points), np.array([4.0, 8.0, 12.0])
)
assert calls["count"] == len(points)
array_func = Function([(1, 10), (2, 20), (3, 30)], interpolation="linear")
calls["count"] = 0
assert np.array_equal(
(vectorized + array_func).get_value(points), np.array([12.0, 24.0, 36.0])
)
assert calls["count"] == 1
calls["count"] = 0
assert np.array_equal(
(vectorized + array_func).get_value(points.tolist()),
np.array([12.0, 24.0, 36.0]),
)
assert calls["count"] == 1
def test_get_value_broadcasts_nd_scalar_and_vector_inputs():
"""ND evaluation should treat any vector argument as a batch."""
func = Function(lambda x, y: x + y, inputs=["x", "y"])
result = func.get_value(1.0, np.array([2.0, 3.0]))
assert np.array_equal(result, np.array([3.0, 4.0]))
def test_regular_grid_get_value_opt_broadcasts_scalar_and_vector_inputs():
"""Regular-grid fast evaluation should also broadcast mixed ND inputs."""
grid_data = np.array([[0.0, 1.0], [10.0, 11.0]])
func = Function.from_grid(
grid_data,
[np.array([0.0, 1.0]), np.array([0.0, 1.0])],
interpolation="Regular_Grid",
extrapolation="Natural",
)
assert func.get_interpolation_method() == "regular_grid"
assert func.get_extrapolation_method() == "natural"
assert np.array_equal(
func.get_value(1.0, np.array([0.0, 1.0])), np.array([10.0, 11.0])
)
assert np.array_equal(
func.get_value_opt(1.0, np.array([0.0, 1.0])), np.array([10.0, 11.0])
)
def test_interpolation_and_extrapolation_names_are_normalized():
"""Supported method names should be case-insensitive without changing behavior."""
func = Function(
[(0, 0), (1, 1), (2, 2)],
interpolation="Linear",
extrapolation="Natural",
)
assert func.get_interpolation_method() == "linear"
assert func.get_extrapolation_method() == "natural"
assert np.isclose(func.get_value(-1), -1.0)
def test_1d_array_source_internal_data_is_sorted():
"""For 1-D array sources, source, domain and image should share sorted order."""
func = Function([(2, 4), (0, 0), (1, 1)], interpolation="linear")
assert np.array_equal(func.source[:, 0], np.array([0.0, 1.0, 2.0]))
assert np.array_equal(func._domain[:, 0], np.array([0.0, 1.0, 2.0]))
assert np.array_equal(func._image, np.array([0.0, 1.0, 4.0]))
def test_nd_callable_negation_does_not_require_eval():
"""ND callable negation should preserve behavior with a normal closure."""
func = Function(lambda x, y: x + 2 * y, inputs=["x", "y"])
assert (-func).get_value(1.0, 2.0) == -5.0
def test_vectorized_constant_extrapolation_integrals():
"""Constant extrapolation definite integrals should accept vector bounds."""
func = Function(
[(0, 0), (1, 1)],
interpolation="linear",
extrapolation="constant",
)
assert np.allclose(func._evaluator.integral(np.array([-2.0, -1.0])), [0.0, 0.0])
assert np.allclose(func._evaluator.integral(np.array([1.0, 2.0])), [0.5, 1.5])
def test_identity_function():
"""Tests the identity_function method of the Function class.
Both with respect to return instances and expected behaviour.
"""
func = Function(lambda x: x**2)
assert isinstance(func.identity_function(), Function)
def test_derivative_function():
"""Tests the derivative_function method of the Function class.
Both with respect to return instances and expected behaviour.
"""
square = Function(lambda x: x**2)
assert isinstance(square.derivative_function(), Function)
def test_integral():
"""Tests the integral method of the Function class.
Both with respect to return instances and expected behaviour.
"""
zero_func = Function(0)
assert isinstance(zero_func.integral(2, 4, numerical=True), float)
assert zero_func.integral(2, 4, numerical=True) == 0
square = Function(lambda x: x**2)
assert isinstance
assert square.integral(2, 4, numerical=True) == -square.integral(
4, 2, numerical=True
)
assert square.integral(2, 4, numerical=False) == -square.integral(
4, 2, numerical=False
)
def test_integral_function():
"""Tests the integral_function method of the Function class.
Both with respect to return instances and expected behaviour.
"""
zero_func = Function(0)
assert isinstance(zero_func, Function)
@pytest.mark.parametrize(
"x, y, z",
[
(0, 0, 11.22540929),
(1, 2, 10),
(2, 3, 15.272727273),
(3, 4, 20),
(4, 5, 24.727272727),
(5, 6, 30),
(10, 10, 25.7201184),
],
)
def test_get_value_opt(x, y, z):
"""Test the get_value_opt method of the Function class. Currently only tests
a 2D function with shepard interpolation method. The tests are made on
points that are present or not in the source array.
Parameters
----------
x : scalar
The x-coordinate.
y : scalar
The y-coordinate.
z : float
The expected interpolated value at (x, y).
"""
x_data = np.array([1.0, 3.0, 5.0])
y_data = np.array([2.0, 4.0, 6.0])
z_data = np.array([10.0, 20.0, 30.0])
source = np.column_stack((x_data, y_data, z_data))
func = Function(source, interpolation="shepard", extrapolation="natural")
assert isinstance(func.get_value_opt(x, y), float)
assert np.isclose(func.get_value_opt(x, y), z, atol=1e-6)
@pytest.mark.parametrize("samples", [2, 50, 1000])
def test_set_discrete_mutator(samples):
"""Tests the set_discrete method of the Function class."""
func = Function(lambda x: x**3)
discretized_func = func.set_discrete(-10, 10, samples, mutate_self=True)
assert isinstance(discretized_func, Function)
assert isinstance(func, Function)
assert discretized_func.source.shape == (samples, 2)
assert func.source.shape == (samples, 2)
@pytest.mark.parametrize("samples", [2, 50, 1000])
def test_set_discrete_non_mutator(samples):
"""Tests the set_discrete method of the Function class.
The mutator argument is set to False.
"""
func = Function(lambda x: x**3)
discretized_func = func.set_discrete(-10, 10, samples, mutate_self=False)
assert isinstance(discretized_func, Function)
assert isinstance(func, Function)
assert discretized_func.source.shape == (samples, 2)
assert callable(func.source)
def test_set_discrete_based_on_model_mutator(linear_func):
"""Tests the set_discrete_based_on_model method of the Function class.
The mutator argument is set to True.
"""
func = Function(lambda x: x**3)
discretized_func = func.set_discrete_based_on_model(linear_func, mutate_self=True)
assert isinstance(discretized_func, Function)
assert isinstance(func, Function)
assert discretized_func.source.shape == (4, 2)
assert func.source.shape == (4, 2)
def test_set_discrete_based_on_model_non_mutator(linear_func):
"""Tests the set_discrete_based_on_model method of the Function class.
The mutator argument is set to False.
"""
func = Function(lambda x: x**3)
discretized_func = func.set_discrete_based_on_model(linear_func, mutate_self=False)
assert isinstance(discretized_func, Function)
assert isinstance(func, Function)
assert discretized_func.source.shape == (4, 2)
assert callable(func.source)
source_array = np.array(
[
[-2, -4, -6],
[-0.75, -1.5, -2.25],
[0, 0, 0],
[0, 1, 1],
[0.5, 1, 1.5],
[1.5, 1, 2.5],
[2, 4, 6],
]
)
cropped_array = np.array([[-0.75, -1.5, -2.25], [0, 0, 0], [0, 1, 1], [0.5, 1, 1.5]])
clipped_array = np.array([[0, 0, 0], [0, 1, 1], [0.5, 1, 1.5]])
@pytest.mark.parametrize(
"array3dsource, array3dcropped",
[
(source_array, cropped_array),
],
)
def test_crop_ndarray(array3dsource, array3dcropped):
"""Tests the functionality of crop method of the Function class.
The source is initialized as a ndarray before cropping.
"""
func = Function(array3dsource, inputs=["x1", "x2"], outputs="y")
cropped_func = func.crop([(-1, 1), (-2, 2)])
assert isinstance(func, Function)
assert isinstance(cropped_func, Function)
assert np.array_equal(cropped_func.source, array3dcropped)
assert isinstance(cropped_func.source, type(func.source))
def test_crop_function():
"""Tests the functionality of crop method of the Function class.
The source is initialized as a function before cropping.
"""
func = Function(
lambda x1, x2: np.sin(x1) * np.cos(x2), inputs=["x1", "x2"], outputs="y"
)
cropped_func = func.crop([(-1, 1), (-2, 2)])
assert isinstance(func, Function)
assert isinstance(cropped_func, Function)
assert callable(func.source)
assert callable(cropped_func.source)
def test_crop_constant():
"""Tests the functionality of crop method of the Function class.
The source is initialized as a single integer constant before cropping.
"""
func = Function(13)
cropped_func = func.crop([(-1, 1)])
assert isinstance(func, Function)
assert isinstance(cropped_func, Function)
assert func._source_type is SourceType.SCALAR
assert func._scalar_value == 13.0
assert cropped_func._source_type is SourceType.SCALAR
assert cropped_func._scalar_value == 13.0
@pytest.mark.parametrize(
"lower, upper",
[
(0.0, 3.0),
(-1.0, 2.0),
],
)
def test_crop_1d_ndarray_values(lower, upper):
"""Test crop on a 1-D ndarray source removes out-of-range rows and
preserves all in-range rows with correct values."""
source = np.array([(x, x**2) for x in range(-2, 6)])
func = Function(source)
cropped = func.crop([(lower, upper)])
assert isinstance(cropped, Function)
assert np.all(cropped.source[:, 0] >= lower)
assert np.all(cropped.source[:, 0] <= upper)
# Check that all source rows within bounds are present
expected = source[(source[:, 0] >= lower) & (source[:, 0] <= upper)]
assert np.array_equal(cropped.source, expected)
@pytest.mark.parametrize(
"x_lim, expected_dim0_bounds",
[
([(-1.0, 1.0)], (-1.0, 1.0)),
([(0.0, 2.0)], (0.0, 2.0)),
],
)
def test_crop_callable_records_cropped_domain_1d(x_lim, expected_dim0_bounds):
"""Test that crop on a callable 1-D Function correctly records
__cropped_domain__ so that subsequent set_discrete honours the bounds."""
func = Function(lambda x: x**2)
cropped = func.crop(x_lim)
assert cropped.__cropped_domain__ is not None
recorded = cropped.__cropped_domain__[0]
assert recorded == expected_dim0_bounds
@pytest.mark.parametrize(
"x_lim",
[
[(-1.0, 1.0), None], # skip second dim
[None, (-2.0, 2.0)], # skip first dim
[(-1.0, 1.0), (-2.0, 2.0)], # both dims
],
)
def test_crop_callable_nd_partial(x_lim):
"""Test crop with None entries skips the corresponding dimension and
only sets __cropped_domain__ for the non-None dims."""
func = Function(lambda x1, x2: x1 + x2, inputs=["x1", "x2"])
cropped = func.crop(x_lim)
assert isinstance(cropped, Function)
assert callable(cropped.source)
domain = cropped.__cropped_domain__
for i, lim in enumerate(x_lim):
if lim is None:
assert domain[i] is None
else:
assert domain[i] == lim
def test_crop_nd_ndarray_removes_out_of_range_rows():
"""Test crop on a 3-D ndarray source keeps only rows whose inputs are
within all specified per-dimension ranges."""
rng = np.random.default_rng(42)
pts = rng.uniform(-3, 3, (200, 3))
zs = pts[:, 0] + pts[:, 1] + pts[:, 2]
source = np.column_stack([pts, zs])
func = Function(source, inputs=["x", "y", "z"])
x_lim = [(-1.0, 1.0), (-1.0, 1.0), (-1.0, 1.0)]
cropped = func.crop(x_lim)
assert isinstance(cropped, Function)
assert np.all(cropped.source[:, 0] >= -1.0)
assert np.all(cropped.source[:, 0] <= 1.0)
assert np.all(cropped.source[:, 1] >= -1.0)
assert np.all(cropped.source[:, 1] <= 1.0)
assert np.all(cropped.source[:, 2] >= -1.0)
assert np.all(cropped.source[:, 2] <= 1.0)
@pytest.mark.parametrize(
"bad_x_lim, exc_type",
[
((-1, 1), TypeError), # not a list
([(0, 1), (0, 1), (0, 1)], ValueError), # too many dims for 2-D func
],
)
def test_crop_invalid_input_raises(bad_x_lim, exc_type):
"""Test that crop raises the appropriate error for invalid x_lim."""
func = Function(lambda x, y: x + y, inputs=["x", "y"])
with pytest.raises(exc_type):
func.crop(bad_x_lim)
@pytest.mark.parametrize(
"array3dsource, array3dclipped",
[
(source_array, clipped_array),
],
)
def test_clip_ndarray(array3dsource, array3dclipped):
"""Tests the functionality of clip method of the Function class.
The source is initialized as a ndarray before clipping.
"""
func = Function(array3dsource, inputs=["x1", "x2"], outputs="y")
clipped_func = func.clip([(-2, 2)])
assert isinstance(func, Function)
assert isinstance(clipped_func, Function)
assert np.array_equal(clipped_func.source, array3dclipped)
assert isinstance(clipped_func.source, type(func.source))
def test_clip_function():
"""Tests the functionality of clip method of the Function class.
The source is initialized as a function before clipping.
"""
func = Function(lambda x: x**2, inputs="x", outputs="y")
clipped_func = func.clip([(-1, 1)])
assert isinstance(func, Function)
assert isinstance(clipped_func, Function)
assert callable(func.source)
assert callable(clipped_func.source)
def test_clip_constant():
"""Tests the functionality of clip method of the Function class.
The source is initialized as a single integer constant before clipping.
"""
func = Function(1)
clipped_func = func.clip([(-2, 2)])
assert isinstance(func, Function)
assert isinstance(clipped_func, Function)
assert func._source_type is SourceType.SCALAR
assert func._scalar_value == 1.0
assert clipped_func._source_type is SourceType.SCALAR
assert clipped_func._scalar_value == 1.0
@pytest.mark.parametrize(
"y_lo, y_hi, x_in, expected_out",
[
(-4.0, 4.0, 0.0, 0.0), # inside range, unchanged
(-4.0, 4.0, 2.0, 4.0), # inside range, unchanged
(-4.0, 4.0, 3.0, 4.0), # clamped at upper bound
(-4.0, 4.0, -3.0, 4.0), # clamped at upper bound (x**2)
(1.0, 9.0, 0.0, 1.0), # clamped at lower bound
(1.0, 9.0, 4.0, 9.0), # clamped at upper bound
],
)
def test_clip_callable_clamps_output_values(y_lo, y_hi, x_in, expected_out):
"""Test that clip on a callable Function clamps output values to the
specified range rather than removing any domain points."""
func = Function(lambda x: x**2, inputs="x", outputs="y")
clipped = func.clip([(y_lo, y_hi)])
assert np.isclose(clipped(x_in), expected_out)
@pytest.mark.parametrize(
"y_lo, y_hi, n_rows_kept",
[
(-3.0, 3.0, 5), # z=-6 and z=6 excluded; remaining 5 rows in range
(-10.0, 10.0, 7), # all rows kept
(0.0, 0.1, 1), # only row with z≈0
],
)
def test_clip_ndarray_2d_removes_rows_outside_range(y_lo, y_hi, n_rows_kept):
"""Test that clip on a 2-D ndarray source removes rows whose output
column falls outside the specified y_lim range."""
func = Function(source_array, inputs=["x1", "x2"], outputs="y")
clipped = func.clip([(y_lo, y_hi)])
assert isinstance(clipped, Function)
assert np.all(clipped.source[:, 2] >= y_lo)
assert np.all(clipped.source[:, 2] <= y_hi)
assert len(clipped.source) == n_rows_kept
def test_clip_constant_clamps_output():
"""Test that clipping a constant Function clamps its output to y_lim.
Function(5) stores source as a scalar, so clip clamps the value directly;
values are clamped to the specified range rather than raising."""
func = Function(5) # constant 5, stored as SCALAR
clipped = func.clip([(10.0, 20.0)]) # 5 < 10, so output should be clamped to 10
assert clipped.get_value(0) == 10.0
clipped_hi = func.clip([(-1.0, 3.0)]) # 5 > 3, clamped to 3
assert clipped_hi.get_value(0) == 3.0
@pytest.mark.parametrize(
"bad_y_lim, exc_type",
[
((-1, 1), TypeError), # not a list
([(-1, 1), (-1, 1)], ValueError), # wrong length for single-output func
],
)
def test_clip_invalid_input_raises(bad_y_lim, exc_type):
"""Test that clip raises the appropriate error for invalid y_lim."""
func = Function(lambda x: x**2, inputs="x", outputs="y")
with pytest.raises(exc_type):
func.clip(bad_y_lim)
@pytest.mark.parametrize(
"x, y, expected_x, expected_y",
[
(
np.array([1, 2, 3, 4, 5, 6]),
np.array([10, 20, 30, 40, 50000, 60]),
np.array([1, 2, 3, 4, 6]),
np.array([10, 20, 30, 40, 60]),
),
],
)
def test_remove_outliers_iqr(x, y, expected_x, expected_y):
"""Test the function remove_outliers_iqr which is expected to remove
outliers from the data based on the Interquartile Range (IQR) method.
"""
func = Function(source=np.column_stack((x, y)))
filtered_func = func.remove_outliers_iqr(threshold=1.5)
# Check if the outliers are removed
assert np.array_equal(filtered_func.x_array, expected_x)
assert np.array_equal(filtered_func.y_array, expected_y)
# Check if the other attributes are preserved
assert filtered_func.__inputs__ == func.__inputs__
assert filtered_func.__outputs__ == func.__outputs__
assert filtered_func.__interpolation__ == func.__interpolation__
assert filtered_func.__extrapolation__ == func.__extrapolation__
assert filtered_func.title == func.title
def test_set_get_value_opt():
"""Test the set_value_opt and get_value_opt methods of the Function class."""
func = Function(lambda x: x**2)
func.set_source(np.array([[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]))
func.set_interpolation("linear")
func.set_get_value_opt()
assert func.get_value_opt(2.5) == 6.5
def test_get_image_dim(linear_func):
"""Test the get_img_dim method of the Function class."""
assert linear_func.get_image_dim() == 1
def test_get_domain_dim(linear_func):
"""Test the get_domain_dim method of the Function class."""
assert linear_func.get_domain_dim() == 1
def test_bool(linear_func):
"""Test the __bool__ method of the Function class."""
assert bool(linear_func)
def test_getters(func_from_csv, func_2d_from_csv):
"""Test the different getters of the Function class.
Parameters
----------
func_from_csv : rocketpy.Function
A Function object created from a .csv file.
"""
assert func_from_csv.get_inputs() == ["Scalar"]
assert func_from_csv.get_outputs() == ["Scalar"]
assert func_from_csv.get_interpolation_method() == "spline"
assert func_from_csv.get_extrapolation_method() == "constant"
assert np.isclose(func_from_csv.get_value(0), 0.0, atol=1e-6)
assert np.isclose(func_from_csv.get_value_opt(0), 0.0, atol=1e-6)
assert func_2d_from_csv.get_inputs() == ["Input 1", "Input 2"]
assert func_2d_from_csv.get_outputs() == ["Scalar"]
assert func_2d_from_csv.get_interpolation_method() == "shepard"
assert func_2d_from_csv.get_extrapolation_method() == "natural"
assert np.isclose(func_2d_from_csv.get_value(0.1, 0.8), 0.058, atol=1e-6)
assert np.isclose(func_2d_from_csv.get_value_opt(0.1, 0.8), 0.058, atol=1e-6)
def test_setters(func_from_csv, func_2d_from_csv):
"""Test the different setters of the Function class.
Parameters
----------
func_from_csv : rocketpy.Function
A Function object created from a .csv file.
"""
# Test set methods
func_from_csv.set_inputs(["Scalar2"])
assert func_from_csv.get_inputs() == ["Scalar2"]
func_from_csv.set_outputs(["Scalar2"])
assert func_from_csv.get_outputs() == ["Scalar2"]
func_from_csv.set_interpolation("linear")
assert func_from_csv.get_interpolation_method() == "linear"
func_from_csv.set_extrapolation("natural")
assert func_from_csv.get_extrapolation_method() == "natural"
func_2d_from_csv.set_inputs(["Scalar1", "Scalar2"])