Coverage for src/cvx/json/numpyencoder.py: 53%

17 statements  

« prev     ^ index     » next       coverage.py v7.10.3, created at 2025-08-17 08:01 +0000

1# Copyright 2023 Stanford University Convex Optimization Group 

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"""JSON encoder for NumPy data types. 

15 

16This module provides a custom JSON encoder that can handle NumPy data types 

17by converting them to standard Python types that can be serialized to JSON. 

18""" 

19 

20import json 

21 

22import numpy as np 

23 

24 

25class NumpyEncoder(json.JSONEncoder): 

26 """Custom encoder for numpy data types.""" 

27 

28 def default(self, obj): 

29 """Handle numpy types by converting them to Python standard types. 

30 

31 Args: 

32 obj: The object to encode 

33 

34 Returns: 

35 A JSON serializable version of the object 

36 """ 

37 # Integer types 

38 if isinstance( 

39 obj, 

40 np.int_ 

41 | np.intc 

42 | np.intp 

43 | np.int8 

44 | np.int16 

45 | np.int32 

46 | np.int64 

47 | np.uint8 

48 | np.uint16 

49 | np.uint32 

50 | np.uint64, 

51 ): 

52 return int(obj) 

53 

54 # Float types 

55 elif isinstance(obj, np.float16 | np.float32 | np.float64): 

56 return float(obj) 

57 

58 # Complex types 

59 elif isinstance(obj, np.complex64 | np.complex128): 

60 return {"real": obj.real, "imag": obj.imag} 

61 

62 # Array types 

63 elif isinstance(obj, np.ndarray): 

64 return obj.tolist() 

65 

66 # Boolean types 

67 elif isinstance(obj, np.bool_): 

68 return bool(obj) 

69 

70 # Void type 

71 elif isinstance(obj, np.void): 

72 return None 

73 

74 # Fall back to the default encoder 

75 return json.JSONEncoder.default(self, obj)