Debian Codegraph @

test/jpypetest/test_jfloat.py

raw symbols SCIP
1 # *****************************************************************************
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # See NOTICE file for details.
16 #
17 # *****************************************************************************
18 import random
19 from unittest.util import safe_repr
20
21 import _jpype
22
23 import common
24 import jpype
25 from jpype import java
26 from jpype.types import *
27 try:
28 import numpy as np
29 except ImportError:
30 pass
31
32
33 class JFloatTestCase(common.JPypeTestCase):
34 def setUp(self):
35 common.JPypeTestCase.setUp(self)
36 self.value = 1.0 + 1.0 / 65536
37 self.cls = JClass("jpype.common.Fixture")
38 self.fixture = self.cls()
39
40 def compareFloatEqual(self, x, y, msg=None):
41 if x == y:
42 return
43 if x < 0:
44 x = -x
45 if y < 0:
46 y = -y
47 a = (x + y) / 2
48 b = (x - y)
49 if b < 0:
50 b = -b
51 if b < a * 1e-7:
52 return
53 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(x),
54 safe_repr(y)))
55 raise self.failureException(msg)
56
57 @common.requireInstrumentation
58 def testJPNumberFloat_int(self):
59 jd = JFloat(1)
60 _jpype.fault("PyJPNumberFloat_int")
61 with self.assertRaisesRegex(SystemError, "fault"):
62 int(jd)
63 _jpype.fault("PyJPModule_getContext")
64 with self.assertRaisesRegex(SystemError, "fault"):
65 int(jd)
66 int(jd)
67
68 @common.requireInstrumentation
69 def testJPNumberFloat_float(self):
70 jd = JFloat(1)
71 _jpype.fault("PyJPNumberFloat_float")
72 with self.assertRaisesRegex(SystemError, "fault"):
73 float(jd)
74 _jpype.fault("PyJPModule_getContext")
75 with self.assertRaisesRegex(SystemError, "fault"):
76 float(jd)
77 float(jd)
78
79 @common.requireInstrumentation
80 def testJPNumberFloat_str(self):
81 jd = JFloat(1)
82 _jpype.fault("PyJPNumberFloat_str")
83 with self.assertRaisesRegex(SystemError, "fault"):
84 str(jd)
85 _jpype.fault("PyJPModule_getContext")
86 with self.assertRaisesRegex(SystemError, "fault"):
87 str(jd)
88 str(jd)
89
90 @common.requireInstrumentation
91 def testJPNumberFloat_repr(self):
92 jd = JFloat(1)
93 _jpype.fault("PyJPNumberFloat_repr")
94 with self.assertRaisesRegex(SystemError, "fault"):
95 repr(jd)
96 _jpype.fault("PyJPModule_getContext")
97 with self.assertRaisesRegex(SystemError, "fault"):
98 repr(jd)
99 repr(jd)
100
101 @common.requireInstrumentation
102 def testJPNumberFloat_compare(self):
103 jd = JFloat(1)
104 _jpype.fault("PyJPNumberFloat_compare")
105 with self.assertRaisesRegex(SystemError, "fault"):
106 jd == 1
107 _jpype.fault("PyJPModule_getContext")
108 with self.assertRaisesRegex(SystemError, "fault"):
109 jd == 1
110 jd == 1
111
112 @common.requireInstrumentation
113 def testJPNumberFloat_hash(self):
114 jd = JFloat(1)
115 _jpype.fault("PyJPNumberFloat_hash")
116 with self.assertRaises(SystemError):
117 hash(jd)
118 _jpype.fault("PyJPModule_getContext")
119 with self.assertRaises(SystemError):
120 hash(jd)
121 hash(jd)
122
123 @common.requireInstrumentation
124 def testFault(self):
125 _jpype.fault("JPFloatType::findJavaConversion")
126 with self.assertRaises(SystemError):
127 JFloat(1.0)
128
129 @common.requireInstrumentation
130 def testConversionFault(self):
131 _jpype.fault("JPFloatType::findJavaConversion")
132 with self.assertRaisesRegex(SystemError, "fault"):
133 JFloat._canConvertToJava(object())
134
135 @common.requireInstrumentation
136 def testArrayFault(self):
137 ja = JArray(JFloat)(5)
138 _jpype.fault("JPJavaFrame::NewFloatArray")
139 with self.assertRaisesRegex(SystemError, "fault"):
140 JArray(JFloat)(1)
141 _jpype.fault("JPJavaFrame::SetFloatArrayRegion")
142 with self.assertRaisesRegex(SystemError, "fault"):
143 ja[0] = 0
144 _jpype.fault("JPJavaFrame::GetFloatArrayRegion")
145 with self.assertRaisesRegex(SystemError, "fault"):
146 print(ja[0])
147 _jpype.fault("JPJavaFrame::GetFloatArrayElements")
148 # Special case, only BufferError is allowed from getBuffer
149 with self.assertRaises(BufferError):
150 memoryview(ja[0:3])
151 _jpype.fault("JPJavaFrame::ReleaseFloatArrayElements")
152 with self.assertRaisesRegex(SystemError, "fault"):
153 ja[0:3] = bytes([1, 2, 3])
154 _jpype.fault("JPJavaFrame::ReleaseFloatArrayElements")
155 with self.assertRaisesRegex(SystemError, "fault"):
156 jpype.JObject(ja[::2], jpype.JObject)
157 _jpype.fault("JPJavaFrame::ReleaseFloatArrayElements")
158
159 def f():
160 # Special case no fault is allowed
161 memoryview(ja[0:3])
162 f()
163 _jpype.fault("JPFloatType::setArrayRange")
164 with self.assertRaisesRegex(SystemError, "fault"):
165 ja[1:3] = [0, 0]
166
167 def testFromJIntWiden(self):
168 self.assertEqual(JFloat(JByte(123)), 123)
169 self.assertEqual(JFloat(JShort(12345)), 12345)
170 self.assertEqual(JFloat(JInt(12345678)), 12345678)
171 self.assertEqual(JFloat(JLong(12345678)), 12345678)
172
173 def testFromJFloatWiden(self):
174 self.assertEqual(JFloat(JDouble(12345678)), 12345678)
175
176 def testFromNone(self):
177 with self.assertRaises(TypeError):
178 JFloat(None)
179 self.assertEqual(JFloat._canConvertToJava(None), "none")
180
181 def testFromJFloat(self):
182 with self.useEqualityFunc(self.compareFloatEqual):
183 self.assertEqual(JFloat(JFloat(1.2345)), 1.2345)
184
185 def testFromJDouble(self):
186 with self.useEqualityFunc(self.compareFloatEqual):
187 self.assertEqual(JFloat(JDouble(1.2345)), 1.2345)
188
189 def testUnBox(self):
190 pass
191 # with self.useEqualityFunc(self.foo):
192 # self.assertEqual(JFloat(java.lang.Double(1.2345)), 1.2345)
193
194 def testFromFloat(self):
195 with self.useEqualityFunc(self.compareFloatEqual):
196 self.assertEqual(JFloat(1.2345), 1.2345)
197 self.assertEqual(JFloat._canConvertToJava(1.2345), "implicit")
198
199 def testFromLong(self):
200 self.assertEqual(JFloat(12345), 12345)
201 self.assertEqual(JFloat._canConvertToJava(12345), "implicit")
202
203 def testFromObject(self):
204 with self.assertRaises(TypeError):
205 JFloat(object())
206 with self.assertRaises(TypeError):
207 JFloat(JObject())
208 with self.assertRaises(TypeError):
209 JFloat(JString("A"))
210 self.assertEqual(JFloat._canConvertToJava(object()), "none")
211 ja = JArray(JFloat)(5)
212 with self.assertRaises(TypeError):
213 ja[1] = object()
214 jf = JClass("jpype.common.Fixture")
215 with self.assertRaises(TypeError):
216 jf.static_float_field = object()
217 with self.assertRaises(TypeError):
218 jf().float_field = object()
219
220 def testCallFloatFromNone(self):
221 with self.assertRaises(TypeError):
222 self.fixture.callFloat(None)
223 with self.assertRaises(TypeError):
224 self.fixture.static_float_field = None
225 with self.assertRaises(TypeError):
226 self.fixture.float_field = None
227
228 def checkType(self, q):
229 # Check field
230 self.fixture.float_field = q
231 self.assertEqual(self.fixture.float_field, q)
232 self.assertEqual(self.fixture.getFloat(), q)
233 # Check static field
234 self.cls.static_float_field = q
235 self.assertEqual(self.fixture.static_float_field, q)
236 self.assertEqual(self.fixture.getStaticFloat(), q)
237 self.assertEqual(self.cls.getStaticFloat(), q)
238 # Check call
239 self.assertEqual(self.fixture.callFloat(q), q)
240 self.assertEqual(self.cls.callStaticFloat(q), q)
241 # Check throw
242 with self.assertRaises(JException):
243 self.fixture.throwFloat()
244 with self.assertRaises(JException):
245 self.cls.throwStaticFloat()
246 with self.assertRaises(JException):
247 self.fixture.throwStaticFloat()
248
249 def testCheckInt(self):
250 self.checkType(1)
251
252 def testCheckFloat(self):
253 self.checkType(2.0)
254
255 def testCheckRange(self):
256 self.checkType(float(1e340))
257 self.checkType(float(-1e340))
258
259 def testCheckNaN(self):
260 import math
261 nan = float("nan")
262 self.assertTrue(math.isnan(self.fixture.callFloat(nan)))
263 self.fixture.static_float_field = nan
264 self.assertTrue(math.isnan(self.fixture.static_float_field))
265 self.fixture.float_field = nan
266 self.assertTrue(math.isnan(self.fixture.float_field))
267
268 def testCheckInf(self):
269 import math
270 inf = float("inf")
271 self.assertTrue(math.isinf(self.fixture.callFloat(inf)))
272 self.fixture.static_float_field = inf
273 self.assertTrue(math.isinf(self.fixture.static_float_field))
274 self.fixture.float_field = inf
275 self.assertTrue(math.isinf(self.fixture.float_field))
276
277 def testCheckBool(self):
278 self.checkType(True)
279 self.checkType(False)
280
281 def testCheckJBoolean(self):
282 # FIXME fails
283 # self.checkType(JBoolean(True))
284 # self.checkType(JBoolean(False))
285 pass
286
287 def testCheckJChar(self):
288 self.checkType(JChar("A"))
289
290 def testCheckJByte(self):
291 self.checkType(JByte(-128))
292 self.checkType(JByte(127))
293
294 def testCheckJShort(self):
295 self.checkType(JShort(-2**15))
296 self.checkType(JShort(2**15 - 1))
297
298 def testCheckJInt(self):
299 with self.useEqualityFunc(self.compareFloatEqual):
300 self.checkType(JInt(-2**31 + 1))
301 self.checkType(JInt(2**31 - 1))
302
303 def testCheckJLong(self):
304 with self.useEqualityFunc(self.compareFloatEqual):
305 self.checkType(JLong(-2**63 + 1))
306 self.checkType(JLong(2**63 - 1))
307
308 def testCheckJFloat(self):
309 self.checkType(JFloat(1.515313))
310
311 @common.requireNumpy
312 def testCheckNumpyInt8(self):
313 self.checkType(np.random.randint(-127, 128, dtype=np.int8))
314 self.checkType(np.random.randint(0, 255, dtype=np.uint8))
315 self.checkType(np.uint8(0))
316 self.checkType(np.uint8(255))
317 self.checkType(np.int8(-128))
318 self.checkType(np.int8(127))
319
320 @common.requireNumpy
321 def testCheckNumpyInt16(self):
322 self.checkType(np.random.randint(-2**15, 2**15 - 1, dtype=np.int16))
323 self.checkType(np.random.randint(0, 2**16 - 1, dtype=np.uint16))
324 self.checkType(np.uint16(0))
325 self.checkType(np.uint16(2**16 - 1))
326 self.checkType(np.int16(-2**15))
327 self.checkType(np.int16(2**15 - 1))
328
329 @common.requireNumpy
330 def testCheckNumpyInt32(self):
331 with self.useEqualityFunc(self.compareFloatEqual):
332 self.checkType(np.random.randint(-2**31, 2**31 - 1, dtype=np.int32))
333 self.checkType(np.random.randint(0, 2**32 - 1, dtype=np.uint32))
334 self.checkType(np.uint32(0))
335 self.checkType(np.uint32(2**32 - 1))
336 self.checkType(np.int32(-2**31))
337 self.checkType(np.int32(2**31 - 1))
338
339 @common.requireNumpy
340 def testCheckNumpyInt64(self):
341 with self.useEqualityFunc(self.compareFloatEqual):
342 self.checkType(np.random.randint(-2**63, 2**63 - 1, dtype=np.int64))
343 self.checkType(
344 np.uint64(np.random.randint(0, 2**64 - 1, dtype=np.uint64)))
345 self.checkType(np.uint64(0))
346 self.checkType(np.uint64(2**64 - 1))
347 self.checkType(np.int64(-2**63))
348 self.checkType(np.int64(2**63 - 1))
349
350 @common.requireNumpy
351 def testCheckNumpyFloat32(self):
352 self.checkType(np.float32(np.random.rand()))
353
354 @common.requireNumpy
355 def testCheckNumpyFloat64(self):
356 with self.useEqualityFunc(self.compareFloatEqual):
357 self.checkType(np.float64(np.random.rand()))
358
359 def testArrayConversionDouble(self):
360 VALUES = [float(random.random()) for i in range(100)]
361 jarr = JArray(JFloat)(VALUES)
362 self.assertElementsAlmostEqual(VALUES, jarr)
363 result = jarr[:]
364 self.assertElementsAlmostEqual(VALUES, result)
365 result = jarr[2:10]
366 self.assertEqual(len(VALUES[2:10]), len(result))
367 self.assertElementsAlmostEqual(VALUES[2:10], result)
368
369 # empty slice
370 result = jarr[-1:3]
371 expected = VALUES[-1:3]
372 self.assertElementsAlmostEqual(expected, result)
373
374 result = jarr[3:-2]
375 expected = VALUES[3:-2]
376 self.assertElementsAlmostEqual(expected, result)
377
378 @common.requireNumpy
379 def testArraySetFromNPDouble(self):
380 a = np.random.random(100).astype(np.float64)
381 jarr = JArray(JFloat)(100)
382 jarr[:] = a
383 self.assertElementsAlmostEqual(a, jarr)
384
385 @common.requireNumpy
386 def testArrayInitFromNPFloat16(self):
387 a = np.random.random(1000).astype(np.float16)
388 jarr = JArray(JFloat)(a)
389 self.assertElementsEqual(a, jarr)
390
391 @common.requireNumpy
392 def testArrayInitFromNPFloat32(self):
393 a = np.random.random(100).astype(np.float32)
394 jarr = JArray(JFloat)(a)
395 self.assertElementsAlmostEqual(a, jarr)
396
397 @common.requireNumpy
398 def testArrayInitFromNPFloat64(self):
399 a = np.random.random(100).astype(np.float64)
400 jarr = JArray(JFloat)(a)
401 self.assertElementsAlmostEqual(a, jarr)
402
403 def testArraySetRange(self):
404 ja = JArray(JFloat)(3)
405 ja[0:1] = [123]
406 self.assertEqual(ja[0], 123)
407 ja[0:1] = [-1]
408 self.assertEqual(ja[0], -1)
409 ja[0:1] = [java.lang.Double(321)]
410 self.assertEqual(ja[0], 321)
411 with self.assertRaises(TypeError):
412 ja[0:1] = [object()]
413
414 def testArrayHash(self):
415 ja = JArray(JFloat)([1, 2, 3])
416 self.assertIsInstance(hash(ja), int)
417
418 @common.requireNumpy
419 def testArrayBufferDims(self):
420 ja = JArray(JFloat)(5)
421 a = np.zeros((5, 2))
422 with self.assertRaisesRegex(TypeError, "incorrect"):
423 ja[:] = a
424
425 def testArrayBadItem(self):
426 class q(object):
427 def __float__(self):
428 raise SystemError("nope")
429 ja = JArray(JFloat)(5)
430 a = [1, -1, q(), 3, 4]
431 with self.assertRaisesRegex(SystemError, "nope"):
432 ja[:] = a
433
434 def testArrayBadDims(self):
435 class q(bytes):
436 # Lie about our length
437 def __len__(self):
438 return 5
439 a = q([1, 2, 3])
440 ja = JArray(JFloat)(5)
441 with self.assertRaisesRegex(ValueError, "Slice"):
442 ja[:] = [1, 2, 3]
443 with self.assertRaisesRegex(ValueError, "mismatch"):
444 ja[:] = a
445
446 @common.requireNumpy
447 def testNPFloat16(self):
448 v= [0.000000e+00, 5.960464e-08, 1.788139e-07, 1.788139e-07, 4.172325e-07, 8.940697e-07, 1.847744e-06, 3.755093e-06, 7.569790e-06, 1.519918e-05, 3.045797e-05, 6.097555e-05, 6.103516e-05, 3.332520e-01, 1.000000e+00, 6.550400e+04, np.inf, -np.inf]
449 a = np.array(v, dtype=np.float16)
450 jarr = JArray(JFloat)(a)
451 for v1,v2 in zip(a, jarr):
452 self.assertEqual(v1,v2)
453 a = np.array([np.nan], dtype=np.float16)
454 jarr = JArray(JFloat)(a)
455 self.assertTrue(np.isnan(jarr[0]))
456