fovi.sensing.geodesic

Surface geodesics from actual patch centers for fixed-count geometry banks.

class fovi.sensing.geodesic.Path(*args, **kwargs)[source]

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

classmethod cwd()[source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

classmethod home()[source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

samefile(other_path)[source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

iterdir()[source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

glob(pattern)[source]

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern)[source]

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

absolute()[source]

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

resolve(strict=False)[source]

Make the path absolute, resolving all symlinks on the way and also normalizing it.

stat(*, follow_symlinks=True)[source]

Return the result of the stat() system call on this path, like os.stat() does.

owner()[source]

Return the login name of the file owner.

group()[source]

Return the group name of the file gid.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]

Open the file pointed by this path and return a file object, as the built-in open() function does.

read_bytes()[source]

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]

Open the file in text mode, read it, and close the file.

write_bytes(data)[source]

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source]

Open the file in text mode, write to it, and close the file.

Return the path to which the symbolic link points.

touch(mode=0o666, exist_ok=True)[source]

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=0o777, parents=False, exist_ok=False)[source]

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source]

Change the permissions of the path, like os.chmod().

lchmod(mode)[source]

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source]

Remove this directory. The directory must be empty.

lstat()[source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

rename(target)[source]

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source]

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

exists()[source]

Whether this path exists.

is_dir()[source]

Whether this path is a directory.

is_file()[source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]

Check if this path is a POSIX mount point

Whether this path is a symbolic link.

is_block_device()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_fifo()[source]

Whether this path is a FIFO.

is_socket()[source]

Whether this path is a socket.

expanduser()[source]

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

class fovi.sensing.geodesic.Delaunay(points, furthest_site=False, incremental=False, qhull_options=None)

Bases: _QhullUser

Delaunay tessellation in N dimensions.

Added in version 0.9.

Parameters:
  • points (ndarray of floats, shape (npoints, ndim)) – Coordinates of points to triangulate

  • furthest_site (bool, optional) –

    Whether to compute a furthest-site Delaunay triangulation. Default: False

    Added in version 0.12.0.

  • incremental (bool, optional) – Allow adding new points incrementally. This takes up some additional resources.

  • qhull_options (str, optional) –

    Additional options to pass to Qhull. See Qhull manual for details. Option “Qt” is always enabled. Default:”Qbb Qc Qz Qx Q12” for ndim > 4 and “Qbb Qc Qz Q12” otherwise. Incremental mode omits “Qz”.

    Added in version 0.12.0.

points

Coordinates of input points.

Type:

ndarray of double, shape (npoints, ndim)

simplices

Indices of the points forming the simplices in the triangulation. For 2-D, the points are oriented counterclockwise.

Type:

ndarray of ints, shape (nsimplex, ndim+1)

neighbors

Indices of neighbor simplices for each simplex. The kth neighbor is opposite to the kth vertex. For simplices at the boundary, -1 denotes no neighbor.

Type:

ndarray of ints, shape (nsimplex, ndim+1)

equations

[normal, offset] forming the hyperplane equation of the facet on the paraboloid (see Qhull documentation for more).

Type:

ndarray of double, shape (nsimplex, ndim+2)

paraboloid_scale, paraboloid_shift

Scale and shift for the extra paraboloid dimension (see Qhull documentation for more).

Type:

float

transform

Affine transform from x to the barycentric coordinates c. This is defined by:

T c = x - r

At vertex j, c_j = 1 and the other coordinates zero.

For simplex i, transform[i,:ndim,:ndim] contains inverse of the matrix T, and transform[i,ndim,:] contains the vector r.

If the simplex is degenerate or nearly degenerate, its barycentric transform contains NaNs.

Type:

ndarray of double, shape (nsimplex, ndim+1, ndim)

vertex_to_simplex

Lookup array, from a vertex, to some simplex which it is a part of. If qhull option “Qc” was not specified, the list will contain -1 for points that are not vertices of the tessellation.

Type:

ndarray of int, shape (npoints,)

convex_hull

Vertices of facets forming the convex hull of the point set. The array contains the indices of the points belonging to the (N-1)-dimensional facets that form the convex hull of the triangulation.

Note

Computing convex hulls via the Delaunay triangulation is inefficient and subject to increased numerical instability. Use ConvexHull instead.

Type:

ndarray of int, shape (nfaces, ndim)

coplanar

