Skip to main content

Tools for performing efficient Kronecker product-based matrix operations

Project description

Logo

Tests Coverage Status

Overview

This library contains tools for performing efficient matrix operations with Kronecker products. The Kronecker product between two square matrices A and B is constructed as follows.

Math

If A has size (n x n), and B has size (m x m), then their kronecker product has size (mn x mn). The aim of this package is to efficiently caluclate matrix-vector multiplications in this expanded space.

Installation

pip3 install pykronecker

Usage

We create instances of a KroneckerOperator class, which can be broadly treated as if it is a square numpy array. These objects are designed to be used with the @ syntax for matrix multiplication.

Basic operators

Create a KroneckerProduct from two or more square numpy arrays.

import numpy as np
from pykronecker import KroneckerProduct

A = np.random.normal(size=(5, 5))
B = np.random.normal(size=(6, 6))
x = np.random.normal(size=5 * 6)

C = KroneckerProduct([A, B])
print(C @ x) # calculate efficiently using the @ operator

A KronekerSum can be used in much the same way. The Kronecker sum of two square matrices A and B is defined as folows.

Math

from pykronecker import KroneckerSum

D = KroneckerSum([A, B])
print(D @ x)

KroneckerDiag provides support for diagonal matrices.

from pykronecker import KroneckerDiag

E = KroneckerDiag(np.random.normal(size=5 * 6))
print(E @ x)

Deriving new operators

All three of these objects can be added or multiplied together arbitrarily to create new composite operators. In this way, they can be treated similarly to literal numpy arrays.

F = C @ D + C @ E
print(F @ x)

Other possible operations include transposing with .T, and multiplying/dividing by a scalar.

G = 2 * F.T + E / 5 
print(G @ x)

Block operators

Documentation coming soon

Other features

For operators that are products of KroneckerProducts and KroneckerDiags, we can find the inverse with .inv().

H = (C @ E).inv()
print(H @ x)

Summing down an axis or over the whole matrix is supported.

print(F.sum(0))
print(F.sum(1))
print(F.sum())

As is conversion to a literal array

print(H.to_array())

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pykronecker-0.0.2.tar.gz (12.3 kB view hashes)

Uploaded Source

Built Distribution

pykronecker-0.0.2-py3-none-any.whl (13.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page