API Reference

Sparse CP Tensor Decomposition

class barnacle.decomposition.SparseCP(rank, lambdas, nonneg_modes=None, norm_constraint=True, init='random', tol=1e-06, n_iter_max=1000, random_state=None, n_initializations=1)[source]

Bases: DecompositionMixin

Sparse CP decomposition by l1-penalized Alternating Least Squares (ALS)

Parameterizes a rank-rank decomposition of tensor such that:

tensor = [|weights; factors[0], ..., factors[-1]|].

The lambdas values indicate the sparsity-inducing l1 regularization coefficient to be applied to each mode when the model is fit to data. The factor matrices indicated in nonneg_modes are forced to be non-negative, and if norm_constraint = True, the l2 norm of any factor matrix without an l1 sparsity penalty (lambda=0.0) is constrained to be unit length.

Parameters:
  • rank (int) – Number of components.

  • lambdas ([float]) – Vector of length tensor.ndim in which lambdas[i] is the l1 sparsity coefficient for factor[i]. If lambdas is set to all zeros, this is the equivalent of fitting a standard CP decomposition without any sparsity constraints.

  • nonneg_modes ([int], default is None) – List of modes forced to be non-negative.

  • norm_constraint (bool, default is True) – If norm_constraint = True, the l2 norm of any factor matrix without an l1 sparsity penalty (lambda=0.0) is constrained to unit length. If the sparsity penalty of every mode is 0.0, the l2 norm constraint is automatically turned off in every mode.

  • init ({‘random’, CPTensor}, default is ‘random’.) – Values used to initialized the factor matrices. If init == ‘random’ then factor matrices are initialized with uniform distribution using random_state. If init is a previously initialized cp tensor, any weights are incorporated into the last factor, and then the initial weight values for the output decomposition are set to ‘1’.

  • tol (float, default is 1e-6) – Convergence tolerance. The algorithm is considered to have found the global minimum when the change in loss from one iteration to the next falls below the tol threshold. The calculated change in loss is relative when loss > 1 and absolute when loss <= 1. In other words, convergence is defined as :

    \[\frac{\|l^{(n-1)} - l^{(n)}\|}{\max(l^{(n)}, 1)} < t\]

    where \(l^{(n)}\) is the loss at iteration \(n\), and \(t\) is the tolerance threshold set by tol.

  • n_iter_max (int, default is 1000) – Maximum number of iterations. If the algorithm fails to converge according to the tol threshold set, a warning will be raised.

  • random_state ({None, int, numpy.random.RandomState}, default is None) – Random state used to initialized factor matrices and weights.

  • n_initializations (int, default is 1) – Number of random initializations to compute.

property decomposition_
fit_transform(tensor, threads=None, verbose=0, return_losses=False)[source]

Fits n_initializations sparse tensor decomposition models to the provided data tensor, using the als_lasso() method. Fit models are stored with the SparseCP object, and are accessible via the SparseCP.decomposition_(), SparseCP.loss_(), SparseCP.candidates_(), and SparseCP.candidate_losses_() properties.

Parameters:
  • tensor (numpy.ndarray) – Input data tensor.

  • threads (int, default is None) – Maximum number of threads allocated to the algorithm. If threads = None, then all available threads will be used.

  • verbose (int, default is 0) – Level of verbosity.

  • return_losses (bool, default is False) – Activate return of iteration loss values at each iteration.

Returns:

  • cp_tensor ((weight, factors)) –

    • weights1D array of shape (rank,) that contains the weights

      denoting the relative contributio of each factor.

    • factorsList of factors of the CP decomposition where factor

      matrix i is of shape (tensor.shape[i], rank)

  • losses (list) – A list of loss values calculated at each iteration of the algorithm. Only returned when return_losses is set to True.

property loss_
barnacle.decomposition.als_lasso(tensor, rank, lambdas, nonneg_modes=None, norm_constraint=True, init='random', tol=1e-06, n_iter_max=1000, random_state=None, threads=None, verbose=0, return_losses=False)[source]

Computes a rank-rank decomposition of tensor such that:

tensor = [|weights; factors[0], ..., factors[-1]|].

The algorithm aims to minimize the loss as defined by:

\[\|Y - \hat{Y}\|^2 + \lambda_0\|F_0\|_1 + ... + \lambda_{-1}\|F_{-1}\|_1\]

