Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 54 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ From source: `git clone --recursive https://github.com/SparseDifferentiation/Spa
import numpy as np
import sparsediffpy as sp

scope = sp.Scope() # owns the flat variable vector
x = scope.Variable(3, 1) # shapes are always 2-D: (rows, cols)
x = sp.Variable(3, 1) # shapes are always 2-D: (rows, cols)

f = sp.exp(x) + 2.0 * x # build an expression with operators and sp.* atoms
fn = sp.compile(f) # analyze sparsity once
Expand All @@ -31,24 +30,52 @@ print(fn.jacobian().toarray()) # diag(exp(x) + 2), a 3x3 csr_matrix
print(fn.hessian(np.ones(3))) # Hessian of w' f(x) for weights w
```

`forward()` has the shape of `f`, `jacobian()` has shape `(f.size, n_vars)`
and `hessian(w)` has shape `(n_vars, n_vars)`, where `n_vars` is the total
size of all variables in the scope, in declaration order. Values must have
the exact shape of what they set: `x.value` takes an array shaped like `x`,
`hessian(w)` takes `w` shaped like `f` (for vectors a 1-D array also works),
and flat vectors such as `scope.set_values(u)` must be 1-D. Flat vectors (the
rows of the Jacobian, the scope values) are column-major. Reading `x.value`
gives a read-only copy, so assign to `x.value` to change it.
A variable holds its own value: assign `x.value` to choose the point, and every
expression compiled from `x` is evaluated there. Evaluating while a variable has no
value raises an error. Reading `x.value` gives a read-only copy (`None` before it is
set), so assign to `x.value` to change it.

Shapes are always 2-D, `(rows, cols)`, and both are always given: a column is
`sp.Variable(3, 1)` and a row is `sp.Variable(1, 3)`. `forward()` has the shape of `f`, `jacobian()` has shape
`(f.size, n_vars)` and `hessian(w)` has shape `(n_vars, n_vars)`, where `n_vars` is
the total size of the variables in `f`. Values must have the exact shape of what
they set: `x.value` takes an array shaped like `x`, and `hessian(w)` takes `w`
shaped like `f` (for vectors a 1-D array also works).

**Several variables** are stacked in the order they were created, whatever the
order they appear in the expression, so rewriting an expression never moves a
column. Variables the expression does not use are left out. `fn.variables` lists
the variables in stacking order:

```python
import numpy as np
import sparsediffpy as sp

x = sp.Variable(2, 1)
Y = sp.Variable(2, 2)
fn = sp.compile(Y @ x) # fn.variables == [x, Y], fn.n_vars == 6

x.value = [1.0, 2.0]
Y.value = [[3.0, 4.0], [5.0, 6.0]]
J = fn.jacobian() # columns 0-1 belong to x, columns 2-5 to Y
u = fn.get_values() # [1. 2. 3. 5. 4. 6.]: x, then Y column by column
fn.set_values(2 * u) # set all variables from one flat vector
print(Y.value) # [[6. 8.] [10. 12.]]
```

Flat vectors (`set_values`, `get_values`, the rows of the Jacobian) are 1-D and
column-major within each variable. A variable can be used in several compiled
expressions or problems; each stacks its own variables, and setting the variable's
value moves the point of all of them.

**Parameters** are data you can change without recompiling:

```python
import numpy as np
import sparsediffpy as sp

scope = sp.Scope()
x = scope.Variable(3, 1)
A = scope.Parameter(2, 3, value=np.ones((2, 3)))
x = sp.Variable(3, 1)
A = sp.Parameter(2, 3, value=np.ones((2, 3)))
fn = sp.compile(sp.sin(A @ x))

x.value = [0.1, 0.2, 0.3]
Expand All @@ -67,10 +94,12 @@ on a result you want to keep, as for `J1` above.
`sp.Problem(objective, constraints)` exposes the callbacks NLP solvers ask for:
`objective()`, `gradient()`, `constraints()`, `jacobian()` and the Lagrangian
Hessian `hessian(obj_factor, lagrange)` = `obj_factor * H_f + sum_i lagrange_i * H_gi`.
Like `compile`, everything is evaluated at the scope's current values, so a solver
callback sets the flat point with `scope.set_values(u)` and then asks for what it
needs, in any order. Each stage runs once per point and its result is a read-only
array. As with `compile`, `jacobian()` and `hessian(...)` each reuse one
Like `compile`, everything is evaluated at the variables' current values, and
`prob.variables` lists them in stacking order. A solver callback sets the flat point
with `prob.set_values(u)` and then asks for what it needs, in any order. Each stage
runs once per point and set of parameter values, also when the same values are set
again, and its result is a
read-only array. As with `compile`, `jacobian()` and `hessian(...)` each reuse one
`csr_matrix`, so copy a result that has to survive the next evaluation. Here it
drives SciPy:

Expand All @@ -81,13 +110,12 @@ from scipy.optimize import NonlinearConstraint, minimize
import sparsediffpy as sp

# minimize sum(exp(x) - c * x) subject to ||x||^2 <= 1
scope = sp.Scope()
x = scope.Variable(4, 1)
x = sp.Variable(4, 1)
c = np.array([[1.0], [2.0], [3.0], [4.0]]) # constants are 2-D, like variables
prob = sp.Problem(sp.sum(sp.exp(x) - c * x), [sp.sum(x ** 2)])

def at(u, method, *args): # evaluate prob.method(*args) at the flat point u
scope.set_values(u)
prob.set_values(u)
return getattr(prob, method)(*args)

# SciPy keeps the matrices of earlier points, so the callbacks return copies
Expand Down Expand Up @@ -123,15 +151,17 @@ default builds. There is no `cp313t` wheel because NumPy ships none from 2.5
onwards, so that build would have to compile NumPy from source.

The extension declares that it does not need the GIL, so importing it leaves
free threading enabled. Distinct problems can be built and evaluated
concurrently from different threads: the engine keeps no mutable global state,
free threading enabled. Problems that share no variable or parameter can be
built and evaluated concurrently from different threads: the engine keeps no mutable global state,
every problem and expression owns its own buffers, and all inputs and outputs
are copied at the boundary. This assumes a default build, since
`SP_TRACK_MEMORY` adds global allocation counters that are not thread-safe.
Variables and parameters can be created from several threads at once.

A single problem or expression capsule is **not** thread-safe. Do not call into
the same problem from two threads at once, and do not share expression capsules
between problems that are evaluated concurrently. Note that `expr::refcount` is
the same problem from two threads at once, do not set a variable or parameter
while another thread evaluates a problem that uses it, and do not share expression
capsules between problems that are evaluated concurrently. Note that `expr::refcount` is
a plain `int`, so breaking this rule corrupts the heap rather than merely
interleaving calls, as it would under the GIL.

Expand Down
2 changes: 1 addition & 1 deletion sparsediffpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from sparsediffpy import _sparsediffengine # noqa: F401
from sparsediffpy._expression import ( # noqa: F401
DimensionError, Expression, Parameter, Scope, Variable, broadcast, index_flat,
DimensionError, Expression, Parameter, Variable, broadcast, index_flat,
)
from sparsediffpy._atoms import ( # noqa: F401
asinh, atan, atan2, atanh, cos, diag_vec, entr, exp, hstack, log, logistic,
Expand Down
Loading
Loading