sklearn.utils.extmath.weighted_mode(a, w, *, axis=0) [source]

Returns an array of the weighted modal (most common) value in a. If there is more than one such value, only the first is returned. The bin-count for the modal bins is also returned. This is an extension of the algorithm in scipy.stats.mode.  Parameters

aarray-like

n-dimensional array of which to find mode(s).
warray-like

n-dimensional array of weights for each value.
axisint, default=0

Axis along which to operate. Default is 0, i.e. the first axis.    Returns

valsndarray

Array of modal values.
scorendarray

Array of weighted counts for each mode.      See also
scipy.stats.mode

  Examples >>> from sklearn.utils.extmath import weighted_mode
>>> x = [4, 1, 4, 2, 4, 2]
>>> weights = [1, 1, 1, 1, 1, 1]
>>> weighted_mode(x, weights)
(array([4.]), array([3.]))
 The value 4 appears three times: with uniform weights, the result is simply the mode of the distribution. >>> weights = [1, 3, 0.5, 1.5, 1, 2]  # deweight the 4's
>>> weighted_mode(x, weights)
(array([2.]), array([3.5]))
 The value 2 has the highest score: it appears twice with weights of 1.5 and 2: the sum of these is 3.5.


sklearn.utils.gen_even_slices(n, n_packs, *, n_samples=None) [source]

Generator to create n_packs slices going up to n.  Parameters

nint

n_packsint

Number of slices to generate.
n_samplesint, default=None

Number of samples. Pass n_samples when the slices are to be used for sparse matrix indexing; slicing off-the-end raises an exception, while it works for NumPy arrays.    Yields
 slice
   Examples >>> from sklearn.utils import gen_even_slices
>>> list(gen_even_slices(10, 1))
[slice(0, 10, None)]
>>> list(gen_even_slices(10, 10))
[slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)]
>>> list(gen_even_slices(10, 5))
[slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)]
>>> list(gen_even_slices(10, 3))
[slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)]


sklearn.utils.graph.single_source_shortest_path_length(graph, source, *, cutoff=None) [source]

Return the shortest path length from source to all reachable nodes. Returns a dictionary of shortest path lengths keyed by target.  Parameters

graph{sparse matrix, ndarray} of shape (n, n)

Adjacency matrix of the graph. Sparse matrix of format LIL is preferred.
sourceint

Starting node for path.
cutoffint, default=None

Depth to stop the search - only paths of length <= cutoff are returned.     Examples >>> from sklearn.utils.graph import single_source_shortest_path_length
>>> import numpy as np
>>> graph = np.array([[ 0, 1, 0, 0],
...                   [ 1, 0, 1, 0],
...                   [ 0, 1, 0, 1],
...                   [ 0, 0, 1, 0]])
>>> list(sorted(single_source_shortest_path_length(graph, 0).items()))
[(0, 0), (1, 1), (2, 2), (3, 3)]
>>> graph = np.ones((6, 6))
>>> list(sorted(single_source_shortest_path_length(graph, 2).items()))
[(0, 1), (1, 1), (2, 0), (3, 1), (4, 1), (5, 1)]


sklearn.utils.graph_shortest_path.graph_shortest_path()
Perform a shortest-path graph search on a positive directed or undirected graph.  Parameters

dist_matrixarraylike or sparse matrix, shape = (N,N)

Array of positive distances. If vertex i is connected to vertex j, then dist_matrix[i,j] gives the distance between the vertices. If vertex i is not connected to vertex j, then dist_matrix[i,j] = 0
directedboolean

if True, then find the shortest path on a directed graph: only progress from a point to its neighbors, not the other way around. if False, then find the shortest path on an undirected graph: the algorithm can progress from a point to its neighbors and vice versa.
methodstring [‘auto’|’FW’|’D’]

method to use. Options are ‘auto’ : attempt to choose the best method for the current problem ‘FW’ : Floyd-Warshall algorithm. O[N^3] ‘D’ : Dijkstra’s algorithm with Fibonacci stacks. O[(k+log(N))N^2]    Returns

Gnp.ndarray, float, shape = [N,N]

G[i,j] gives the shortest distance from point i to point j along the graph.     Notes As currently implemented, Dijkstra’s algorithm does not work for graphs with direction-dependent distances when directed == False. i.e., if dist_matrix[i,j] and dist_matrix[j,i] are not equal and both are nonzero, method=’D’ will not necessarily yield the correct result. Also, these routines have not been tested for graphs with negative distances. Negative distances can lead to infinite cycles that must be handled by specialized algorithms.


sklearn.utils.indexable(*iterables) [source]

Make arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays.  Parameters

*iterables{lists, dataframes, ndarrays, sparse matrices}

List of objects to ensure sliceability.


sklearn.utils.metaestimators.if_delegate_has_method(delegate) [source]

Create a decorator for methods that are delegated to a sub-estimator This enables ducktyping by hasattr returning True according to the sub-estimator.  Parameters

delegatestring, list of strings or tuple of strings

Name of the sub-estimator that can be accessed as an attribute of the base object. If a list or a tuple of names are provided, the first sub-estimator that is an attribute of the base object will be used.


sklearn.utils.multiclass.is_multilabel(y) [source]

Check if y is in a multilabel format.  Parameters

yndarray of shape (n_samples,)

Target values.    Returns

outbool