where \(Y\) is the input tensor, \(\hat{Y}\) is the model reconstruction of the input tensor, and the following terms encompass the l1 norm (calculated column-wise) of each factor matrix \(F_i\) multiplied by its corresponding sparsity coefficient \(\lambda_i\). Any mode for which \(\lambda\) has been set to zero will incur no sparsity penalty.

Furthermore, the factor matrices indicated in the nonneg_modes parameter are forced to be non-negative, and if norm_constraint = True, the l2 norm of any factor matrix without an l1 sparsity penalty (\(\lambda=0.0\)) is constrained to be unit length.

Parameters:
  • tensor (numpy.ndarray) – Input data tensor.

  • rank (int) – Number of components.

  • lambdas ([float]) – Vector of length tensor.ndim in which lambdas[i] is the l1 sparsity coefficient for factor[i]. If lambdas is set to all zeros, this is the equivalent of fitting a standard CP decomposition without any sparsity constraints.

  • nonneg_modes ([int], default is None) – List of modes forced to be non-negative.

  • norm_constraint (bool, default is True) – If norm_constraint = True, the l2 norm of any factor matrix without an l1 sparsity penalty (\(\lambda=0.0\)) is constrained to unit length. If the sparsity penalty of every mode is 0.0, the l2 norm constraint is automatically turned off in every mode.

  • init ({‘random’, CPTensor}, default is ‘random’.) – Values used to initialized the factor matrices. If init = ‘random’ then factor matrices are initialized with uniform distribution using random_state. If init is a previously initialized cp tensor, any weights are incorporated into the last factor, and then the initial weight values for the output decomposition are set to ‘1’.

  • tol (float, default is 1e-6) – Convergence tolerance. The algorithm is considered to have found the global minimum when the change in loss from one iteration to the next falls below the tol threshold. The calculated change in loss is relative when loss > 1 and absolute when loss <= 1. In other words, convergence is defined as :

    \[\frac{\|l^{(n-1)} - l^{(n)}\|}{\max(l^{(n)}, 1)} < t\]

    where \(l^{(n)}\) is the loss at iteration \(n\), and \(t\) is the tolerance threshold set by tol.

  • n_iter_max (int, default is 1000) – Maximum number of iterations. If the algorithm fails to converge according to the tol threshold set, a warning will be raised.

  • random_state ({None, int, numpy.random.RandomState}, default is None) – Random state used to initialized factor matrices and weights.

  • threads (int, default is None) – Maximum number of threads allocated to the algorithm. If threads = None, then all available threads will be used.

  • verbose (int, default is 0) – Level of verbosity.

  • return_losses (bool, default is False) – Activate return of iteration loss values at each iteration.

Returns:

  • cp_tensor ((weight, factors)) –

    • weights1D array of shape (rank,) that contains the weights denoting

      the relative contribution of each factor.

    • factorsList of factors of the CP decomposition where factor matrix

      i is of shape (tensor.shape[i], rank)

  • losses (list) – A list of loss values calculated at each iteration of the algorithm. Only returned when return_losses is set to True.

Fast Iterative Shrinkage/Thresholding Algorithm (FISTA)

barnacle.fista.create_gradient(AtA, At_b)[source]

Helper function to generate gradient function.

Parameters:
  • AtA (numpy.ndarray) – The matrix A^T A.

  • At_b (numpy.ndarray) – The vector A^T b.

Returns:

grad – Gradient function.

Return type:

function

barnacle.fista.create_loss(AtA, At_b)[source]

Helper function to generate loss function.

Parameters:
  • AtA (numpy.ndarray) – The matrix A^T A.

  • At_b (numpy.ndarray) – The vector A^T b.

Returns:

loss – Loss function.

Return type:

function

barnacle.fista.fista_solve(lhs, rhs, l1_reg, nonnegative, normalize, init, n_iter_max=100, return_err=False)[source]

Use the FISTA algorithm to define and solve the optimisation problem:

min_x ||Ax - b||^2 + reg * g(x)

Where reg is an l1 regularisation coefficient, and g(x) is a proximal operator applied to x. The proximal operator can optionally incorporate (individually or in combination):

  • l1 regularization

  • non-negativity constraint

  • l2 norm constraint: ||x|| <= 1

L1 regularization and l2 norm constraint cannot be applied in combination.

Optimization is acheived using the Fast Iterative Shrinkage Thresholding Algorithm (FISTA) with backtracking, as described in Beck & Teboulle (2009) [8], in combination with adaptive restart as described in O’Donoghue & Candès (2012) [9].

