API of the PaSam Package

The pasam package is organized into the modules ‘Lattice’, ‘Sampling’, and ‘Utilities’:

Lattice

This module defines the lattice grid elements and the associated value maps.

class pasam.lattice.Lattice(nodes)

Lattice defines the computational lattice.

A lattice is defined by a one-, two-, or three-dimensional regular grid of strictly increasing node values. The grid can then be considered as a tensor product of all nodes, as for example:

Lattice(nodes=[[0, 2, 4, 6], [-1, 0, 1]])

    +1  +-------+-------+-------+
        |       |       |       |
     0  +-------+-------+-------+
        |       |       |       |
    -1  +-------+-------+-------+
        0       2       4       6
Parameters:nodes (list of array_like) – Tensor product nodes.
nodes

Tensor product nodes.

Type:list of ndarray
indices_from_point(components)

Returns the indices for the nearest node in each direction.

Parameters:components (array_like, shape=(n,)) – Components of point.
Returns:Indices of closest node.
Return type:tuple
linear_index_from_point(components)

Returns the linear index for the nearest node in the grid.

Parameters:components (array_like, shape=(n,)) – Components of point.
Returns:Linear index of closest node.
Return type:int
linear_indices()

Returns the array of linear indices.

The array has the shape self.nnodes_dim

Returns:Linear indices.
Return type:ndarray, shape=self.nnodes_dim
ndim

The dimensionality of the lattice.

Returns:int
nnodes

The total number of nodes in the lattice.

Returns:int
nnodes_dim

The total number of nodes in the lattice.

Returns:tuple
class pasam.lattice.LatticeMap(lattice, values, dtype=None)

LatticeMap defines a value map associated to a Lattice.

A lattice map is the combination of a lattice and a value map associated to in a one-, two-, or three-dimensional regular grid of nodes: The grid can then be considered as a tensor product of all nodes, as for example:

nodes = [[0, 2, 4, 6], [-1, 0, 1]]
values = [
    0.1, 0,2, 0.3, 0.4,
    0.5, 0.6, 0.7, 0.8,
    0.9, 1.0, 1.1, 1.2,
]
LatticeMap(nodes, values)

    +1 0.9-----1.0-----1.1-----1.2
        |       |       |       |
     0 0.5-----0.6-----0.7-----0.8
        |       |       |       |
    -1 0.1-----0.2-----0.3-----0.4
        0       2       4       6

The index order is Fortran-like such that it first iterates along the lowest dimension.

Parameters:
  • lattice (Lattice or list of array_like) – Object defining the computational lattice.
  • values (array_like, shape=(n,)) – Map values associated to the lattice nodes.
  • dtype (data-type, optional) – The desired data-type for the map values. If not given, then the type will be determined as the minimum requirement by numpy.
lattice

Object defining the computational lattice.

Type:Lattice
values

Map values associated to the lattice nodes.

Type:ndarray, shape=(n,)
classmethod from_txt(file)

Produces a lattice map object from a .txt file.

The structure of a latticemap text file is reported in the function readfile_latticemap().

Parameters:file (str or pathlib.Path) – File or filename.
Returns:Lattice map from file.
Return type:LatticeMap
indices_from_point(components)

Returns the indices for the nearest node in the lattice.

Parameters:components (array_like, shape=(n,)) – Components of point.
Returns:Indices of closest node.
Return type:tuple
ndim

The dimensionality of the lattice map.

Returns:int
normalize_sum(axis=None)

Normalizes the values such that they sum up to one.

Parameters:axis (int, optional) – Specifies the axis of the values along which to compute the norm. If axis is not provided the the complete map will be normalized to sum up to one.
Returns:Lattice map object with normalized values.
Return type:LatticeMap
slice(dim: int, ind: int)

Returns a slice where position pos is fixed in dimension dim.

Parameters:
  • dim (int) – Static dimension for the slice.
  • ind (int) – Index of slicing position.
Returns:

Slice of self.

Return type:

LatticeMap

to_txt(file)

Writes a lattice map objects to a .txt file.

The structure of a latticemap text file is reported in the function readfile_latticemap().

Parameters:file (str or pathlib.Path) – File or filename.
Returns:None
pasam.lattice.readfile_latticemap(file) → pasam.lattice.LatticeMap

Reads a lattice map text file.

The structure of the lattice map file is as follows:

-----------------------------------------
|  <nnodes_dim>                         |
|  <nodes_x>                            |
|  <nodes_y>                            |
|  (<nodes_z>)                          |
|  values(x=0,...,n-1; y=0, (z=0))      |
|  values(x=0,...,n-1; y=1, (z=0))      |
|  ...                                  |
|  values(x=0,...,n-1; y=m-1, (z=0))    |
|  values(x=0,...,n-1; y=0, (z=1))      |
|  ...                                  |
|  values(x=0,...,n-1; y=0, (z=r-1))    |
-----------------------------------------

In the case of two-dimensional maps, the quantities in parentheses are omitted.

Parameters:file (str or pathlib.Path) – File or filename.
Returns:Lattice map from file.
Return type:LatticeMap
pasam.lattice.readfile_nodes_values(file)

Similar as readfile_latticemap() but directly returns the nodes and the values.

pasam.lattice.writefile_latticemap(map_, file)

Writes a lattice map text file.

The structure of the lattice map file is as follows:

-----------------------------------------
|  <nnodes_dim>                         |
|  <nodes_x>                            |
|  <nodes_y>                            |
|  (<nodes_z>)                          |
|  values(x=0,...,n-1; y=0, (z=0))      |
|  values(x=0,...,n-1; y=1, (z=0))      |
|  ...                                  |
|  values(x=0,...,n-1; y=m-1, (z=0))    |
|  values(x=0,...,n-1; y=0, (z=1))      |
|  ...                                  |
|  values(x=0,...,n-1; y=0, (z=r-1))    |
-----------------------------------------

In the case of two-dimensional maps, the quantities in parentheses are omitted.

Parameters:
  • map (LatticeMap) – Lattice map to write.
  • file (str or pathlib.Path) – File or filename.
Returns:

None

Sampling

This module defines the trajectory sampling algorithms.

class pasam.sampling.GantryDominant2D(lattice, ratio=1.0, order='random')

GantryDominant2D is a 2D gantry dominated trajectory sampler.

It is designed to sample trajectories in two-dimensional domains as e.g.:

          --------------------------------------
          |            ****        0000000000  |
          | ***      **    *       0000000000  |
          **   ******       *        000000    |
          |                  *         00      |
DIM_TABLE |      00           *                |
          |    000000          *****        **** Trajectory
          |  0000000000             ***  ***   |
          |  0000000000                **      |
          --------------------------------------
                       DIM_GANTRY

where the zeros indicate prior conditioning. The trajectories are guided by a prior probability map describing higher and lower passage frequencies.

Notes

If the ratio is too small, the trajectory can not jump to upper or lower neighbors but only straight right (or left). Consider the following setup:

            ________________________________
           |       |       |       |       |
           |       |   B   |   E   |   H   |
           |_______|_______|_______|_______|
           |       |       |       |       |
DIM_TABLE  |   A   |   C   |   F   |   I   |
           |_______|_______|_______|_______|
           |       |       |       |       |
           |       |   D   |   G   |   J   |
           |_______|_______|_______|_______|

                     DIM_GANTRY

where the nodes are chosen to have horizontal and vertical spread of 1.0. Let us fix a ratio value of 0.5. This means that when moving from the first row to the second (distance=1.0) the trajectory is free to move up or down anything between +0.5 and -0.5 (distance*ratio = 0.5). We observe that in this case, it is not possible to jump from A to B or D, because the vertical difference is 1.0 which is higher than 0.5. Therefore, from A it is only possible to move to C.