Return True, if y is in a multilabel format, else `False.     Examples >>> import numpy as np
>>> from sklearn.utils.multiclass import is_multilabel
>>> is_multilabel([0, 1, 0, 1])
False
>>> is_multilabel([[1], [0, 2], []])
False
>>> is_multilabel(np.array([[1, 0], [0, 0]]))
True
>>> is_multilabel(np.array([[1], [0], [0]]))
False
>>> is_multilabel(np.array([[1, 0, 0]]))
True


sklearn.utils.multiclass.type_of_target(y) [source]

Determine the type of data indicated by the target. Note that this type is the most specific type that can be inferred. For example:
binary is more specific but compatible with multiclass.
multiclass of integers is more specific but compatible with continuous.
multilabel-indicator is more specific but compatible with multiclass-multioutput.   Parameters

yarray-like
  Returns

target_typestr

One of:  ‘continuous’: y is an array-like of floats that are not all integers, and is 1d or a column vector. ‘continuous-multioutput’: y is a 2d array of floats that are not all integers, and both dimensions are of size > 1. ‘binary’: y contains <= 2 discrete values and is 1d or a column vector. ‘multiclass’: y contains more than two discrete values, is not a sequence of sequences, and is 1d or a column vector. ‘multiclass-multioutput’: y is a 2d array that contains more than two discrete values, is not a sequence of sequences, and both dimensions are of size > 1. ‘multilabel-indicator’: y is a label indicator matrix, an array of two dimensions with at least two columns, and at most 2 unique values. ‘unknown’: y is array-like but none of the above, such as a 3d array, sequence of sequences, or an array of non-sequence objects.      Examples >>> import numpy as np
>>> type_of_target([0.1, 0.6])
'continuous'
>>> type_of_target([1, -1, -1, 1])
'binary'
>>> type_of_target(['a', 'b', 'a'])
'binary'
>>> type_of_target([1.0, 2.0])
'binary'
>>> type_of_target([1, 0, 2])
'multiclass'
>>> type_of_target([1.0, 0.0, 3.0])
'multiclass'
>>> type_of_target(['a', 'b', 'c'])
'multiclass'
>>> type_of_target(np.array([[1, 2], [3, 1]]))
'multiclass-multioutput'
>>> type_of_target([[1, 2]])
'multilabel-indicator'
>>> type_of_target(np.array([[1.5, 2.0], [3.0, 1.6]]))
'continuous-multioutput'
>>> type_of_target(np.array([[0, 1], [1, 1]]))
'multilabel-indicator'


sklearn.utils.multiclass.unique_labels(*ys) [source]

Extract an ordered array of unique labels.  We don’t allow:

 mix of multilabel and multiclass (single label) targets mix of label indicator matrix and anything else, because there are no explicit labels) mix of label indicator matrices of different sizes mix of string and integer labels    At the moment, we also don’t allow “multiclass-multioutput” input type.  Parameters

*ysarray-likes
  Returns

outndarray of shape (n_unique_labels,)

An ordered array of unique labels.     Examples >>> from sklearn.utils.multiclass import unique_labels
>>> unique_labels([3, 5, 5, 5, 7, 7])
array([3, 5, 7])
>>> unique_labels([1, 2, 3, 4], [2, 2, 3, 4])
array([1, 2, 3, 4])
>>> unique_labels([1, 2, 10], [5, 11])
array([ 1,  2,  5, 10, 11])


sklearn.utils.murmurhash3_32()
Compute the 32bit murmurhash3 of key at seed. The underlying implementation is MurmurHash3_x86_32 generating low latency 32bits hash suitable for implementing lookup tables, Bloom filters, count min sketch or feature hashing.  Parameters

keynp.int32, bytes, unicode or ndarray of dtype=np.int32

The physical object to hash.
seedint, default=0

Integer seed for the hashing algorithm.
positivebool, default=False

 True: the results is casted to an unsigned int

from 0 to 2 ** 32 - 1  False: the results is casted to a signed int

from -(2 ** 31) to 2 ** 31 - 1


sklearn.utils.parallel_backend(backend, n_jobs=- 1, inner_max_num_threads=None, **backend_params) [source]

Change the default backend used by Parallel inside a with block. If backend is a string it must match a previously registered implementation using the register_parallel_backend function. By default the following backends are available:  ‘loky’: single-host, process-based parallelism (used by default), ‘threading’: single-host, thread-based parallelism, ‘multiprocessing’: legacy single-host, process-based parallelism.  ‘loky’ is recommended to run functions that manipulate Python objects. ‘threading’ is a low-overhead alternative that is most efficient for functions that release the Global Interpreter Lock: e.g. I/O-bound code or CPU-bound code in a few calls to native code that explicitly releases the GIL. In addition, if the dask and distributed Python packages are installed, it is possible to use the ‘dask’ backend for better scheduling of nested parallel calls without over-subscription and potentially distribute parallel calls over a networked cluster of several hosts. It is also possible to use the distributed ‘ray’ backend for distributing the workload to a cluster of nodes. To use the ‘ray’ joblib backend add the following lines: >>> from ray.util.joblib import register_ray
>>> register_ray()
>>> with parallel_backend("ray"):
...     print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
[-1, -2, -3, -4, -5]
 Alternatively the backend can be passed directly as an instance. By default all available workers will be used (n_jobs=-1) unless the caller passes an explicit value for the n_jobs parameter. This is an alternative to passing a backend='backend_name' argument to the Parallel class constructor. It is particularly useful when calling into library code that uses joblib internally but does not expose the backend argument in its own API. >>> from operator import neg
>>> with parallel_backend('threading'):
...     print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
...
[-1, -2, -3, -4, -5]
 Warning: this function is experimental and subject to change in a future version of joblib. Joblib also tries to limit the oversubscription by limiting the number of threads usable in some third-party library threadpools like OpenBLAS, MKL or OpenMP. The default limit in each worker is set to max(cpu_count() // effective_n_jobs, 1) but this limit can be overwritten with the inner_max_num_threads argument which will be used to set this limit in the child processes.  New in version 0.10.


sklearn.utils.random.sample_without_replacement()
Sample integers without replacement. Select n_samples integers from the set [0, n_population) without replacement.  Parameters

n_populationint

The size of the set to sample from.
n_samplesint

The number of integer to sample.
random_stateint, RandomState instance or None, default=None

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
method{“auto”, “tracking_selection”, “reservoir_sampling”, “pool”}, default=’auto’

If method == “auto”, the ratio of n_samples / n_population is used to determine which algorithm to use: If ratio is between 0 and 0.01, tracking selection is used. If ratio is between 0.01 and 0.99, numpy.random.permutation is used. If ratio is greater than 0.99, reservoir sampling is used. The order of the selected integers is undefined. If a random order is desired, the selected subset should be shuffled. If method ==”tracking_selection”, a set based implementation is used which is suitable for n_samples <<< n_population. If method == “reservoir_sampling”, a reservoir sampling algorithm is used which is suitable for high memory constraint or when O(n_samples) ~ O(n_population). The order of the selected integers is undefined. If a random order is desired, the selected subset should be shuffled. If method == “pool”, a pool based algorithm is particularly fast, even faster than the tracking selection method. However, a vector containing the entire population has to be initialized. If n_samples ~ n_population, the reservoir sampling method is faster.    Returns

outndarray of shape (n_samples,)

The sampled subsets of integer. The subset of selected integer might not be randomized, see the method argument.


sklearn.utils.register_parallel_backend(name, factory, make_default=False) [source]

Register a new Parallel backend factory. The new backend can then be selected by passing its name as the backend argument to the Parallel class. Moreover, the default backend can be overwritten globally by setting make_default=True. The factory can be any callable that takes no argument and return an instance of ParallelBackendBase. Warning: this function is experimental and subject to change in a future version of joblib.  New in version 0.10.


sklearn.utils.resample(*arrays, replace=True, n_samples=None, random_state=None, stratify=None) [source]

Resample arrays or sparse matrices in a consistent way. The default strategy implements one step of the bootstrapping procedure.  Parameters

*arrayssequence of array-like of shape (n_samples,) or (n_samples, n_outputs)

Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension.
replacebool, default=True

Implements resampling with replacement. If False, this will implement (sliced) random permutations.
n_samplesint, default=None

Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. If replace is False it should not be larger than the length of arrays.
random_stateint, RandomState instance or None, default=None

Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See Glossary.
stratifyarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

If not None, data is split in a stratified fashion, using this as the class labels.    Returns

resampled_arrayssequence of array-like of shape (n_samples,) or (n_samples, n_outputs)

Sequence of resampled copies of the collections. The original arrays are not impacted.      See also
shuffle

  Examples It is possible to mix sparse and dense arrays in the same run: >>> X = np.array([[1., 0.], [2., 1.], [0., 0.]])
>>> y = np.array([0, 1, 2])

>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)

>>> from sklearn.utils import resample
>>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
>>> X
array([[1., 0.],
       [2., 1.],
       [1., 0.]])

>>> X_sparse
<3x2 sparse matrix of type '<... 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

>>> X_sparse.toarray()
array([[1., 0.],
       [2., 1.],
       [1., 0.]])

>>> y
array([0, 1, 0])

>>> resample(y, n_samples=2, random_state=0)
array([0, 1])
 Example using stratification: >>> y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
>>> resample(y, n_samples=5, replace=False, stratify=y,
...          random_state=0)
[1, 1, 1, 0, 1]


sklearn.utils.safe_mask(X, mask) [source]

Return a mask which is safe to use on X.  Parameters

X{array-like, sparse matrix}

Data on which to apply mask.
maskndarray

Mask to be used on X.    Returns
 mask


sklearn.utils.safe_sqr(X, *, copy=True) [source]

Element wise squaring of array-likes and sparse matrices.  Parameters

X{array-like, ndarray, sparse matrix}

copybool, default=True

Whether to create a copy of X and operate on it or to perform inplace computation (default behaviour).    Returns

X ** 2element wise square


sklearn.utils.shuffle(*arrays, random_state=None, n_samples=None) [source]

Shuffle arrays or sparse matrices in a consistent way. This is a convenience alias to resample(*arrays, replace=False) to do random permutations of the collections.  Parameters

*arrayssequence of indexable data-structures

Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension.
random_stateint, RandomState instance or None, default=None

Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See Glossary.
n_samplesint, default=None

Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. It should not be larger than the length of arrays.    Returns

shuffled_arrayssequence of indexable data-structures

Sequence of shuffled copies of the collections. The original arrays are not impacted.      See also
resample

  Examples It is possible to mix sparse and dense arrays in the same run: >>> X = np.array([[1., 0.], [2., 1.], [0., 0.]])
>>> y = np.array([0, 1, 2])

>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)

>>> from sklearn.utils import shuffle
>>> X, X_sparse, y = shuffle(X, X_sparse, y, random_state=0)
>>> X
array([[0., 0.],
       [2., 1.],
       [1., 0.]])

>>> X_sparse
<3x2 sparse matrix of type '<... 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>

>>> X_sparse.toarray()
array([[0., 0.],
       [2., 1.],
       [1., 0.]])

>>> y
array([2, 1, 0])

>>> shuffle(y, n_samples=2, random_state=0)
array([0, 1])


sklearn.utils.sparsefuncs.incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None) [source]

Compute incremental mean and variance along an axis on a CSR or CSC matrix. last_mean, last_var are the statistics computed at the last step by this function. Both must be initialized to 0-arrays of the proper size, i.e. the number of features in X. last_n is the number of samples encountered until now.  Parameters

XCSR or CSC sparse matrix of shape (n_samples, n_features)

Input data.
axis{0, 1}

Axis along which the axis should be computed.
last_meanndarray of shape (n_features,) or (n_samples,), dtype=floating

Array of means to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
last_varndarray of shape (n_features,) or (n_samples,), dtype=floating

Array of variances to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
last_nfloat or ndarray of shape (n_features,) or (n_samples,), dtype=floating

Sum of the weights seen so far, excluding the current weights If not float, it should be of shape (n_samples,) if axis=0 or (n_features,) if axis=1. If float it corresponds to having same weights for all samples (or features).
weightsndarray of shape (n_samples,) or (n_features,), default=None

If axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted.  New in version 0.24.     Returns

meansndarray of shape (n_features,) or (n_samples,), dtype=floating

Updated feature-wise means if axis = 0 or sample-wise means if axis = 1.
variancesndarray of shape (n_features,) or (n_samples,), dtype=floating

Updated feature-wise variances if axis = 0 or sample-wise variances if axis = 1.
nndarray of shape (n_features,) or (n_samples,), dtype=integral

Updated number of seen samples per feature if axis=0 or number of seen features per sample if axis=1. If weights is not None, n is a sum of the weights of the seen samples or features instead of the actual number of seen samples or features.     Notes NaNs are ignored in the algorithm.


sklearn.utils.sparsefuncs.inplace_column_scale(X, scale) [source]

Inplace column scaling of a CSC/CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Matrix to normalize using the variance of the features. It should be of CSC or CSR format.
scalendarray of shape (n_features,), dtype={np.float32, np.float64}

Array of precomputed feature-wise values to use for scaling.


sklearn.utils.sparsefuncs.inplace_csr_column_scale(X, scale) [source]

Inplace column scaling of a CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Matrix to normalize using the variance of the features. It should be of CSR format.
scalendarray of shape (n_features,), dtype={np.float32, np.float64}

Array of precomputed feature-wise values to use for scaling.


sklearn.utils.sparsefuncs.inplace_row_scale(X, scale) [source]

Inplace row scaling of a CSR or CSC matrix. Scale each row of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Matrix to be scaled. It should be of CSR or CSC format.
scalendarray of shape (n_features,), dtype={np.float32, np.float64}

Array of precomputed sample-wise values to use for scaling.


sklearn.utils.sparsefuncs.inplace_swap_column(X, m, n) [source]

Swaps two columns of a CSC/CSR matrix in-place.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Matrix whose two columns are to be swapped. It should be of CSR or CSC format.
mint

Index of the column of X to be swapped.
nint

Index of the column of X to be swapped.


sklearn.utils.sparsefuncs.inplace_swap_row(X, m, n) [source]

Swaps two rows of a CSC/CSR matrix in-place.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Matrix whose two rows are to be swapped. It should be of CSR or CSC format.
mint

Index of the row of X to be swapped.
nint

Index of the row of X to be swapped.


sklearn.utils.sparsefuncs.mean_variance_axis(X, axis, weights=None, return_sum_weights=False) [source]

Compute mean and variance along an axis on a CSR or CSC matrix.  Parameters

Xsparse matrix of shape (n_samples, n_features)

Input data. It can be of CSR or CSC format.
axis{0, 1}

Axis along which the axis should be computed.
weightsndarray of shape (n_samples,) or (n_features,), default=None

if axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted.  New in version 0.24.
return_sum_weightsbool, default=False

If True, returns the sum of weights seen for each feature if axis=0 or each sample if axis=1.  New in version 0.24.     Returns

meansndarray of shape (n_features,), dtype=floating

Feature-wise means.
variancesndarray of shape (n_features,), dtype=floating

Feature-wise variances.
sum_weightsndarray of shape (n_features,), dtype=floating

Returned if return_sum_weights is True.


sklearn.utils.sparsefuncs_fast.inplace_csr_row_normalize_l1()
Inplace row normalize using the l1 norm


sklearn.utils.sparsefuncs_fast.inplace_csr_row_normalize_l2()
Inplace row normalize using the l2 norm


sklearn.utils.validation.check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=<built-in function all>) [source]

Perform is_fitted validation for estimator. Checks if the estimator is fitted by verifying the presence of fitted attributes (ending with a trailing underscore) and otherwise raises a NotFittedError with the given message. This utility is meant to be used internally by estimators themselves, typically in their own predict / transform methods.  Parameters

estimatorestimator instance

estimator instance for which the check is performed.
attributesstr, list or tuple of str, default=None

Attribute name(s) given as string or a list/tuple of strings Eg.: ["coef_", "estimator_", ...], "coef_" If None, estimator is considered fitted if there exist an attribute that ends with a underscore and does not start with double underscore.
msgstr, default=None

The default error message is, “This %(name)s instance is not fitted yet. Call ‘fit’ with appropriate arguments before using this estimator.” For custom messages if “%(name)s” is present in the message string, it is substituted for the estimator name. Eg. : “Estimator, %(name)s, must be fitted before sparsifying”.
all_or_anycallable, {all, any}, default=all

Specify whether all or any of the given attributes must exist.    Returns
 None
  Raises
 NotFittedError

If the attributes are not found.


sklearn.utils.validation.check_memory(memory) [source]

Check that memory is joblib.Memory-like. joblib.Memory-like means that memory can be converted into a joblib.Memory instance (typically a str denoting the location) or has the same interface (has a cache method).  Parameters

memoryNone, str or object with the joblib.Memory interface
  Returns

memoryobject with the joblib.Memory interface
  Raises
 ValueError

If memory is not joblib.Memory-like.


sklearn.utils.validation.check_symmetric(array, *, tol=1e-10, raise_warning=True, raise_exception=False) [source]

Make sure that array is 2D, square and symmetric. If the array is not symmetric, then a symmetrized version is returned. Optionally, a warning or exception is raised if the matrix is not symmetric.  Parameters

array{ndarray, sparse matrix}

Input object to check / convert. Must be two-dimensional and square, otherwise a ValueError will be raised.
tolfloat, default=1e-10

Absolute tolerance for equivalence of arrays. Default = 1E-10.
raise_warningbool, default=True

If True then raise a warning if conversion is required.
raise_exceptionbool, default=False

If True then raise an exception if array is not symmetric.    Returns

array_sym{ndarray, sparse matrix}

Symmetrized version of the input array, i.e. the average of array and array.transpose(). If sparse, then duplicate entries are first summed and zeros are eliminated.


sklearn.utils.validation.column_or_1d(y, *, warn=False) [source]

Ravel column or 1d numpy array, else raises an error.  Parameters

yarray-like

warnbool, default=False

To control display of warnings.    Returns

yndarray


sklearn.utils.validation.has_fit_parameter(estimator, parameter) [source]

Checks whether the estimator’s fit method supports the given parameter.  Parameters

estimatorobject

An estimator to inspect.
parameterstr

The searched parameter.    Returns
 is_parameter: bool

Whether the parameter was found to be a named parameter of the estimator’s fit method.     Examples >>> from sklearn.svm import SVC
>>> has_fit_parameter(SVC(), "sample_weight")
True


sklearn.utils._safe_indexing(X, indices, *, axis=0) [source]

Return rows, items or columns of X using indices.  Warning This utility is documented, but private. This means that backward compatibility might be broken without any deprecation cycle.   Parameters

Xarray-like, sparse-matrix, list, pandas.DataFrame, pandas.Series

Data from which to sample rows, items or columns. list are only supported when axis=0.
indicesbool, int, str, slice, array-like

 If axis=0, boolean and integer array-like, integer slice, and scalar integer are supported.

If axis=1:

 to select a single column, indices can be of int type for all X types and str only for dataframe. The selected subset will be 1D, unless X is a sparse matrix in which case it will be 2D. to select multiples columns, indices can be one of the following: list, array, slice. The type used in these containers can be one of the following: int, ‘bool’ and str. However, str is only supported when X is a dataframe. The selected subset will be 2D.
axisint, default=0

The axis along which X will be subsampled. axis=0 will select rows while axis=1 will select columns.    Returns
 subset

Subset of X on axis 0 or 1.     Notes CSR, CSC, and LIL sparse matrices are supported. COO sparse matrices are not supported.


pygame._sdl2.touch

 pygame module to work with touch input   New in pygame 2: This module requires SDL2.    pygame._sdl2.touch.get_num_devices()
 get the number of touch devices get_num_devices() -> int  Return the number of available touch devices.
   pygame._sdl2.touch.get_device()
 get the a touch device id for a given index get_device(index) -> touchid
Parameters:

index (int) -- This number is at least 0 and less than the number of devices.    Return an integer id associated with the given index.
   pygame._sdl2.touch.get_num_fingers()
 the number of active fingers for a given touch device get_num_fingers(touchid) -> int  Return the number of fingers active for the touch device whose id is touchid.
   pygame._sdl2.touch.get_finger()
 get information about an active finger get_finger(touchid, index) -> int
Parameters:

touchid (int) -- The touch device id.
index (int) -- The index of the finger to return information about, between 0 and the number of active fingers.      Return a dict for the finger index active on touchid. The dict contains these keys: id         the id of the finger (an integer).
x          the normalized x position of the finger, between 0 and 1.
y          the normalized y position of the finger, between 0 and 1.
pressure   the amount of pressure applied by the finger, between 0 and 1.


pygame._sdl2.touch.get_device()
 get the a touch device id for a given index get_device(index) -> touchid
Parameters:

index (int) -- This number is at least 0 and less than the number of devices.    Return an integer id associated with the given index.


pygame._sdl2.touch.get_finger()
 get information about an active finger get_finger(touchid, index) -> int
Parameters:

touchid (int) -- The touch device id.
index (int) -- The index of the finger to return information about, between 0 and the number of active fingers.      Return a dict for the finger index active on touchid. The dict contains these keys: id         the id of the finger (an integer).
x          the normalized x position of the finger, between 0 and 1.
y          the normalized y position of the finger, between 0 and 1.
pressure   the amount of pressure applied by the finger, between 0 and 1.


pygame._sdl2.touch.get_num_devices()
 get the number of touch devices get_num_devices() -> int  Return the number of available touch devices.


pygame._sdl2.touch.get_num_fingers()
 the number of active fingers for a given touch device get_num_fingers(touchid) -> int  Return the number of fingers active for the touch device whose id is touchid.


pygame.BufferProxy

 pygame object to export a surface buffer through an array protocol BufferProxy(<parent>) -> BufferProxy  BufferProxy is a pygame support type, designed as the return value of the Surface.get_buffer() and Surface.get_view() methods. For all Python versions a BufferProxy object exports a C struct and Python level array interface on behalf of its parent object's buffer. For CPython 2.6 and later a new buffer interface is also exported. In pygame, BufferProxy is key to implementing the pygame.surfarray module. BufferProxy instances can be created directly from Python code, either for a parent that exports an interface, or from a Python dict describing an object's buffer layout. The dict entries are based on the Python level array interface mapping. The following keys are recognized:
 "shape" : tuple The length of each array dimension as a tuple of integers. The length of the tuple is the number of dimensions in the array. "typestr" : string The array element type as a length 3 string. The first character gives byteorder, '<' for little-endian, '>' for big-endian, and '|' for not applicable. The second character is the element type, 'i' for signed integer, 'u' for unsigned integer, 'f' for floating point, and 'V' for an chunk of bytes. The third character gives the bytesize of the element, from '1' to '9' bytes. So, for example, "<u4" is an unsigned 4 byte little-endian integer, such as a 32 bit pixel on a PC, while "|V3" would represent a 24 bit pixel, which has no integer equivalent. "data" : tuple The physical buffer start address and a read-only flag as a length 2 tuple. The address is an integer value, while the read-only flag is a bool—False for writable, True for read-only. "strides" : tuple : (optional) Array stride information as a tuple of integers. It is required only of non C-contiguous arrays. The tuple length must match that of "shape". "parent" : object : (optional) The exporting object. It can be used to keep the parent object alive while its buffer is visible. "before" : callable : (optional) Callback invoked when the BufferProxy instance exports the buffer. The callback is given one argument, the "parent" object if given, otherwise None. The callback is useful for setting a lock on the parent. "after" : callable : (optional) Callback invoked when an exported buffer is released. The callback is passed on argument, the "parent" object if given, otherwise None. The callback is useful for releasing a lock on the parent.
 The BufferProxy class supports subclassing, instance variables, and weak references.  New in pygame 1.8.0.   Extended in pygame 1.9.2.    parent
 Return wrapped exporting object. parent -> Surface parent -> <parent>  The Surface which returned the BufferProxy object or the object passed to a BufferProxy call.
   length
 The size, in bytes, of the exported buffer. length -> int  The number of valid bytes of data exported. For discontinuous data, that is data which is not a single block of memory, the bytes within the gaps are excluded from the count. This property is equivalent to the Py_buffer C struct len field.
   raw
 A copy of the exported buffer as a single block of bytes. raw -> bytes  The buffer data as a str/bytes object. Any gaps in the exported data are removed.
   write()
 Write raw bytes to object buffer. write(buffer, offset=0)  Overwrite bytes in the parent object's data. The data must be C or F contiguous, otherwise a ValueError is raised. Argument buffer is a str/bytes object. An optional offset gives a start position, in bytes, within the buffer where overwriting begins. If the offset is negative or greater that or equal to the buffer proxy's length value, an IndexException is raised. If len(buffer) > proxy.length + offset, a ValueError is raised.


length
 The size, in bytes, of the exported buffer. length -> int  The number of valid bytes of data exported. For discontinuous data, that is data which is not a single block of memory, the bytes within the gaps are excluded from the count. This property is equivalent to the Py_buffer C struct len field.


parent
 Return wrapped exporting object. parent -> Surface parent -> <parent>  The Surface which returned the BufferProxy object or the object passed to a BufferProxy call.


raw
 A copy of the exported buffer as a single block of bytes. raw -> bytes  The buffer data as a str/bytes object. Any gaps in the exported data are removed.


write()
 Write raw bytes to object buffer. write(buffer, offset=0)  Overwrite bytes in the parent object's data. The data must be C or F contiguous, otherwise a ValueError is raised. Argument buffer is a str/bytes object. An optional offset gives a start position, in bytes, within the buffer where overwriting begins. If the offset is negative or greater that or equal to the buffer proxy's length value, an IndexException is raised. If len(buffer) > proxy.length + offset, a ValueError is raised.


pygame.camera

 pygame module for camera use  Pygame currently supports only Linux and v4l2 cameras. EXPERIMENTAL!: This API may change or disappear in later pygame releases. If you use this, your code will very likely break with the next pygame release. The Bayer to RGB function is based on: Sonix SN9C101 based webcam basic I/F routines
Copyright (C) 2004 Takafumi Mizuno <taka-qce@ls-a.jp>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE. New in pygame 1.9.0.   pygame.camera.colorspace()
 Surface colorspace conversion colorspace(Surface, format, DestSurface = None) -> Surface  Allows for conversion from "RGB" to a destination colorspace of "HSV" or "YUV". The source and destination surfaces must be the same size and pixel depth. This is useful for computer vision on devices with limited processing power. Capture as small of an image as possible, transform.scale() it even smaller, and then convert the colorspace to YUV or HSV before doing any processing on it.
   pygame.camera.list_cameras()
 returns a list of available cameras list_cameras() -> [cameras]  Checks the computer for available cameras and returns a list of strings of camera names, ready to be fed into pygame.camera.Camera.
   pygame.camera.Camera
 load a camera Camera(device, (width, height), format) -> Camera  Loads a v4l2 camera. The device is typically something like "/dev/video0". Default width and height are 640 by 480. Format is the desired colorspace of the output. This is useful for computer vision purposes. The default is RGB. The following are supported:

RGB - Red, Green, Blue
YUV - Luma, Blue Chrominance, Red Chrominance
HSV - Hue, Saturation, Value
   start()
 opens, initializes, and starts capturing start() -> None  Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.
   stop()
 stops, uninitializes, and closes the camera stop() -> None  Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.
   get_controls()
 gets current values of user controls get_controls() -> (hflip = bool, vflip = bool, brightness)  If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.
   set_controls()
 changes camera settings if supported by the camera set_controls(hflip = bool, vflip = bool, brightness) -> (hflip = bool, vflip = bool, brightness)  Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.
   get_size()
 returns the dimensions of the images being recorded get_size() -> (width, height)  Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.
   query_image()
 checks if a frame is ready query_image() -> bool  If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.
   get_image()
 captures an image as a Surface get_image(Surface = None) -> Surface  Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.
   get_raw()
 returns an unmodified image as a string get_raw() -> string  Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


pygame.camera.Camera
 load a camera Camera(device, (width, height), format) -> Camera  Loads a v4l2 camera. The device is typically something like "/dev/video0". Default width and height are 640 by 480. Format is the desired colorspace of the output. This is useful for computer vision purposes. The default is RGB. The following are supported:

RGB - Red, Green, Blue
YUV - Luma, Blue Chrominance, Red Chrominance
HSV - Hue, Saturation, Value
   start()
 opens, initializes, and starts capturing start() -> None  Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.
   stop()
 stops, uninitializes, and closes the camera stop() -> None  Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.
   get_controls()
 gets current values of user controls get_controls() -> (hflip = bool, vflip = bool, brightness)  If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.
   set_controls()
 changes camera settings if supported by the camera set_controls(hflip = bool, vflip = bool, brightness) -> (hflip = bool, vflip = bool, brightness)  Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.
   get_size()
 returns the dimensions of the images being recorded get_size() -> (width, height)  Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.
   query_image()
 checks if a frame is ready query_image() -> bool  If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.
   get_image()
 captures an image as a Surface get_image(Surface = None) -> Surface  Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.
   get_raw()
 returns an unmodified image as a string get_raw() -> string  Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


get_controls()
 gets current values of user controls get_controls() -> (hflip = bool, vflip = bool, brightness)  If the camera supports it, get_controls will return the current settings for horizontal and vertical image flip as bools and brightness as an int. If unsupported, it will return the default values of (0, 0, 0). Note that the return values here may be different than those returned by set_controls, though these are more likely to be correct.


get_image()
 captures an image as a Surface get_image(Surface = None) -> Surface  Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.


get_raw()
 returns an unmodified image as a string get_raw() -> string  Gets an image from a camera as a string in the native pixelformat of the camera. Useful for integration with other libraries.


get_size()
 returns the dimensions of the images being recorded get_size() -> (width, height)  Returns the current dimensions of the images being captured by the camera. This will return the actual size, which may be different than the one specified during initialization if the camera did not support that size.


query_image()
 checks if a frame is ready query_image() -> bool  If an image is ready to get, it returns true. Otherwise it returns false. Note that some webcams will always return False and will only queue a frame when called with a blocking function like get_image(). This is useful to separate the framerate of the game from that of the camera without having to use threading.


set_controls()
 changes camera settings if supported by the camera set_controls(hflip = bool, vflip = bool, brightness) -> (hflip = bool, vflip = bool, brightness)  Allows you to change camera settings if the camera supports it. The return values will be the input values if the camera claims it succeeded or the values previously in use if not. Each argument is optional, and the desired one can be chosen by supplying the keyword, like hflip. Note that the actual settings being used by the camera may not be the same as those returned by set_controls.


start()
 opens, initializes, and starts capturing start() -> None  Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.


stop()
 stops, uninitializes, and closes the camera stop() -> None  Stops recording, uninitializes the camera, and closes it. Once a camera is stopped, the below functions cannot be used until it is started again.


pygame.camera.colorspace()
 Surface colorspace conversion colorspace(Surface, format, DestSurface = None) -> Surface  Allows for conversion from "RGB" to a destination colorspace of "HSV" or "YUV". The source and destination surfaces must be the same size and pixel depth. This is useful for computer vision on devices with limited processing power. Capture as small of an image as possible, transform.scale() it even smaller, and then convert the colorspace to YUV or HSV before doing any processing on it.


pygame.camera.list_cameras()
 returns a list of available cameras list_cameras() -> [cameras]  Checks the computer for available cameras and returns a list of strings of camera names, ready to be fed into pygame.camera.Camera.


pygame.cdrom

 pygame module for audio cdrom control  The cdrom module manages the CD and DVD drives on a computer. It can also control the playback of audio CDs. This module needs to be initialized before it can do anything. Each CD object you create represents a cdrom drive and must also be initialized individually before it can do most things.   pygame.cdrom.init()
 initialize the cdrom module init() -> None  Initialize the cdrom module. This will scan the system for all CD devices. The module must be initialized before any other functions will work. This automatically happens when you call pygame.init(). It is safe to call this function more than once.
   pygame.cdrom.quit()
 uninitialize the cdrom module quit() -> None  Uninitialize the cdrom module. After you call this any existing CD objects will no longer work. It is safe to call this function more than once.
   pygame.cdrom.get_init()
 true if the cdrom module is initialized get_init() -> bool  Test if the cdrom module is initialized or not. This is different than the CD.init() since each drive must also be initialized individually.
   pygame.cdrom.get_count()
 number of cd drives on the system get_count() -> count  Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system.
   pygame.cdrom.CD
 class to manage a cdrom drive CD(id) -> CD  You can create a CD object for each cdrom on the system. Use pygame.cdrom.get_count() to determine how many drives actually exist. The id argument is an integer of the drive, starting at zero. The CD object is not initialized, you can only call CD.get_id() and CD.get_name() on an uninitialized drive. It is safe to create multiple CD objects for the same drive, they will all cooperate normally.   init()
 initialize a cdrom drive for use init() -> None  Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized. There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.
   quit()
 uninitialize a cdrom drive for use quit() -> None  Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.
   get_init()
 true if this cd device initialized get_init() -> bool  Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.
   play()
 start playing audio play(track, start=None, end=None) -> None  Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played. If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc. See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback. Note, track 0 is the first track on the CD. Track numbers start at zero.
   stop()
 stop audio playback stop() -> None  Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.
   pause()
 temporarily stop audio playback pause() -> None  Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing. Note, track 0 is the first track on the CD. Track numbers start at zero.
   resume()
 unpause audio playback resume() -> None  Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.
   eject()
 eject or open the cdrom drive eject() -> None  This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.
   get_id()
 the index of the cdrom drive get_id() -> id  Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.
   get_name()
 the system name of the cdrom drive get_name() -> name  Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.
   get_busy()
 true if the drive is playing audio get_busy() -> bool  Returns True if the drive busy playing back audio.
   get_paused()
 true if the drive is paused get_paused() -> bool  Returns True if the drive is currently paused.
   get_current()
 the current audio playback position get_current() -> track, seconds  Returns both the current track and time of that track. This method works when the drive is either playing or paused. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_empty()
 False if a cdrom is in the drive get_empty() -> bool  Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.
   get_numtracks()
 the number of tracks on the cdrom get_numtracks() -> count  Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.
   get_track_audio()
 true if the cdrom track has audio data get_track_audio(track) -> bool  Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_all()
 get all track information get_all() -> [(audio, start, end, length), ...]  Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.
   get_track_start()
 start time of a cdrom track get_track_start(track) -> seconds  Return the absolute time in seconds where at start of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_track_length()
 length of a cdrom track get_track_length(track) -> seconds  Return a floating point value in seconds of the length of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.


pygame.cdrom.CD
 class to manage a cdrom drive CD(id) -> CD  You can create a CD object for each cdrom on the system. Use pygame.cdrom.get_count() to determine how many drives actually exist. The id argument is an integer of the drive, starting at zero. The CD object is not initialized, you can only call CD.get_id() and CD.get_name() on an uninitialized drive. It is safe to create multiple CD objects for the same drive, they will all cooperate normally.   init()
 initialize a cdrom drive for use init() -> None  Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized. There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.
   quit()
 uninitialize a cdrom drive for use quit() -> None  Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.
   get_init()
 true if this cd device initialized get_init() -> bool  Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.
   play()
 start playing audio play(track, start=None, end=None) -> None  Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played. If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc. See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback. Note, track 0 is the first track on the CD. Track numbers start at zero.
   stop()
 stop audio playback stop() -> None  Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.
   pause()
 temporarily stop audio playback pause() -> None  Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing. Note, track 0 is the first track on the CD. Track numbers start at zero.
   resume()
 unpause audio playback resume() -> None  Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.
   eject()
 eject or open the cdrom drive eject() -> None  This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.
   get_id()
 the index of the cdrom drive get_id() -> id  Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.
   get_name()
 the system name of the cdrom drive get_name() -> name  Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.
   get_busy()
 true if the drive is playing audio get_busy() -> bool  Returns True if the drive busy playing back audio.
   get_paused()
 true if the drive is paused get_paused() -> bool  Returns True if the drive is currently paused.
   get_current()
 the current audio playback position get_current() -> track, seconds  Returns both the current track and time of that track. This method works when the drive is either playing or paused. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_empty()
 False if a cdrom is in the drive get_empty() -> bool  Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.
   get_numtracks()
 the number of tracks on the cdrom get_numtracks() -> count  Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.
   get_track_audio()
 true if the cdrom track has audio data get_track_audio(track) -> bool  Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_all()
 get all track information get_all() -> [(audio, start, end, length), ...]  Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.
   get_track_start()
 start time of a cdrom track get_track_start(track) -> seconds  Return the absolute time in seconds where at start of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.
   get_track_length()
 length of a cdrom track get_track_length(track) -> seconds  Return a floating point value in seconds of the length of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.


eject()
 eject or open the cdrom drive eject() -> None  This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped.


get_all()
 get all track information get_all() -> [(audio, start, end, length), ...]  Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc.


get_busy()
 true if the drive is playing audio get_busy() -> bool  Returns True if the drive busy playing back audio.


get_current()
 the current audio playback position get_current() -> track, seconds  Returns both the current track and time of that track. This method works when the drive is either playing or paused. Note, track 0 is the first track on the CD. Track numbers start at zero.


get_empty()
 False if a cdrom is in the drive get_empty() -> bool  Return False if there is a cdrom currently in the drive. If the drive is empty this will return True.


get_id()
 the index of the cdrom drive get_id() -> id  Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD.


get_init()
 true if this cd device initialized get_init() -> bool  Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually.


get_name()
 the system name of the cdrom drive get_name() -> name  Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD.


get_numtracks()
 the number of tracks on the cdrom get_numtracks() -> count  Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks.


get_paused()
 true if the drive is paused get_paused() -> bool  Returns True if the drive is currently paused.


get_track_audio()
 true if the cdrom track has audio data get_track_audio(track) -> bool  Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom. Note, track 0 is the first track on the CD. Track numbers start at zero.


get_track_length()
 length of a cdrom track get_track_length(track) -> seconds  Return a floating point value in seconds of the length of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.


get_track_start()
 start time of a cdrom track get_track_start(track) -> seconds  Return the absolute time in seconds where at start of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.


init()
 initialize a cdrom drive for use init() -> None  Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized. There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two.


pause()
 temporarily stop audio playback pause() -> None  Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing. Note, track 0 is the first track on the CD. Track numbers start at zero.


play()
 start playing audio play(track, start=None, end=None) -> None  Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played. If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc. See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback. Note, track 0 is the first track on the CD. Track numbers start at zero.


quit()
 uninitialize a cdrom drive for use quit() -> None  Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile.


resume()
 unpause audio playback resume() -> None  Unpause a paused CD. If the CD is not paused or already playing, this method does nothing.


stop()
 stop audio playback stop() -> None  Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio.


pygame.cdrom.get_count()
 number of cd drives on the system get_count() -> count  Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system.


pygame.cdrom.get_init()
 true if the cdrom module is initialized get_init() -> bool  Test if the cdrom module is initialized or not. This is different than the CD.init() since each drive must also be initialized individually.


pygame.cdrom.init()
 initialize the cdrom module init() -> None  Initialize the cdrom module. This will scan the system for all CD devices. The module must be initialized before any other functions will work. This automatically happens when you call pygame.init(). It is safe to call this function more than once.


pygame.cdrom.quit()
 uninitialize the cdrom module quit() -> None  Uninitialize the cdrom module. After you call this any existing CD objects will no longer work. It is safe to call this function more than once.


pygame.Color

 pygame object for color representations Color(r, g, b) -> Color Color(r, g, b, a=255) -> Color Color(color_value) -> Color  The Color class represents RGBA color values using a value range of 0 to 255 inclusive. It allows basic arithmetic operations — binary operations +, -, *, //, %, and unary operation ~ — to create new colors, supports conversions to other color spaces such as HSV or HSL and lets you adjust single color channels. Alpha defaults to 255 (fully opaque) when not given. The arithmetic operations and correct_gamma() method preserve subclasses. For the binary operators, the class of the returned color is that of the left hand color object of the operator. Color objects support equality comparison with other color objects and 3 or 4 element tuples of integers. There was a bug in pygame 1.8.1 where the default alpha was 0, not 255 like previously. Color objects export the C level array interface. The interface exports a read-only one dimensional unsigned byte array of the same assigned length as the color. For CPython 2.6 and later, the new buffer interface is also exported, with the same characteristics as the array interface. The floor division, //, and modulus, %, operators do not raise an exception for division by zero. Instead, if a color, or alpha, channel in the right hand color is 0, then the result is 0. For example: # These expressions are True
Color(255, 255, 255, 255) // Color(0, 64, 64, 64) == Color(0, 3, 3, 3)
Color(255, 255, 255, 255) % Color(64, 64, 64, 0) == Color(63, 63, 63, 0)
Parameters:

r (int) -- red value in the range of 0 to 255 inclusive
g (int) -- green value in the range of 0 to 255 inclusive
b (int) -- blue value in the range of 0 to 255 inclusive
a (int) -- (optional) alpha value in the range of 0 to 255 inclusive, default is 255
color_value (Color or str or int or tuple(int, int, int, [int]) or list(int, int, int, [int])) -- color value (see note below for the supported formats)  Note  Supported color_value formats:
 - Color object: clones the given Color object - color name str: name of the color to use, e.g. 'red' (all the supported name strings can be found in the colordict module) - HTML color format str: '#rrggbbaa' or '#rrggbb', where rr, gg, bb, and aa are 2-digit hex numbers in the range of 0 to 0xFF inclusive, the aa (alpha) value defaults to 0xFF if not provided - hex number str: '0xrrggbbaa' or '0xrrggbb', where rr, gg, bb, and aa are 2-digit hex numbers in the range of 0x00 to 0xFF inclusive, the aa (alpha) value defaults to 0xFF if not provided - int: int value of the color to use, using hex numbers can make this parameter more readable, e.g. 0xrrggbbaa, where rr, gg, bb, and aa are 2-digit hex numbers in the range of 0x00 to 0xFF inclusive, note that the aa (alpha) value is not optional for the int format and must be provided - tuple/list of int color values: (R, G, B, A) or (R, G, B), where R, G, B, and A are int values in the range of 0 to 255 inclusive, the A (alpha) value defaults to 255 if not provided
Returns:

a newly created Color object
Return type:

Color      Changed in pygame 2.0.0: Support for tuples, lists, and Color objects when creating Color objects.   Changed in pygame 1.9.2: Color objects export the C level array interface.   Changed in pygame 1.9.0: Color objects support 4-element tuples of integers.   Changed in pygame 1.8.1: New implementation of the class.    r
 Gets or sets the red value of the Color. r -> int  The red value of the Color.
   g
 Gets or sets the green value of the Color. g -> int  The green value of the Color.
   b
 Gets or sets the blue value of the Color. b -> int  The blue value of the Color.
   a
 Gets or sets the alpha value of the Color. a -> int  The alpha value of the Color.
   cmy
 Gets or sets the CMY representation of the Color. cmy -> tuple  The CMY representation of the Color. The CMY components are in the ranges C = [0, 1], M = [0, 1], Y = [0, 1]. Note that this will not return the absolutely exact CMY values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the CMY mapping from 0-1 rounding errors may cause the CMY values to differ slightly from what you might expect.
   hsva
 Gets or sets the HSVA representation of the Color. hsva -> tuple  The HSVA representation of the Color. The HSVA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSV values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSV mapping from 0-100 and 0-360 rounding errors may cause the HSV values to differ slightly from what you might expect.
   hsla
 Gets or sets the HSLA representation of the Color. hsla -> tuple  The HSLA representation of the Color. The HSLA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSL values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSL mapping from 0-100 and 0-360 rounding errors may cause the HSL values to differ slightly from what you might expect.
   i1i2i3
 Gets or sets the I1I2I3 representation of the Color. i1i2i3 -> tuple  The I1I2I3 representation of the Color. The I1I2I3 components are in the ranges I1 = [0, 1], I2 = [-0.5, 0.5], I3 = [-0.5, 0.5]. Note that this will not return the absolutely exact I1I2I3 values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the I1I2I3 mapping from 0-1 rounding errors may cause the I1I2I3 values to differ slightly from what you might expect.
   normalize()
 Returns the normalized RGBA values of the Color. normalize() -> tuple  Returns the normalized RGBA values of the Color as floating point values.
   correct_gamma()
 Applies a certain gamma value to the Color. correct_gamma (gamma) -> Color  Applies a certain gamma value to the Color and returns a new Color with the adjusted RGBA values.
   set_length()
 Set the number of elements in the Color to 1,2,3, or 4. set_length(len) -> None  The default Color length is 4. Colors can have lengths 1,2,3 or 4. This is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to get the length of a Color do len(acolor).  New in pygame 1.9.0.
   lerp()
 returns a linear interpolation to the given Color. lerp(Color, float) -> Color  Returns a Color which is a linear interpolation between self and the given Color in RGBA space. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.  New in pygame 2.0.1.
   premul_alpha()
 returns a Color where the r,g,b components have been multiplied by the alpha. premul_alpha() -> Color  Returns a new Color where each of the red, green and blue colour channels have been multiplied by the alpha channel of the original color. The alpha channel remains unchanged. This is useful when working with the BLEND_PREMULTIPLIED blending mode flag for pygame.Surface.blit(), which assumes that all surfaces using it are using pre-multiplied alpha colors.  New in pygame 2.0.0.
   update()
 Sets the elements of the color update(r, g, b) -> None update(r, g, b, a=255) -> None update(color_value) -> None  Sets the elements of the color. See parameters for pygame.Color() for the parameters of this function. If the alpha value was not set it will not change.  New in pygame 2.0.1.


a
 Gets or sets the alpha value of the Color. a -> int  The alpha value of the Color.


b
 Gets or sets the blue value of the Color. b -> int  The blue value of the Color.


cmy
 Gets or sets the CMY representation of the Color. cmy -> tuple  The CMY representation of the Color. The CMY components are in the ranges C = [0, 1], M = [0, 1], Y = [0, 1]. Note that this will not return the absolutely exact CMY values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the CMY mapping from 0-1 rounding errors may cause the CMY values to differ slightly from what you might expect.


correct_gamma()
 Applies a certain gamma value to the Color. correct_gamma (gamma) -> Color  Applies a certain gamma value to the Color and returns a new Color with the adjusted RGBA values.


g
 Gets or sets the green value of the Color. g -> int  The green value of the Color.


hsla
 Gets or sets the HSLA representation of the Color. hsla -> tuple  The HSLA representation of the Color. The HSLA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSL values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSL mapping from 0-100 and 0-360 rounding errors may cause the HSL values to differ slightly from what you might expect.


hsva
 Gets or sets the HSVA representation of the Color. hsva -> tuple  The HSVA representation of the Color. The HSVA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Note that this will not return the absolutely exact HSV values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the HSV mapping from 0-100 and 0-360 rounding errors may cause the HSV values to differ slightly from what you might expect.


i1i2i3
 Gets or sets the I1I2I3 representation of the Color. i1i2i3 -> tuple  The I1I2I3 representation of the Color. The I1I2I3 components are in the ranges I1 = [0, 1], I2 = [-0.5, 0.5], I3 = [-0.5, 0.5]. Note that this will not return the absolutely exact I1I2I3 values for the set RGB values in all cases. Due to the RGB mapping from 0-255 and the I1I2I3 mapping from 0-1 rounding errors may cause the I1I2I3 values to differ slightly from what you might expect.


lerp()
 returns a linear interpolation to the given Color. lerp(Color, float) -> Color  Returns a Color which is a linear interpolation between self and the given Color in RGBA space. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.  New in pygame 2.0.1.


normalize()
 Returns the normalized RGBA values of the Color. normalize() -> tuple  Returns the normalized RGBA values of the Color as floating point values.


premul_alpha()
 returns a Color where the r,g,b components have been multiplied by the alpha. premul_alpha() -> Color  Returns a new Color where each of the red, green and blue colour channels have been multiplied by the alpha channel of the original color. The alpha channel remains unchanged. This is useful when working with the BLEND_PREMULTIPLIED blending mode flag for pygame.Surface.blit(), which assumes that all surfaces using it are using pre-multiplied alpha colors.  New in pygame 2.0.0.


r
 Gets or sets the red value of the Color. r -> int  The red value of the Color.


set_length()
 Set the number of elements in the Color to 1,2,3, or 4. set_length(len) -> None  The default Color length is 4. Colors can have lengths 1,2,3 or 4. This is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to get the length of a Color do len(acolor).  New in pygame 1.9.0.


update()
 Sets the elements of the color update(r, g, b) -> None update(r, g, b, a=255) -> None update(color_value) -> None  Sets the elements of the color. See parameters for pygame.Color() for the parameters of this function. If the alpha value was not set it will not change.  New in pygame 2.0.1.


pygame.cursors

 pygame module for cursor resources  Pygame offers control over the system hardware cursor. Pygame only supports black and white cursors for the system. You control the cursor with functions inside pygame.mouse. This cursors module contains functions for loading and decoding various cursor formats. These allow you to easily store your cursors in external files or directly as encoded python strings. The module includes several standard cursors. The pygame.mouse.set_cursor() function takes several arguments. All those arguments have been stored in a single tuple you can call like this: >>> pygame.mouse.set_cursor(*pygame.cursors.arrow) The following variables can be passed to pygame.mouse.set_cursor function:
 pygame.cursors.arrow pygame.cursors.diamond pygame.cursors.broken_x pygame.cursors.tri_left pygame.cursors.tri_right
 This module also contains a few cursors as formatted strings. You'll need to pass these to pygame.cursors.compile() function before you can use them. The example call would look like this: >>> cursor = pygame.cursors.compile(pygame.cursors.textmarker_strings)
>>> pygame.mouse.set_cursor((8, 16), (0, 0), *cursor) The following strings can be converted into cursor bitmaps with pygame.cursors.compile() :
 pygame.cursors.thickarrow_strings pygame.cursors.sizer_x_strings pygame.cursors.sizer_y_strings pygame.cursors.sizer_xy_strings pygame.cursor.textmarker_strings
   pygame.cursors.compile()
 create binary cursor data from simple strings compile(strings, black='X', white='.', xor='o') -> data, mask  A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function. If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black. The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this thickarrow_strings = (               #sized 24x24
  "XX                      ",
  "XXX                     ",
  "XXXX                    ",
  "XX.XX                   ",
  "XX..XX                  ",
  "XX...XX                 ",
  "XX....XX                ",
  "XX.....XX               ",
  "XX......XX              ",
  "XX.......XX             ",
  "XX........XX            ",
  "XX........XXX           ",
  "XX......XXXXX           ",
  "XX.XXX..XX              ",
  "XXXX XX..XX             ",
  "XX   XX..XX             ",
  "     XX..XX             ",
  "      XX..XX            ",
  "      XX..XX            ",
  "       XXXX             ",
  "       XX               ",
  "                        ",
  "                        ",
  "                        ")
   pygame.cursors.load_xbm()
 load cursor data from an XBM file load_xbm(cursorfile) -> cursor_args load_xbm(cursorfile, maskfile) -> cursor_args  This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images. Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor. The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method. The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function.


pygame.cursors.compile()
 create binary cursor data from simple strings compile(strings, black='X', white='.', xor='o') -> data, mask  A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function. If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black. The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this thickarrow_strings = (               #sized 24x24
  "XX                      ",
  "XXX                     ",
  "XXXX                    ",
  "XX.XX                   ",
  "XX..XX                  ",
  "XX...XX                 ",
  "XX....XX                ",
  "XX.....XX               ",
  "XX......XX              ",
  "XX.......XX             ",
  "XX........XX            ",
  "XX........XXX           ",
  "XX......XXXXX           ",
  "XX.XXX..XX              ",
  "XXXX XX..XX             ",
  "XX   XX..XX             ",
  "     XX..XX             ",
  "      XX..XX            ",
  "      XX..XX            ",
  "       XXXX             ",
  "       XX               ",
  "                        ",
  "                        ",
  "                        ")


pygame.cursors.load_xbm()
 load cursor data from an XBM file load_xbm(cursorfile) -> cursor_args load_xbm(cursorfile, maskfile) -> cursor_args  This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images. Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor. The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method. The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function.