Parameters:
  • lhs (numpy.ndarray) – The matrix A^T A.

  • rhs (numpy.ndarray) – The vector A^T b.

  • l1_reg (float) – L1 regularization coefficient reg.

  • nonnegative (bool) – If True, applies a non-negativity constraint to the solution x.

  • normalize (bool) – If True, applies an l2 norm constraint to x such that ||x|| <= 1.

  • init (numpy.ndarray) – Initialization of x.

  • n_iter_max (int, default is 100) – Maximal number of iterations.

  • return_err (bool, default is False) – Return iteration errors if true.

Returns:

  • x (numpy.ndarray) – The solution x that minimizes the given optimization problem.

  • losses (list) – If return_err = True, a list of iteration errors.

barnacle.fista.fista_step(x, y, t, lipschitz, smooth_grad_y, l1_reg, prox)[source]

Function to take one FISTA step.

Parameters:
  • x (numpy.ndarray) – Initial solution vector x.

  • y (numpy.ndarray) – Initial solution vector x with momentum.

  • t (float) – Momentum coefficient.

  • lipschitz (float) – Lipschitz coefficient.

  • smooth_grad_y (numpy.ndarray) – Gradient of y.

  • l1_reg (float) – L1 regularization coefficient.

  • prox (function) – Proximal operator.

Returns:

  • new_x (numpy.ndarray) – Updated solution vector x.

  • new_y (numpy.ndarray) – Updated solution vector x with momentum.

  • new_t (float) – Updated momentum coefficient.

barnacle.fista.l1_prox(x, reg)[source]

Proximal operator to apply l1 sparsity penalty.

Parameters:
  • x (numpy.ndarray) – Input array.

  • reg (float) – L1 sparsity penalty (reg >= 0).

Returns:

x – Input array with l1 proximal operation applied.

Return type:

numpy.ndarray

barnacle.fista.l2ball_prox(x, reg)[source]

Proximal operator to apply l2 normalization constraint. Constrains l2-norm of x to be less than or equal to 1.

Parameters:
  • x (numpy.ndarray) – Input array.

  • reg (float) – Not necessary, but included for continuity of the proximal operator call signature.

Returns:

x – Input array with l2 norm constraint applied.

Return type:

numpy.ndarray

barnacle.fista.minimise_fista(lhs, rhs, init, l1_reg, prox, n_iter=10, tol=1e-06, return_err=False, line_search=True)[source]

Use the FISTA algorithm to solve the given optimisation problem:

min_x ||Ax - b||^2 + reg * g(x)

Optimization is acheived using the Fast Iterative Shrinkage Thresholding Algorithm (FISTA) with backtracking, as described in Beck & Teboulle (2009) [8], in combination with adaptive restart as described in O’Donoghue & Candès (2012) [9].

Parameters:
  • lhs (numpy.ndarray) – The matrix A^T A.

  • rhs (numpy.ndarray) – The vector A^T b.

  • init (numpy.ndarray) – Initialization of x.

  • l1_reg (float) – L1 regularization coefficient reg.

  • prox (function) – The proximal operator g().

  • n_iter (int, default is 10) – Maximal number of iterations.

  • tol (float, default is 1e-6) – Convergence tolerance.

  • return_err (bool, default is False) – Return iteration errors if true.

  • line_search (bool, default is True) – Perform backtracking line search if True.

Returns:

  • x (numpy.ndarray) – The solution x that minimizes the given optimization problem.

  • losses (list) – If return_err = True, a list of iteration errors.

barnacle.fista.nn_l1_prox(x, reg)[source]

Proximal operator to apply nonnegative constraint in combination with an l1 sparsity penalty.

Parameters:
  • x (numpy.ndarray) – Input array.

  • reg (float) – L1 sparsity penalty (reg >= 0).

Returns:

x – Input array with non-negativity constraint and l1 proximal operation applied.

Return type:

numpy.ndarray

barnacle.fista.nn_l2ball_prox(x, reg)[source]

Proximal operator to apply nonnegative constraint in combination with an l2 normalization constraint.

Parameters:
  • x (numpy.ndarray) – Input array.

  • reg (float) – Not necessary, but included for continuity of the proximal operator call signature.

Returns:

x – Input array with non-negativity and l2 norm constraints applied.

Return type:

numpy.ndarray

barnacle.fista.nn_prox(x, reg)[source]

Proximal operator to apply non-negativity constraint.

