-
Notifications
You must be signed in to change notification settings - Fork 2
/
Snakefile
5204 lines (4925 loc) · 296 KB
/
Snakefile
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
# required to fix this strange problem:
# https://stackoverflow.com/questions/64797838/libgcc-s-so-1-must-be-installed-for-pthread-cancel-to-work
import ctypes
libgcc_s = ctypes.CDLL('libgcc_s.so.1')
import os
import math
import itertools
import re
import imageio
import time
import os.path as op
from glob import glob
import numpy as np
from foveated_metamers import utils
import numpyro
import multiprocessing
configfile:
# config is in the same directory as this file
op.join(op.dirname(op.realpath(workflow.snakefile)), 'config.yml')
if not op.isdir(config["DATA_DIR"]):
raise Exception("Cannot find the dataset at %s" % config["DATA_DIR"])
# for some reason, I can't get os.system('module list') to work
# properly on NYU Greene (it always returns a non-zero exit
# code). However, they do have the CLUSTER environmental variable
# defined, so we can use that
if os.system("module list") == 0 or os.environ.get("CLUSTER", None):
# then we're on the cluster
ON_CLUSTER = True
numpyro.set_host_device_count(multiprocessing.cpu_count())
else:
ON_CLUSTER = False
numpyro.set_host_device_count(4)
wildcard_constraints:
num="[0-9]+",
pad_mode="constant|symmetric",
period="[0-9]+",
size="[0-9,]+",
bits="[0-9]+",
img_preproc="full|degamma|range-[,.0-9]+|downsample-[0-9.]+_range-[,.0-9]+",
# einstein for testing setup, fountain for comparing with Freeman and
# Simoncelli, 2011 metamers, sherlock for example with text, for
# presentations
preproc_image_name="|".join([im+'_?[a-z]*' for im in config['IMAGE_NAME']['ref_image']])+"|einstein|fountain|sherlock_[0-9]",
preproc="|_degamma|degamma",
gpu="0|1",
sess_num="|".join([f'{i:02d}' for i in config['PSYCHOPHYSICS']['SESSIONS']]),
run_num="|".join([f'{i:02d}' for i in config['PSYCHOPHYSICS']['RUNS']]),
comp='met|ref|met-downsample-2|met-natural|ref-natural|met-pink',
save_all='|_saveall',
gammacorrected='|_gamma-corrected',
plot_focus='|_focus-subject|_focus-image',
ecc_mask="|_eccmask-[0-9]+",
logscale="log|linear",
mcmc_model="partially-pooled|unpooled|partially-pooled-interactions-[.0-9]+|partially-pooled-interactions",
fixation_cross="cross|nocross",
cutout="cutout|nocutout|cutout_V1_natural-seed|cutout_RGC_natural-seed|nocutout_small|cutout_downsample|cutout_V1_natural-seed_init|cutout_RGC_natural-seed_init",
compressed="|_compressed",
context="paper|poster",
mcmc_plot_type="performance|params-(linear|log)-(none|lines|ci)",
# don't capture experiment-mse for x, but capture anything else, because
# experiment-mse is a different rule
x="(?!experiment-mse)(.*)",
mse="experiment_mse|full_image_mse",
seed="[0-9]+",
line="offset|nooffset",
gif_direction="forward|reverse",
scaling_extended="|_scaling-extended",
osf_model_name='energy|luminance',
# these are the only possible schematics
schematic_name='|'.join([f.replace(op.join('reports', 'figures', ''), '').replace('.svg', '')
for f in glob(op.join('reports', 'figures', '*svg'))]),
yaxis_dbl='single|double',
t_width='[0-9.]+',
window_type='cosine|gaussian',
width='fullwidth|halfwidth',
ruleorder:
collect_training_metamers > collect_training_noise > collect_metamers > demosaic_image > preproc_image > crop_image > generate_image > degamma_image > create_metamers > mcmc_compare_plot > mcmc_plots > mcmc_performance_comparison_figure > embed_bitmaps_into_figure > compose_figures > copy_schematic
config['INKSCAPE_PREF_FILE'] = op.expanduser(config['INKSCAPE_PREF_FILE'])
config['FREEMAN_METAMER_PATH'] = op.expanduser(config['FREEMAN_METAMER_PATH'])
config['MATLABPYRTOOLS_PATH'] = op.expanduser(config['MATLABPYRTOOLS_PATH'])
LINEAR_IMAGES = config['IMAGE_NAME']['ref_image']
MODELS = [config[i]['model_name'] for i in ['RGC', 'V1']]
IMAGES = config['DEFAULT_METAMERS']['image_name']
# this is ugly, but it's easiest way to just replace the one format
# target while leaving the others alone
DATA_DIR = config['DATA_DIR']
if not DATA_DIR.endswith('/'):
DATA_DIR += '/'
REF_IMAGE_TEMPLATE_PATH = config['REF_IMAGE_TEMPLATE_PATH'].replace("{DATA_DIR}/", DATA_DIR)
# the regex here removes all string formatting codes from the string,
# since Snakemake doesn't like them
METAMER_TEMPLATE_PATH = re.sub(":.*?}", "}", config['METAMER_TEMPLATE_PATH'].replace("{DATA_DIR}/", DATA_DIR))
MAD_TEMPLATE_PATH = re.sub(":.*?}", "}", config['MAD_TEMPLATE_PATH'].replace("{DATA_DIR}/", DATA_DIR))
METAMER_LOG_PATH = METAMER_TEMPLATE_PATH.replace('metamers/{model_name}', 'logs/metamers/{model_name}').replace('_metamer.png', '.log')
MAD_LOG_PATH = MAD_TEMPLATE_PATH.replace('mad_images/{model_name}', 'logs/mad_images/{model_name}').replace('_mad.png', '.log')
CONTINUE_TEMPLATE_PATH = (METAMER_TEMPLATE_PATH.replace('metamers/{model_name}', 'metamers_continue/{model_name}')
.replace("{clamp_each_iter}/", "{clamp_each_iter}/attempt-{num}_iter-{extra_iter}"))
CONTINUE_LOG_PATH = CONTINUE_TEMPLATE_PATH.replace('metamers_continue/{model_name}', 'logs/metamers_continue/{model_name}').replace('_metamer.png', '.log')
TEXTURE_DIR = config['TEXTURE_DIR']
if TEXTURE_DIR.endswith(os.sep) or TEXTURE_DIR.endswith('/'):
TEXTURE_DIR = TEXTURE_DIR[:-1]
if op.exists(TEXTURE_DIR) and len(os.listdir(TEXTURE_DIR)) <= 800 and 'textures-subset-for-testing' not in TEXTURE_DIR:
raise Exception(f"TEXTURE_DIR {TEXTURE_DIR} is incomplete!")
BEHAVIORAL_DATA_DATES = {
'V1_norm_s6_gaussian': {
'ref': {
'sub-00': {'sess-00': '2021-Mar-23', 'sess-01': '2021-Mar-24', 'sess-02': '2021-Mar-24'},
'sub-01': {'sess-00': '2021-Mar-30', 'sess-01': '2021-Mar-30', 'sess-02': '2021-Apr-01'},
'sub-02': {'sess-00': '2021-Apr-14', 'sess-01': '2021-Apr-16', 'sess-02': '2021-Apr-21'},
'sub-03': {'sess-00': '2021-Apr-02', 'sess-01': '2021-Apr-07', 'sess-02': '2021-Apr-09'},
'sub-04': {'sess-00': '2021-Apr-05', 'sess-01': '2021-Apr-06', 'sess-02': '2021-Apr-12'},
'sub-05': {'sess-00': '2021-Apr-30', 'sess-01': '2021-May-05', 'sess-02': '2021-May-11'},
'sub-06': {'sess-00': '2021-May-14', 'sess-01': '2021-May-17', 'sess-02': '2021-May-18'},
'sub-07': {'sess-00': '2021-Apr-23', 'sess-01': '2021-Apr-26', 'sess-02': '2021-Apr-28'},
},
'met': {
'sub-00': {'sess-00': '2021-Apr-05', 'sess-01': '2021-Apr-07', 'sess-02': '2021-Apr-08'},
'sub-01': {'sess-00': '2021-Apr-28', 'sess-01': '2021-Apr-28', 'sess-02': '2021-Apr-28'},
'sub-02': {'sess-00': '2021-May-03', 'sess-01': '2021-May-04', 'sess-02': '2021-May-05'},
'sub-03': {'sess-00': '2021-May-03', 'sess-01': '2021-May-04', 'sess-02': '2021-May-12'},
'sub-04': {'sess-00': '2021-May-11', 'sess-01': '2021-May-12', 'sess-02': '2021-May-18'},
'sub-05': {'sess-00': '2021-May-12', 'sess-01': '2021-May-17', 'sess-02': '2021-May-18'},
'sub-06': {'sess-00': '2021-May-25', 'sess-01': '2021-May-26', 'sess-02': '2021-May-28'},
'sub-07': {'sess-00': '2021-Apr-30', 'sess-01': '2021-Apr-30', 'sess-02': '2021-May-03'},
},
'met-downsample-2': {
'sub-00': {'sess-00': '2021-May-04', 'sess-01': '2021-May-05', 'sess-02': '2021-May-06'},
},
'met-natural': {
'sub-00': {'sess-00': '2021-Jul-14', 'sess-01': '2021-Jul-14', 'sess-02': '2021-Jul-15'},
},
'ref-natural': {
'sub-00': {'sess-00': '2021-Jul-07', 'sess-01': '2021-Jul-13', 'sess-02': '2021-Jul-13'},
},
},
'RGC_norm_gaussian': {
'ref': {
'sub-00': {'sess-00': '2021-Apr-02', 'sess-01': '2021-Apr-06', 'sess-02': '2021-Apr-06'},
'sub-01': {'sess-00': '2021-Apr-16', 'sess-01': '2021-Apr-16', 'sess-02': '2021-Apr-16'},
'sub-02': {'sess-00': '2021-Apr-07', 'sess-01': '2021-Apr-08', 'sess-02': '2021-Apr-12'},
'sub-03': {'sess-00': '2021-Apr-27', 'sess-01': '2021-Apr-28', 'sess-02': '2021-Apr-30'},
'sub-04': {'sess-00': '2021-Apr-21', 'sess-01': '2021-Apr-23', 'sess-02': '2021-Apr-27'},
'sub-05': {'sess-00': '2021-Apr-14', 'sess-01': '2021-Apr-23', 'sess-02': '2021-Apr-27'},
'sub-06': {'sess-00': '2021-Apr-14', 'sess-01': '2021-May-05', 'sess-02': '2021-May-12'},
'sub-07': {'sess-00': '2021-Apr-14', 'sess-01': '2021-Apr-16', 'sess-02': '2021-Apr-21'},
},
'met': {
'sub-00': {'sess-00': '2021-Apr-09'},
}
}
}
rule get_all_mcmc_plots:
input:
[op.join(config["DATA_DIR"], 'mcmc', '{model_name}', 'task-split_comp-{comp}',
'task-split_comp-{comp}_mcmc_{mcmc_model}_{hyper}_{plot_name}.png').format(
mcmc_model=mc, model_name=m, comp=c, plot_name=p,
hyper=utils.get_mcmc_hyperparams({}, mcmc_model=mc, model_name=m, comp=c))
for mc in ['unpooled', 'partially-pooled', 'partially-pooled-interactions']
for m in MODELS
for c in {'V1_norm_s6_gaussian': ['met', 'ref', 'met-natural', 'met-downsample-2', 'ref-natural']}.get(m, ['met', 'ref'])
for p in ['diagnostics', 'performance', 'post-pred-check', 'psychophysical-params', 'grouplevel', 'param-corr_image',
'param-corr_subject'] + {'partially-pooled-interactions': ['metaparams', 'interaction-params', 'param-avg-method', 'params'],
'partially-pooled': ['metaparams', 'param-avg-method', 'param-corr_a0', 'param-corr_s0', 'params']}.get(mc, [])
]
# quick rule to check that there are GPUs available and the environment
# has been set up correctly.
rule test_setup_all:
input:
[op.join(config['DATA_DIR'], 'test_setup', '{}_gpu-{}', 'einstein').format(m, g) for g in [0, 1]
for m in MODELS],
rule test_setup:
input:
lambda wildcards: utils.generate_metamer_paths(model_name=wildcards.model_name,
image_name='einstein_degamma_size-256,256',
scaling=1.0,
gpu=wildcards.gpu_num,
max_iter=210,
seed=0)[0].replace('metamer.png', 'synthesis-1.png')
output:
directory(op.join(config['DATA_DIR'], 'test_setup', '{model_name}_gpu-{gpu_num}', 'einstein')),
log:
op.join(config['DATA_DIR'], 'logs', 'test_setup', '{model_name}_gpu-{gpu_num}', 'einstein.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'test_setup', '{model_name}_gpu-{gpu_num}', 'einstein_benchmark.txt')
run:
import contextlib
import shutil
import os.path as op
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
print("Copying outputs from %s to %s" % (op.dirname(input[0]), output[0]))
# Copy over only those files that were generated by the call
# with the correct gpu_num wildcard, ignore the others
# (wildcards.gpu_num can only take values 0 or 1)
ignore_gpu = {0: '*_gpu-1*', 1: '*_gpu-0*'}[int(wildcards.gpu_num)]
shutil.copytree(op.dirname(input[0]), output[0], ignore=shutil.ignore_patterns(ignore_gpu))
rule all_refs:
input:
[utils.get_ref_image_full_path(utils.get_gamma_corrected_ref_image(i))
for i in IMAGES],
[utils.get_ref_image_full_path(i) for i in IMAGES],
# for this project, our input images are linear images, but if you want
# to run this process on standard images, they have had a gamma
# correction applied to them. since we'll be displaying them on a linear
# display, we want to remove this correction (see
# https://www.cambridgeincolour.com/tutorials/gamma-correction.htm for
# an explanation)
rule degamma_image:
input:
op.join(config['DATA_DIR'], 'ref_images', '{image_name}.png')
output:
op.join(config['DATA_DIR'], 'ref_images', '{image_name}-degamma-{bits}.png')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}-degamma-{bits}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}-degamma-{bits}'
'_benchmark.txt')
run:
import imageio
import contextlib
import foveated_metamers as fov
from skimage import color
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
im = imageio.imread(input[0])
# when loaded in, the range of this will be 0 to 255, we
# want to convert it to 0 to 1
im = fov.utils.convert_im_to_float(im)
# convert to grayscale
im = color.rgb2gray(im)
# 1/2.2 is the standard encoding gamma for jpegs, so we
# raise this to its reciprocal, 2.2, in order to reverse
# it
im = im**2.2
dtype = eval('np.uint%s' % wildcards.bits)
imageio.imwrite(output[0], fov.utils.convert_im_to_int(im, dtype))
rule demosaic_image:
input:
op.join(config['DATA_DIR'], 'raw_images', '{image_name}.NEF')
output:
op.join(config['DATA_DIR'], 'ref_images', '{image_name}.tiff')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}_benchmark.txt')
params:
tiff_file = lambda wildcards, input: input[0].replace('NEF', 'tiff')
shell:
"dcraw -v -4 -q 3 -T {input}; "
"mv {params.tiff_file} {output}"
rule crop_image:
input:
op.join(config['DATA_DIR'], 'ref_images', '{image_name}.tiff')
output:
op.join(config['DATA_DIR'], 'ref_images', '{image_name}_size-{size}.png')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}_size-{size}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_name}_size-{size}_benchmark.txt')
run:
import imageio
import contextlib
from skimage import color
import foveated_metamers as fov
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
im = imageio.imread(input[0])
curr_shape = np.array(im.shape)[:2]
target_shape = [int(i) for i in wildcards.size.split(',')]
print(curr_shape, target_shape)
if len(target_shape) == 1:
target_shape = 2* target_shape
target_shape = np.array(target_shape)
crop_amt = curr_shape - target_shape
# this is ugly, but I can't come up with an easier way to make
# sure that we skip a dimension if crop_amt is 0 for it
cropped_im = im
for i, c in enumerate(crop_amt):
if c == 0:
continue
else:
if i == 0:
cropped_im = cropped_im[c//2:-c//2]
elif i == 1:
cropped_im = cropped_im[:, c//2:-c//2]
else:
raise Exception("Can only crop up to two dimensions!")
cropped_im = color.rgb2gray(cropped_im)
imageio.imwrite(output[0], fov.utils.convert_im_to_int(cropped_im, np.uint16))
# tiffs can't be read in using the as_gray arg, so we
# save it as a png, and then read it back in as_gray and
# save it back out
cropped_im = imageio.imread(output[0], as_gray=True)
imageio.imwrite(output[0], cropped_im.astype(np.uint16))
rule preproc_image:
input:
op.join(config['DATA_DIR'], 'ref_images', '{preproc_image_name}_size-{size}.png')
output:
op.join(config['DATA_DIR'], 'ref_images_preproc', '{preproc_image_name}_{img_preproc}_size-{size}.png')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_image_preproc',
'{preproc_image_name}_{img_preproc}_size-{size}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_image_preproc',
'{preproc_image_name}_{img_preproc}_size-{size}_benchmark.txt')
run:
import imageio
import contextlib
import numpy as np
from skimage import transform
import foveated_metamers as fov
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
im = imageio.imread(input[0])
dtype = im.dtype
im = np.array(im, dtype=np.float32)
print("Original image has dtype %s" % dtype)
if 'full' in wildcards.img_preproc:
print("Setting image to use full dynamic range")
# set the minimum value to 0
im = im - im.min()
# set the maximum value to 1
im = im / im.max()
elif 'range' in wildcards.img_preproc:
a, b = re.findall('range-([.0-9]+),([.0-9]+)', wildcards.img_preproc)[0]
a, b = float(a), float(b)
print(f"Setting range to {a:02f}, {b:02f}")
if a > b:
raise Exception("For consistency, with range-a,b preprocessing, b must be"
" greater than a, but got {a} > {b}!")
# set the minimum value to 0
im = im - im.min()
# set the maximum value to 1
im = im / im.max()
# and then rescale
im = im * (b - a) + a
else:
print("Image will *not* use full dynamic range")
im = im / np.iinfo(dtype).max
if 'downsample' in wildcards.img_preproc:
downscale = float(re.findall('downsample-([.0-9]+)_', wildcards.img_preproc)[0])
im = transform.pyramid_reduce(im, downscale)
# always save it as 16 bit
print("Saving as 16 bit")
im = fov.utils.convert_im_to_int(im, np.uint16)
imageio.imwrite(output[0], im)
rule gamma_correct_ref_image:
input:
op.join(config['DATA_DIR'], 'ref_images{ref_suffix}', '{preproc_image_name}_{image_suffix}.png')
output:
op.join(config['DATA_DIR'], 'ref_images{ref_suffix}', '{preproc_image_name}_gamma-corrected_{image_suffix}.png')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_images{ref_suffix}', '{preproc_image_name}_gamma-corrected_{image_suffix}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_images{ref_suffix}', '{preproc_image_name}_gamma-corrected_{image_suffix}_benchmark.txt')
run:
import imageio
import contextlib
import numpy as np
import foveated_metamers as fov
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
im = imageio.imread(input[0])
dtype = im.dtype
im = np.array(im, dtype=np.float32)
print("Original image has dtype %s" % dtype)
im = im / np.iinfo(dtype).max
print("Raising image to 1/2.2, to gamma correct it")
im = im ** (1/2.2)
# always save it as 16 bit
print("Saving as 16 bit")
im = fov.utils.convert_im_to_int(im, np.uint16)
imageio.imwrite(output[0], im)
rule pad_image:
input:
op.join(config["DATA_DIR"], 'ref_images', '{image_name}.{ext}')
output:
op.join(config["DATA_DIR"], 'ref_images', '{image_name}_{pad_mode}.{ext}')
log:
op.join(config["DATA_DIR"], 'logs', 'ref_images', '{image_name}_{pad_mode}-{ext}.log')
benchmark:
op.join(config["DATA_DIR"], 'logs', 'ref_images', '{image_name}_{pad_mode}-{ext}_benchmark.txt')
run:
import foveated_metamers as fov
import contextlib
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
fov.stimuli.pad_image(input[0], wildcards.pad_mode, output[0])
rule generate_image:
output:
op.join(config['DATA_DIR'], 'ref_images', '{image_type}_period-{period}_size-{size}.png')
log:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_type}_period-{period}_size-'
'{size}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'ref_images', '{image_type}_period-{period}_size-'
'{size}_benchmark.txt')
run:
import foveated_metamers as fov
import contextlib
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
fov.stimuli.create_image(wildcards.image_type, int(wildcards.size), output[0],
int(wildcards.period))
rule preproc_textures:
input:
TEXTURE_DIR
output:
directory(TEXTURE_DIR + "_{preproc}")
log:
op.join(config['DATA_DIR'], 'logs', '{preproc}_textures.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', '{preproc}_textures_benchmark.txt')
run:
import imageio
import contextlib
from glob import glob
import os.path as op
import os
from skimage import color
import foveated_metamers as fov
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
os.makedirs(output[0])
for i in glob(op.join(input[0], '*.jpg')):
im = imageio.imread(i)
im = fov.utils.convert_im_to_float(im)
if im.ndim == 3:
# then it's a color image, and we need to make it grayscale
im = color.rgb2gray(im)
if 'degamma' in wildcards.preproc:
# 1/2.2 is the standard encoding gamma for jpegs, so we
# raise this to its reciprocal, 2.2, in order to reverse
# it
im = im ** 2.2
# save as a 16 bit png
im = fov.utils.convert_im_to_int(im, np.uint16)
imageio.imwrite(op.join(output[0], op.split(i)[-1].replace('jpg', 'png')), im)
rule gen_norm_stats:
input:
TEXTURE_DIR + "{preproc}"
output:
# here V1 and texture could be considered wildcards, but they're
# the only we're doing this for now
op.join(config['DATA_DIR'], 'norm_stats', 'V1_texture{preproc}_'
'norm_stats-{num}.pt' )
log:
op.join(config['DATA_DIR'], 'logs', 'norm_stats', 'V1_texture'
'{preproc}_norm_stats-{num}.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'norm_stats', 'V1_texture'
'{preproc}_norm_stats-{num}_benchmark.txt')
params:
index = lambda wildcards: (int(wildcards.num) * 100, (int(wildcards.num)+1) * 100)
run:
import contextlib
import sys
sys.path.append(op.join(op.dirname(op.realpath(__file__)), 'extra_packages'))
import plenoptic_part as pop
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
# scaling doesn't matter here
v1 = pop.PooledV1(1, (512, 512), num_scales=6)
pop.optim.generate_norm_stats(v1, input[0], output[0], (512, 512),
index=params.index)
# we need to generate the stats in blocks, and then want to re-combine them
rule combine_norm_stats:
input:
lambda wildcards: [op.join(config['DATA_DIR'], 'norm_stats', 'V1_texture'
'{preproc}_norm_stats-{num}.pt').format(num=i, **wildcards)
for i in range(math.ceil(len(os.listdir(TEXTURE_DIR))/100))]
output:
op.join(config['DATA_DIR'], 'norm_stats', 'V1_texture{preproc}_norm_stats.pt' )
log:
op.join(config['DATA_DIR'], 'logs', 'norm_stats', 'V1_texture'
'{preproc}_norm_stats.log')
benchmark:
op.join(config['DATA_DIR'], 'logs', 'norm_stats', 'V1_texture'
'{preproc}_norm_stats_benchmark.txt')
run:
import torch
import contextlib
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
combined_stats = {}
to_combine = [torch.load(i) for i in input]
for k, v in to_combine[0].items():
if isinstance(v, dict):
d = {}
for l in v:
s = []
for i in to_combine:
s.append(i[k][l])
d[l] = torch.cat(s, 0)
combined_stats[k] = d
else:
s = []
for i in to_combine:
s.append(i[k])
combined_stats[k] = torch.cat(s, 0)
torch.save(combined_stats, output[0])
def get_mem_estimate(wildcards, partition=None):
r"""estimate the amount of memory that this will need, in GB
"""
try:
if 'size-2048,2600' in wildcards.image_name:
if 'gaussian' in wildcards.model_name or 'Obs' in wildcards.model_name:
if 'V1' in wildcards.model_name or 'Obs' in wildcards.model_name:
if float(wildcards.scaling) < .1:
mem = 128
else:
mem = 64
elif 'RGC' in wildcards.model_name:
# this is an approximation of the size of their windows,
# and if you have at least 3 times this memory, you're
# good. double-check this value -- the 1.36 is for
# converting form 2048,3528 (which the numbers came
# from) to 2048,2600 (which has 1.36x fewer pixels)
window_size = 1.17430726 / (1.36*float(wildcards.scaling))
mem = int(5 * window_size)
# running out of memory for larger scaling values, so let's
# never request less than 32 GB
mem = max(mem, 32)
elif 'cosine' in wildcards.model_name:
if 'V1' in wildcards.model_name:
# most it will need is 32 GB
mem = 32
elif 'RGC' in wildcards.model_name:
# this is an approximation of the size of their windows,
# and if you have at least 3 times this memory, you're
# good
window_size = 0.49238059 / float(wildcards.scaling)
mem = int(5 * window_size)
else:
mem = 32
else:
# don't have a good estimate for these
mem = 16
except AttributeError:
# then we don't have a image_name wildcard (and thus this is
# being called by cache_windows)
if wildcards.size == '2048,2600':
if wildcards.window_type == 'gaussian':
# this is an approximation of the size of their windows,
# and if you have at least 3 times this memory, you're
# good. double-check this value -- the 1.36 is for
# converting form 2048,3528 (which the numbers came
# from) to 2048,2600 (which has 1.36x fewer pixels)
window_size = 1.17430726 / (1.36*float(wildcards.scaling))
mem = int(5 * window_size)
elif wildcards.window_type == 'cosine':
# this is an approximation of the size of their windows,
# and if you have at least 3 times this memory, you're
# good
window_size = 0.49238059 / float(wildcards.scaling)
mem = int(5 * window_size)
else:
# don't have a good estimate here
mem = 16
try:
if wildcards.save_all:
# for this estimate, RGC with scaling .095 went from 36GB requested
# to about 54GB used when stored iterations went from 100 to 1000.
# that's 1.5x higher, and we add a bit of a buffer. also, don't
# want to reduce memory estimate
mem_factor = max((int(wildcards.max_iter) / 100) * (1.7/10), 1)
mem *= mem_factor
except AttributeError:
# then we're missing either the save_all or max_iter wildcard, in which
# case this is probably cache_windows and the above doesn't matter
pass
mem = int(np.ceil(mem))
if partition == 'rusty':
if int(wildcards.gpu) == 0:
# in this case, we *do not* want to specify memory (we'll get the
# whole node allocated but slurm could still kill the job if we go
# over requested memory). setting mem=0 requests all memory on node
mem = '0'
else:
# we'll be plugging this right into the mem request to slurm, so it
# needs to be exactly correct
mem = f"{mem}GB"
return mem
rule cache_windows:
output:
op.join(config["DATA_DIR"], 'windows_cache', 'scaling-{scaling}_size-{size}_e0-{min_ecc}_'
'em-{max_ecc}_w-{t_width}_{window_type}.pt')
log:
op.join(config["DATA_DIR"], 'logs', 'windows_cache', 'scaling-{scaling}_size-{size}_e0-'
'{min_ecc}_em-{max_ecc}_w-{t_width}_{window_type}.log')
benchmark:
op.join(config["DATA_DIR"], 'logs', 'windows_cache', 'scaling-{scaling}_size-{size}_e0-'
'{min_ecc}_em-{max_ecc}_w-{t_width}_{window_type}.benchmark.txt')
resources:
mem = get_mem_estimate,
run:
import contextlib
import plenoptic as po
import sys
sys.path.append(op.join(op.dirname(op.realpath(__file__)), '..', 'extra_packages', 'pooling-windows'))
import pooling
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
img_size = [int(i) for i in wildcards.size.split(',')]
kwargs = {}
if wildcards.window_type == 'cosine':
t_width = float(wildcards.t_width)
std_dev = None
min_ecc = float(wildcards.min_ecc)
elif wildcards.window_type == 'gaussian':
std_dev = float(wildcards.t_width)
t_width = None
min_ecc = float(wildcards.min_ecc)
pooling.PoolingWindows(float(wildcards.scaling), img_size, min_ecc,
float(wildcards.max_ecc), cache_dir=op.dirname(output[0]),
transition_region_width=t_width, std_dev=std_dev,
window_type=wildcards.window_type, **kwargs)
def get_norm_dict(wildcards):
if 'norm' in wildcards.model_name or wildcards.model_name.startswith('Obs'):
preproc = ''
# lienar images should also use the degamma'd textures
if 'degamma' in wildcards.image_name or any([i in wildcards.image_name for i in LINEAR_IMAGES]):
preproc += '_degamma'
return op.join(config['DATA_DIR'], 'norm_stats', f'V1_texture{preproc}'
'_norm_stats.pt')
else:
return []
def get_windows(wildcards):
r"""determine the cached window path for the specified model
"""
wildcards = dict(wildcards)
window_template = op.join(config["DATA_DIR"], 'windows_cache', 'scaling-{scaling}_size-{size}'
'_e0-{min_ecc:.03f}_em-{max_ecc:.01f}_w-{t_width}_{window_type}.pt')
try:
if 'size-' in wildcards['image_name']:
im_shape = wildcards['image_name'][wildcards['image_name'].index('size-') + len('size-'):]
im_shape = im_shape.replace('.png', '')
im_shape = [int(i) for i in im_shape.split(',')]
else:
try:
im = imageio.imread(REF_IMAGE_TEMPLATE_PATH.format(image_name=wildcards['image_name']))
im_shape = im.shape
except FileNotFoundError:
raise Exception("Can't find input image %s or infer its shape, so don't know what "
"windows to cache!" %
REF_IMAGE_TEMPLATE_PATH.format(image_name=wildcards['image_name']))
except KeyError:
# then there was no wildcards['image_name'], so grab the first one from
# the DEFAULT_METAMERS list
default_im = IMAGES[0]
im_shape = default_im[default_im.index('size-') + len('size-'):]
im_shape = im_shape.replace('.png', '')
im_shape = [int(i) for i in im_shape.split(',')]
try:
max_ecc=float(wildcards['max_ecc'])
min_ecc=float(wildcards['min_ecc'])
except KeyError:
# then there was no wildcards['max / min_ecc'], so grab the default values
min_ecc = config['DEFAULT_METAMERS']['min_ecc']
max_ecc = config['DEFAULT_METAMERS']['max_ecc']
t_width = 1.0
if 'cosine' in wildcards['model_name']:
window_type = 'cosine'
elif 'gaussian' in wildcards['model_name'] or wildcards['model_name'].startswith('Obs'):
window_type = 'gaussian'
scaling = wildcards['scaling']
# make sure that scaling is 0-padded, if appropriate. e.g., 0.01, not .01
if isinstance(scaling, str) and scaling[0] == '.':
scaling = '0' + scaling
if wildcards['model_name'].startswith("RGC"):
# RGC model only needs a single scale of PoolingWindows.
size = ','.join([str(i) for i in im_shape])
return window_template.format(scaling=scaling, size=size,
max_ecc=max_ecc, t_width=t_width,
min_ecc=min_ecc, window_type=window_type,)
elif wildcards['model_name'].startswith('V1') or wildcards['model_name'].startswith('Obs'):
windows = []
# need them for every scale
try:
num_scales = int(re.findall('s([0-9]+)', wildcards['model_name'])[0])
except (IndexError, ValueError):
num_scales = 4
for i in range(num_scales):
output_size = ','.join([str(int(np.ceil(j / 2**i))) for j in im_shape])
windows.append(window_template.format(scaling=scaling, size=output_size,
max_ecc=max_ecc,
min_ecc=min_ecc,
t_width=t_width, window_type=window_type))
return windows
def get_partition(wildcards, cluster):
# if our V1 scaling value is small enough, we need a V100 and must specify
# it. otherwise, we can use any GPU, because they'll all have enough
# memory. The partition name depends on the cluster (greene or rusty), so
# we have two different params, one for each, and the cluster config grabs
# the right one. For now, greene doesn't require setting partition.
if cluster not in ['greene', 'rusty']:
raise Exception(f"Don't know how to handle cluster {cluster}")
if int(wildcards.gpu) == 0:
if cluster == 'rusty':
return 'ccn'
elif cluster == 'greene':
return None
else:
if cluster == 'rusty':
return 'gpu'
elif cluster == 'greene':
return None
def get_constraint(wildcards, cluster):
if int(wildcards.gpu) > 0 and cluster == 'rusty':
return 'v100-32gb'
else:
return ''
def get_cpu_num(wildcards):
if int(wildcards.gpu) > 0:
# then we're using the GPU and so don't really need CPUs
cpus = 1
else:
# these are all based on estimates from rusty (which automatically
# gives each job 28 nodes), and checking seff to see CPU usage
try:
if float(wildcards.scaling) > .06:
cpus = 21
elif float(wildcards.scaling) > .03:
cpus = 26
else:
cpus = 28
except AttributeError:
# then we don't have a scaling attribute
cpus = 10
return cpus
def get_init_image(wildcards):
if wildcards.init_type in ['white', 'gray', 'pink', 'blue']:
return []
else:
try:
# then this is just a noise level, and there is no input required
float(wildcards.init_type)
return []
except ValueError:
return utils.get_ref_image_full_path(wildcards.init_type)
rule create_metamers:
input:
ref_image = lambda wildcards: utils.get_ref_image_full_path(wildcards.image_name),
windows = get_windows,
norm_dict = get_norm_dict,
init_image = get_init_image,
output:
METAMER_TEMPLATE_PATH.replace('_metamer.png', '.pt'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'summary.csv'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'history.csv'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'history.png'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'synthesis.mp4'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'synthesis.png'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'window_check.svg'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'rep.png'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'windowed.png'),
METAMER_TEMPLATE_PATH.replace('metamer.png', 'metamer-16.png'),
METAMER_TEMPLATE_PATH.replace('.png', '.npy'),
report(METAMER_TEMPLATE_PATH),
log:
METAMER_LOG_PATH,
benchmark:
METAMER_LOG_PATH.replace('.log', '_benchmark.txt'),
resources:
gpu = lambda wildcards: int(wildcards.gpu),
cpus_per_task = get_cpu_num,
mem = get_mem_estimate,
# this seems to be the best, anymore doesn't help and will eventually hurt
num_threads = 9,
params:
rusty_mem = lambda wildcards: get_mem_estimate(wildcards, 'rusty'),
cache_dir = lambda wildcards: op.join(config['DATA_DIR'], 'windows_cache'),
# if we can use a GPU, synthesis doesn't take very long. If we can't,
# it takes forever (7 days is probably not enough, but it's the most I
# can request on the cluster -- will then need to manually ask for more
# time).
time = lambda wildcards: {1: '12:00:00', 0: '7-00:00:00'}[int(wildcards.gpu)],
rusty_partition = lambda wildcards: get_partition(wildcards, 'rusty'),
rusty_constraint = lambda wildcards: get_constraint(wildcards, 'rusty'),
run:
import foveated_metamers as fov
import contextlib
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
# bool('False') == True, so we do this to avoid that
# situation
if wildcards.clamp_each_iter == 'True':
clamp_each_iter = True
elif wildcards.clamp_each_iter == 'False':
clamp_each_iter = False
if wildcards.coarse_to_fine == 'False':
coarse_to_fine = False
else:
coarse_to_fine = wildcards.coarse_to_fine
if wildcards.init_type not in ['white', 'blue', 'pink', 'gray']:
init_type = fov.utils.get_ref_image_full_path(wildcards.init_type)
else:
init_type = wildcards.init_type
if resources.gpu == 1:
get_gid = True
elif resources.gpu == 0:
get_gid = False
else:
raise Exception("Multiple gpus are not supported!")
if wildcards.save_all:
save_all = True
else:
save_all = False
with fov.utils.get_gpu_id(get_gid, on_cluster=ON_CLUSTER) as gpu_id:
fov.create_metamers.main(wildcards.model_name, float(wildcards.scaling),
input.ref_image, int(wildcards.seed), float(wildcards.min_ecc),
float(wildcards.max_ecc), float(wildcards.learning_rate),
int(wildcards.max_iter), float(wildcards.loss_thresh),
int(wildcards.loss_change_iter), output[0],
init_type, gpu_id, params.cache_dir, input.norm_dict,
wildcards.optimizer, float(wildcards.fract_removed),
float(wildcards.loss_fract),
float(wildcards.loss_change_thresh), coarse_to_fine,
wildcards.clamp, clamp_each_iter, wildcards.loss,
save_all=save_all, num_threads=resources.num_threads)
rule continue_metamers:
input:
ref_image = lambda wildcards: utils.get_ref_image_full_path(wildcards.image_name),
norm_dict = get_norm_dict,
continue_path = lambda wildcards: utils.find_attempts(dict(wildcards)).replace('_metamer.png', '.pt'),
init_image = get_init_image,
output:
CONTINUE_TEMPLATE_PATH.replace('_metamer.png', '.pt'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'summary.csv'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'history.csv'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'history.png'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'synthesis.mp4'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'synthesis.png'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'window_check.svg'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'rep.png'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'windowed.png'),
CONTINUE_TEMPLATE_PATH.replace('metamer.png', 'metamer-16.png'),
CONTINUE_TEMPLATE_PATH.replace('.png', '.npy'),
report(CONTINUE_TEMPLATE_PATH),
log:
CONTINUE_LOG_PATH,
benchmark:
CONTINUE_LOG_PATH.replace('.log', '_benchmark.txt'),
resources:
gpu = lambda wildcards: int(wildcards.gpu),
mem = get_mem_estimate,
cpus_per_task = get_cpu_num,
# this seems to be the best, anymore doesn't help and will eventually hurt
num_threads = 12,
params:
cache_dir = lambda wildcards: op.join(config['DATA_DIR'], 'windows_cache'),
time = lambda wildcards: {'V1': '12:00:00', 'RGC': '7-00:00:00'}[wildcards.model_name.split('_')[0]],
rusty_partition = lambda wildcards: get_partition(wildcards, 'rusty'),
rusty_constraint = lambda wildcards: get_constraint(wildcards, 'rusty'),
run:
import foveated_metamers as fov
import contextlib
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
# bool('False') == True, so we do this to avoid that
# situation
if wildcards.clamp_each_iter == 'True':
clamp_each_iter = True
elif wildcards.clamp_each_iter == 'False':
clamp_each_iter = False
if wildcards.coarse_to_fine == 'False':
coarse_to_fine = False
else:
coarse_to_fine = wildcards.coarse_to_fine
if wildcards.init_type not in ['white', 'blue', 'pink', 'gray']:
init_type = fov.utils.get_ref_image_full_path(wildcards.init_type)
else:
init_type = wildcards.init_type
if resources.gpu == 1:
get_gid = True
elif resources.gpu == 0:
get_gid = False
else:
raise Exception("Multiple gpus are not supported!")
with fov.utils.get_gpu_id(get_gid, on_cluster=ON_CLUSTER) as gpu_id:
# this is the same as the original call in the
# create_metamers rule, except we replace max_iter with
# extra_iter, set learning_rate to None, and add the
# input continue_path at the end
fov.create_metamers.main(wildcards.model_name, float(wildcards.scaling),
input.ref_image, int(wildcards.seed), float(wildcards.min_ecc),
float(wildcards.max_ecc), None,
int(wildcards.extra_iter), float(wildcards.loss_thresh),
int(wildcards.loss_change_iter), output[0],
init_type, gpu_id, params.cache_dir, input.norm_dict,
wildcards.optimizer, float(wildcards.fract_removed),
float(wildcards.loss_fract),
float(wildcards.loss_change_thresh), coarse_to_fine,
wildcards.clamp, clamp_each_iter, wildcards.loss,
input.continue_path, num_threads=resources.num_threads)
rule gamma_correct_metamer:
input:
lambda wildcards: [m.replace('metamer.png', 'metamer.npy') for m in
utils.generate_metamer_paths(**wildcards)]
output:
report(METAMER_TEMPLATE_PATH.replace('metamer.png', 'metamer_gamma-corrected.png'))
log:
METAMER_LOG_PATH.replace('.log', '_gamma-corrected.log')
benchmark:
METAMER_LOG_PATH.replace('.log', '_gamma-corrected_benchmark.txt')
run:
import foveated_metamers as fov
import contextlib
import numpy as np
import shutil
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
if output[0].endswith('metamer_gamma-corrected.png'):
if ('degamma' in wildcards.image_name or
any([i in wildcards.image_name for i in LINEAR_IMAGES])):
print(f"Saving gamma-corrected image {output[0]} as np.uint8")
im = np.load(input[0])
im = im ** (1/2.2)
im = fov.utils.convert_im_to_int(im, np.uint8)
imageio.imwrite(output[0], im)
else:
print("Image already gamma-corrected, copying to {output[0]}")
shutil.copy(output[0].replace('_gamma-corrected', ''), output[0])
# for subject to learn task structure: comparing noise and reference images
rule collect_training_noise:
input:
# this duplication is *on purpose*. it's the easiest way of making sure
# each of them show up twice in our stimuli array and description
# dataframe
op.join(config['DATA_DIR'], 'ref_images', 'uniform-noise_size-2048,2600.png'),
op.join(config['DATA_DIR'], 'ref_images', 'pink-noise_size-2048,2600.png'),
op.join(config['DATA_DIR'], 'ref_images', 'uniform-noise_size-2048,2600.png'),
op.join(config['DATA_DIR'], 'ref_images', 'pink-noise_size-2048,2600.png'),
[utils.get_ref_image_full_path(i) for i in IMAGES[:2]],
output:
op.join(config["DATA_DIR"], 'stimuli', 'training_noise', 'stimuli_comp-{comp}.npy'),
report(op.join(config["DATA_DIR"], 'stimuli', 'training_noise', 'stimuli_description_comp-{comp}.csv')),
log:
op.join(config["DATA_DIR"], 'logs', 'stimuli', 'training_noise', 'stimuli_comp-{comp}.log'),
benchmark:
op.join(config["DATA_DIR"], 'logs', 'stimuli', 'training_noise', 'stimuli_comp-{comp}_benchmark.txt'),
run:
import foveated_metamers as fov
import contextlib
import pandas as pd
with open(log[0], 'w', buffering=1) as log_file:
with contextlib.redirect_stdout(log_file), contextlib.redirect_stderr(log_file):
fov.stimuli.collect_images(input[:6], output[0])
df = []
for i, p in enumerate(input):