Considering the spread across two rows (distance=2.0), we have a vertical freedom of 1.0. This would technically allow to start at A and end on E. However, due to the discretization of the grid it would request to go the path A-C-E or A-B-E what would violate at least once the maximum ratio of 0.5.

In such cases it is better to adapt the grid and design it more according to the desired ratio as e.g:

 ________________________________
|               |               |
|               |       B       |
|_______________|_______________|
|               |               |
|       A       |       C       |
|_______________|_______________|
|               |               |
|               |       D       |
|_______________|_______________|

In the latter setup we can keep a ratio of 0.5 and it would be allowed to jump from A to B or from A to D.

Args
lattice (Lattice or list of array_like): Object defining the
computational lattice.
ratio (float): Ratio describing the agility of the table with respect
to the gantry.
order (str {‘random’, ‘max_val’, ‘max_random’}, optional): Order in
which the trajectory points are sampled. ‘random’ randomly selects one gantry position after the other. ‘max_val’ treats the gantry positions according to the maximum value in the prior probability map. ‘max_random’ samples positions according to their maximum value in the prior probability map.
compute_adjacency_graph()

Computes and stores the adjacency graph of the sampler.

Not that we consider a directed graph where the edges always go from the lower to the higher nodes such that the graph:

    2---3
   / \  |
  /   \ |
 /     \|
1---4---5

would give the adjacency matrix:

  | 1   2   3   4   5
--|--------------------
1 |     *       *
2 |         *       *
3 |                 *
4 |                 *
5 |

In this matrix, the rows represent ‘arriving’ and the columns ‘departing’ edges.

compute_condition_map(conditions=None, validate=False)

Computes a lattice map representing the union of a set of conditions.

Parameters:
  • conditions (list, optional) – Set of conditions of either strings (that indicate the path of a conditioning file), array_like objects (that represent conditioning points), or conditioning lattice maps.
  • validate (bool, optional) – Inspect the given conditioning with respect to the sampler settings and if necessary correct it.
Returns:

Conditioning map.

Return type:

LatticeMap

set_prior_cond(conditions=None, validate=False)

Sets the prior conditioning map of the sampler with the possibility to validate it.

The prior probability map is updated whenever a new prior conditioning map is set.

Parameters:
  • conditions (list, optional) – Set of conditions of either strings (that indicate the path of a conditioning file), array_like objects (that represent conditioning points), or conditioning lattice maps.
  • validate (bool, optional) – Inspect the given conditioning with respect to the sampler settings and if necessary correct it.
Returns:

None

set_prior_prob(map_, energy=False)

Sets the prior probability attribute of the sampler.

It is possible to provide prior probability values (energy=False) or probability energy values (energy=True). In the latter case, the values are transformed to un-normalized probability measures by:

prior_prob.values = exp(-map_.values)

where exp denotes the exponential function.

Parameters:
  • map (LatticeMap) – Prior map
  • energy (bool) – Indicates if the prior map represents probability values (false) or probability energy (true).
Returns:

None

class pasam.sampling.Sampler(lattice)

Base class for sampling algorithms.

Args
lattice (Lattice or list of array_like): Object defining the
computational lattice.
prior_cond

Returns the prior conditioning map.

Returns:LatticeMap
prior_prob

Returns the prior probability map.

Returns:LatticeMap
set_prior_cond(conditions=None, validate=False) → None

Sets the prior conditioning map.

Parameters:
  • conditions (list, optional) – Set of conditions.
  • validate (bool, optional) – Inspect the given conditioning with respect to the sampler settings and if necessary correct it.
Returns:

None

set_prior_prob(map_: pasam.lattice.LatticeMap, energy: bool = False) → None

Set’s the prior probability map.

Parameters:
  • map (LatticeMap) – Prior probability or energy map.
  • energy (bool) – Indicates whether the energy (True) or the probability (False) values are provided.
Returns:

None

class pasam.sampling.Trajectory(points)

Definition of dynamic trajectories.

Parameters:points (array_like of array_like) – Sequence of trajectory points.
points