Parameters:
  • x (numpy.ndarray) – Input array.

  • reg (float) – Not necessary, but included for continuity of the proximal operator call signature.

Returns:

x – Input array with non-negativity constraint applied.

Return type:

numpy.ndarray

Tensor Manipulations

class barnacle.tensors.Component(component)[source]

Bases: CPTensor

Rank-1 CPTensor that constitutes one component of the CPTensor from which it was derived.

support(modes=None, boolean=False, thold=None)[source]

Method that returns the indices of all non-zero elements. Optionally, if a tuple of thresholds is provided, elements greater than thold[0] and less than thold[1] will be considered zero-valued.

Parameters:
  • mode (int, list of ints, default is None) – Mode(s) of Component to extract support from. If modes=None, all Component modes will be included.

  • boolean (bool, default is False) – If True, returns non-zero indices of each mode as an array of booleans. Otherwise indices are returned as an array of ints.

  • thold (tuple of ints, default is None) – Thresholds of values to be considered zero-valued. Values greater than or equal to thold[0] and less than or equal to thold[1] will be considered zero-valued.

Returns:

indices – Arrays of Component indices. One array for each mode. If mode is an int, just the index array of the corresponding mode is returned.

Return type:

numpy.ndarray or list of numpy.ndarrays

class barnacle.tensors.SimSparseCPTensor(cp_tensor)[source]

Bases: SparseCPTensor

Class container for methods related to simulated sparse CP tensors.

to_tensor(noise_level=0, sparse_noise=False, noise_distribution=None, random_state=None)[source]

Generate optionally noisey data tensor from factorized CP tensor. This method overwrites the tensorly.cp_tensor.CPTensor.to_tensor() parent method.

Parameters:
  • noise_level (float, optional) – Scale factor for the noise tensor, relative to the l2 norms.

  • sparse_noise (bool) – If True, will set all positions in the noise matrix that correspond to sparse positions in the signal matrix to zero. Default is False.

  • noise_distribution (scipy.stats.rv_continuous, optional) – Parameterized continuous distribution to generate the noise tensor. This parameter cannot be None if noise_level > 0.

  • random_state ({None, int, numpy.random.RandomState}, optional) – Random state to seed the noise_distribution generator.

Returns:

data – Tensorized data formatted in an n-dimensional numpy array.

Return type:

numpy.ndarray

class barnacle.tensors.SparseCPTensor(cp_tensor)[source]

Bases: CPTensor

Class container for methods related to sparse CP tensors.

get_clusters(mode, boolean=False, thold=None)[source]

Each component of a factor matrix resulting from a sparse tensor decomposition can be considered as a cluster, where the support (indices of non-zero values) delineates cluster membership. This method extracts a list of indices, one for each component, delineating cluster memberships indicated by the factor matrix in one mode of the decomposition. Indices can either be an array of integers, or a boolean array spanning the length of the mode.

Parameters:
  • mode (int) – Mode to get clusters from.

  • boolean (bool, default is False) – If True, returns non-zero indices of each mode as an array of booleans. Otherwise indices are returned as an array of ints.

  • thold (tuple of ints, default is None) – Thresholds of values to be considered zero-valued. Values greater than or equal to thold[0] and less than or equal to thold[1] will be considered zero-valued.

Returns:

clusters – List of cluster indices of the selected mode.

Return type:

list of numpy.ndarrays

get_components()[source]

Generate list of Component objects from SparseCPTensor factors.

Returns:

components – List of Component objects, where components[i] is the i-th factor of the parent SparseCPTensor.

Return type:

list of Components

barnacle.tensors.simulated_sparse_tensor(shape, rank, densities=None, factor_dist_list=None, weights=None, random_state=None)[source]

Generates simulated data in the form of a sparse cp_tensor

Parameters:
  • shape (tuple of ints) – Tensor shape where len(shape) = n modes in tensor.

  • rank (int) – The number of components in the tensor.

  • densities (list of floats [0.0, 1.0], optional) – The proportion of elements that are non-zero in the factor matrices. Must be the same length as the shape parameter. If not set, the densities are set to 1 for fully dense factor matrices.

  • factor_dist_list (list of scipy.stats._distn_infrastructure.rv_frozen, optional) – Distributions from which the factor matrices will be drawn. Must be the same length as the shape parameter and must have a .rvs() method for drawing random values, and a random_state attribute specifying state. Example: scipy.stats.uniform()

  • weights (list of floats, optional) – Weights to assign to each factor. If not set, then defaults to ones.

  • random_state ({None, int, np.random.RandomState}) – Random state to seed the value_distribution and cluster_size_distribution generators.

