clfft 0.3.2

Bindings for clFFT, a FFT library for OpenCL.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
/* ************************************************************************
 * Copyright 2013 Advanced Micro Devices, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ************************************************************************/


#pragma once
#if !defined( CLFFT_CLTRANSFORM_H )
#define CLFFT_CLTRANSFORM_H


#include <iostream>
#include <vector>
#include "clFFT.h"
#include "../library/private.h"
#include "../client/openCL.misc.h"
#include "buffer.h"
#include "test_constants.h"

//	Custom deleter functions for our unique_ptr smart pointer class
struct clMem_deleter
{
	template <class T> void operator()(T* clMemObj)
	{
		if( clMemObj != NULL )
			OPENCL_V_THROW( ::clReleaseMemObject( clMemObj ), "Error: In clReleaseMemObject\n" );
	};
};

struct plan_handle_deleter
{
	template <class T> void operator()(T* handle)
	{
		if( *handle )
		{
			clfftDestroyPlan( handle );
		}
		clfftTeardown( ); // when multi-GPU tests are written, this will need to occur in the gtest cleanup
	};
};

struct clEvent_deleter
{
	template <class T> void operator()(T* clEventObj)
	{
		if( clEventObj != NULL )
			OPENCL_V_THROW( clReleaseEvent( clEventObj ), "Error: In clReleaseEvent\n" );
	};
};

struct clCommQueue_deleter
{
	template <class T> void operator()(T* clQueueObj)
	{
		if( clQueueObj != NULL )
			OPENCL_V_THROW( clReleaseCommandQueue( clQueueObj ), "Error: In clReleaseCommandQueue\n" );
	};
};

struct clContext_deleter
{
	template <class T> void operator()(T* clContextObj)
	{
		if( clContextObj != NULL )
			OPENCL_V_THROW( clReleaseContext( clContextObj ), "Error: In clReleaseContext\n" );
	};
};

template <class T>
class Precision_Setter
{
public:
    Precision_Setter(clfftPlanHandle plan_handle)
    {
        throw std::runtime_error("Precision_Setter: this code path should never be executed");
    }

private:
    Precision_Setter(){}
};

template<>
class Precision_Setter<float>
{
public:
    Precision_Setter(clfftPlanHandle plan_handle)
    {
	    EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanPrecision( plan_handle, CLFFT_SINGLE ));
    }

private:
    Precision_Setter(){}
};

template<>
class Precision_Setter<double>
{
public:
    Precision_Setter(clfftPlanHandle plan_handle)
    {
		clfftStatus ret = clfftSetPlanPrecision( plan_handle, CLFFT_DOUBLE );

		//	If device does not support double precision, skip this test, don't fail it
		if( ret == CLFFT_DEVICE_NO_DOUBLE )
			throw std::runtime_error("CLFFT_DEVICE_NO_DOUBLE");

		EXPECT_EQ( CLFFT_SUCCESS, ret );
    }

private:
    Precision_Setter(){}
};

 /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
 /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
template <class T, class cl_T>
class clfft {
private:
	clfftLayout _input_layout, _output_layout;
	clfftResultLocation _placeness;

	buffer<T> input;
	buffer<T> output;
	
	size_t number_of_data_points;
	T _forward_scale, _backward_scale;
	cl_uint commandQueueFlags;
	bool init_failure;
	bool dataset_too_large;

	cl_device_type deviceType;
	std::unique_ptr< clfftPlanHandle, plan_handle_deleter > plan_handle;

	clfftDirection _transformation_direction;
	clfftDim dimension;

	std::vector<size_t> lengths;

	static const bool printInfo = false;

	//	OpenCL resources that need to be carefully managed
	std::unique_ptr< _cl_context, clContext_deleter > context;
	std::unique_ptr< _cl_command_queue, clCommQueue_deleter > queue;
	std::vector< std::unique_ptr< _cl_mem, clMem_deleter > > cl_mem_input;
	std::vector< std::unique_ptr< _cl_mem, clMem_deleter > > cl_mem_output;
	std::vector< cl_device_id >	device_id;
public:
	/*****************************************************/
	clfft(  const clfftDim dimensions_in, const size_t* lengths_in,
			const size_t* input_strides_in, const size_t* output_strides_in,
			const size_t batch_size_in,
			const size_t input_distance_in, const size_t output_distance_in,
			const clfftLayout input_layout_in, const clfftLayout output_layout_in,
			const clfftResultLocation placeness_in )
		try
		: _input_layout( input_layout_in )
		, _output_layout( output_layout_in )
		, _placeness( placeness_in )
		, input( 	static_cast<size_t>(dimensions_in),
					lengths_in,
					input_strides_in,
					batch_size_in,
					input_distance_in,
					cl_layout_to_buffer_layout( _input_layout ),
					_placeness
				)
		, output(	static_cast<size_t>(dimensions_in),
					lengths_in,
					output_strides_in,
					batch_size_in,
					output_distance_in,
					cl_layout_to_buffer_layout( _output_layout ),
					_placeness
				)
		, number_of_data_points( input.number_of_data_points())
		, _forward_scale( 1.0f )
		, _backward_scale( 1.0f/T(number_of_data_points) )
		, commandQueueFlags( 0 )
		, init_failure( false )
		, dataset_too_large( false )
		, deviceType( 0 )
		, plan_handle( new clfftPlanHandle )
		, _transformation_direction( ENDDIRECTION )
		, dimension( dimensions_in )

