Skip to content

Latest commit

 

History

History
170 lines (126 loc) · 3.49 KB

numpy.org

File metadata and controls

170 lines (126 loc) · 3.49 KB

NumPy: creating and manipulating numerical data

This section was adapted from the Scipy lecture notes, which was written by Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen.

License: Creative Commons Attribution 4.0 International License (CC-by)

Adapted for py4cl by B.Dudson (2019).

The following examples assume that you have already loaded py4cl

(ql:quickload :py4cl)

and then imported python modules as lisp packages using:

(py4cl:import-module "numpy" :as "np")

Functions for creating arrays

(np:ones '(3 3)) ; => #2A((1.0 1.0 1.0)
                 ;        (1.0 1.0 1.0)
                 ;        (1.0 1.0 1.0))
(np:zeros '(2 2)) ; => #2A((0.0 0.0)
                  ; =>     (0.0 0.0))
(np:arange 10) ; => #(0 1 2 3 4 5 6 7 8 9)
(np:eye 3)     ; => #2A((1.0 0.0 0.0)
               ;        (0.0 1.0 0.0)
               ;        (0.0 0.0 1.0))
(np:diag #(1 2 3 4))  ; => #2A((1 0 0 0)
                      ;        (0 2 0 0)
                      ;        (0 0 3 0)
                      ;        (0 0 0 4))

Indexing and slicing

For creating slices of arrays the python slice function can be imported:

(py4cl:import-function "slice")

Using this, arrays can be sliced:

(py4cl:chain (np.arange 10) ([] (slice 2 9 3))) ; (slice start end step)
 ; => #(2 5 8)

Note that the last index is not included:

(py4cl:chain (np.arange 10) ([] (slice nil 4)))  ; => #(0 1 2 3)

All three slice components are not required: by default, start is 0, end is the last and step is 1

Reverse an array

(py4cl:chain #(1 2 3 4) ([] (slice nil nil -1)))
; => #(4 3 2 1)

Elementwise operations

Important: Array multiplication is not matrix multiplication:

(let ((c (np:ones '(3 3))))
  (py4cl:python-eval c "*" c))

  ; => #2A((1.0 1.0 1.0)
  ;        (1.0 1.0 1.0)
  ;        (1.0 1.0 1.0))

Matrix multiplication:

(let ((c (np:ones '(3 3))))
  (py4cl:chain c (dot c)))
  ; => #2A((3.0 3.0 3.0)
  ;        (3.0 3.0 3.0)
  ;        (3.0 3.0 3.0))

Basic reductions

Computing sums

(np:sum #(1 2 3 4)) ;=> 10
(py4cl:chain (np.array #(1 2 3 4)) (sum)) ; => 10

Sum by rows and by columns:

(let ((x #2A((1 1) (2 2))))
  (np:sum x :axis 0))  ; => #(3 3)
(let ((x #2A((1 1) (2 2))))
  (py4cl:chain x (sum :axis 1))) ; => #(2 4)

Slicing and then summing:

(let ((x #2A((1 1) (2 2))))
  (py4cl:chain x ([] 1 (slice 0 nil)) (sum))) ; => 4