Indices of coplanar points and the corresponding indices of the nearest facet and the nearest vertex. Coplanar points are input points which were not included in the triangulation due to numerical precision issues.

If option “Qc” is not specified, this list is not computed.

Added in version 0.12.0.

Type:

ndarray of int, shape (ncoplanar, 3)

vertex_neighbor_vertices

Neighboring vertices of vertices. The indices of neighboring vertices of vertex k are indices[indptr[k]:indptr[k+1]].

Type:

tuple of two ndarrays of int; (indptr, indices)

furthest_site

True if this was a furthest site triangulation and False if not.

Added in version 1.4.0.

Raises:
  • QhullError – Raised when Qhull encounters an error condition, such as geometrical degeneracy when options to resolve are not enabled.

  • ValueError – Raised if an incompatible array is given as input.

Notes

The tessellation is computed using the Qhull library Qhull library.

Note

Unless you pass in the Qhull option “QJ”, Qhull does not guarantee that each input point appears as a vertex in the Delaunay triangulation. Omitted points are listed in the coplanar attribute.

Examples

Triangulation of a set of points:

>>> import numpy as np
>>> points = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])
>>> from scipy.spatial import Delaunay
>>> tri = Delaunay(points)

We can plot it:

>>> import matplotlib.pyplot as plt
>>> plt.triplot(points[:,0], points[:,1], tri.simplices)
>>> plt.plot(points[:,0], points[:,1], 'o')
>>> plt.show()

Point indices and coordinates for the two triangles forming the triangulation:

>>> tri.simplices
array([[2, 3, 0],                 # may vary
       [3, 1, 0]], dtype=int32)

Note that depending on how rounding errors go, the simplices may be in a different order than above.

>>> points[tri.simplices]
array([[[ 1. ,  0. ],            # may vary
        [ 1. ,  1. ],
        [ 0. ,  0. ]],
       [[ 1. ,  1. ],
        [ 0. ,  1.1],
        [ 0. ,  0. ]]])

Triangle 0 is the only neighbor of triangle 1, and it’s opposite to vertex 1 of triangle 1:

>>> tri.neighbors[1]
array([-1,  0, -1], dtype=int32)
>>> points[tri.simplices[1,1]]
array([ 0. ,  1.1])

We can find out which triangle points are in:

>>> p = np.array([(0.1, 0.2), (1.5, 0.5), (0.5, 1.05)])
>>> tri.find_simplex(p)
array([ 1, -1, 1], dtype=int32)

The returned integers in the array are the indices of the simplex the corresponding point is in. If -1 is returned, the point is in no simplex. Be aware that the shortcut in the following example only works correctly for valid points as invalid points result in -1 which is itself a valid index for the last simplex in the list.

>>> p_valids = np.array([(0.1, 0.2), (0.5, 1.05)])
>>> tri.simplices[tri.find_simplex(p_valids)]
array([[3, 1, 0],                 # may vary
       [3, 1, 0]], dtype=int32)

We can also compute barycentric coordinates in triangle 1 for these points:

>>> b = tri.transform[1,:2].dot(np.transpose(p - tri.transform[1,2]))
>>> np.c_[np.transpose(b), 1 - b.sum(axis=0)]
array([[ 0.1       ,  0.09090909,  0.80909091],
       [ 1.5       , -0.90909091,  0.40909091],
       [ 0.5       ,  0.5       ,  0.        ]])

The coordinates for the first point are all positive, meaning it is indeed inside the triangle. The third point is on an edge, hence its null third coordinate.

__init__(points, furthest_site=False, incremental=False, qhull_options=None)
add_points(points, restart=False)

Process a set of additional new points.

Parameters:
  • points (ndarray) – New points to add. The dimensionality should match that of the initial points.

  • restart (bool, optional) – Whether to restart processing from scratch, rather than adding points incrementally.

Raises:

QhullError – Raised when Qhull encounters an error condition, such as geometrical degeneracy when options to resolve are not enabled.

See also

close

Notes

You need to specify incremental=True when constructing the object to be able to add points incrementally. Incremental addition of points is also not possible after close has been called.

property convex_hull

Vertices of facets forming the convex hull of the point set.

Type:

ndarray of int, shape (nfaces, ndim)

The array contains the indices of the points belonging to the (N-1)-dimensional facets that form the convex hull of the triangulation.

Note

Computing convex hulls via the Delaunay triangulation is inefficient and subject to increased numerical instability. Use ConvexHull instead.