	{
		if( _placeness == CLFFT_INPLACE )
		{
			if( ( is_real( _input_layout ) && is_planar( _output_layout ) ) ||
				( is_planar( _input_layout ) && is_real( _output_layout ) ) )
			{
				throw std::runtime_error( "in-place transforms may not be real<->planar" );
			}
		}

		*plan_handle = 0;
		clfftSetupData setupData;
		clfftInitSetupData( &setupData );
		clfftSetup( &setupData );

		for( int i = 0; i < max_dimension; i++ )
		{
			if( i < dimension )
				lengths.push_back( lengths_in[i] );
			else
				lengths.push_back( 1 );
		}

		initialize_openCL();
		initialize_plan();
	}
	catch( const std::exception& ) {
		throw;
	}

	/*****************************************************/
	~clfft()
	{}

	/*****************************************************/
	bool is_real( const clfftLayout layout )
	{
		return layout == CLFFT_REAL;
	}

	/*****************************************************/
	bool is_planar( const clfftLayout layout )
	{
		return (layout == CLFFT_COMPLEX_PLANAR || layout == CLFFT_HERMITIAN_PLANAR);
	}

	/*****************************************************/
	bool is_interleaved( const clfftLayout layout )
	{
		return (layout == CLFFT_COMPLEX_INTERLEAVED || layout == CLFFT_HERMITIAN_INTERLEAVED);
	}

	/*****************************************************/
	bool is_complex( const clfftLayout layout )
	{
		return (layout == CLFFT_COMPLEX_INTERLEAVED || layout == CLFFT_COMPLEX_PLANAR);
	}

	/*****************************************************/
	bool is_hermitian( const clfftLayout layout )
	{
		return (layout == CLFFT_HERMITIAN_INTERLEAVED || layout == CLFFT_HERMITIAN_PLANAR);
	}

	/*****************************************************/
	void initialize_openCL() {
		try
		{
			cl_context tempContext = NULL;
			device_id = initializeCL(
				g_device_type,
				g_device_id,
				g_platform_id,
				tempContext,
				printInfo
			);
			context = std::unique_ptr< _cl_context, clContext_deleter >( tempContext );

			if( input.size_in_bytes() > cl_device_max_memory_to_allocate(0) ||
				output.size_in_bytes() > cl_device_max_memory_to_allocate(0))
			{
				throw std::runtime_error("problem too large for device");
			}

			cl_int status = 0;
			queue	= std::unique_ptr< _cl_command_queue, clCommQueue_deleter >(
					::clCreateCommandQueue( context.get( ), device_id[ 0 ], commandQueueFlags, &status ) );
			OPENCL_V_THROW( status, "Creating Command Queue ( ::clCreateCommandQueue() )" );

			// make the new buffer
			const size_t bufferSizeBytes = input.size_in_bytes( );

			for( cl_int i = 0; i < CLFFT_COMPLEX_INTERLEAVED; ++i )
			{
				cl_int status = 0;
				std::unique_ptr< _cl_mem, clMem_deleter > inBuff(
						::clCreateBuffer( context.get( ), CL_MEM_READ_WRITE, bufferSizeBytes, NULL, &status) );
				OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

				cl_mem_input.push_back( std::move( inBuff ) );

				std::unique_ptr< _cl_mem, clMem_deleter > outBuff(
						::clCreateBuffer( context.get( ), CL_MEM_READ_WRITE, bufferSizeBytes, NULL, &status) );
				OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

				cl_mem_output.push_back( std::move( outBuff ) );
			}
		}
		catch( const std::exception& )
		{
			throw;
		}
	}

