@@ -153,6 +153,74 @@ subroutine test_torch_tensor_add()
153
153
154
154
end subroutine test_torch_tensor_add
155
155
156
+ @test
157
+ subroutine test_torch_tensor_negative()
158
+ use FUnit
159
+ use ftorch, only: assignment(=), operator(-), ftorch_int, torch_kCPU, torch_kFloat32, &
160
+ torch_tensor, torch_tensor_delete, torch_tensor_empty, &
161
+ torch_tensor_from_array, torch_tensor_to_array
162
+ use ftorch_test_utils, only: assert_allclose
163
+ use, intrinsic :: iso_fortran_env, only: sp => real32
164
+ use, intrinsic :: iso_c_binding, only : c_associated, c_int64_t
165
+
166
+ implicit none
167
+
168
+ ! Set working precision for reals
169
+ integer, parameter :: wp = sp
170
+
171
+ type(torch_tensor) :: tensor1, tensor2
172
+ integer, parameter :: ndims = 2
173
+ integer(ftorch_int), parameter :: tensor_layout(ndims) = [1, 2]
174
+ integer(c_int64_t), parameter, dimension(ndims) :: tensor_shape = [2, 3]
175
+ integer, parameter :: dtype = torch_kFloat32
176
+ integer, parameter :: device_type = torch_kCPU
177
+ real(wp), dimension(2,3), target :: in_data
178
+ real(wp), dimension(:,:), pointer :: out_data
179
+ real(wp), dimension(2,3) :: expected
180
+ logical :: test_pass
181
+
182
+ ! Create two arbitrary input arrays
183
+ in_data(:,:) = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
184
+
185
+ ! Create tensors based off the input array
186
+ call torch_tensor_from_array(tensor1, in_data, tensor_layout, device_type)
187
+
188
+ ! Create another empty tensor and assign it to the negative of the first using the overloaded
189
+ ! negative operator
190
+ call torch_tensor_empty(tensor2, ndims, tensor_shape, dtype, device_type)
191
+ tensor2 = -tensor1
192
+
193
+ ! Check input arrays are unchanged by the negation
194
+ expected(:,:) = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
195
+ if (.not. assert_allclose(in_data, expected, test_name="test_torch_tensor_negative")) then
196
+ call clean_up()
197
+ print *, "Error :: first input array was changed during subtraction"
198
+ stop 999
199
+ end if
200
+
201
+ ! Extract Fortran array from the assigned tensor and compare the data in the tensor to the
202
+ ! negative of the input array
203
+ call torch_tensor_to_array(tensor2, out_data, shape(in_data))
204
+ expected(:,:) = -in_data
205
+ if (.not. assert_allclose(out_data, expected, test_name="test_torch_tensor_negative")) then
206
+ call clean_up()
207
+ print *, "Error :: incorrect output from overloaded subtraction operator"
208
+ stop 999
209
+ end if
210
+
211
+ call clean_up()
212
+
213
+ contains
214
+
215
+ ! Subroutine for freeing memory and nullifying pointers used in the unit test
216
+ subroutine clean_up()
217
+ nullify(out_data)
218
+ call torch_tensor_delete(tensor1)
219
+ call torch_tensor_delete(tensor2)
220
+ end subroutine clean_up
221
+
222
+ end subroutine test_torch_tensor_negative
223
+
156
224
@test
157
225
subroutine test_torch_tensor_subtract()
158
226
use FUnit
0 commit comments