find_simplex(self, xi, bruteforce=False, tol=None)

Find the simplices containing the given points.

Parameters:
  • xi (ndarray of double, shape (..., ndim)) – Points to locate

  • bruteforce (bool, optional) – Whether to only perform a brute-force search

  • tol (float, optional) – Tolerance allowed in the inside-triangle check. Default is 100*eps.

Returns:

i – Indices of simplices containing each point. Points outside the triangulation get the value -1.

Return type:

ndarray of int, same shape as xi

Notes

This uses an algorithm adapted from Qhull’s qh_findbestfacet, which makes use of the connection between a convex hull and a Delaunay triangulation. After finding the simplex closest to the point in N+1 dimensions, the algorithm falls back to directed search in N dimensions.

lift_points(self, x)

Lift points to the Qhull paraboloid.

plane_distance(self, xi)

Compute hyperplane distances to the point xi from all simplices.

property points
property transform

Affine transform from x to the barycentric coordinates c.

Type:

ndarray of double, shape (nsimplex, ndim+1, ndim)

This is defined by:

T c = x - r

At vertex j, c_j = 1 and the other coordinates zero.

For simplex i, transform[i,:ndim,:ndim] contains inverse of the matrix T, and transform[i,ndim,:] contains the vector r.

property vertex_neighbor_vertices

Neighboring vertices of vertices.

Tuple of two ndarrays of int: (indptr, indices). The indices of neighboring vertices of vertex k are indices[indptr[k]:indptr[k+1]].

property vertex_to_simplex

Lookup array, from a vertex, to some simplex which it is a part of.

Type:

ndarray of int, shape (npoints,)

class fovi.sensing.geodesic.SamplingCoords(fov, cmf_a, res, device='cpu', style='isotropic', dtype=torch.float, max_val=1, isotropic_plotting_type='v1like', fov_type='circular', field_geometry='planar', radius_norm=2.0)[source]

Bases: object

Object for storing multiple coordinate systems relevant to a set of visual field samples.

Parameters:
  • fov (float) – Field-of-view in degrees.

  • cmf_a (float) – A parameter from the CMF: M(r)=1/(r+a). Smaller a = stronger foveation.

  • res (int) – Resolution, corresponding to the side length of a cartesian grid or the number of radii in polar (before any adjustments are made to match a target cartesian grid).

  • device (str) – What device to operate on.

  • style (str) – What type of sampling.

  • dtype (torch.dtype) – What data type to use.

  • fov_type (str) – One of 'circular', 'square', or 'wang'. The last is only valid for warped Cartesian sensor styles.

  • radius_norm (float) – Norm measuring native-plane radius for warped Cartesian styles. 2.0 gives circular iso-eccentricity shells; inf gives square shells, which pair with fov_type='square' to retain every cell.

__init__(fov, cmf_a, res, device='cpu', style='isotropic', dtype=torch.float, max_val=1, isotropic_plotting_type='v1like', fov_type='circular', field_geometry='planar', radius_norm=2.0)[source]
as_grid(values: Tensor, sample_dim: int = -1) → Tensor[source]

Replace a canonical sample axis with the sensor’s image axes.

Cartesian grids return upright rows down and columns right. Log-polar grids retain their radius/angle ordering. Other axes are unchanged.

Parameters:
  • values – Tensor with one axis containing all canonical samples.

  • sample_dim – Sample axis; use zero for coordinates shaped (N, 2).

Returns:

Tensor with the sample axis replaced by height and width.

native_to_visual(coordinates: Tensor) → Tensor[source]

Map (…, 2) native Cartesian warp coordinates to the visual chart.

Visual chart radius one is half the configured FoV. For spherical geometry this is angular eccentricity, not a pinhole projection. The unbounded chart includes masked cells outside the model footprint; renderers must handle their own angular padding domain.

visual_to_native(coordinates: Tensor) → Tensor[source]

Map (…, 2) normalized visual-chart positions to the native grid.

pad_cartesian(padding_distance=0.5, device=None, dtype=None)[source]

Generate additional cartesian coordinates for padding around the sampling grid.

Parameters:
  • padding_distance (float) – Padding extent in normalized coordinates. For spherical radial grids, measured from the real retinal rim, retaining at least one complete neighboring ring. Planar/legacy radial grids retain the historical interval starting at the first outer ring, which can overshoot the requested rim margin by one ring. Preserve that behavior for checkpoint KNN compatibility. Warped Cartesian and log-polar layouts pad in their own grid coordinates using a whole number of grid intervals.

  • device (str, optional) – Device to place the coordinates on. Defaults to None.

  • dtype (torch.dtype, optional) – Data type for the coordinates. Defaults to None.