	/*****************************************************/
	void initialize_plan()
	{
		EXPECT_EQ( CLFFT_SUCCESS, clfftCreateDefaultPlan( plan_handle.get(), context.get( ), dimension, &lengths[0] ) );
		set_layouts( _input_layout, _output_layout );
		placeness( _placeness );
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanInStride( *plan_handle, dimension, input.strides()));
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanOutStride( *plan_handle, dimension, output.strides()));
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanBatchSize( *plan_handle, input.batch_size()));
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanDistance( *plan_handle, input.distance(), output.distance()));
		Precision_Setter<T> setter(*plan_handle);
	}

	/*****************************************************/
	std::string input_strides_plaintext()
	{
		size_t strides[3];
		clfftGetPlanInStride( *plan_handle, dimension, &strides[0] );

		std::ostringstream my_strides_stream;

		for( int i = 0; i < dimension; i++ )
			my_strides_stream << strides[i] << " ";

		std::string my_strides( my_strides_stream.str() );
		my_strides.erase( my_strides.end() - 1 ); // chomp off trailing space

		return my_strides;
	}

	/*****************************************************/
	std::string output_strides_plaintext()
	{
		size_t strides[3];
		clfftGetPlanOutStride( *plan_handle, dimension, &strides[0] );

		std::ostringstream my_strides_stream;

		for( int i = 0; i < dimension; i++ )
			my_strides_stream << strides[i] << " ";

		std::string my_strides( my_strides_stream.str() );
		my_strides.erase( my_strides.end() - 1 ); // chomp off trailing space

		return my_strides;
	}

	/*****************************************************/
	std::string lengths_plaintext()
	{
		size_t lengths[3];
		clfftGetPlanLength( *plan_handle, dimension, &lengths[0] );

		std::ostringstream my_lengths_stream;

		for( int i = 0; i < dimension; i++ )
			my_lengths_stream << lengths[i] << " ";

		std::string my_lengths( my_lengths_stream.str() );
		my_lengths.erase( my_lengths.end() - 1 ); // chomp off trailing space

		return my_lengths;
	}

	/*****************************************************/
	std::string layout_plaintext( clfftLayout layout )
	{
		switch( layout )
		{
		case CLFFT_REAL:
			return "real";
		case CLFFT_HERMITIAN_INTERLEAVED:
			return "hermitian interleaved";
		case CLFFT_HERMITIAN_PLANAR:
			return "hermitian planar";
		case CLFFT_COMPLEX_INTERLEAVED:
			return "complex interleaved";
		case CLFFT_COMPLEX_PLANAR:
			return "complex planar";
		default:
			throw std::runtime_error( "invalid layout in layout_plaintext()" );
		}
	}

	/*****************************************************/
	void refresh_plan()
	{
		clfftDestroyPlan(plan_handle.get());
		initialize_plan();
	}

	/*****************************************************/
	layout::buffer_layout_t cl_layout_to_buffer_layout( clfftLayout cl_layout )
	{
		if( cl_layout == CLFFT_REAL )
			return layout::real;
		else if( cl_layout == CLFFT_HERMITIAN_PLANAR )
			return layout::hermitian_planar;
		else if( cl_layout == CLFFT_COMPLEX_PLANAR )
			return layout::complex_planar;
		else if( cl_layout == CLFFT_HERMITIAN_INTERLEAVED )
			return layout::hermitian_interleaved;
		else if( cl_layout == CLFFT_COMPLEX_INTERLEAVED )
			return layout::complex_interleaved;
		else
			throw std::runtime_error( "invalid cl_layout" );
	}

	/*****************************************************/
	void verbose_output()
	{
		if(verbose)
		{
			std::cout << "transform parameters as seen by clfft:" << std::endl;

			clfftDim dim;
			cl_uint dimensions;
			clfftGetPlanDim( *plan_handle, &dim, &dimensions );

			std::cout << dimensions << " dimension(s): " << lengths_plaintext() << std::endl;

			size_t batch;
			clfftGetPlanBatchSize( *plan_handle, &batch );
			std::cout << "batch: " << batch << std::endl;

			clfftPrecision precision;
			clfftGetPlanPrecision( *plan_handle, &precision );
			if( precision == CLFFT_SINGLE ) std::cout << "single precision" << std::endl;
			else if( precision == CLFFT_DOUBLE ) std::cout << "double precision" << std::endl;
			else throw std::runtime_error( "can't figure out the precision in verbose_output()" );

			if( placeness() == CLFFT_INPLACE ) std::cout << "in-place" << std::endl;
			else std::cout << "out-of-place" << std::endl;

			get_layouts();
			std::cout << layout_plaintext(_input_layout) << " -> " << layout_plaintext(_output_layout) << std::endl;

			std::cout << "input stride(s): " << input_strides_plaintext() << std::endl;
			std::cout << "output stride(s): " << output_strides_plaintext() << std::endl;

			size_t input_distance, output_distance;
			clfftGetPlanDistance( *plan_handle, &input_distance, &output_distance );
			std::cout << "input distance: " << input_distance << std::endl;
			std::cout << "output distance: " << output_distance << std::endl;
		}
	}

	/*****************************************************/
	clfftResultLocation placeness() {
		clfftResultLocation res;
		EXPECT_EQ( CLFFT_SUCCESS, clfftGetResultLocation( *plan_handle, &res ) );
		return res;
	}

	/*****************************************************/
	void set_forward_transform() {
		_transformation_direction = CLFFT_FORWARD;
	}

	/*****************************************************/
	void set_backward_transform() {
		_transformation_direction = CLFFT_BACKWARD;
	}

	/*****************************************************/
	void set_transposed() {
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanTransposeResult( *plan_handle, CLFFT_TRANSPOSED ) );
	}

	/*****************************************************/
	void set_layouts( clfftLayout new_input_layout, clfftLayout new_output_layout )
	{
		cl_mem_input.clear( );
		cl_mem_output.clear( );

		// make the new input buffer
		const size_t input_buffer_size_in_bytes = input.size_in_bytes();

		size_t number_of_input_buffers;

		if( is_planar( new_input_layout ) )
			number_of_input_buffers = 2;
		else if( is_real( new_input_layout ) || is_interleaved( new_input_layout ) )
			number_of_input_buffers = 1;
		else
			throw std::runtime_error( "we shouldn't make it here [set_layouts(), input]" );

		for( size_t i = 0; i < number_of_input_buffers; ++i )
		{
			cl_int status = 0;
			std::unique_ptr< _cl_mem, clMem_deleter > buff(
				::clCreateBuffer( context.get( ), CL_MEM_READ_WRITE, input_buffer_size_in_bytes, NULL, &status) );
			OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

			cl_mem_input.push_back( std::move( buff ) );
		}

		// make the new output buffer
		const size_t output_buffer_size_in_bytes = output.size_in_bytes();

		size_t number_of_output_buffers;

		if( is_planar( new_output_layout ) )
			number_of_output_buffers = 2;
		else if( is_real( new_output_layout ) || is_interleaved( new_output_layout ) )
			number_of_output_buffers = 1;
		else
			throw std::runtime_error( "we shouldn't make it here [set_layouts(), input]" );

		for( size_t i = 0; i < number_of_output_buffers; ++i )
		{
			cl_int status = 0;
			std::unique_ptr< _cl_mem, clMem_deleter > buff(
				::clCreateBuffer( context.get( ), CL_MEM_READ_WRITE, output_buffer_size_in_bytes, NULL, &status) );
			OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

			cl_mem_output.push_back( std::move( buff ) );
		}

		EXPECT_EQ( CLFFT_SUCCESS, clfftSetLayout( *plan_handle, new_input_layout, new_output_layout ) );
		get_layouts();
	}

	/*****************************************************/
	// swap_layouts should only be used with in-place real-to-complex or complex-to-real transforms
	void swap_layouts()
	{
		get_layouts();
		clfftLayout new_input_layout = _output_layout;
		clfftLayout new_output_layout = _input_layout;

		EXPECT_EQ( CLFFT_SUCCESS, clfftSetLayout( *plan_handle, new_input_layout, new_output_layout ) );
		get_layouts();

		refresh_plan();
	}

	/*****************************************************/
	clfftLayout input_layout() {
		get_layouts();
		return _input_layout;
	}

	/*****************************************************/
	clfftLayout output_layout() {
		get_layouts();
		return _output_layout;
	}

	/*****************************************************/
	void forward_scale( T in ) {
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanScale( *plan_handle, CLFFT_FORWARD, static_cast<float>( in ) ) );
		_forward_scale = forward_scale();
	}

	/*****************************************************/
	void backward_scale( T in ) {
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetPlanScale( *plan_handle, CLFFT_BACKWARD, static_cast<float>( in ) ) );
		_backward_scale = backward_scale();
	}

	/*****************************************************/
	T forward_scale() {
		cl_T scale;
		EXPECT_EQ( CLFFT_SUCCESS, clfftGetPlanScale( *plan_handle, CLFFT_FORWARD, reinterpret_cast<cl_float*>(&scale) ));
		return scale;
	}

	/*****************************************************/
	T backward_scale() {
		cl_T scale;
		EXPECT_EQ( CLFFT_SUCCESS, clfftGetPlanScale( *plan_handle, CLFFT_BACKWARD, reinterpret_cast<cl_float*>(&scale) ));
		return scale;
	}

	/*****************************************************/
	void set_input_to_value( T real )
	{
		input.set_all_to_value( real );
	}

	/*****************************************************/
	void set_input_to_value( T real, T imag )
	{
		input.set_all_to_value( real, imag );
	}

	/*****************************************************/
	void set_input_to_sawtooth(T max) {
		input.set_all_to_sawtooth(max);
	}

	/*****************************************************/
	void set_input_to_impulse() {
		input.set_all_to_impulse();
	}

	/*****************************************************/
	// yes, the "super duper global seed" is horrible
	// alas, i'll have TODO it better later
	void set_input_to_random()
	{
		input.set_all_to_random_data( 10, super_duper_global_seed );
	}

	/*****************************************************/
	void set_input_to_buffer( buffer<T> other_buffer ) {
		input = other_buffer;
	}

	/*****************************************************/
	void set_input_precallback(unsigned int localMemSize = 0) {
		cl_int status = 0;
		clfftPrecision precision;
		clfftGetPlanPrecision( *plan_handle, &precision );

		const char* precallbackstr;
		
		if (localMemSize > 0)
		{
			//Test for LDS in precallback function
			precallbackstr = STRINGIFY(PRE_MULVAL_LDS);
		}
		else
		{
			if (input.is_interleaved() )
			{
				precallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(PRE_MULVAL) : STRINGIFY(PRE_MULVAL_DP);
			}
			else if (input.is_planar())
			{
				precallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(PRE_MULVAL_PLANAR) : STRINGIFY(PRE_MULVAL_PLANAR_DP);
			}
			else if (input.is_real())
			{
				precallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(PRE_MULVAL_REAL) : STRINGIFY(PRE_MULVAL_REAL_DP);
			}
		}

		//precallback user data
		buffer<T> userdata( 	static_cast<size_t>(dimension),
					input.lengths(),
					input.strides(),
					input.batch_size(),
					input.distance(),
					layout::real,
					_placeness
					);

		userdata.set_all_to_random_data(lengths[0], 10);
		
		// make the new buffer
		const size_t bufferSizeBytes = userdata.size_in_bytes( );

		cl_mem userdataBuff = clCreateBuffer( context.get( ), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, bufferSizeBytes, userdata.real_ptr(), &status);
		OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

		//Register the callback
		OPENCL_V_THROW (clfftSetPlanCallback(*plan_handle, "mulval_pre", precallbackstr, localMemSize, PRECALLBACK, &userdataBuff, 1), "clFFTSetPlanCallback failed");
	}

		/*****************************************************/
	void set_input_precallback_userdatatype() {
		cl_int status = 0;

		const char* precallbackstr = STRINGIFY(PRE_MULVAL_UDT);

		size_t totalPts = input.total_number_of_points_including_data_and_intervening();

		buffer<T> temp( 	static_cast<size_t>(dimension),
					input.lengths(),
					input.strides(),
					input.batch_size(),
					input.distance(),
					layout::real,
					_placeness
					);

		temp.set_all_to_random_data(lengths[0], 10);

		std::vector<USER_DATA> userdata(totalPts);
		size_t the_index;
		for( size_t batch = 0; batch < input.batch_size(); batch++) 
			for( size_t z = 0; z < input.length(dimz); z++) 
				for( size_t y = 0; y < input.length(dimy); y++) 
					for( size_t x = 0; x < input.length(dimx); x++) 
					{
						the_index = ( input.stride(dimx) * x + input.stride(dimy) * y + input.stride(dimz) * z + input.distance() * batch );

						userdata[the_index].scalar1 = (float)temp.real(x, y, z, batch);
						userdata[the_index].scalar2 = 1;
					}

		cl_mem userdataBuff = clCreateBuffer(context.get( ), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(USER_DATA) * totalPts, (void*)&userdata[0], &status);
		OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

		//Register the callback
		OPENCL_V_THROW (clfftSetPlanCallback(*plan_handle, "mulval_pre", precallbackstr, 0, PRECALLBACK, &userdataBuff, 1), "clFFTSetPlanCallback failed");
	}

		/*****************************************************/
	void set_output_postcallback(unsigned int localMemSize = 0) {
		cl_int status = 0;
		clfftPrecision precision;
		clfftGetPlanPrecision( *plan_handle, &precision );

		const char* postcallbackstr;
		
		if (localMemSize > 0)
		{
			//Test for LDS in postcallback function
			postcallbackstr = STRINGIFY(POST_MULVAL_LDS);
		}
		else
		{
			if (output.is_interleaved() )
			{
				postcallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(POST_MULVAL) : STRINGIFY(POST_MULVAL_DP);
			}
			else if (output.is_planar())
			{
				postcallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(POST_MULVAL_PLANAR) : STRINGIFY(POST_MULVAL_PLANAR_DP);
			}
			else if (output.is_real())
			{
				postcallbackstr = (precision == CLFFT_SINGLE) ? STRINGIFY(POST_MULVAL_REAL) : STRINGIFY(POST_MULVAL_REAL_DP);
			}
		}

		//post-callback user data
		buffer<T> userdata( 	static_cast<size_t>(dimension),
					output.lengths(),
					output.strides(),
					output.batch_size(),
					output.distance(),
					layout::real,
					_placeness
					);

		userdata.set_all_to_random_data(lengths[0], 10);
		
		// make the new buffer
		const size_t bufferSizeBytes = userdata.size_in_bytes( );

		cl_mem userdataBuff = clCreateBuffer( context.get( ), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, bufferSizeBytes, userdata.real_ptr(), &status);
		OPENCL_V_THROW( status, "Creating Buffer ( ::clCreateBuffer() )" );

		//Register the post-callback
		OPENCL_V_THROW (clfftSetPlanCallback(*plan_handle, "mulval_post", postcallbackstr, localMemSize, POSTCALLBACK, &userdataBuff, 1), "clFFTSetPlanCallback failed");
	}

	/*****************************************************/
	bool device_list_has_devices() {
		return !device_id.empty();
	}

	/*****************************************************/
	// returns true if the memory required for input + output (if applicable) + intermediate (if applicable) buffers
	// is too large compared with the OpenCL device's memory size
	bool total_memory_footprint_is_too_large_for_device() {
		throw_if_device_list_is_empty();

		// In order to call clfftEnqueueTransform, we need to pass naked pointers
		cl_command_queue tempQueue = queue.get( );
		size_t buffer_size = 0;

		EXPECT_EQ( CLFFT_SUCCESS, clfftBakePlan(*plan_handle, 1, &tempQueue, NULL, NULL ));
		EXPECT_EQ( CLFFT_SUCCESS, clfftGetTmpBufSize(*plan_handle, &buffer_size ));

		cl_ulong total_memory_size = input.size_in_bytes() + buffer_size;

		// we are only going to include the result space if the transform is out of place
		if( placeness() == CLFFT_OUTOFPLACE )
		{
			total_memory_size += output.size_in_bytes();
		}

		cl_ulong global_memory_size = cl_device_max_global_memory(0);

		// we don't want to bog down the CPU with ginormous problem sizes
		// so we chop the global memory way down to keep things manageable
		if( g_device_type == CL_DEVICE_TYPE_CPU )
		{
			global_memory_size /= 8;
		}

		return total_memory_size > global_memory_size;
	}

	/*****************************************************/
	void throw_if_total_memory_footprint_is_too_large_for_device()
	{
		if( total_memory_footprint_is_too_large_for_device() )
		{
			throw std::runtime_error("problem too large for device");
		}
	}

	/*****************************************************/
	void throw_if_device_list_is_empty()
	{
		if( !device_list_has_devices() ) {
			throw std::runtime_error("device list is empty at transform");
		}
	}

	/*****************************************************/
	void transform(bool explicit_intermediate_buffer = use_explicit_intermediate_buffer) {
		verbose_output();

		throw_if_device_list_is_empty();

		cl_int status;

		// In order to call clfftEnqueueTransform, we need to pass naked pointers
		cl_command_queue tempQueue = queue.get( );
		std::unique_ptr< _cl_event, clEvent_deleter > tempEvent;
		std::unique_ptr< _cl_mem, clMem_deleter > intermediate_buffer;

		throw_if_total_memory_footprint_is_too_large_for_device();

		write_local_input_buffer_to_gpu();
		if( placeness() == CLFFT_OUTOFPLACE )
			write_local_output_buffer_to_gpu();

		try
		{
			size_t buffer_size = 0;
			EXPECT_EQ( CLFFT_SUCCESS, clfftBakePlan(*plan_handle, 1, &tempQueue, NULL, NULL ));
			EXPECT_EQ( CLFFT_SUCCESS, clfftGetTmpBufSize(*plan_handle, &buffer_size ));

			if( explicit_intermediate_buffer )
			{
				// the buffer size is already stashed above
				// now we want to make the intermediate buffer to pass in (if necessary)
				if (buffer_size)
				{
					// because unique_ptrs are funky, we have to create a temp_buffer
					// and then std::move it to the intermediate_buffer
					std::unique_ptr< _cl_mem, clMem_deleter > temp_buffer(
						::clCreateBuffer( context.get( ),
								  CL_MEM_READ_WRITE,
								  buffer_size,
								  NULL,
								  &status) );
					OPENCL_V_THROW( status, "Creating intermediate Buffer ( ::clCreateBuffer() )" );

					intermediate_buffer = std::move( temp_buffer );
				}
			}

			cl_mem	tempInput[2];
			cl_mem	tempOutput[2];
			for( cl_uint i = 0; i < cl_mem_input.size( ); ++i )
				tempInput[ i ] = cl_mem_input[ i ].get( );

			for( cl_uint i = 0; i < cl_mem_output.size( ); ++i )
				tempOutput[ i ] = cl_mem_output[ i ].get( );

			cl_event tevent = NULL;
			if( buffer_size )
			{
				status = clfftEnqueueTransform(*plan_handle,
								  _transformation_direction,
								  1,
								  &tempQueue,
								  0,
								  NULL,
								  &tevent,
								  &tempInput[ 0 ],
								  &tempOutput[ 0 ],
								  intermediate_buffer.get() );
			}
			else
			{
				status = clfftEnqueueTransform(*plan_handle,
								  _transformation_direction,
								  1,
								  &tempQueue,
								  0,
								  NULL,
								  &tevent,
								  &tempInput[ 0 ],
								  &tempOutput[ 0 ],
								  NULL );
			}
            clFinish(tempQueue);
			tempEvent.reset(tevent); tevent = NULL;

			if( status != CLFFT_SUCCESS )
			{
				throw std::runtime_error(prettyPrintclFFTStatus(status).c_str());
			}

			// wait for the kernel call to finish execution
			const cl_event revent = tempEvent.get();
            cl_int wait_status = clWaitForEvents(1, &revent);
			if( wait_status == CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST )
			{
				cl_int error_code;
				clGetEventInfo( revent, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &error_code, NULL );
				throw std::runtime_error(prettyPrintclFFTStatus(error_code).c_str());
			}
            else if( wait_status != CL_SUCCESS )
            {
				throw std::runtime_error(prettyPrintclFFTStatus(wait_status).c_str());
            }
		}
		catch (const std::exception& ) {
			std::cout << "Exception occurred during clfftEnqueueTransform"
					  << __FILE__ << __LINE__ << std::endl;
			throw;
		}

		if( in_place() ) {
			capture_input();
		}
		else {
			capture_output();
		}

		get_layouts();
		if( placeness() == CLFFT_INPLACE )
		{
			if( is_real( _input_layout ) && is_hermitian( _output_layout ) )
			{
				input.change_real_to_hermitian( output.strides(), output.distance() );
			}
			else if( is_hermitian( _input_layout ) && is_real( _output_layout ) )
			{
				input.change_hermitian_to_real( output.strides(), output.distance() );
			}
		}

		// there's no way to know if in-place transforms have written in bad places,
		// because depending on input and output strides, the state of the memory
		// between points is not necessarily the NaN that we set it to
		if( _placeness != CLFFT_INPLACE )
		{
			input.make_sure_padding_was_not_overwritten();
			output.make_sure_padding_was_not_overwritten();
		}
	}

	/*****************************************************/
	size_t maximum_problem_size() {
		int device_index = 0;
		//N.B. if this class ever needs to support more than one device at once
		//(i.e., multiple GPUs or CPU+GPU), device index will need to be variable
		//to choose the device of interest
		return cl_device_max_memory_to_allocate(device_index)/(sizeof(T)*2);
		//TODO *2 needs to be either *1 or *2, depending, once real numbers are implemented in clfft
	}

	/*****************************************************/
	size_t number_of_opencl_devices() {
		return device_id.size();
	}


	/*****************************************************/
	bool initialize_failed() {
		return init_failure;
	}

	/*****************************************************/
	bool dataset_is_too_large_for_device() {
		return dataset_too_large;
	}

	/*****************************************************/
	buffer<T> & input_buffer()
	{
		return input;
	}

	/*****************************************************/
	buffer<T> & output_buffer()
	{
		return output;
	}

	/*****************************************************/
	buffer<T> & result()
	{
		if( placeness() == CLFFT_INPLACE )
			return input;
		else if( placeness() == CLFFT_OUTOFPLACE )
			return output;
		else
			throw std::runtime_error( "invalid placeness" );
	}

