forked from pvieito/PythonKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumpyConversion.swift
More file actions
158 lines (139 loc) · 6.08 KB
/
NumpyConversion.swift
File metadata and controls
158 lines (139 loc) · 6.08 KB
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
//===-- NumpyConversion.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the `ConvertibleFromNumpyArray` protocol for bridging
// `numpy.ndarray`.
//
//===----------------------------------------------------------------------===//
/// The `numpy` Python module.
/// Note: Global variables are lazy, so the following declaration won't produce
/// a Python import error until it is first used.
private let np = Python.import("numpy")
private let ctypes = Python.import("ctypes")
/// A type that can be initialized from a `numpy.ndarray` instance represented
/// as a `PythonObject`.
public protocol ConvertibleFromNumpyArray {
init?(numpy: PythonObject)
}
/// A type that is bitwise compatible with one or more NumPy scalar types.
public protocol NumpyScalarCompatible {
/// The NumPy scalar types that this type is bitwise compatible with. Must
/// be nonempty.
static var numpyScalarTypes: [PythonObject] { get }
/// The Python `ctypes` scalar type corresponding to this type.
static var ctype: PythonObject { get }
}
extension Bool : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.bool_, Python.bool]
public static var ctype: PythonObject { return ctypes.c_bool }
}
extension UInt8 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint8]
public static var ctype: PythonObject { return ctypes.c_uint8 }
}
extension Int8 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int8]
public static var ctype: PythonObject { return ctypes.c_int8 }
}
extension UInt16 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint16]
public static var ctype: PythonObject { return ctypes.c_uint16 }
}
extension Int16 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int16]
public static var ctype: PythonObject { return ctypes.c_int16 }
}
extension UInt32 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint32]
public static var ctype: PythonObject { return ctypes.c_uint32 }
}
extension Int32 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int32]
public static var ctype: PythonObject { return ctypes.c_int32 }
}
extension UInt64 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint64]
public static var ctype: PythonObject { return ctypes.c_uint64 }
}
extension Int64 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int64]
public static var ctype: PythonObject { return ctypes.c_int64 }
}
extension Float : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.float32]
public static var ctype: PythonObject { return ctypes.c_float }
}
extension Double : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.float64]
public static var ctype: PythonObject { return ctypes.c_double }
}
extension Array : ConvertibleFromNumpyArray
where Element : NumpyScalarCompatible {
/// Creates an `Array` with the same shape and scalars as the specified
/// `numpy.ndarray` instance.
///
/// - Parameter numpyArray: The `numpy.ndarray` instance to convert.
/// - Precondition: The `numpy` Python package must be installed.
/// - Returns: `numpyArray` converted to an `Array`. Returns `nil` if
/// `numpyArray` is not 1-D or does not have a compatible scalar `dtype`.
public init?(numpy numpyArray: PythonObject) {
// Check if input is a `numpy.ndarray` instance.
guard Python.isinstance(numpyArray, np.ndarray) == true else {
return nil
}
// Check if the dtype of the `ndarray` is compatible with the `Element`
// type.
guard Element.numpyScalarTypes.contains(numpyArray.dtype) else {
return nil
}
// Only 1-D `ndarray` instances can be converted to `Array`.
let pyShape = numpyArray.__array_interface__["shape"]
guard let shape = Array<Int>(pyShape) else { return nil }
guard shape.count == 1 else {
return nil
}
// Make sure that the array is contiguous in memory. This does a copy if
// the array is not already contiguous in memory.
let contiguousNumpyArray = np.ascontiguousarray(numpyArray)
guard let ptrVal =
UInt(contiguousNumpyArray.__array_interface__["data"].tuple2.0) else {
return nil
}
guard let ptr = UnsafePointer<Element>(bitPattern: ptrVal) else {
fatalError("numpy.ndarray data pointer was nil")
}
// This code avoids constructing and initialize from `UnsafeBufferPointer`
// because that uses the `init<S : Sequence>(_ elements: S)` initializer,
// which performs unnecessary copying.
let dummyPointer = UnsafeMutablePointer<Element>.allocate(capacity: 1)
let scalarCount = shape.reduce(1, *)
self.init(repeating: dummyPointer.move(), count: scalarCount)
dummyPointer.deallocate()
withUnsafeMutableBufferPointer { buffPtr in
buffPtr.baseAddress!.update(from: ptr, count: scalarCount)
}
}
}
public extension Array where Element : NumpyScalarCompatible {
/// Creates a 1-D `numpy.ndarray` instance with the same scalars as this
/// `Array`.
///
/// - Precondition: The `numpy` Python package must be installed.
func makeNumpyArray() -> PythonObject {
return withUnsafeBytes { bytes in
let data = ctypes.cast(Int(bitPattern: bytes.baseAddress),
ctypes.POINTER(Element.ctype))
let ndarray = np.ctypeslib.as_array(data, shape: PythonObject(tupleOf: count))
return np.copy(ndarray)
}
}
}