Returns:

Additional cartesian coordinates for padding.

Return type:

torch.Tensor

get_strided_coords(stride, auto_match_cart_resources=0, in_cart_res=None, force_less_than=True, max_val=1)[source]

Return a strided version of the coordinates.

Parameters:
  • stride (int) – Stride factor for downsampling coordinates.

  • auto_match_cart_resources (int) – Automatic matching parameter for cartesian resources.

  • in_cart_res (int, optional) – Input cartesian resolution. Required for ‘fixn’ style.

  • force_less_than (bool, optional) – Whether to force less than target resolution. Defaults to True.

  • max_val (float, optional) – Maximum value for coordinates. Defaults to 1.

Returns:

A tuple containing:
  • SamplingCoords: New SamplingCoords object with strided coordinates.

  • int: Number of output radii.

  • int: Corresponding output cartesian resolution.

Return type:

tuple

to(device=None, dtype=None)[source]

Move the SamplingCoords object to a different device and/or change data type.

Parameters:
  • device (str, optional) – Target device. Defaults to None.

  • dtype (torch.dtype, optional) – Target data type. Defaults to None.

Returns:

SamplingCoords object on the specified device/dtype.

Return type:

SamplingCoords

get_scatter_sizes()[source]

Calculate approximate size to be used for plotting in scatter plots.

Scales linearly with eccentricity, as occurs in KNN-sampling of the sensor manifold. However, this is not precisely tuned to the particular warping parameters.

Returns:

Receptive field sizes for each sampling point.

Return type:

torch.Tensor

clone(fov=None, cmf_a=None, resolution=None, device=None, style=None, dtype=None, max_val=None, isotropic_plotting_type=None, fov_type=None, field_geometry=None, radius_norm=None)[source]

Return a deep copy of the SamplingCoords object with optional parameter overrides.

Parameters:
  • fov (float, optional) – Field-of-view in degrees. Defaults to current value.

  • cmf_a (float, optional) – A parameter from the CMF. Defaults to current value.

  • resolution (int, optional) – Resolution parameter. Defaults to current value.

  • device (str, optional) – Device to place coordinates on. Defaults to current value.

  • style (str, optional) – Sampling style. Defaults to current value.

  • dtype (torch.dtype, optional) – Data type. Defaults to current value.

  • max_val (float, optional) – Maximum coordinate value. Defaults to current value.

Returns:

A new SamplingCoords object with the specified parameters.

Return type:

SamplingCoords

class fovi.sensing.geodesic.ExactGeodesicSolver(vertices, faces, device=None)[source]

Bases: object

Exact surface geodesic distances from vertices of one triangle mesh.

Parameters:
  • vertices – (V, 3) or (V, 2) vertex positions; planar input lies in z = 0.

  • faces – (F, 3) vertex indices of the triangles. The mesh must be an edge-manifold (each edge borders at most two faces) of non-degenerate triangles. Vertices not referenced by any face are unreachable.

  • device – Warp device for the solves; CPU by default, which suits a few solves on a large mesh.

__init__(vertices, faces, device=None)[source]
distances(source: int) → ndarray[source]

(V,) float64 distances from one source vertex; inf if unreachable.

distances_from_each(sources: Iterable[int]) → ndarray[source]

(S, V) float64 distances, one row per source vertex, solved in one batch.

fovi.sensing.geodesic.geodesic_cache_directory() → Path | None[source]

Resolve the model’s persistent cache; an empty override disables caching.

fovi.sensing.geodesic.patch_geodesic_distances(inputs: SamplingCoords, patches: SamplingCoords, cache_dir: Path | None = None) → Tensor[source]

Return [real + padding samples, patches] distances on the cortical mesh.

Triangulate in the visual coordinate chart, but measure on the embedded cortical surface. Include the actual patch centers as mesh vertices, rather than moving each source to its nearest retinal sample. Distances are exact on this piecewise-linear mesh, an approximation to the smooth manifold. Construction is CPU-only and stays outside the training hot path.

fovi.sensing.geodesic._solve_surface_geodesics(visual: ndarray, cortical: ndarray, sample_count: int) → ndarray[source]

Solve all sample/patch pairs on one joint triangulated surface.