private:
	/*****************************************************/
	void get_layouts() {
		EXPECT_EQ( CLFFT_SUCCESS, clfftGetLayout( *plan_handle, &_input_layout, &_output_layout ) );
	}

	/*****************************************************/
	// after transform() is run:
	//   if in-place transformation -- the results will be in the input buffer
	//	 otherwise -- the results will be in the output buffer
	void placeness( clfftResultLocation placeness )
	{
		EXPECT_EQ( CLFFT_SUCCESS, clfftSetResultLocation( *plan_handle, placeness ) );
	}

	/*****************************************************/
	bool in_place() {
		clfftResultLocation placeness;
		clfftGetResultLocation( *plan_handle, &placeness );
		return (placeness == CLFFT_INPLACE) ? true : false;
	}

	/*****************************************************/
	void capture_output() {
		if( is_planar( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_output[REAL].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.real_ptr(), 0, NULL, NULL), "reading output buffer - planar real ( ::clEnqueueReadBuffer() )" );
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_output[IMAG].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.imag_ptr(), 0, NULL, NULL), "reading output buffer - planar imaginary ( ::clEnqueueReadBuffer() )" );
		}
		else if( is_interleaved( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_output[0].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.interleaved_ptr(), 0, NULL, NULL), "reading output buffer - interleaved ( ::clEnqueueReadBuffer() )" );
		}
		else if( is_real( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_output[REAL].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.real_ptr(), 0, NULL, NULL), "reading output buffer - planar real ( ::clEnqueueReadBuffer() )" );
		}
		else
		{
			throw std::runtime_error( "we shouldn't make it here [capture_output()]" );
		}
	}

	/*****************************************************/
	void capture_input() {
		if( is_planar( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_input[REAL].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.real_ptr(), 0, NULL, NULL), "reading input buffer - planar real ( ::clEnqueueReadBuffer() )" );
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_input[IMAG].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.imag_ptr(), 0, NULL, NULL), "reading input buffer - planar imaginary ( ::clEnqueueReadBuffer() )" );
		}
		else if( is_interleaved ( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_input[0].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.interleaved_ptr(), 0, NULL, NULL), "reading input buffer - interleaved ( ::clEnqueueReadBuffer() )" );
		}
		else if( is_real( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueReadBuffer( queue.get( ), cl_mem_input[REAL].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.real_ptr(), 0, NULL, NULL), "reading input buffer - planar real ( ::clEnqueueReadBuffer() )" );
		}
		else
		{
			throw std::runtime_error( "we shouldn't make it here [capture_input()]" );
		}
	}

	/*****************************************************/
	void write_local_output_buffer_to_gpu() {
		if( is_planar( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_output[REAL].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.real_ptr(), 0, NULL, NULL), "writing output buffer - planar real ( ::clEnqueueWriteBuffer() )" );
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_output[IMAG].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.imag_ptr(), 0, NULL, NULL), "writing output buffer - planar imaginary ( ::clEnqueueWriteBuffer() )" );
		}
		else if( is_interleaved ( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_output[0].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.interleaved_ptr(), 0, NULL, NULL), "writing output buffer - interleaved ( ::clEnqueueWriteBuffer() )" );
		}
		else if( is_real( output_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_output[REAL].get( ), CL_TRUE, 0,
					output.size_in_bytes(), output.real_ptr(), 0, NULL, NULL), "writing output buffer - planar real ( ::clEnqueueWriteBuffer() )" );
		}
		else
		{
			throw std::runtime_error( "we shouldn't make it here [write_local_output_buffer_to_gpu()]" );
		}
	}

	/*****************************************************/
	void write_local_input_buffer_to_gpu() {
		if( is_planar( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_input[REAL].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.real_ptr(), 0, NULL, NULL), "writing input buffer - planar real ( ::clEnqueueWriteBuffer() )" );
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_input[IMAG].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.imag_ptr(), 0, NULL, NULL), "writing input buffer - planar imaginary ( ::clEnqueueWriteBuffer() )" );
		}
		else if( is_interleaved( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_input[0].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.interleaved_ptr(), 0, NULL, NULL), "writing input buffer - interleaved ( ::clEnqueueWriteBuffer() )" );
		}
		else if( is_real( input_layout() ) ) {
			OPENCL_V_THROW( clEnqueueWriteBuffer( queue.get( ), cl_mem_input[REAL].get( ), CL_TRUE, 0,
					input.size_in_bytes(), input.real_ptr(), 0, NULL, NULL), "writing input buffer - planar real ( ::clEnqueueWriteBuffer() )" );
		}
		else
		{
			throw std::runtime_error( "we shouldn't make it here [write_local_input_buffer_to_gpu()]" );
		}
	}


	/*****************************************************/
	cl_ulong cl_device_max_memory_to_allocate(size_t device_index) {
		if( number_of_opencl_devices() == 0 || device_index > number_of_opencl_devices() )
		{
			return 0;
		}
		else
		{
			cl_ulong device_max_to_allocate = 0;
			OPENCL_V_THROW( ::clGetDeviceInfo( device_id[device_index], CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof( cl_ulong ), &device_max_to_allocate, NULL ),
				"Getting CL_DEVICE_MAX_MEM_ALLOC_SIZE device info ( ::clGetDeviceInfo() )" );

			return device_max_to_allocate;
		}
	}


	/*****************************************************/
	cl_ulong cl_device_max_global_memory(size_t device_index) {
		if( number_of_opencl_devices() == 0 || device_index > number_of_opencl_devices() )
		{
			return 0;
		}
		else
		{
			cl_ulong global_mem_size = 0;
			OPENCL_V_THROW( ::clGetDeviceInfo( device_id[device_index], CL_DEVICE_GLOBAL_MEM_SIZE, sizeof( cl_ulong ), &global_mem_size, NULL ),
				"Getting CL_DEVICE_GLOBAL_MEM_SIZE device info ( ::clGetDeviceInfo() )" );

			return global_mem_size;
		}
	}

	#if defined(PERSISTENT_PLANS_FEATURE_HAS_BEEN_DEFEATURED_WHICH_MEANS_IT_IS_NO_LONGER_A_FEATURE)
	/*****************************************************/
	void write_plan_to_file(std::string filename)
	{
		cl_command_queue tempQueue = queue.get( );
		EXPECT_EQ( CLFFT_SUCCESS, clfftBakePlan(*plan_handle, 1, &tempQueue, NULL, NULL ));
		// we need to make sure the plan is baked before we write it out, or we won't get any juicy binaries along with it

		clfftWritePlanToDisk(*plan_handle, filename.c_str());
	}

	/*****************************************************/
	void read_plan_from_file(std::string filename)
	{
		clfftReadPlanFromDisk( *plan_handle, filename.c_str() );

		// if we've changed from the default for input and output layouts, we need to re-set the layouts to make sure buffers get set up completely
		set_layouts( input_layout(), output_layout() );
	}
	#endif
};

#endif