Returns:

sim_cp – Parameterized simulated data.

Return type:

SimSparseCPTensor

Utility Functions

barnacle.utils.cluster_buddies_matrix(cluster_set)[source]

Generates a square matrix of size n x n where n is the length of the boolean array indicating membership in each cluster. Note that this length should be the same for each cluster included in cluster_set. Each entry matrix[i][j] is the number of times that element i and element j co-occur in the same cluster (i.e. the number of times index i and index j are both True in the same cluster).

Parameters:

cluster_set (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each cluster included in the set.

Returns:

matrix – An n x n array of integers in which each entry matrix[i][j] is the number of times element i and element j co-occur in a cluster included in the cluster_set.

Return type:

numpy.ndarray

barnacle.utils.consolidate_cp(cp_tensor)[source]

Removes zeroed out factors from cp tensor.

Parameters:

cp_tensor (tensorly.cp_tensor.CPTensor) – CP tensor decomposition.

Returns:

cleaned_cp – CP tensor decomposition with zero factors removed. Rank of cleaned_cp is less than or equal to rank of input cp_tensor.

Return type:

tensorly.cp_tensor.CPTensor

barnacle.utils.jaccard_matrix(true_clusters, inferred_clusters)[source]

Generates an n x m matrix where n is the number of true_clusters and m is the number of inferred_clusters, and where each entry matrix[i][j] is the jaccard score comparing true_clusters[i] with inferred_clusters[j].

Note that the length of the boolean array indicating cluster membership should be the same for each cluster.

Parameters:
  • true_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the ground truth clusters.

  • inferred_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the clusters to be compared against ground truth.

Returns:

matrix – An n x m matrix where n is the number of true_clusters and m is the number of inferred_clusters, and where each entry matrix[i][j] is the jaccard score comparing true_clusters[i] with inferred_clusters[j].

Return type:

numpy.ndarray

barnacle.utils.pairs_precision_recall(true_clusters, inferred_clusters)[source]

Evaluates two metrics, precision and recall, designed to compare pairwise membership of the elements included in a set of inferred_clusters against the pairwise membership of elements in a ground truth set of true_clusters. To evaluate, the number of times each pair of elements (e.g. cluster[0] and cluster[1]) co-occurs is counted in both the set of true_clusters as well as the set of inferred_clusters. Precision measures the proportion of pairwise co-occurrences in the inferred_clusters that are also found in the true_clusters. Recall measures the proportion of pairwise co-occurences in the true_clusters that are reproduced in the inferred_clusters. Both metrics range between 0 and 1.

For a complete description, see Methods section and Supplementary Figure 1 of Saelens et al. (2018) [15].

Parameters:
  • true_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the ground truth clusters. Each array should be the same length.

  • inferred_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the clusters to be compared against ground truth. Each array should be the same length.

Returns:

  • precision (float) – Precision score (ranges between 0 and 1).

  • recall (float) – Recall score (ranges between 0 and 1).

barnacle.utils.permute_tensor(tensor, mode, random_state=None)[source]

Function to independently permute each of the fibers of an input tensor along a specified mode.

Parameters:
  • tensor (numpy.ndarray) – Input tensor.

  • mode (int) – Mode along which fibers will be permuted.

  • random_state ({None, int, numpy.random.RandomState}, default is None) – Random state used to randomly permute tensor fibers.

Returns:

tensor_out – Randomly permuted tensor.

Return type:

numpy.ndarray

barnacle.utils.plot_factors_heatmap(factors, ratios=False, mask_thold=None, reference_factors=None, figsize=None, heatmap_kwargs=None)[source]

Plot a heatmap visualization of cp_tensor factors

Parameters:
  • factors (list of numpy.ndarray) – The factors to be plotted

  • ratios ({bool, list of ints},) – True = heights of plots are proportional to dimensions of factors False = heights of plots are identical list of ints = manual assignment of height ratios

  • mask_thold (tuple of floats) – Interval (inclusive) between which all values will be masked out of heatmaps. Example: (0, 0) = only values that are exactly zero will be masked.

  • reference_factors (list of numpy.ndarray, optional) – A second set of baseline factors to be plotted. Sizes and shapes are assumed to be the same as in factors. If not None, reference_factors will be plotted in the first column, and factors in the second.

  • figsize (2-tuple, optional) – Size of the figure

  • heatmap_kwargs (dict, optional) – Keyword arguments to be passed to each heatmap in the figure

Returns:

  • fig (matplotlib.figure.Figure) – Matplotlib figure object

  • ax (matplotlib.axes._subplots.AxesSubplot) – Matplotlib axes object

barnacle.utils.recovery_relevance(true_clusters, inferred_clusters)[source]

Evaluates two metrics, recovery and relevance, designed to compare a set of inferred_clusters against a ground truth set of true_clusters. Recovery measures how well the true clusters are recovered by the inferred clusters, and is the mean of the Jaccard indices of the best match from the inferred_clusters for each of the true_clusters. Relevance measures how well the inferred clusters are representative of the true clusters, and is the mean of the Jaccard indices of the best match from the true_clusters for each of the inferred_clusters. Both metrics range between 0 and 1.

For a complete description, see Methods section and Supplementary Figure 1 of Saelens et al. (2018) [15].

Parameters:
  • true_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the ground truth clusters. Each array should be the same length.

  • inferred_clusters (list of boolean numpy.ndarrays) – List of boolean arrays indicating cluster membership for each of the clusters to be compared against ground truth. Each array should be the same length.

Returns:

  • recovery (float) – Recovery score (ranges between 0 and 1).

  • relevance (float) – Relevance score (ranges between 0 and 1).

barnacle.utils.subset_cp_tensor(cp_tensor, subset_indices)[source]

Selects subset of cp_tensor based on provided indices

Parameters:
  • cp_tensor (tensorly.CPTensor) – CPTensor object with (weights, factors).

  • subset_indices (dict(int: index-like)) – Dictionary with mode as key and value an integer index of the positions to be downselected from cp_tensor. Example: {1: [0, 1, 3, 4, 5, 8]}

Returns:

subset_cp – Subset CPTensor.

Return type:

tensorly.CPTensor

barnacle.utils.visualize_3d_tensor(tensor, shell=True, midpoint=None, range_color=None, opacity=0.5, bg_color='#fff', aspectmode='data', show_colorbar=True, label_axes=True, axes_names=None, figure_kwargs=None)[source]

Plot an interactive visualization of a 3d tensor using plotly

This method uses the plotly.express.scatter_3d() function to plot a visualization of the input data tensor. It is intended primarily for use with three dimensional tensors, but can handle lower dimensional data as well.

Parameters:
  • tensor (3 dimensional numpy.ndarray) – Three dimensional numpy array containing tensor data

  • shell (bool) – Plot only the points on the outer sides of the tensor. Default is True.

  • midpoint (float, optional) – Midpoint value of the color scale, coded white.

  • range_color (2-tuple, optional) – Range of the color scale, formatted (low, high).

  • opacity (float) – Opacity of the points on the plot, ranges from 0 to 1. Default is 0.5.

  • bg_color (str) – Color of the plot background. Set to ‘rgba(0,0,0,0)’ for transparent background. Default is ‘#fff’.

  • aspectmode ({‘data’, ‘cube’, ‘auto’}) –

    Option passed to plotly to control the proportions of the axes:

    ‘data’ : axes are in proportion to the data ranges ‘cube’ : axes are drawn as a cube, regardless of data ranges ‘auto’ : ‘data’ if no axis is > 4x any other axis, otherwise ‘cube’

    Default is ‘data’.

  • label_axes (bool) – Plot axes label names and scales. Defalut is True.

  • show_colorbar (bool) – Plot legend. Defalut is True

  • axes_names (list, optional) – Names of axes. Length must equal the number of modes in the tensor. When set to None, default names in the form of ‘axisX’ are used. Default is None.

  • figure_kwargs (dict, optional) – Keyword arguments to be passed to the plotly.express.scatter_3d() function. Default is None.

Returns:

fig – Plotly figure object. A number of options are available to this object, including show() and save().

Return type:

plotly.graph_objs._figure.Figure

barnacle.utils.zeros_cp(shape, rank)[source]

Return a tensorly.cp_tensor.CPTensor of the specified size and rank, consisting of all zeros.

Parameters:
  • shape (tuple of ints) – Tensor shape where len(shape) = n modes in tensor.

  • rank (int) – The number of components in the tensor.

Returns:

zero_cp – CPTensor of all zeros.

Return type:

tensorly.cp_tensor.CPTensor