Sequence of trajectory points.

Type:list of tuple
classmethod from_txt(file)

Generates a trajectory object from .txt files.

The form of the text file must be as follows:

-------------------------
|  <len>                |
|  points[0]            |
|  points[1]            |
|     ...               |
|  points[-1]           |
-------------------------
Parameters:file (str or pathlib.Path) – File or filename.
Returns:Trajectory from file.
Return type:Trajectory
to_latticemap(lattice, dtype=None)

Generates a boolean lattice map indicating the trajectory.

Parameters:lattice (Lattice) – Object defining the computational lattice.
dtype (data-type, optional): The desired data-type for the map values.
If not given, then the type will be determined as the minimum requirement by numpy.
Returns:Boolean trajectory according to a lattice grid.
Return type:LatticeMap
to_txt(file)

Writes a trajectory to a text file.

The form of the text file is as follows:

-------------------------
|  <len>                |
|  points[0]            |
|  points[1]            |
|     ...               |
|  points[-1]           |
-------------------------
Parameters:file (str or pathlib.Path) – File or filename.
Returns:None

Utilities

This module defines some generic package tools.

pasam.utils.ams_val_map_to_bool_map(vals)

Assigns 0 to True and 1 to False.

By default, the AMS generates files where the permitted nodes have values 0 and the blocked nodes have value 1 but for the module it is more convenient to use False for blocked and True for permitted nodes.

pasam.utils.cartesian_product(*args, order='F')

Cartesian product for a set of containers.

Parameters:
  • args (array_like of array_like) – Input arguments to be composed.
  • order (str {'C', 'F'}) – ‘F’ for Fortran and ‘C’ for C-type ordering.
Returns:

list of tuples

Notes

This function is equivalent to the function itertools.product but in addiction the ordering can be chosen (‘F’ or ‘C’).

For an input with two lists:

args = [[a, b, c], [e, f]]

it produces a list of tuples such that:

order='F':
[(a, e), (b, e), (c, e),
 (a, f), (b, f), (c, f)],

order='C':
[(a, e), (a, f),
 (b, e), (b, f),
 (c, e), (c, f)].
pasam.utils.findall_num_in_str(s)

Extracts all numbers in a string.

Parameters:s (str) – Input string containing numbers
Returns:List of numbers (float or int)
Return type:list
pasam.utils.isincreasing(values, strict=True)

Checks if a set of values is increasing.

Parameters:
  • values (array_like, shape=(n,)) – Set of values
  • strict (bool, optional) – Strictly (strict=True) or simply (strict=False) increasing.
Returns:

bool

pasam.utils.readlines_(file, remove_blank_lines=False)

Reading txt file (similar to builtin readlines).

In addition to the standard implementation of readlines for _io.TextIOWrapper, this version provides the possibility to remove empty text lines.

Parameters:
  • file (str or pathlib.Path) – File or filename.
  • remove_blank_lines (bool, optional) – Remove blank lines.
Returns:

All non empty lines of text file

Return type:

list(str)

pasam.utils.within_conical_opening(center, distance, ratio, points)

Indicates whether the points are within (True) or outside (False) of a conical opening.

An example of a conical (symmetric) opening with distributed points:

            center
               *                 ---
              / \                 |
             /   \                |
            /     \            distance
           /       \              |
          /         \             |
         /___________\           ---

        |-------------|        distance * ratio

   *---------*----*--------*   points
   |         |    |        |
[False,    True, True,   False]    return

where distance is the height of the triangle, the opening is the product distance * ratio and points is a set of real values. For the given example above, two out of four points are lying within the conical (symmetric) opening.

Parameters:
  • center (float) – Center of the cone.
  • distance (float) – Distance from the center.
  • ratio (float) – Ratio of the opening by distance.
  • points (ndarray, shape=(n,)) – Set of real values.
Returns:

Indicator for points inside (True) and outside

(False) of the conical opening.

Return type:

array-like, shape=(n,)