-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathtest_interpolatedimage.py
More file actions
1937 lines (1689 loc) · 85.8 KB
/
Copy pathtest_interpolatedimage.py
File metadata and controls
1937 lines (1689 loc) · 85.8 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
# Copyright (c) 2012-2026 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
import numpy as np
import os
import platform
import galsim
from galsim_test_helpers import *
path, filename = os.path.split(__file__) # Get the path to this file for use below...
# For reference tests:
TESTDIR=os.path.join(path, "interpolant_comparison_files")
# Some arbitrary kx, ky k space values to test
KXVALS = np.array((1.30, 0.71, -4.30)) * np.pi / 2.
KYVALS = np.array((0.80, -0.02, -0.31,)) * np.pi / 2.
# The timing tests can be unreliable in environments with other processes running at the
# same time. So we disable them by default. However, on a clean system, they should all pass.
test_timing = False
@pytest.fixture
def ref():
# This reference image will be used in a number of tests below, so make it at the start.
g1 = galsim.Gaussian(sigma = 3.1, flux=2.4).shear(g1=0.2,g2=0.1)
g2 = galsim.Gaussian(sigma = 1.9, flux=3.1).shear(g1=-0.4,g2=0.3).shift(-0.3,0.5)
g3 = galsim.Gaussian(sigma = 4.1, flux=1.6).shear(g1=0.1,g2=-0.1).shift(0.7,-0.2)
final = g1 + g2 + g3
ref_image = galsim.ImageD(128,128)
scale = 0.4
# The reference image was drawn with the old convention, which is now use_true_center=False
final.drawImage(image=ref_image, scale=scale, method='sb', use_true_center=False)
return final, ref_image
@timer
def test_roundtrip(ref):
"""Test round trip from Image to InterpolatedImage back to Image.
"""
final, ref_image = ref
# for each type, try to make an InterpolatedImage, and check that when we draw an image from
# that InterpolatedImage that it is the same as the original
ftypes = [np.float32, np.float64]
ref_array = np.array([
[0.01, 0.08, 0.07, 0.02],
[0.13, 0.38, 0.52, 0.06],
[0.09, 0.41, 0.44, 0.09],
[0.04, 0.11, 0.10, 0.01] ])
test_scale = 2.0
for array_type in ftypes:
image_in = galsim.Image(ref_array.astype(array_type))
np.testing.assert_array_equal(
ref_array.astype(array_type),image_in.array,
err_msg="Array from input Image differs from reference array for type %s"%
array_type)
test_array = np.zeros(ref_array.shape, dtype=array_type)
for wcs in [ galsim.PixelScale(2.0),
galsim.JacobianWCS(2.1, 0.3, -0.4, 2.3),
galsim.AffineTransform(-0.3, 2.1, 1.8, 0.1, galsim.PositionD(0.3, -0.4)) ]:
interp = galsim.InterpolatedImage(image_in, wcs=wcs)
image_out = galsim.Image(test_array, wcs=wcs)
interp.drawImage(image_out, method='no_pixel')
np.testing.assert_almost_equal(
ref_array.astype(array_type),image_out.array,
err_msg="Output Image differs from reference for type %s, wcs %s"%
(array_type,wcs))
# And using scale, which is equivalent to the first pass above (but hits a different
# code path).
interp = galsim.InterpolatedImage(image_in, scale=test_scale)
image_out = galsim.Image(test_array, scale=test_scale)
interp.drawImage(image_out, method='no_pixel')
np.testing.assert_array_equal(
ref_array.astype(array_type),image_out.array,
err_msg="Output Image differs from reference for type %s, scale %s"%
(array_type,test_scale))
gsp = galsim.GSParams(xvalue_accuracy=1.e-8, kvalue_accuracy=1.e-8)
interp2 = galsim.InterpolatedImage(image_in, scale=test_scale, gsparams=gsp)
assert interp2 != interp
assert interp2 == interp.withGSParams(gsp)
assert interp2 == interp.withGSParams(xvalue_accuracy=1.e-8, kvalue_accuracy=1.e-8)
assert interp2.x_interpolant.gsparams == gsp
assert interp2.k_interpolant.gsparams == gsp
assert interp.x_interpolant.gsparams != gsp
assert interp.k_interpolant.gsparams != gsp
# Lanczos doesn't quite get the flux right. Wrong at the 5th decimal place.
# Gary says that's expected -- Lanczos isn't technically flux conserving.
# He applied the 1st order correction to the flux, but expect to be wrong at around
# the 10^-5 level.
# Anyway, Quintic seems to be accurate enough.
# And this is now the default, so no need to do anything special here.
check_basic(interp, "InterpolatedImage", approx_maxsb=True)
do_shoot(interp,image_out,"InterpolatedImage")
# Test kvalues
test_im = galsim.Image(16,16,scale=0.2)
do_kvalue(interp,test_im,"InterpolatedImage")
# Check picklability
check_pickle(interp, lambda x: x.drawImage(method='no_pixel'))
check_pickle(interp)
# Test using a non-c-contiguous image (.T transposes the image, making it Fortran order)
image_T = galsim.Image(ref_array.astype(array_type).T)
interp = galsim.InterpolatedImage(image_T, scale=test_scale)
test_array = np.zeros(ref_array.T.shape, dtype=array_type)
image_out = galsim.Image(test_array, scale=test_scale)
interp.drawImage(image_out, method='no_pixel')
np.testing.assert_array_equal(
ref_array.T.astype(array_type),image_out.array,
err_msg="Transposed array failed InterpolatedImage roundtrip.")
check_basic(interp, "InterpolatedImage (Fortran ordering)", approx_maxsb=True)
# Check that folding_threshold and maxk_threshold update stepk and maxk
# Do this with the larger ref_image, since this one is too small to have any difference
# from different folding_threshold values.
scale = 0.3
ii1 = galsim.InterpolatedImage(ref_image, scale=scale)
gsp = galsim.GSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4)
ii2 = galsim.InterpolatedImage(ref_image, scale=scale, gsparams=gsp)
assert ii2 == ii1.withGSParams(gsp)
assert ii2.stepk != ii1.stepk
assert ii2.maxk != ii1.maxk
assert ii2.stepk == ii1.withGSParams(folding_threshold=1.e-4).stepk
assert ii2.maxk == ii1.withGSParams(maxk_threshold=1.e-4).maxk
@timer
def test_interpolant():
from scipy.special import sici
# Test aspects of using the interpolants directly.
# Test function for pickle tests
im = galsim.Gaussian(sigma=4).drawImage()
test_func = lambda x : (
galsim.InterpolatedImage(im, x_interpolant=x).drawImage(method='no_pixel'))
x = np.linspace(-10, 10, 141)
# Delta
d = galsim.Delta()
print(repr(d.gsparams))
print(repr(galsim.GSParams()))
assert d.gsparams == galsim.GSParams()
assert d.xrange == 0
assert d.ixrange == 0
assert np.isclose(d.krange, 2.*np.pi / d.gsparams.kvalue_accuracy)
assert np.isclose(d.krange, 2.*np.pi * d._i.urange())
assert d.positive_flux == 1
assert d.negative_flux == 0
print(repr(d))
check_pickle(d, test_func)
check_pickle(galsim.Delta())
check_pickle(galsim.Interpolant.from_name('delta'))
true_xval = np.zeros_like(x)
true_xval[np.abs(x) < d.gsparams.kvalue_accuracy/2] = 1./d.gsparams.kvalue_accuracy
np.testing.assert_allclose(d.xval(x), true_xval)
np.testing.assert_allclose(d.kval(x), 1.)
assert np.isclose(d.xval(x[12]), true_xval[12])
assert np.isclose(d.kval(x[12]), 1.)
# Nearest
n = galsim.Nearest()
assert n.gsparams == galsim.GSParams()
assert n.xrange == 0.5
assert n.ixrange == 1
assert np.isclose(n.krange, 2. / n.gsparams.kvalue_accuracy)
assert n.positive_flux == 1
assert n.negative_flux == 0
check_pickle(n, test_func)
check_pickle(galsim.Nearest())
check_pickle(galsim.Interpolant.from_name('nearest'))
true_xval = np.zeros_like(x)
true_xval[np.abs(x) < 0.5] = 1
np.testing.assert_allclose(n.xval(x), true_xval)
true_kval = np.sinc(x/2/np.pi)
np.testing.assert_allclose(n.kval(x), true_kval)
assert np.isclose(n.xval(x[12]), true_xval[12])
assert np.isclose(n.kval(x[12]), true_kval[12])
# Conserves dc flux:
# Most interpolants (not Delta above) conserve a constant (DC) flux.
# This means input points separated by 1 pixel with any subpixel phase
# will sum to 1. The input x array has 7 phases, so the total sum is 7.
print('Nearest sum = ',np.sum(n.xval(x)))
assert np.isclose(np.sum(n.xval(x)), 7.0)
# SincInterpolant
s = galsim.SincInterpolant()
assert s.gsparams == galsim.GSParams()
assert np.isclose(s.xrange, 1./(np.pi * s.gsparams.kvalue_accuracy))
assert s.ixrange == 2*np.ceil(s.xrange)
assert np.isclose(s.krange, np.pi)
assert np.isclose(s.krange, 2.*np.pi * s._i.urange())
assert np.isclose(s.positive_flux, 3.18726437) # Empirical -- this is a regression test
assert np.isclose(s.negative_flux, s.positive_flux-1., rtol=1.e-4)
check_pickle(galsim.SincInterpolant())
check_pickle(galsim.Interpolant.from_name('sinc'))
true_xval = np.sinc(x)
np.testing.assert_allclose(s.xval(x), true_xval)
true_kval = np.zeros_like(x)
true_kval[np.abs(x) < np.pi] = 1.
np.testing.assert_allclose(s.kval(x), true_kval)
assert np.isclose(s.xval(x[12]), true_xval[12])
assert np.isclose(s.kval(x[12]), true_kval[12])
# Conserves dc flux:
# This one would conserve dc flux, but we don't go out far enough.
# At +- 10 pixels, it's only about 6.86
print('Sinc sum = ',np.sum(s.xval(x)))
assert np.isclose(np.sum(s.xval(x)), 7.0, rtol=0.02)
# Linear
l = galsim.Linear()
assert l.gsparams == galsim.GSParams()
assert l.xrange == 1.
assert l.ixrange == 2
assert np.isclose(l.krange, 2./l.gsparams.kvalue_accuracy**0.5)
assert np.isclose(l.krange, 2.*np.pi * l._i.urange())
assert l.positive_flux == 1
assert l.negative_flux == 0
check_pickle(l, test_func)
check_pickle(galsim.Linear())
check_pickle(galsim.Interpolant.from_name('linear'))
true_xval = np.zeros_like(x)
true_xval[np.abs(x) < 1] = 1. - np.abs(x[np.abs(x) < 1])
np.testing.assert_allclose(l.xval(x), true_xval)
true_kval = np.sinc(x/2/np.pi)**2
np.testing.assert_allclose(l.kval(x), true_kval)
assert np.isclose(l.xval(x[12]), true_xval[12])
assert np.isclose(l.kval(x[12]), true_kval[12])
# Conserves dc flux:
print('Linear sum = ',np.sum(l.xval(x)))
assert np.isclose(np.sum(l.xval(x)), 7.0)
# Cubic
c = galsim.Cubic()
assert c.gsparams == galsim.GSParams()
assert c.xrange == 2.
assert c.ixrange == 4
assert np.isclose(c.krange, 2. * (3**1.5 / 8 / c.gsparams.kvalue_accuracy)**(1./3.))
assert np.isclose(c.krange, 2.*np.pi * c._i.urange())
assert np.isclose(c.positive_flux, 13./12.)
assert np.isclose(c.negative_flux, 1./12.)
check_pickle(c, test_func)
check_pickle(galsim.Cubic())
check_pickle(galsim.Interpolant.from_name('cubic'))
true_xval = np.zeros_like(x)
ax = np.abs(x)
m = ax < 1
true_xval[m] = 1. + ax[m]**2 * (1.5*ax[m]-2.5)
m = (1 <= ax) & (ax < 2)
true_xval[m] = -0.5 * (ax[m]-1) * (2.-ax[m])**2
np.testing.assert_allclose(c.xval(x), true_xval)
sx = np.sinc(x/2/np.pi)
cx = np.cos(x/2)
true_kval = sx**3 * (3*sx - 2*cx)
np.testing.assert_allclose(c.kval(x), true_kval)
assert np.isclose(c.xval(x[12]), true_xval[12])
assert np.isclose(c.kval(x[12]), true_kval[12])
# Conserves dc flux:
print('Cubic sum = ',np.sum(c.xval(x)))
assert np.isclose(np.sum(c.xval(x)), 7.0)
# Quintic
q = galsim.Quintic()
assert q.gsparams == galsim.GSParams()
assert q.xrange == 3.
assert q.ixrange == 6
assert np.isclose(q.krange, 2. * (5**2.5 / 108 / q.gsparams.kvalue_accuracy)**(1./3.))
assert np.isclose(q.krange, 2.*np.pi * q._i.urange())
assert np.isclose(q.positive_flux, (13018561. / 11595672.) + (17267. / 14494590.) * 31**0.5)
assert np.isclose(q.negative_flux, q.positive_flux-1.)
check_pickle(q, test_func)
check_pickle(galsim.Quintic())
check_pickle(galsim.Interpolant.from_name('quintic'))
true_xval = np.zeros_like(x)
ax = np.abs(x)
m = ax < 1.
true_xval[m] = 1. + ax[m]**3 * (-95./12. + 23./2.*ax[m] - 55./12.*ax[m]**2)
m = (1 <= ax) & (ax < 2)
true_xval[m] = (ax[m]-1) * (2.-ax[m]) * (23./4. - 29./2.*ax[m] + 83./8.*ax[m]**2
- 55./24.*ax[m]**3)
m = (2 <= ax) & (ax < 3)
true_xval[m] = (ax[m]-2) * (3.-ax[m])**2 * (-9./4. + 25./12.*ax[m] - 11./24.*ax[m]**2)
np.testing.assert_allclose(q.xval(x), true_xval)
sx = np.sinc(x/2/np.pi)
cx = np.cos(x/2)
true_kval = sx**5 * (sx*(55.-19./4. * x**2) + cx*(x**2/2. - 54.))
np.testing.assert_allclose(q.kval(x), true_kval)
assert np.isclose(q.xval(x[12]), true_xval[12])
assert np.isclose(q.kval(x[12]), true_kval[12])
# Conserves dc flux:
print('Quintic sum = ',np.sum(q.xval(x)))
assert np.isclose(np.sum(q.xval(x)), 7.0)
# Lanczos
l3 = galsim.Lanczos(3)
assert l3.gsparams == galsim.GSParams()
assert l3.conserve_dc == True
assert l3.n == 3
assert l3.xrange == l3.n
assert l3.ixrange == 2*l3.n
assert np.isclose(l3.krange, 2.*np.pi * l3._i.urange()) # No analytic version for this one.
print(l3.positive_flux, l3.negative_flux)
assert np.isclose(l3.positive_flux, 1.1793639) # Empirical -- this is a regression test
assert np.isclose(l3.negative_flux, l3.positive_flux-1., rtol=1.e-4)
check_pickle(l3, test_func)
check_pickle(galsim.Lanczos(n=7, conserve_dc=False))
check_pickle(galsim.Lanczos(3))
check_pickle(galsim.Interpolant.from_name('lanczos7'))
check_pickle(galsim.Interpolant.from_name('lanczos9F'))
check_pickle(galsim.Interpolant.from_name('lanczos8T'))
assert_raises(ValueError, galsim.Interpolant.from_name, 'lanczos3A')
assert_raises(ValueError, galsim.Interpolant.from_name, 'lanczosF')
assert_raises(ValueError, galsim.Interpolant.from_name, 'lanzos')
# Note: 1-7 all have special case code, so check them. 8 uses the generic code.
for n in [1, 2, 3, 4, 5, 6, 7, 8]:
ln = galsim.Lanczos(n, conserve_dc=False)
assert ln.conserve_dc == False
assert ln.n == n
true_xval = np.zeros_like(x)
true_xval[np.abs(x) < n] = np.sinc(x[np.abs(x)<n]) * np.sinc(x[np.abs(x)<n]/n)
np.testing.assert_allclose(ln.xval(x), true_xval, rtol=1.e-5, atol=1.e-10)
assert np.isclose(ln.xval(x[12]), true_xval[12])
# Lanczos notably does not conserve dc flux
print('Lanczos(%s,conserve_dc=False) sum = '%n,np.sum(ln.xval(x)))
# With conserve_dc=True, it does a bit better, but still only to 1.e-4 accuracy.
lndc = galsim.Lanczos(n, conserve_dc=True)
np.testing.assert_allclose(lndc.xval(x), true_xval, rtol=0.3, atol=1.e-10)
print('Lanczos(%s,conserve_dc=True) sum = '%n,np.sum(lndc.xval(x)))
assert np.isclose(np.sum(lndc.xval(x)), 7.0, rtol=1.e-4)
# The math for kval (at least when conserve_dc=False) is complicated, but tractable.
# It ends up using the Si function, which is in scipy as scipy.special.sici
vp = n * (x/np.pi + 1)
vm = n * (x/np.pi - 1)
true_kval = ( (vm-1) * sici(np.pi*(vm-1))[0]
-(vm+1) * sici(np.pi*(vm+1))[0]
-(vp-1) * sici(np.pi*(vp-1))[0]
+(vp+1) * sici(np.pi*(vp+1))[0] ) / (2*np.pi)
np.testing.assert_allclose(ln.kval(x), true_kval, rtol=1.e-4, atol=1.e-8)
assert np.isclose(ln.kval(x[12]), true_kval[12])
# Base class is invalid.
assert_raises(NotImplementedError, galsim.Interpolant)
# 2d arrays are invalid.
x2d = np.ones((5,5))
with assert_raises(galsim.GalSimValueError):
q.xval(x2d)
with assert_raises(galsim.GalSimValueError):
q.kval(x2d)
@timer
def test_unit_integrals():
# Test Interpolant.unit_integrals
interps = [galsim.Delta(),
galsim.Nearest(),
galsim.SincInterpolant(),
galsim.Linear(),
galsim.Cubic(),
galsim.Quintic(),
galsim.Lanczos(3),
galsim.Lanczos(3, conserve_dc=False),
galsim.Lanczos(17),
]
for interp in interps:
print(str(interp))
# Compute directly with int1d
n = interp.ixrange//2 + 1
direct_integrals = np.zeros(n)
if isinstance(interp, galsim.Delta):
# int1d doesn't handle this well.
direct_integrals[0] = 1
else:
for k in range(n):
direct_integrals[k] = galsim.integ.int1d(interp.xval, k-0.5, k+0.5)
print('direct: ',direct_integrals)
# Get from unit_integrals method (sometimes using analytic formulas)
integrals = interp.unit_integrals()
print('integrals: ',len(integrals),integrals)
assert len(integrals) == n
np.testing.assert_allclose(integrals, direct_integrals, atol=1.e-12)
if n > 10:
print('n>10 for ',repr(interp))
integrals2 = interp.unit_integrals(max_len=10)
assert len(integrals2) == 10
np.testing.assert_equal(integrals2, integrals[:10])
# Test making shorter versions before longer ones
interp = galsim.Lanczos(11)
short = interp.unit_integrals(max_len=5)
long = interp.unit_integrals(max_len=10)
med = interp.unit_integrals(max_len=8)
full = interp.unit_integrals()
assert len(full) > 10
np.testing.assert_equal(short, full[:5])
np.testing.assert_equal(med, full[:8])
np.testing.assert_equal(long, full[:10])
@timer
def test_fluxnorm():
"""Test that InterpolatedImage class responds properly to instructions about flux normalization.
"""
# define values
# Note that im_lin_scale should be even, since the auto-sized drawImage() command always
# produces an even-sized image. If the even/odd-ness doesn't match then the interpolant will
# come into play, and the exact checks will fail.
im_lin_scale = 6 # make an image with this linear scale
im_fill_value = 3. # fill it with this number
im_scale = 1.3
test_flux = 0.7
# First, make some Image with some total flux value (sum of pixel values) and scale
im = galsim.ImageF(im_lin_scale, im_lin_scale, scale=im_scale, init_value=im_fill_value)
total_flux = im_fill_value*(im_lin_scale**2)
np.testing.assert_equal(total_flux, im.array.sum(),
err_msg='Created array with wrong total flux')
# Check that if we make an InterpolatedImage with flux normalization, it keeps that flux
interp = galsim.InterpolatedImage(im) # note, flux normalization is the default
np.testing.assert_almost_equal(total_flux, interp.flux, decimal=9,
err_msg='Did not keep flux normalization')
# Check that this is preserved when drawing
im2 = interp.drawImage(scale = im_scale, method='no_pixel')
np.testing.assert_almost_equal(total_flux, im2.array.sum(), decimal=9,
err_msg='Drawn image does not have expected flux normalization')
check_pickle(interp, lambda x: x.drawImage(method='no_pixel'))
check_pickle(interp)
# Now make an InterpolatedImage but tell it sb normalization
interp_sb = galsim.InterpolatedImage(im, normalization = 'sb')
# Check that when drawing, the sum is equal to what we expect if the original image had been
# surface brightness
im3 = interp_sb.drawImage(scale = im_scale, method='no_pixel')
np.testing.assert_almost_equal(total_flux*(im_scale**2)/im3.array.sum(), 1.0, decimal=6,
err_msg='Did not use surface brightness normalization')
# Check that when drawing with sb normalization, the sum is the same as the original
im4 = interp_sb.drawImage(scale = im_scale, method='sb')
np.testing.assert_almost_equal(total_flux/im4.array.sum(), 1.0, decimal=6,
err_msg='Failed roundtrip for sb normalization')
np.testing.assert_almost_equal(
im4.array.max(), interp_sb.max_sb, 5,
err_msg="InterpolatedImage max_sb did not match maximum pixel value")
check_pickle(interp_sb, lambda x: x.drawImage(method='no_pixel'))
check_pickle(interp_sb)
# Finally make an InterpolatedImage but give it some other flux value
interp_flux = galsim.InterpolatedImage(im, flux=test_flux)
# Check that it has that flux
np.testing.assert_equal(test_flux, interp_flux.flux,
err_msg = 'InterpolatedImage did not use flux keyword')
# Check that this is preserved when drawing
im5 = interp_flux.drawImage(scale = im_scale, method='no_pixel')
np.testing.assert_almost_equal(test_flux/im5.array.sum(), 1.0, decimal=6,
err_msg = 'Drawn image does not reflect flux keyword')
check_pickle(interp_flux, lambda x: x.drawImage(method='no_pixel'))
check_pickle(interp_flux)
@timer
def test_exceptions():
"""Test failure modes for InterpolatedImage class.
"""
# Check that provided image has valid bounds
with assert_raises(galsim.GalSimUndefinedBoundsError):
galsim.InterpolatedImage(image=galsim.ImageF(scale=1.))
# Scale must be set
with assert_raises(galsim.GalSimIncompatibleValuesError):
galsim.InterpolatedImage(image=galsim.ImageF(5, 5))
# Image must be real type (F or D)
with assert_raises(galsim.GalSimValueError):
galsim.InterpolatedImage(image=galsim.ImageI(5, 5, scale=1))
# Image must have non-zero flux
with assert_raises(galsim.GalSimValueError):
galsim.InterpolatedImage(image=galsim.ImageF(5, 5, scale=1, init_value=0.))
# Can't shoot II with SincInterpolant
ii = galsim.InterpolatedImage(image=galsim.ImageF(5, 5, scale=1, init_value=1.),
x_interpolant='sinc',
# Use larger than normal kvalue_accuracy to avoid image being
# really huge for SincInterpolant before exception is raised.
gsparams=galsim.GSParams(kvalue_accuracy=1.e-3))
with assert_raises(galsim.GalSimError):
ii.drawImage(method='phot')
with assert_raises(galsim.GalSimError):
ii.shoot(n_photons=3)
# Check types of inputs
im = galsim.ImageF(5, 5, scale=1., init_value=10.)
assert_raises(TypeError, galsim.InterpolatedImage, image=im.array)
assert_raises(TypeError, galsim.InterpolatedImage, im, wcs=galsim.PixelScale(1.), scale=1.)
assert_raises(TypeError, galsim.InterpolatedImage, im, wcs=1.)
assert_raises(TypeError, galsim.InterpolatedImage, im, pad_image=im.array)
assert_raises(TypeError, galsim.InterpolatedImage, im, noise_pad_size=33)
assert_raises(TypeError, galsim.InterpolatedImage, im, noise_pad=33)
# Other invalid values:
assert_raises(ValueError, galsim.InterpolatedImage, im, normalization='invalid')
assert_raises(ValueError, galsim.InterpolatedImage, im, x_interpolant='invalid')
assert_raises(ValueError, galsim.InterpolatedImage, im, k_interpolant='invalid')
assert_raises(ValueError, galsim.InterpolatedImage, im, pad_factor=0.)
assert_raises(ValueError, galsim.InterpolatedImage, im, pad_factor=-1.)
assert_raises(ValueError, galsim.InterpolatedImage, im, noise_pad_size=33, noise_pad=im.wcs)
assert_raises(ValueError, galsim.InterpolatedImage, im, noise_pad_size=33, noise_pad=-1.)
assert_raises(ValueError, galsim.InterpolatedImage, im, noise_pad_size=-33, noise_pad=1.)
@timer
def test_operations_simple(run_slow):
"""Simple test of operations on InterpolatedImage: shear, magnification, rotation, shifting."""
# Make some nontrivial image that can be described in terms of sums and convolutions of
# GSObjects. We want this to be somewhat hard to describe, but should be at least
# critically-sampled, so put in an Airy PSF.
gal_flux = 1000.
pix_scale = 0.03 # arcsec
bulge_frac = 0.3
bulge_hlr = 0.3 # arcsec
bulge_e = 0.15
bulge_pos_angle = 30.*galsim.degrees
disk_hlr = 0.6 # arcsec
disk_e = 0.5
disk_pos_angle = 60.*galsim.degrees
lam = 800 # nm NB: don't use lambda - that's a reserved word.
tel_diam = 2.4 # meters
lam_over_diam = lam * 1.e-9 / tel_diam # radians
lam_over_diam *= 206265 # arcsec
im_size = 512
# define subregion for comparison
comp_region=30 # compare the central region of this linear size
comp_bounds = galsim.BoundsI(1,comp_region,1,comp_region)
comp_bounds = comp_bounds.shift(galsim.PositionI((im_size-comp_region)/2,
(im_size-comp_region)/2))
bulge = galsim.Sersic(4, half_light_radius=bulge_hlr)
bulge = bulge.shear(e=bulge_e, beta=bulge_pos_angle)
disk = galsim.Exponential(half_light_radius = disk_hlr)
disk = disk.shear(e=disk_e, beta=disk_pos_angle)
gal = bulge_frac*bulge + (1.-bulge_frac)*disk
gal = gal.withFlux(gal_flux)
psf = galsim.Airy(lam_over_diam)
obj = galsim.Convolve([gal, psf])
im = obj.drawImage(scale=pix_scale)
# Turn it into an InterpolatedImage with default param settings
int_im = galsim.InterpolatedImage(im)
# Shear it, and compare with expectations from GSObjects directly
test_g1=-0.07
test_g2=0.1
test_decimal=2 # in % difference, i.e. 2 means 1% agreement
test_int_im = int_im.shear(g1=test_g1, g2=test_g2)
ref_obj = obj.shear(g1=test_g1, g2=test_g2)
# make large images
im = galsim.ImageD(im_size, im_size)
ref_im = galsim.ImageD(im_size, im_size)
test_int_im.drawImage(image=im, scale=pix_scale, method='no_pixel')
ref_obj.drawImage(image=ref_im, scale=pix_scale)
# define subregion for comparison
im_sub = im.subImage(comp_bounds)
ref_im_sub = ref_im.subImage(comp_bounds)
diff_im=im_sub-ref_im_sub
rel = diff_im/im_sub
zeros_arr = np.zeros((comp_region, comp_region))
# require relative difference to be smaller than some amount
np.testing.assert_array_almost_equal(rel.array, zeros_arr,
test_decimal,
err_msg='Sheared InterpolatedImage disagrees with reference')
# Also test drawing into a larger image to test some of the indexing adjustments
# in fillXImage.
big_im = galsim.Image(2*im_size,2*im_size, scale=pix_scale)
test_int_im.drawImage(image=big_im, method='no_pixel')
big_comp_bounds = galsim.BoundsI(1,comp_region,1,comp_region)
big_comp_bounds = big_comp_bounds.shift(galsim.PositionI((2*im_size-comp_region)/2,
(2*im_size-comp_region)/2))
big_im_sub = big_im.subImage(big_comp_bounds)
print('comp_bounds = ',comp_bounds)
print('big_comp_bounds = ',big_comp_bounds)
print('center = ',big_im[big_im.center])
print('sub center = ',big_im_sub[big_im_sub.center])
print('ref center = ',ref_im[ref_im.center])
np.testing.assert_allclose(big_im_sub.array, ref_im_sub.array, rtol=0.01)
# The check_pickle tests should all pass below, but the a == eval(repr(a)) check can take a
# really long time, so we only do that if run_slow is True.
irreprable = not run_slow
check_pickle(test_int_im, lambda x: x.drawImage(nx=5, ny=5, scale=0.1, method='no_pixel'),
irreprable=irreprable)
check_pickle(test_int_im, irreprable=irreprable)
# Magnify it, and compare with expectations from GSObjects directly
test_mag = 1.08
test_decimal=2 # in % difference, i.e. 2 means 1% agreement
comp_region=30 # compare the central region of this linear size
test_int_im = int_im.magnify(test_mag)
ref_obj = obj.magnify(test_mag)
# make large images
im = galsim.ImageD(im_size, im_size)
ref_im = galsim.ImageD(im_size, im_size)
test_int_im.drawImage(image=im, scale=pix_scale, method='no_pixel')
ref_obj.drawImage(image=ref_im, scale=pix_scale)
# define subregion for comparison
im_sub = im.subImage(comp_bounds)
ref_im_sub = ref_im.subImage(comp_bounds)
diff_im=im_sub-ref_im_sub
rel = diff_im/im_sub
zeros_arr = np.zeros((comp_region, comp_region))
# require relative difference to be smaller than some amount
np.testing.assert_array_almost_equal(rel.array, zeros_arr,
test_decimal,
err_msg='Magnified InterpolatedImage disagrees with reference')
check_pickle(test_int_im, lambda x: x.drawImage(nx=5, ny=5, scale=0.1, method='no_pixel'),
irreprable=irreprable)
check_pickle(test_int_im, irreprable=irreprable)
# Lens it (shear and magnify), and compare with expectations from GSObjects directly
test_g1 = -0.03
test_g2 = -0.04
test_mag = 0.74
test_decimal=2 # in % difference, i.e. 2 means 1% agreement
comp_region=30 # compare the central region of this linear size
test_int_im = int_im.lens(test_g1, test_g2, test_mag)
ref_obj = obj.lens(test_g1, test_g2, test_mag)
# make large images
im = galsim.ImageD(im_size, im_size)
ref_im = galsim.ImageD(im_size, im_size)
test_int_im.drawImage(image=im, scale=pix_scale, method='no_pixel')
ref_obj.drawImage(image=ref_im, scale=pix_scale)
# define subregion for comparison
im_sub = im.subImage(comp_bounds)
ref_im_sub = ref_im.subImage(comp_bounds)
diff_im=im_sub-ref_im_sub
rel = diff_im/im_sub
zeros_arr = np.zeros((comp_region, comp_region))
# require relative difference to be smaller than some amount
np.testing.assert_array_almost_equal(rel.array, zeros_arr,
test_decimal,
err_msg='Lensed InterpolatedImage disagrees with reference')
check_pickle(test_int_im, lambda x: x.drawImage(nx=5, ny=5, scale=0.1, method='no_pixel'),
irreprable=irreprable)
check_pickle(test_int_im, irreprable=irreprable)
# Rotate it, and compare with expectations from GSObjects directly
test_rot_angle = 32.*galsim.degrees
test_decimal=2 # in % difference, i.e. 2 means 1% agreement
comp_region=30 # compare the central region of this linear size
test_int_im = int_im.rotate(test_rot_angle)
ref_obj = obj.rotate(test_rot_angle)
# make large images
im = galsim.ImageD(im_size, im_size)
ref_im = galsim.ImageD(im_size, im_size)
test_int_im.drawImage(image=im, scale=pix_scale, method='no_pixel')
ref_obj.drawImage(image=ref_im, scale=pix_scale)
# define subregion for comparison
im_sub = im.subImage(comp_bounds)
ref_im_sub = ref_im.subImage(comp_bounds)
diff_im=im_sub-ref_im_sub
rel = diff_im/im_sub
zeros_arr = np.zeros((comp_region, comp_region))
# require relative difference to be smaller than some amount
np.testing.assert_array_almost_equal(rel.array, zeros_arr,
test_decimal,
err_msg='Rotated InterpolatedImage disagrees with reference')
check_pickle(test_int_im, lambda x: x.drawImage(nx=5, ny=5, scale=0.1, method='no_pixel'),
irreprable=irreprable)
check_pickle(test_int_im, irreprable=irreprable)
# Shift it, and compare with expectations from GSObjects directly
x_shift = -0.31
y_shift = 0.87
test_decimal=2 # in % difference, i.e. 2 means 1% agreement
comp_region=30 # compare the central region of this linear size
test_int_im = int_im.shift(x_shift, y_shift)
ref_obj = obj.shift(x_shift, y_shift)
# make large images
im = galsim.ImageD(im_size, im_size)
ref_im = galsim.ImageD(im_size, im_size)
test_int_im.drawImage(image=im, scale=pix_scale, method='no_pixel')
ref_obj.drawImage(image=ref_im, scale=pix_scale)
# define subregion for comparison
im_sub = im.subImage(comp_bounds)
ref_im_sub = ref_im.subImage(comp_bounds)
diff_im=im_sub-ref_im_sub
rel = diff_im/im_sub
zeros_arr = np.zeros((comp_region, comp_region))
# require relative difference to be smaller than some amount
np.testing.assert_array_almost_equal(rel.array, zeros_arr,
test_decimal,
err_msg='Shifted InterpolatedImage disagrees with reference')
check_pickle(test_int_im, lambda x: x.drawImage(nx=5, ny=5, scale=0.1, method='no_pixel'),
irreprable=irreprable)
check_pickle(test_int_im, irreprable=irreprable)
@timer
def test_operations():
"""Test of operations on complicated InterpolatedImage: shear, magnification, rotation,
shifting.
"""
test_decimal = 3
# Make some nontrivial image
im = galsim.fits.read('./real_comparison_images/test_images.fits') # read in first real galaxy
# in test catalog
int_im = galsim.InterpolatedImage(im)
orig_mom = im.FindAdaptiveMom()
# Magnify by some amount and make sure change is as expected
mu = 0.92
new_int_im = int_im.magnify(mu)
test_im = galsim.ImageF(im.bounds)
new_int_im.drawImage(image = test_im, scale = im.scale, method='no_pixel')
new_mom = test_im.FindAdaptiveMom()
np.testing.assert_almost_equal(new_mom.moments_sigma/np.sqrt(mu),
orig_mom.moments_sigma, test_decimal,
err_msg = 'Size of magnified InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.observed_shape.e1, orig_mom.observed_shape.e1,
test_decimal,
err_msg = 'e1 of magnified InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.observed_shape.e2, orig_mom.observed_shape.e2,
test_decimal,
err_msg = 'e2 of magnified InterpolatedImage from HST disagrees with expectations')
check_pickle(new_int_im, lambda x: x.drawImage(method='no_pixel'))
check_pickle(new_int_im)
# Shift, make sure change in moments is as expected
x_shift = 0.92
y_shift = -0.16
new_int_im = int_im.shift(x_shift, y_shift)
test_im = galsim.ImageF(im.bounds)
new_int_im.drawImage(image = test_im, scale = im.scale, method='no_pixel')
new_mom = test_im.FindAdaptiveMom()
np.testing.assert_almost_equal(new_mom.moments_sigma, orig_mom.moments_sigma,
test_decimal,
err_msg = 'Size of shifted InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.moments_centroid.x-x_shift, orig_mom.moments_centroid.x,
test_decimal,
err_msg = 'x centroid of shifted InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.moments_centroid.y-y_shift, orig_mom.moments_centroid.y,
test_decimal,
err_msg = 'y centroid of shifted InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.observed_shape.e1, orig_mom.observed_shape.e1,
test_decimal,
err_msg = 'e1 of shifted InterpolatedImage from HST disagrees with expectations')
np.testing.assert_almost_equal(new_mom.observed_shape.e2, orig_mom.observed_shape.e2,
test_decimal,
err_msg = 'e2 of shifted InterpolatedImage from HST disagrees with expectations')
check_pickle(new_int_im, lambda x: x.drawImage(method='no_pixel'))
check_pickle(new_int_im)
@timer
def test_uncorr_padding(run_slow):
"""Test for uncorrelated noise padding of InterpolatedImage."""
# Set up some defaults: use weird image sizes / shapes and noise variances.
decimal_precise=5
decimal_coarse=2
orig_nx = 147
orig_ny = 174
noise_var = 1.73
big_nx = 519
big_ny = 482
orig_seed = 151241
# first, make a noise image
orig_img = galsim.ImageF(orig_nx, orig_ny, scale=1.)
gd = galsim.GaussianDeviate(orig_seed, mean=0., sigma=np.sqrt(noise_var))
orig_img.addNoise(galsim.DeviateNoise(gd))
# make it into an InterpolatedImage with some zero-padding
# (note that default is zero-padding, by factors of several)
int_im = galsim.InterpolatedImage(orig_img)
# draw into a larger image
big_img = galsim.ImageF(big_nx, big_ny)
int_im.drawImage(big_img, scale=1., method='no_pixel')
# check that variance is diluted by expected amount - should be exact, so check precisely!
# Note that this only works if the big image has the same even/odd-ness in the two sizes.
# Otherwise the center of the original image will fall between pixels in the big image.
# Then the variance will be smoothed somewhat by the interpolant.
big_var_expected = np.var(orig_img.array)*float(orig_nx*orig_ny)/(big_nx*big_ny)
np.testing.assert_almost_equal(
np.var(big_img.array), big_var_expected, decimal=decimal_precise,
err_msg='Variance not diluted by expected amount when zero-padding')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
# make it into an InterpolatedImage with noise-padding
int_im = galsim.InterpolatedImage(orig_img, noise_pad=noise_var,
noise_pad_size=max(big_nx,big_ny),
rng = galsim.GaussianDeviate(orig_seed))
# draw into a larger image
big_img = galsim.ImageF(big_nx, big_ny)
int_im.drawImage(big_img, scale=1., method='no_pixel')
# check that variance is same as original - here, we cannot be too precise because the padded
# region is not huge and the comparison will be, well, noisy.
print('measured var = ',np.var(big_img.array))
np.testing.assert_almost_equal(
np.var(big_img.array), noise_var, decimal=decimal_coarse,
err_msg='Variance not correct after padding image with noise')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
else:
# On pytest runs, use a smaller noise_pad_size for the pickle tests so it doesn't take
# so long to serialize.
int_im = galsim.InterpolatedImage(orig_img, noise_pad=noise_var,
pad_factor=1,
noise_pad_size=max(orig_nx+10,orig_ny+10),
rng = galsim.GaussianDeviate(orig_seed))
check_pickle(int_im)
# check that if we pass in a RNG, it is actually used to pad with the same noise field
# basically, redo all of the above steps and draw into a new image, make sure it's the same as
# previous.
int_im = galsim.InterpolatedImage(orig_img, noise_pad=noise_var,
noise_pad_size=max(big_nx,big_ny),
rng = galsim.GaussianDeviate(orig_seed))
big_img_2 = galsim.ImageF(big_nx, big_ny)
int_im.drawImage(big_img_2, scale=1., method='no_pixel')
np.testing.assert_array_almost_equal(
big_img_2.array, big_img.array, decimal=decimal_precise,
err_msg='Cannot reproduce noise-padded image with same choice of seed')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
# Finally check inputs: what if we give it an input variance that is neg? A list?
with assert_raises(ValueError):
galsim.InterpolatedImage(orig_img, noise_pad=-1., noise_pad_size=20)
@timer
def test_pad_image(run_slow):
"""Test padding an InterpolatedImage with a pad_image."""
decimal=2 # all are coarse, since there are slight changes from odd/even centering issues.
noise_sigma = 1.73
noise_var = noise_sigma**2
orig_seed = 12345
rng = galsim.BaseDeviate(orig_seed)
noise = galsim.GaussianNoise(rng, sigma=noise_sigma)
# make the original image
orig_nx = 64
orig_ny = 64
orig_img = galsim.ImageF(orig_nx, orig_ny, scale=1.)
galsim.Exponential(scale_radius=1.7,flux=1000).drawImage(orig_img, method='no_pixel')
orig_img.addNoise(noise)
orig_img.setCenter(0,0)
# We'll draw into a larger image for the tests
pad_factor = 4
big_nx = pad_factor*orig_nx
big_ny = pad_factor*orig_ny
big_img = galsim.ImageF(big_nx, big_ny, scale=1.)
big_img.setCenter(0,0)
# Use a few different kinds of shapes for that padding.
for (pad_nx, pad_ny) in [ (160,160), (179,191), (256,256), (305, 307) ]:
# make the pad_image
pad_img = galsim.ImageF(pad_nx, pad_ny, scale=1.)
pad_img.addNoise(noise)
pad_img.setCenter(0,0)
# make an interpolated image padded with the pad_image, and outside of that
int_im = galsim.InterpolatedImage(orig_img, pad_image=pad_img, use_true_center=False)
# draw into the larger image
int_im.drawImage(big_img, use_true_center=False, method='no_pixel')
# check that variance is diluted by expected amount
# Note -- we don't use np.var, since that computes the variance relative to the
# actual mean value. We just want sum(I^2)/Npix relative to the nominal I=0 value.
var1 = np.sum(orig_img.array**2)
if pad_nx > big_nx and pad_ny > big_ny:
var2 = np.sum(pad_img[big_img.bounds].array**2)
else:
var2 = np.sum(pad_img.array**2)
var2 -= np.sum(pad_img[orig_img.bounds].array**2)
var_expected = (var1 + var2) / (big_nx*big_ny)
big_img.setCenter(0,0)
np.testing.assert_almost_equal(
np.mean(big_img.array**2), var_expected, decimal=decimal,
err_msg='Variance not correct when padding with image')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
if pad_nx < big_nx and pad_ny < big_ny:
# now also pad with noise_pad outside of the pad_image
int_im = galsim.InterpolatedImage(orig_img, pad_image=pad_img, noise_pad=noise_var/2,
noise_pad_size=max(big_nx,big_ny),
rng=rng, use_true_center=False)
int_im.drawImage(big_img, use_true_center=False, method='no_pixel')
var3 = (noise_var/2) * float(big_nx*big_ny - pad_nx*pad_ny)
var_expected = (var1 + var2 + var3) / (big_nx*big_ny)
np.testing.assert_almost_equal(
np.mean(big_img.array**2), var_expected, decimal=decimal,
err_msg='Variance not correct after padding with image and extra noise')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
@timer
def test_corr_padding(run_slow):
"""Test for correlated noise padding of InterpolatedImage."""
# Set up some defaults for tests.
decimal_precise=4
decimal_coarse=2
imgfile = 'fits_files/blankimg.fits'
orig_nx = 187
orig_ny = 164
big_nx = 319
big_ny = 322
orig_seed = 151241
# Read in some small image of a noise field from HST.
im = galsim.fits.read(imgfile)
# Make a CorrrlatedNoise out of it.
cn = galsim.CorrelatedNoise(im, galsim.BaseDeviate(orig_seed))
# first, make a noise image
orig_img = galsim.ImageF(orig_nx, orig_ny, scale=1.)
orig_img.addNoise(cn)
# make it into an InterpolatedImage with some zero-padding
# (note that default is zero-padding, by factors of several)
int_im = galsim.InterpolatedImage(orig_img)
# draw into a larger image
big_img = galsim.ImageF(big_nx, big_ny)
int_im.drawImage(big_img, scale=1., method='no_pixel')
# check that variance is diluted by expected amount - should be exact, so check precisely!
big_var_expected = np.var(orig_img.array)*float(orig_nx*orig_ny)/(big_nx*big_ny)
np.testing.assert_almost_equal(np.var(big_img.array), big_var_expected, decimal=decimal_precise,
err_msg='Variance not diluted by expected amount when zero-padding')
if run_slow:
check_pickle(int_im, lambda x: x.drawImage(nx=200, ny=200, scale=1, method='no_pixel'))
check_pickle(int_im)
# make it into an InterpolatedImage with noise-padding
int_im = galsim.InterpolatedImage(orig_img, rng=galsim.GaussianDeviate(orig_seed),
noise_pad=im, noise_pad_size=max(big_nx,big_ny))
# draw into a larger image
big_img = galsim.ImageF(big_nx, big_ny, scale=1.)
int_im.drawImage(big_img, method='no_pixel')
# check that variance is same as original - here, we cannot be too precise because the padded
# region is not huge and the comparison will be, well, noisy.