matscipy package
Subpackages
- matscipy.contact_mechanics package
- matscipy.fracture_mechanics package
- Submodules
- matscipy.fracture_mechanics.clusters module
- matscipy.fracture_mechanics.crack module
RectilinearAnisotropicCrack
RectilinearAnisotropicCrack.__init__()
RectilinearAnisotropicCrack.set_plane_stress()
RectilinearAnisotropicCrack.set_plane_strain()
RectilinearAnisotropicCrack.displacements()
RectilinearAnisotropicCrack.deformation_gradient()
RectilinearAnisotropicCrack.stresses()
RectilinearAnisotropicCrack.rtheta()
RectilinearAnisotropicCrack.k1g()
RectilinearAnisotropicCrack.k1gsqG()
displacement_residuals()
displacement_residual()
deformation_gradient_residuals()
deformation_gradient_residual()
CubicCrystalCrack
CubicCrystalCrack.__init__()
CubicCrystalCrack.k1g()
CubicCrystalCrack.k1gsqG()
CubicCrystalCrack.displacements_from_cylinder_coordinates()
CubicCrystalCrack.displacements_from_cartesian_coordinates()
CubicCrystalCrack.displacements()
CubicCrystalCrack.deformation_gradient_from_cylinder_coordinates()
CubicCrystalCrack.deformation_gradient_from_cartesian_coordinates()
CubicCrystalCrack.deformation_gradient()
CubicCrystalCrack.crack_tip_position()
CubicCrystalCrack.crack_tip_position_y()
CubicCrystalCrack.scale_displacements()
CubicCrystalCrack.stresses_from_cylinder_coordinates()
CubicCrystalCrack.stresses_from_cartesian_coordinates()
CubicCrystalCrack.stresses()
SinclairCrack
SinclairCrack.__init__()
SinclairCrack.pack()
SinclairCrack.unpack()
SinclairCrack.get_dofs()
SinclairCrack.set_dofs()
SinclairCrack.u_cle()
SinclairCrack.fit_cle()
SinclairCrack.update_atoms()
SinclairCrack.set_atoms()
SinclairCrack.get_crack_tip_force()
SinclairCrack.get_xdot()
SinclairCrack.get_k_force()
SinclairCrack.get_forces()
SinclairCrack.update_precon()
SinclairCrack.get_precon()
SinclairCrack.optimize()
SinclairCrack.get_potential_energy()
SinclairCrack.rescale_k()
SinclairCrack.arc_length_continuation()
SinclairCrack.plot()
SinclairCrack.animate()
isotropic_modeI_crack_tip_stress_field()
isotropic_modeI_crack_tip_displacement_field()
IsotropicStressField
strain_to_G()
G_to_strain()
get_strain()
get_energy_release_rate()
get_stress_intensity_factor()
fit_crack_stress_field()
find_tip_coordination()
find_tip_broken_bonds()
find_tip_stress_field()
plot_stress_fields()
thin_strip_displacement_y()
print_crack_system()
ConstantStrainRate
- matscipy.fracture_mechanics.crackpathsel module
- matscipy.fracture_mechanics.energy_release module
- matscipy.fracture_mechanics.idealbrittlesolid module
triangular_lattice_slab()
find_triangles_2d()
IdealBrittleSolid
IdealBrittleSolid.implemented_properties
IdealBrittleSolid.default_parameters
IdealBrittleSolid.__init__()
IdealBrittleSolid.set_reference_crystal()
IdealBrittleSolid.calculate()
IdealBrittleSolid.get_wave_speeds()
IdealBrittleSolid.get_elastic_moduli()
IdealBrittleSolid.get_youngs_modulus()
IdealBrittleSolid.get_poisson_ratio()
IdealBrittleSolid.band_structure()
IdealBrittleSolid.calculate_numerical_forces()
IdealBrittleSolid.calculate_numerical_stress()
IdealBrittleSolid.calculate_properties()
IdealBrittleSolid.calculation_required()
IdealBrittleSolid.check_state()
IdealBrittleSolid.directory
IdealBrittleSolid.discard_results_on_any_change
IdealBrittleSolid.export_properties()
IdealBrittleSolid.get_atoms()
IdealBrittleSolid.get_charges()
IdealBrittleSolid.get_default_parameters()
IdealBrittleSolid.get_dipole_moment()
IdealBrittleSolid.get_forces()
IdealBrittleSolid.get_magnetic_moment()
IdealBrittleSolid.get_magnetic_moments()
IdealBrittleSolid.get_potential_energies()
IdealBrittleSolid.get_potential_energy()
IdealBrittleSolid.get_property()
IdealBrittleSolid.get_stress()
IdealBrittleSolid.get_stresses()
IdealBrittleSolid.ignored_changes
IdealBrittleSolid.label
IdealBrittleSolid.read()
IdealBrittleSolid.read_atoms()
IdealBrittleSolid.reset()
IdealBrittleSolid.set()
IdealBrittleSolid.set_label()
IdealBrittleSolid.todict()
find_crack_tip()
set_initial_velocities()
set_constraints()
extend_strip()
- Module contents
- matscipy.calculators package
Submodules
matscipy.angle_distribution module
- matscipy.angle_distribution.angle_distribution(i, j, dr, nbins, *args)
Compute a bond angle distribution from a neighbour list.
- Parameters:
i (array_like) – Neighbour list, including list of distance vectors.
j (array_like) – Neighbour list, including list of distance vectors.
dr (array_like) – Neighbour list, including list of distance vectors.
nbins (int) – Number of bins for bond angle histogram.
cutoff (float, optional) – Bond length cutoff, i.e. consider only bonds shorter than this length.
matscipy.atomic_strain module
Compute deformation gradient tensor and D^2_min measure for non-affine displacements. See: Falk, Langer, Phys. Rev. E 57, 7192 (1998)
- matscipy.atomic_strain.get_XIJ(nat, i_now, dr_now, dr_old)
Calculates the X_{ij} matrix
- matscipy.atomic_strain.get_YIJ(nat, i_now, dr_old)
Calculates the Y_{ij} matrix
- matscipy.atomic_strain.array_inverse(A)
Compute inverse for each matrix in a list of matrices. This is faster than calling numpy.linalg.inv for each matrix.
- matscipy.atomic_strain.get_delta_plus_epsilon_dgesv(nat, i_now, dr_now, dr_old)
Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix
- matscipy.atomic_strain.get_delta_plus_epsilon(nat, i_now, dr_now, dr_old)
Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix
- matscipy.atomic_strain.get_D_square_min(atoms_now, atoms_old, i_now, j_now, delta_plus_epsilon=None)
Calculate the D^2_min norm of Falk and Langer
- matscipy.atomic_strain.atomic_strain(atoms_now, atoms_old, cutoff=None, neighbours=None)
Calculate deformation gradient tensor and D^2_min measure for non-affine displacements. See: Falk, Langer, Phys. Rev. B 57, 7192 (1998)
Parameters:
- atoms_nowase.Atoms
Current atomic configuration
- atoms_oldase.Atoms
Reference atomic configuration
- cutofffloat
Neighbor list cutoff.
- neighbours( array_like, array_like )
Neighbor list. Automatically computed if not provided.
Returns:
- delta_plus_epsilonarray
3x3 deformation gradient tensor for each atom.
- residualarray
D^2_min norm for each atom
matscipy.elasticity module
- matscipy.elasticity.full_3x3_to_Voigt_6_index(i, j)
- matscipy.elasticity.Voigt_6_to_full_3x3_strain(strain_vector)
Form a 3x3 strain matrix from a 6 component vector in Voigt notation
- matscipy.elasticity.Voigt_6_to_full_3x3_stress(stress_vector)
Form a 3x3 stress matrix from a 6 component vector in Voigt notation
- matscipy.elasticity.full_3x3_to_Voigt_6_strain(strain_matrix)
Form a 6 component strain vector in Voigt notation from a 3x3 matrix
- matscipy.elasticity.full_3x3_to_Voigt_6_stress(stress_matrix)
Form a 6 component stress vector in Voigt notation from a 3x3 matrix
- matscipy.elasticity.Voigt_6x6_to_full_3x3x3x3(C)
Convert from the Voigt representation of the stiffness matrix to the full 3x3x3x3 representation.
- Parameters:
C (array_like) – 6x6 stiffness matrix (Voigt notation).
- Returns:
C – 3x3x3x3 stiffness matrix.
- Return type:
array_like
- matscipy.elasticity.full_3x3x3x3_to_Voigt_6x6(C, tol=0.001, check_symmetry=True)
Convert from the full 3x3x3x3 representation of the stiffness matrix to the representation in Voigt notation. Checks symmetry in that process.
- matscipy.elasticity.Voigt_6x6_to_cubic(C)
Convert the Voigt 6x6 representation into the cubic elastic constants C11, C12 and C44.
- matscipy.elasticity.cubic_to_Voigt_6x6(C11, C12, C44)
- matscipy.elasticity.invariants(s, syy=None, szz=None, syz=None, sxz=None, sxy=None, full_3x3_to_Voigt_6=<function full_3x3_to_Voigt_6_stress>)
- matscipy.elasticity.rotate_cubic_elastic_constants(C11, C12, C44, A, tol=1e-06)
Return rotated elastic moduli for a cubic crystal given the elastic constant in standard C11, C12, C44 notation.
- Parameters:
C11 (float) – Cubic elastic moduli.
C12 (float) – Cubic elastic moduli.
C44 (float) – Cubic elastic moduli.
A (array_like) – 3x3 rotation matrix.
- Returns:
C – 6x6 matrix of rotated elastic constants (Voigt notation).
- Return type:
array
- matscipy.elasticity.rotate_elastic_constants(C, A, tol=1e-06)
Return rotated elastic moduli for a general crystal given the elastic constant in Voigt notation.
- Parameters:
C (array_like) – 6x6 matrix of elastic constants (Voigt notation).
A (array_like) – 3x3 rotation matrix.
- Returns:
C – 6x6 matrix of rotated elastic constants (Voigt notation).
- Return type:
array
- class matscipy.elasticity.CubicElasticModuli(C11, C12, C44)
Bases:
object
- tol = 1e-06
- __init__(C11, C12, C44)
Initialize a cubic system with elastic constants C11, C12, C44
- rotate(A)
Compute the rotated stiffness matrix
- stiffness()
Return the elastic constants
- compliance()
Return the compliance coefficients
- matscipy.elasticity.measure_triclinic_elastic_constants(a, delta=0.001, optimizer=None, logfile=None, **kwargs)
Brute-force measurement of elastic constants for a triclinic (general) unit cell.
- Parameters:
a (ase.Atoms) – Atomic configuration.
optimizer (ase.optimizer.*) – Optimizer to use for atomic position. Does not optimize atomic position if set to None.
delta (float) – Strain increment for analytical derivatives of stresses.
- Returns:
C – 6x6 matrix of the elastic constants in Voigt notation.
- Return type:
array_like
- matscipy.elasticity.generate_strained_configs(at0, symmetry='triclinic', N_steps=5, delta=0.01)
Generate a sequence of strained configurations
- Parameters:
a (ase.Atoms) – Bulk crystal configuration - both unit cell and atomic positions should be relaxed before calling this routine.
symmetry (string) – Symmetry to use to determine which strain patterns are necessary. Default is ‘triclininc’, i.e. no symmetry.
N_steps (int) – Number of atomic configurations to generate for each strain pattern. Default is 5. Absolute strain values range from -delta*N_steps/2 to +delta*N_steps/2.
delta (float) – Strain increment for analytical derivatives of stresses. Default 1e-2
- Returns:
Generator which yields a sequence of ase.Atoms instances corresponding
to the minima set of strained conifugurations required to evaluate the
full 6x6 C_ij matrix under the assumed symmetry.
- matscipy.elasticity.fit_elastic_constants(a, symmetry='triclinic', N_steps=5, delta=0.01, optimizer=None, verbose=True, graphics=False, logfile=None, **kwargs)
Compute elastic constants by linear regression of stress vs. strain
- Parameters:
a (ase.Atoms or list of ase.Atoms) – Either a single atomic configuration or a list of strained configurations. If a single configuration is given, it is passed
generate_strained_configs()
along with symmetry, N_steps, and delta to generate the set of strained configurations.symmetry (string) – Symmetry to use to determine which strain patterns are necessary. Default is ‘triclininc’, i.e. no symmetry.
N_steps (int) – Number of atomic configurations to generate for each strain pattern. Default is 5. Absolute strain values range from -delta*N_steps/2 to +delta*N_steps/2.
delta (float) – Strain increment for analytical derivatives of stresses. Default is 1e-2.
optimizer (ase.optimizer.*) – Optimizer to use for atomic positions (internal degrees of freedom) for each applied strain. Initial config a is not optimised, and should already have relaxed cell and atomic positions. Does not optimize atomic positions if set to None.
verbose (bool) – If True, print additional infomation about the quality of fit and summarise results of C_ij and estimated errors. Default True.
graphics (bool) – If True, use
matplotlib.pyplot
to plot the stress vs. strain curve for each C_ij component fitted. Default True.logfile (bool) – Log file to write optimizer output to. Default None (i.e. suppress output).
**kwargs (dict) – Additional arguments to pass to optimizer.run() method e.g. fmax.
- Returns:
C (array_like) – 6x6 matrix of the elastic constants in Voigt notation.
C_err (array_like) – If scipy.stats module is available then error estimates for each C_ij component are obtained from the accuracy of the linear regression. Otherwise an array of np.zeros((6,6)) is returned.
Notes
Code originally adapted from elastics.py script, available from http://github.com/djw/elastic-constants
- matscipy.elasticity.youngs_modulus(C, l)
Calculate approximate Youngs modulus E_l from 6x6 elastic constants matrix C_ij
This is the modulus for loading in the l direction. For the exact answer, taking into account elastic anisotropuy, rotate the C_ij matrix to the correct frame, compute the compliance matrix:
C = ... # 6x6 C_ij matrix in crystal frame A = ... # rotation matrix Cr = rotate_elastic_constants(C, A) S = np.inv(Cr) E_x = 1/S[0, 0] # Young's modulus for a pull in x direction E_y = 1/S[1, 1] # Young's modulus for a pull in y direction E_z = 1/S[0, 0] # Young's modulus for a pull in z direction
Notes
Formula is from W. Brantley, Calculated elastic constants for stress problems associated with semiconductor devices. J. Appl. Phys., 44, 534 (1973).
- matscipy.elasticity.poisson_ratio(C, l, m)
Calculate approximate Poisson ratio
u_{lm} from 6x6 elastic constant matrix C_{ij}
This is the response in m direction to pulling in l direction. Result is dimensionless.
Formula is from W. Brantley, Calculated elastic constants for stress problems associated with semiconductor devices. J. Appl. Phys., 44, 534 (1973).
- matscipy.elasticity.elastic_moduli(C, l=array([1, 0, 0]), R=None, tol=1e-06)
Calculate elastic moduli from 6x6 elastic constant matrix C_{ij}.
The elastic moduli calculated are: Young’s muduli, Poisson’s ratios, shear moduli, bulk mudulus and bulk mudulus tensor.
If a direction l is specified, the system is rotated to have it as its x direction (see Notes for details). If R is specified the system is rotated according to it.
- Parameters:
C (array_like) – 6x6 stiffness matrix (Voigt notation).
l (array_like, optional) – 3D direction vector for pull (the default is the x direction of the original system)
R (array_like, optional) – 3x3 rotation matrix.
tol (float, optional) – tolerance for checking validity of rotation and comparison of vectors.
- Returns:
E (array_like) – Young’s modulus for a stress in each of the three directions of the rotated system.
nu (array_like) – 3x3 matrix with Poisson’s ratios.
Gm (array_like) – 3x3 matrix with shear moduli.
B (float) – Bulk modulus.
K (array_like) – 3x3 matrix with bulk modulus tensor.
Notes
It works by rotating the elastic constant tensor to the desired direction, so it should be valid for arbitrary crystal structures. If only l is specified there is an infinite number of possible rotations. The chosen one is a rotation along the axis orthogonal to the plane defined by the vectors (1, 0, 0) and l.
Bulk modulus tensor as defined in O. Rand and V. Rovenski, “Analytical Methods in Anisotropic Elasticity”, Birkh”auser (2005), pp. 71.
- matscipy.elasticity.nonaffine_elastic_contribution(atoms, eigenvalues=None, eigenvectors=None, pc_parameters=None, cg_parameters={'M': None, 'atol': 1e-05, 'callback': None, 'maxiter': None, 'tol': 1e-05, 'x0': None})
Compute the correction of non-affine displacements to the elasticity tensor. The computation of the occuring inverse of the Hessian matrix is bypassed by using a cg solver.
If eigenvalues and and eigenvectors are given the inverse of the Hessian can be easily computed.
- Parameters:
atoms (ase.Atoms) – Atomic configuration in a local or global minima.
eigenvalues (array) – Eigenvalues in ascending order obtained by diagonalization of Hessian matrix. If given, use eigenvalues and eigenvectors to compute non-affine contribution.
eigenvectors (array) – Eigenvectors corresponding to eigenvalues.
cg_parameters (dict) –
Dictonary for the conjugate-gradient solver.
- x0: {array, matrix}
Starting guess for the solution.
- tol/atol: float, optional
Tolerances for convergence, norm(residual) <= max(tol*norm(b), atol).
- maxiter: int
Maximum number of iterations. Iteration will stop after maxiter steps even if the specified tolerance has not been achieved.
- M: {sparse matrix, dense matrix, LinearOperator}
Preconditioner for A.
- callback: function
User-supplied function to call after each iteration.
pc_parameters (dict) –
Dictonary for the incomplete LU decomposition of the Hessian.
- A: array_like
Sparse matrix to factorize.
- drop_tol: float
Drop tolerance for an incomplete LU decomposition.
- fill_factor: float
Specifies the fill ratio upper bound.
- drop_rule: str
Comma-separated string of drop rules to use.
- permc_spec: str
How to permute the columns of the matrix for sparsity.
- diag_pivot_thresh: float
Threshold used for a diagonal entry to be an acceptable pivot.
- relax: int
Expert option for customizing the degree of relaxing supernodes.
- panel_size: int
Expert option for customizing the panel size.
- options: dict
Dictionary containing additional expert options to SuperLU.
matscipy.hydrogenate module
- matscipy.hydrogenate.hydrogenate(a, cutoff, bond_length, b=None, mask=[True, True, True], exclude=None, vacuum=None)
Hydrogenate a slab of material at its periodic boundary conditions. Boundary conditions are turned into nonperiodic.
- Parameters:
a (ase.Atoms) – Atomic configuration.
cutoff (float) – Cutoff for neighbor counting.
bond_length (float) – X-H bond length for hydrogenation.
b (ase.Atoms, optional) – If present, this is the configuration to hydrogenate. Number of atoms must be identical to a object. All bonds present in a but not present in b will be hydrogenated in b.
mask (list of bool) – Cartesian directions which to hydrogenate, only if b argument is not given.
exclude (array_like) – Boolean array masking atoms to be excluded from hydrogenation.
vacuum (float, optional) – Add this much vacuum after hydrogenation.
- Returns:
a – Atomic configuration of the hydrogenated slab.
- Return type:
ase.Atoms
matscipy.io module
matscipy.logger module
Log status to screen.
- matscipy.logger.hdr_str(s, x)
Return header description strings
- matscipy.logger.hdrfmt_str(x, i)
Return header format string for datatype x
- matscipy.logger.numfmt_str(x, i)
Return numeric format string for datatype x
- matscipy.logger.flatten(x)
- class matscipy.logger.Logger(logfile=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, outevery=1, sepevery=10)
Bases:
object
- __init__(logfile=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, outevery=1, sepevery=10)
- flush()
- set_logfile(logfile)
- pr(s, caller=None, logfile=None)
- warn(s, caller=None)
- st(hdr, vals, force_print=False)
- iteration_finished()
- get_logfile()
- has_logfile()
- set_outevery(outevery)
matscipy.neighbours module
- class matscipy.neighbours.Neighbourhood(atom_types=None)
Bases:
ABC
Abstract class defining a neighbourhood of atoms (pairs, triplets).
- __init__(atom_types=None)
Initialize with atoms and optional atom types.
- abstract get_pairs(atoms: Atoms, quantities: str, cutoff=None)
Return requested data on pairs.
- abstract get_triplets(atoms: Atoms, quantities: str, neighbours=None, cutoff=None, full_connectivity=False)
Return requested data on triplets.
- static mask(pair_distances, cutoff)
- static make_result(quantities, connectivity, D, d, S, accepted_quantities) List
Construct result list.
- static compute_distances(atoms: Atoms, connectivity: ndarray, indices: List[int]) Tuple[ndarray, ndarray]
Return distances and vectors for connectivity.
- connected_triplets(atoms: Atoms, pair_list, triplet_list, nb_pairs)
- triplet_to_numbers(atoms: Atoms, i, j, k)
- find_triplet_types(atoms: Atoms, i, j, k)
Return triplet types from atom ids.
- static lexsort(connectivity: ndarray)
- abstract double_neighbourhood()
Return neighbourhood with double cutoff/connectivity.
- abstract reverse_pair_indices(i_p: ndarray, j_p: ndarray, r_p: ndarray)
Return indices of reverse pairs.
- class matscipy.neighbours.CutoffNeighbourhood(atom_types=None, pair_types=None, triplet_types=None, cutoff: float | dict | None = None)
Bases:
Neighbourhood
Class defining neighbourhood based on proximity.
- __init__(atom_types=None, pair_types=None, triplet_types=None, cutoff: float | dict | None = None)
Initialize with atoms, atom types, pair types and cutoff.
- Parameters:
atom_types (ArrayLike) – atom types array
pair_types (function of 2 atom type arrays) – maps 2 atom types array to an array of pair types
cutoff (float or dict) –
- Cutoff for neighbor search. It can be
A single float: This is a global cutoff for all elements.
A dictionary: This specifies cutoff values for element
pairs. Specification accepts element numbers of symbols. Example: {(1, 6): 1.1, (1, 1): 1.0, (‘C’, ‘C’): 1.85} - A list/array with a per atom value: This specifies the radius of an atomic sphere for each atoms. If spheres overlap, atoms are within each others neighborhood.
- get_pairs(atoms: Atoms, quantities: str, cutoff=None)
Return pairs and quantities from conventional neighbour list.
- get_triplets(atoms: Atoms, quantities: str, neighbours=None, cutoff=None)
Return triplets and quantities from conventional neighbour list.
- double_neighbourhood()
Return neighbourhood with double cutoff/connectivity.
- reverse_pair_indices(i_p: ndarray, j_p: ndarray, r_p: ndarray)
Return indices of reverse pairs.
- static compute_distances(atoms: Atoms, connectivity: ndarray, indices: List[int]) Tuple[ndarray, ndarray]
Return distances and vectors for connectivity.
- connected_triplets(atoms: Atoms, pair_list, triplet_list, nb_pairs)
- find_triplet_types(atoms: Atoms, i, j, k)
Return triplet types from atom ids.
- static lexsort(connectivity: ndarray)
- static make_result(quantities, connectivity, D, d, S, accepted_quantities) List
Construct result list.
- static mask(pair_distances, cutoff)
- triplet_to_numbers(atoms: Atoms, i, j, k)
- class matscipy.neighbours.MolecularNeighbourhood(molecules: Molecules, atom_types=None, double_cutoff=False)
Bases:
Neighbourhood
Class defining neighbourhood based on molecular connectivity.
- __init__(molecules: Molecules, atom_types=None, double_cutoff=False)
Initialze with atoms and molecules.
- double_neighbourhood()
Return neighbourhood with double cutoff/connectivity.
- property molecules
Molecules instance that defines neighbourhood.
- property pair_type
Map atom types to pair types.
- property triplet_type
Map atom types to triplet types.
- static double_connectivity(connectivity: ndarray) ndarray
Sort and stack connectivity + reverse connectivity.
- complete_connectivity(typeoffset: int = 0)
Add angles to pair connectivity.
- get_pairs(atoms: Atoms, quantities: str, cutoff=None)
Return pairs and quantities from connectivities.
- get_triplets(atoms: Atoms, quantities: str, neighbours=None, cutoff=None)
Return triplets and quantities from connectivities.
- find_triplet_types(atoms: Atoms, i, j, k)
Return triplet types from atom ids.
- reverse_pair_indices(i_p: ndarray, j_p: ndarray, r_p: ndarray)
Return indices of reverse pairs.
- static compute_distances(atoms: Atoms, connectivity: ndarray, indices: List[int]) Tuple[ndarray, ndarray]
Return distances and vectors for connectivity.
- connected_triplets(atoms: Atoms, pair_list, triplet_list, nb_pairs)
- static lexsort(connectivity: ndarray)
- static make_result(quantities, connectivity, D, d, S, accepted_quantities) List
Construct result list.
- static mask(pair_distances, cutoff)
- triplet_to_numbers(atoms: Atoms, i, j, k)
- matscipy.neighbours.mic(dr, cell, pbc=None)
Apply minimum image convention to an array of distance vectors.
- Parameters:
dr (array_like) – Array of distance vectors.
cell (array_like) – Simulation cell.
pbc (array_like, optional) – Periodic boundary conditions in x-, y- and z-direction. Default is to assume periodic boundaries in all directions.
- Returns:
dr – Array of distance vectors, wrapped according to the minimum image convention.
- Return type:
array
- matscipy.neighbours.neighbour_list(quantities, atoms=None, cutoff=None, positions=None, cell=None, pbc=None, numbers=None, cell_origin=None)
Compute a neighbor list for an atomic configuration. Atoms outside periodic boundaries are mapped into the box. Atoms outside nonperiodic boundaries are included in the neighbor list but the complexity of neighbor list search for those can become n^2.
The neighbor list is sorted by first atom index ‘i’, but not by second atom index ‘j’.
The neighbour list accepts either an ASE Atoms object or positions and cell vectors individually.
- quantitiesstr
Quantities to compute by the neighbor list algorithm. Each character in this string defines a quantity. They are returned in a tuple of the same order. Possible quantities are
‘i’ : first atom index ‘j’ : second atom index ‘d’ : absolute distance ‘D’ : distance vector ‘S’ : shift vector (number of cell boundaries crossed by the bond
between atom i and j). With the shift vector S, the distances D between atoms can be computed from: D = a.positions[j]-a.positions[i]+S.dot(a.cell)
- atomsase.Atoms
Atomic configuration. (Default: None)
- cutofffloat or dict
- Cutoff for neighbor search. It can be
A single float: This is a global cutoff for all elements.
A dictionary: This specifies cutoff values for element pairs. Specification accepts element numbers of symbols. Example: {(1, 6): 1.1, (1, 1): 1.0, (‘C’, ‘C’): 1.85}
A list/array with a per atom value: This specifies the radius of an atomic sphere for each atoms. If spheres overlap, atoms are within each others neighborhood.
- positionsarray_like
Atomic positions. (Default: None)
- cellarray_like
Cell vectors as a 3x3 matrix. (Default: Shrink wrapped cell)
- pbcarray_like
3-vector containing periodic boundary conditions in all three directions. (Default: Nonperiodic box)
- numbersarray_like
Array containing the atomic numbers.
- i, j, …array
Tuple with arrays for each quantity specified above. Indices in i are returned in ascending order 0..len(a), but the order of (i,j) pairs is not guaranteed.
Examples assume Atoms object a and numpy imported as np. 1. Coordination counting:
i = neighbor_list(‘i’, a, 1.85) coord = np.bincount(i)
- Coordination counting with different cutoffs for each pair of species
- i = neighbor_list(‘i’, a,
{(‘H’, ‘H’): 1.1, (‘C’, ‘H’): 1.3, (‘C’, ‘C’): 1.85})
coord = np.bincount(i)
- Pair distribution function:
d = neighbor_list(‘d’, a, 10.00) h, bin_edges = np.histogram(d, bins=100) pdf = h/(4*np.pi/3*(bin_edges[1:]**3 - bin_edges[:-1]**3)) * a.get_volume()/len(a)
- Pair potential:
i, j, d, D = neighbor_list(‘ijdD’, a, 5.0) energy = (-C/d**6).sum() pair_forces = (6*C/d**5 * (D/d).T).T forces_x = np.bincount(j, weights=pair_forces[:, 0], minlength=len(a)) - np.bincount(i, weights=pair_forces[:, 0], minlength=len(a)) forces_y = np.bincount(j, weights=pair_forces[:, 1], minlength=len(a)) - np.bincount(i, weights=pair_forces[:, 1], minlength=len(a)) forces_z = np.bincount(j, weights=pair_forces[:, 2], minlength=len(a)) - np.bincount(i, weights=pair_forces[:, 2], minlength=len(a))
- Dynamical matrix for a pair potential stored in a block sparse format:
from scipy.sparse import bsr_matrix i, j, dr, abs_dr = neighbor_list(‘ijDd’, atoms) energy = (dr.T / abs_dr).T dynmat = -(dde * (energy.reshape(-1, 3, 1) * energy.reshape(-1, 1, 3)).T).T -(de / abs_dr * (np.eye(3, dtype=energy.dtype) - (energy.reshape(-1, 3, 1) * energy.reshape(-1, 1, 3))).T).T dynmat_bsr = bsr_matrix((dynmat, j, first_i), shape=(3*len(a), 3*len(a)))
dynmat_diag = np.empty((len(a), 3, 3)) for x in range(3):
- for y in range(3):
dynmat_diag[:, x, y] = -np.bincount(i, weights=dynmat[:, x, y])
- dynmat_bsr += bsr_matrix((dynmat_diag, np.arange(len(a)),
np.arange(len(a) + 1)),
shape=(3 * len(a), 3 * len(a)))
i_n, j_n, dr_nc, abs_dr_n = neighbour_list(‘ijDd’, atoms, dict)
- e_nc = (dr_nc.T/abs_dr_n).T
D_ncc = -(dde_n * (e_nc.reshape(-1,3,1) * e_nc.reshape(-1,1,3)).T).T D_ncc += -(de_n/abs_dr_n * (np.eye(3, dtype=e_nc.dtype) - (e_nc.reshape(-1,3,1) * e_nc.reshape(-1,1,3))).T).T
D = bsr_matrix((D_ncc, j_n, first_i), shape=(3*nat,3*nat))
Ddiag_icc = np.empty((nat,3,3)) for x in range(3):
- for y in range(3):
Ddiag_icc[:,x,y] = -np.bincount(i_n, weights = D_ncc[:,x,y])
D += bsr_matrix((Ddiag_icc,np.arange(nat),np.arange(nat+1)), shape=(3*nat,3*nat))
return D
- matscipy.neighbours.triplet_list(first_neighbours, abs_dr_p=None, cutoff=None, i_p=None, j_p=None)
Compute a triplet list for an atomic configuration. The triple list is a mask that can be applied to the corresponding neighbour list to mask triplet properties. The triplet list accepts an first_neighbour array (generated by first_neighbours) as input.
- Parameters:
first_neighbours (array) – adresses of the first time an atom occours in the neighour list
- Returns:
ij_t, ik_t (array) – lists of adresses that form triples in the pair lists
jk_t (array (if and only if i_p, j_p, first_i != None)) – list of pairs jk that connect each triplet ij, ik between atom j and k
Example
i_n, j_n, abs_dr_p = neighbour_list(‘ijd’, atoms=atoms, cutoff=cutoff)
first_i = np.array([0, 2, 6, 10], dtype=’int32’) a = triplet_list(first_i, [2.2]*9+[3.0], 2.6)
# one may obtain first_ij by using find_ij = first_neighbours(len(i_p), ij_t) # or (slower but less parameters and more general, # i.e for every ordered list) first_ij = get_jump_indicies(ij_t)
- matscipy.neighbours.find_indices_of_reversed_pairs(i_n, j_n, abs_dr_n)
Find neighbor list indices where reversed pairs are stored
Given list of identifiers of neighbor atoms i_n and j_n, determines the list of indices reverse into the neighbor list where each pair is reversed, i.e. i_n[reverse[n]]=j_n[n] and j_n[reverse[n]]=i_n[n] for each index n in the neighbor list
In the case of small periodic systems, one needs to be careful, because the same pair may appear more than one time, with different pair distances. Therefore, the pair distance must be taken into account.
We assume that there is in fact one reversed pair for every pair. However, we do not check this assumption in order to avoid overhead.
- Parameters:
i_n (array_like) – array of atom identifiers
j_n (array_like) – array of atom identifiers
abs_dr_n (array_like) – pair distances
- Returns:
reverse – array of indices into i_n and j_n
- Return type:
numpy.ndarray
- matscipy.neighbours.find_common_neighbours(i_n, j_n, nat)
Find common neighbors of pairs of atoms
For each pair
(i1, j1)
in the neighbor list, find all other pairs(i2, j1)
which share the samej1
. This includes(i1,j1)
itself. In this way, create a list withn
blocks of rows, wheren
is the length of the neighbor list. All rows in a block have the samej1
. Each row corresponds to one triplet(i1, j1 ,i2)
. The number of rows in the block is equal to the total number of neighbors ofj1
.- Parameters:
i_n (array_like) – array of atom identifiers
j_n (array_like) – array of atom identifiers
nat (int) – number of atoms
- Returns:
cnl_i1_i2 (array) – atom numbers i1 and i2
cnl_j1 (array) – shared neighbor of i1 and i2
nl_index_i1_j1 (array) – index in the neighbor list of pair i1, j1
nl_index_i2_j1 (array) – index in the neighbor list of pair i2, j1
Examples
Accumulate random numbers for pairs with common neighbors:
>>> import numpy as np >>> import matscipy >>> from ase.lattice.cubic import FaceCenteredCubic >>> from matscipy.neighbours import neighbour_list, find_common_neighbours >>> cutoff = 6.5 >>> atoms = FaceCenteredCubic('Cu', size=[4, 4, 4]) >>> nat = len(atoms.numbers) >>> print(nat) 256 >>> i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd', atoms, cutoff) >>> print(i_n.shape) (22016,) >>> cnl_i1_i2, cnl_j1, nl_index_i1_j1, nl_index_i2_j1 = find_common_neighbours(i_n, j_n, nat) >>> print(cnl_i1_i2.shape) (1893376, 2) >>> unique_pairs_i1_i2, bincount_bins = np.unique(cnl_i1_i2, axis=0, return_inverse=True) >>> print(unique_pairs_i1_i2.shape) (65536, 2) >>> tmp = np.random.rand(cnl_i1_i2.shape[0]) >>> my_sum = np.bincount(bincount_bins, weights=tmp, minlength=unique_pairs_i1_i2.shape[0]) >>> print(my_sum.shape) (65536,)
matscipy.rings module
- matscipy.rings.ring_statistics(a, cutoff, maxlength=-1)
Compute number of shortest path rings in sample. See: D.S. Franzblau, Phys. Rev. B 44, 4925 (1991)
- Parameters:
a (ase.Atoms) – Atomic configuration.
cutoff (float) – Cutoff for neighbor counting.
maxlength (float, optional) – Maximum ring length. Search for rings will stop at this length. This is useful to speed up calculations for large systems.
- Returns:
ringstat – Array with number of shortest path rings.
- Return type:
array
matscipy.socketcalc module
- matscipy.socketcalc.pack_atoms_to_reftraj_str(at, label)
- matscipy.socketcalc.pack_atoms_to_xyz_str(at, label)
- matscipy.socketcalc.unpack_reftraj_str_to_atoms(data)
- matscipy.socketcalc.pack_results_to_reftraj_output_str(at)
- matscipy.socketcalc.unpack_reftraj_output_str_to_results(data)
- matscipy.socketcalc.unpack_xyz_str_to_results(data)
- class matscipy.socketcalc.AtomsRequestHandler(request, client_address, server)
Bases:
StreamRequestHandler
- handle()
- __init__(request, client_address, server)
- disable_nagle_algorithm = False
- finish()
- rbufsize = -1
- setup()
- timeout = None
- wbufsize = 0
- class matscipy.socketcalc.AtomsServerSync(server_address, RequestHandlerClass, clients, bind_and_activate=True, max_attempts=3, bgq=False, logger=<matscipy.logger.Logger object>)
Bases:
TCPServer
- allow_reuse_address = True
- __init__(server_address, RequestHandlerClass, clients, bind_and_activate=True, max_attempts=3, bgq=False, logger=<matscipy.logger.Logger object>)
Constructor. May be extended, do not override.
- request_queue_size = 5
- server_activate()
Called by constructor to activate the server.
May be overridden.
- shutdown_clients()
- shutdown()
Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock.
- put(at, client_id, label, force_restart=False)
- join_all()
- get_results()
- address_family = 2
- close_request(request)
Called to clean up an individual request.
- fileno()
Return socket file number.
Interface required by selector.
- finish_request(request, client_address)
Finish one request by instantiating RequestHandlerClass.
- get_request()
Get the request and client address from the socket.
May be overridden.
- handle_error(request, client_address)
Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
- handle_request()
Handle one request, possibly blocking.
Respects self.timeout.
- handle_timeout()
Called if no new request arrives within self.timeout.
Overridden by ForkingMixIn.
- process_request(request, client_address)
Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
- serve_forever(poll_interval=0.5)
Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread.
- server_bind()
Called by constructor to bind the socket.
May be overridden.
- server_close()
Called to clean-up the server.
May be overridden.
- service_actions()
Called by the serve_forever() loop.
May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop.
- shutdown_request(request)
Called to shutdown and close an individual request.
- socket_type = 1
- timeout = None
- verify_request(request, client_address)
Verify the request. May be overridden.
Return True if we should proceed with this request.
- class matscipy.socketcalc.AtomsServerAsync(server_address, RequestHandlerClass, clients, bind_and_activate=True, max_attempts=3, bgq=False, logger=<matscipy.logger.Logger object>)
Bases:
AtomsServerSync
,ThreadingMixIn
Asynchronous (threaded) version of AtomsServer
- shutdown()
Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock.
- shutdown_clients()
- __init__(server_address, RequestHandlerClass, clients, bind_and_activate=True, max_attempts=3, bgq=False, logger=<matscipy.logger.Logger object>)
Constructor. May be extended, do not override.
- address_family = 2
- allow_reuse_address = True
- block_on_close = True
- close_request(request)
Called to clean up an individual request.
- daemon_threads = False
- fileno()
Return socket file number.
Interface required by selector.
- finish_request(request, client_address)
Finish one request by instantiating RequestHandlerClass.
- get_request()
Get the request and client address from the socket.
May be overridden.
- get_results()
- handle_error(request, client_address)
Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
- handle_request()
Handle one request, possibly blocking.
Respects self.timeout.
- handle_timeout()
Called if no new request arrives within self.timeout.
Overridden by ForkingMixIn.
- join_all()
- process_request(request, client_address)
Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
- process_request_thread(request, client_address)
Same as in BaseServer but as a thread.
In addition, exception handling is done here.
- put(at, client_id, label, force_restart=False)
- request_queue_size = 5
- serve_forever(poll_interval=0.5)
Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread.
- server_activate()
Called by constructor to activate the server.
May be overridden.
- server_bind()
Called by constructor to bind the socket.
May be overridden.
- server_close()
Called to clean-up the server.
May be overridden.
- service_actions()
Called by the serve_forever() loop.
May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop.
- shutdown_request(request)
Called to shutdown and close an individual request.
- socket_type = 1
- timeout = None
- verify_request(request, client_address)
Verify the request. May be overridden.
Return True if we should proceed with this request.
- matscipy.socketcalc.AtomsServer
alias of
AtomsServerAsync
- class matscipy.socketcalc.Client(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001)
Bases:
object
Represents a single Client job
Used by AtomsServer to start, restart and shutdown clients running on the Compute Nodes.
- __init__(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001)
- extra_args(label=None)
Return list of additional command line arguments to be passed to client
- start(label=None)
Start an individual client.
Raises RuntimeError if this client is already running.
- shutdown(block=True)
Request a client to shutdown.
If block=True, does not return until shutdown is complete. If block=False, waits for the client to shutdown in a new thread. Check self.waits_thread.isAlive() to see when shutdown has finished. (This function also returns a handle to the wait thread when block=False).
- wait_for_shutdown()
Block until a client has shutdown.
Typically called automatically by shutdown() or start_or_restart().
Shutdown should previously have been initiated by queuing a ‘shutdown’ or ‘restart’ request. Waits CLIENT_TIMEOUT for graceful shutdown. If client is still alive, a SIGTERM signal is sent. If this has had no effect after a further CLIENT_TIMEOUT, then a SIGKILL is sent. Does not return until the SIGKILL has taken effect.
This function also marks shutdown task as complete in servers’s input_q for this client.
- start_or_restart(at, label, restart=False)
Start or restart a client
If restart=True, wait for previous client to shutdown first. Calls write_input_files() followed by start().
- preprocess(at, label, force_restart=False)
Prepare client for a calculation.
Starts client if this is the first task for it, or schedules a restart if new configuration is not compatible with the last one submitted to the queue (see is_compatible() method).
Many be extended in subclasses to e.g. sort the atoms by atomic number. If Atoms object needs to be changed, a copy should be returned rather than updating it inplace.
Returns (at, first_time).
- postprocess(at, label)
Post-process results of calculation.
May be overrriden in subclasses to e.g. reverse sort order applied in preprocess().
- is_compatible(old_at, new_at, label)
Check if new_at and old_at are compatible.
Returns True if calculation can be continued, or False if client must be restarted before it can process new_at.
- write_input_files(at, label)
- class matscipy.socketcalc.QUIPClient(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001, param_files=None)
Bases:
Client
Subclass of Client for running QUIP calculations.
Initial input files are written in extended XYZ format, and subsequent communication is via sockets, in either REFTRAJ or XYZ format.
- __init__(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001, param_files=None)
- write_input_files(at, label)
- extra_args(label=None)
Return list of additional command line arguments to be passed to client
- is_compatible(old_at, new_at, label)
Check if new_at and old_at are compatible.
Returns True if calculation can be continued, or False if client must be restarted before it can process new_at.
- postprocess(at, label)
Post-process results of calculation.
May be overrriden in subclasses to e.g. reverse sort order applied in preprocess().
- preprocess(at, label, force_restart=False)
Prepare client for a calculation.
Starts client if this is the first task for it, or schedules a restart if new configuration is not compatible with the last one submitted to the queue (see is_compatible() method).
Many be extended in subclasses to e.g. sort the atoms by atomic number. If Atoms object needs to be changed, a copy should be returned rather than updating it inplace.
Returns (at, first_time).
- shutdown(block=True)
Request a client to shutdown.
If block=True, does not return until shutdown is complete. If block=False, waits for the client to shutdown in a new thread. Check self.waits_thread.isAlive() to see when shutdown has finished. (This function also returns a handle to the wait thread when block=False).
- start(label=None)
Start an individual client.
Raises RuntimeError if this client is already running.
- start_or_restart(at, label, restart=False)
Start or restart a client
If restart=True, wait for previous client to shutdown first. Calls write_input_files() followed by start().
- wait_for_shutdown()
Block until a client has shutdown.
Typically called automatically by shutdown() or start_or_restart().
Shutdown should previously have been initiated by queuing a ‘shutdown’ or ‘restart’ request. Waits CLIENT_TIMEOUT for graceful shutdown. If client is still alive, a SIGTERM signal is sent. If this has had no effect after a further CLIENT_TIMEOUT, then a SIGKILL is sent. Does not return until the SIGKILL has taken effect.
This function also marks shutdown task as complete in servers’s input_q for this client.
- class matscipy.socketcalc.QMClient(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001)
Bases:
Client
Abstract subclass of Client for QM calculations
- is_compatible(old_at, new_at, label)
Check if new_at and old_at are compatible.
Returns True if calculation can be continued, or False if client must be restarted before it can process new_at.
- __init__(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001)
- extra_args(label=None)
Return list of additional command line arguments to be passed to client
- postprocess(at, label)
Post-process results of calculation.
May be overrriden in subclasses to e.g. reverse sort order applied in preprocess().
- preprocess(at, label, force_restart=False)
Prepare client for a calculation.
Starts client if this is the first task for it, or schedules a restart if new configuration is not compatible with the last one submitted to the queue (see is_compatible() method).
Many be extended in subclasses to e.g. sort the atoms by atomic number. If Atoms object needs to be changed, a copy should be returned rather than updating it inplace.
Returns (at, first_time).
- shutdown(block=True)
Request a client to shutdown.
If block=True, does not return until shutdown is complete. If block=False, waits for the client to shutdown in a new thread. Check self.waits_thread.isAlive() to see when shutdown has finished. (This function also returns a handle to the wait thread when block=False).
- start(label=None)
Start an individual client.
Raises RuntimeError if this client is already running.
- start_or_restart(at, label, restart=False)
Start or restart a client
If restart=True, wait for previous client to shutdown first. Calls write_input_files() followed by start().
- wait_for_shutdown()
Block until a client has shutdown.
Typically called automatically by shutdown() or start_or_restart().
Shutdown should previously have been initiated by queuing a ‘shutdown’ or ‘restart’ request. Waits CLIENT_TIMEOUT for graceful shutdown. If client is still alive, a SIGTERM signal is sent. If this has had no effect after a further CLIENT_TIMEOUT, then a SIGKILL is sent. Does not return until the SIGKILL has taken effect.
This function also marks shutdown task as complete in servers’s input_q for this client.
- write_input_files(at, label)
- class matscipy.socketcalc.VaspClient(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001, **vasp_args)
Bases:
QMClient
Subclass of Client for running VASP calculations.
Initial input files are written in POSCAR, INCAR, POTCAR and KPOINTS formats, and subsequent communicatin is via sockets in REFTRAJ format.
- __init__(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=0.001, **vasp_args)
- preprocess(at, label, force_restart=False)
Prepare client for a calculation.
Starts client if this is the first task for it, or schedules a restart if new configuration is not compatible with the last one submitted to the queue (see is_compatible() method).
Many be extended in subclasses to e.g. sort the atoms by atomic number. If Atoms object needs to be changed, a copy should be returned rather than updating it inplace.
Returns (at, first_time).
- postprocess(at, label)
Post-process results of calculation.
May be overrriden in subclasses to e.g. reverse sort order applied in preprocess().
- write_input_files(at, label)
- extra_args(label=None)
Return list of additional command line arguments to be passed to client
- is_compatible(old_at, new_at, label)
Check if new_at and old_at are compatible.
Returns True if calculation can be continued, or False if client must be restarted before it can process new_at.
- shutdown(block=True)
Request a client to shutdown.
If block=True, does not return until shutdown is complete. If block=False, waits for the client to shutdown in a new thread. Check self.waits_thread.isAlive() to see when shutdown has finished. (This function also returns a handle to the wait thread when block=False).
- start(label=None)
Start an individual client.
Raises RuntimeError if this client is already running.
- start_or_restart(at, label, restart=False)
Start or restart a client
If restart=True, wait for previous client to shutdown first. Calls write_input_files() followed by start().
- wait_for_shutdown()
Block until a client has shutdown.
Typically called automatically by shutdown() or start_or_restart().
Shutdown should previously have been initiated by queuing a ‘shutdown’ or ‘restart’ request. Waits CLIENT_TIMEOUT for graceful shutdown. If client is still alive, a SIGTERM signal is sent. If this has had no effect after a further CLIENT_TIMEOUT, then a SIGKILL is sent. Does not return until the SIGKILL has taken effect.
This function also marks shutdown task as complete in servers’s input_q for this client.
- class matscipy.socketcalc.CastepClient(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=1.0, **castep_args)
Bases:
QMClient
Subclass of Client for running CASTEP calculations.
Initial input files are written in .cell and .param formats, and subsequent communication is via sockets in REFTRAJ format.
- __init__(client_id, exe, env=None, npj=1, ppn=1, block=None, corner=None, shape=None, jobname='socketcalc', rundir=None, fmt='REFTRAJ', parmode=None, mpirun='mpirun', mpirun_args=['-np'], logger=<matscipy.logger.Logger object>, max_pos_diff=1.0, max_cell_diff=1.0, **castep_args)
- preprocess(at, label, force_restart=False)
Prepare client for a calculation.
Starts client if this is the first task for it, or schedules a restart if new configuration is not compatible with the last one submitted to the queue (see is_compatible() method).
Many be extended in subclasses to e.g. sort the atoms by atomic number. If Atoms object needs to be changed, a copy should be returned rather than updating it inplace.
Returns (at, first_time).
- postprocess(at, label)
Post-process results of calculation.
May be overrriden in subclasses to e.g. reverse sort order applied in preprocess().
- write_input_files(at, label)
- extra_args(label=None)
Return list of additional command line arguments to be passed to client
- is_compatible(old_at, new_at, label)
Check if new_at and old_at are compatible.
Returns True if calculation can be continued, or False if client must be restarted before it can process new_at.
- shutdown(block=True)
Request a client to shutdown.
If block=True, does not return until shutdown is complete. If block=False, waits for the client to shutdown in a new thread. Check self.waits_thread.isAlive() to see when shutdown has finished. (This function also returns a handle to the wait thread when block=False).
- start(label=None)
Start an individual client.
Raises RuntimeError if this client is already running.
- start_or_restart(at, label, restart=False)
Start or restart a client
If restart=True, wait for previous client to shutdown first. Calls write_input_files() followed by start().
- wait_for_shutdown()
Block until a client has shutdown.
Typically called automatically by shutdown() or start_or_restart().
Shutdown should previously have been initiated by queuing a ‘shutdown’ or ‘restart’ request. Waits CLIENT_TIMEOUT for graceful shutdown. If client is still alive, a SIGTERM signal is sent. If this has had no effect after a further CLIENT_TIMEOUT, then a SIGKILL is sent. Does not return until the SIGKILL has taken effect.
This function also marks shutdown task as complete in servers’s input_q for this client.
- class matscipy.socketcalc.SocketCalculator(client, ip=None, atoms=None, port=0, logger=<matscipy.logger.Logger object>, bgq=False)
Bases:
Calculator
ASE-compatible calculator which communicates with remote force engines via sockets using a (synchronous) AtomsServer.
- implemented_properties: List[str] = ['energy', 'forces', 'stress']
Properties calculator can handle (energy, forces, …)
- default_parameters: Dict[str, Any] = {}
Default parameters
- name = 'SocketCalculator'
- __init__(client, ip=None, atoms=None, port=0, logger=<matscipy.logger.Logger object>, bgq=False)
Basic calculator implementation.
- restart: str
Prefix for restart file. May contain a directory. Default is None: don’t restart.
- ignore_bad_restart_file: bool
Deprecated, please do not use. Passing more than one positional argument to Calculator() is deprecated and will stop working in the future. Ignore broken or missing restart file. By default, it is an error if the restart file is missing or broken.
- directory: str or PurePath
Working directory in which to read and write files and perform calculations.
- label: str
Name used for all files. Not supported by all calculators. May contain a directory, but please use the directory parameter for that instead.
- atoms: Atoms object
Optional Atoms object to which the calculator will be attached. When restarting, atoms will get its positions and unit-cell updated from file.
- calculate(atoms, properties, system_changes)
Do the calculation.
- properties: list of str
List of what needs to be calculated. Can be any combination of ‘energy’, ‘forces’, ‘stress’, ‘dipole’, ‘charges’, ‘magmom’ and ‘magmoms’.
- system_changes: list of str
List of what has changed since last calculation. Can be any combination of these six: ‘positions’, ‘numbers’, ‘cell’, ‘pbc’, ‘initial_charges’ and ‘initial_magmoms’.
Subclasses need to implement this, but can ignore properties and system_changes if they want. Calculated properties should be inserted into results dictionary like shown in this dummy example:
self.results = {'energy': 0.0, 'forces': np.zeros((len(atoms), 3)), 'stress': np.zeros(6), 'dipole': np.zeros(3), 'charges': np.zeros(len(atoms)), 'magmom': 0.0, 'magmoms': np.zeros(len(atoms))}
The subclass implementation should first call this implementation to set the atoms attribute and create any missing directories.
- band_structure()
Create band-structure object for plotting.
- calculate_numerical_forces(atoms, d=0.001)
Calculate numerical forces using finite difference.
All atoms will be displaced by +d and -d in all directions.
- calculate_numerical_stress(atoms, d=1e-06, voigt=True)
Calculate numerical stress using finite difference.
- calculate_properties(atoms, properties)
This method is experimental; currently for internal use.
- calculation_required(atoms, properties)
- check_state(atoms, tol=1e-15)
Check for any system changes since last calculation.
- property directory: str
- discard_results_on_any_change = False
Whether we purge the results following any change in the set() method.
- export_properties()
- get_atoms()
- get_charges(atoms=None)
- get_default_parameters()
- get_dipole_moment(atoms=None)
- get_forces(atoms=None)
- get_magnetic_moment(atoms=None)
- get_magnetic_moments(atoms=None)
Calculate magnetic moments projected onto atoms.
- get_potential_energies(atoms=None)
- get_potential_energy(atoms=None, force_consistent=False)
- get_property(name, atoms=None, allow_calculation=True)
Get the named property.
- get_stress(atoms=None)
- get_stresses(atoms=None)
the calculator should return intensive stresses, i.e., such that stresses.sum(axis=0) == stress
- ignored_changes: Set[str] = {}
Properties of Atoms which we ignore for the purposes of cache
- property label
- read(label)
Read atoms, parameters and calculated properties from output file.
Read result from self.label file. Raise ReadError if the file is not there. If the file is corrupted or contains an error message from the calculation, a ReadError should also be raised. In case of succes, these attributes must set:
- atoms: Atoms object
The state of the atoms from last calculation.
- parameters: Parameters object
The parameter dictionary.
- results: dict
Calculated properties like energy and forces.
The FileIOCalculator.read() method will typically read atoms and parameters and get the results dict by calling the read_results() method.
- classmethod read_atoms(restart, **kwargs)
- reset()
Clear all information from old calculation.
- set(**kwargs)
Set parameters like set(key1=value1, key2=value2, …).
A dictionary containing the parameters that have been changed is returned.
Subclasses must implement a set() method that will look at the chaneged parameters and decide if a call to reset() is needed. If the changed parameters are harmless, like a change in verbosity, then there is no need to call reset().
The special keyword ‘parameters’ can be used to read parameters from a file.
- set_label(label)
Set label and convert label to directory and prefix.
Examples:
label=’abc’: (directory=’.’, prefix=’abc’)
label=’dir1/abc’: (directory=’dir1’, prefix=’abc’)
label=None: (directory=’.’, prefix=None)
- shutdown()
- todict(skip_default=True)
matscipy.structure_identification module
matscipy.surface module
- matscipy.surface.gcd(a, b)
Calculate the greatest common divisor of a and b
- class matscipy.surface.MillerIndex(v=None, type='direction')
Bases:
ndarray
Representation of a three of four index Miller direction or plane
A
MillerIndex
can be constructed from vector or parsed from a string:x = MillerIndex('-211') y = MillerIndex('111', type='plane') z = x.cross(y) print x # prints "[-211]" print y # prints "(111)", note round brackets denoting a plane print z.latex() assert(angle_between(x,y) == pi/2.) assert(angle_between(y,z) == pi/2.) assert(angle_between(x,z) == pi/2.)
- brackets = {'direction': '[]', 'direction_family': '<>', 'plane': '()', 'plane_family': '{}'}
- all_brackets = ['[', ']', '<', '>', '(', ')', '{', '}']
- latex()
Format this
MillerIndex
as a LaTeX string
- classmethod parse(s)
Parse a Miller index string
- Negative indices can be denoted by:
leading minus sign, e.g.
[11-2]
trailing
b
(for ‘bar’), e.g.112b
LaTeX
\bar{}
, e.g.[11\bar{2}]
(which renders as \([11\bar{2}]\) in LaTeX)
Leading or trailing brackets of various kinds are ignored. i.e.
[001]
,{001}
,(001)
,[001]
,<001>
,001
are all equivalent.Returns an array of components (i,j,k) or (h,k,i,l)
- simplify()
Simplify by dividing through by greatest common denominator
- simplified()
- norm()
- normalised()
- hat()
- cross(other)
- cosine(other)
- angle(other)
- as4()
- as3()
- plane_spacing(a)
- T
View of the transposed array.
Same as
self.transpose()
.Examples
>>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.T array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.T array([1, 2, 3, 4])
See also
- all(axis=None, out=None, keepdims=False, *, where=True)
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See also
numpy.all
equivalent function
- any(axis=None, out=None, keepdims=False, *, where=True)
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See also
numpy.any
equivalent function
- argmax(axis=None, out=None, *, keepdims=False)
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See also
numpy.argmax
equivalent function
- argmin(axis=None, out=None, *, keepdims=False)
Return indices of the minimum values along the given axis.
Refer to numpy.argmin for detailed documentation.
See also
numpy.argmin
equivalent function
- argpartition(kth, axis=-1, kind='introselect', order=None)
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation.
New in version 1.8.0.
See also
numpy.argpartition
equivalent function
- argsort(axis=-1, kind=None, order=None)
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
numpy.argsort
equivalent function
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Copy of the array, cast to a specified type.
- Parameters:
dtype (str or dtype) – Typecode or data-type to which the array is cast.
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ means any data conversions may be done.
subok (bool, optional) – If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
copy (bool, optional) – By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
- Returns:
arr_t – Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
- Return type:
ndarray
Notes
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.
- Raises:
ComplexWarning – When casting from complex to float or int. To avoid this, one should use
a.real.astype(t)
.
Examples
>>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5])
>>> x.astype(int) array([1, 2, 2])
- base
Base object if memory is from some other object.
Examples
The base of an array that owns its memory is None:
>>> x = np.array([1,2,3,4]) >>> x.base is None True
Slicing creates a view, whose memory is shared with x:
>>> y = x[2:] >>> y.base is x True
- byteswap(inplace=False)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
- Parameters:
inplace (bool, optional) – If
True
, swap bytes in-place, default isFalse
.- Returns:
out – The byteswapped array. If inplace is
True
, this is a view to self.- Return type:
ndarray
Examples
>>> A = np.array([1, 256, 8755], dtype=np.int16) >>> list(map(hex, A)) ['0x1', '0x100', '0x2233'] >>> A.byteswap(inplace=True) array([ 256, 1, 13090], dtype=int16) >>> list(map(hex, A)) ['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped
>>> A = np.array([b'ceg', b'fac']) >>> A.byteswap() array([b'ceg', b'fac'], dtype='|S3')
A.newbyteorder().byteswap()
produces an array with the same valuesbut different representation in memory
>>> A = np.array([1, 2, 3]) >>> A.view(np.uint8) array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) >>> A.newbyteorder().byteswap(inplace=True) array([1, 2, 3]) >>> A.view(np.uint8) array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
- choose(choices, out=None, mode='raise')
Use an index array to construct a new array from a set of choices.
Refer to numpy.choose for full documentation.
See also
numpy.choose
equivalent function
- clip(min=None, max=None, out=None, **kwargs)
Return an array whose values are limited to
[min, max]
. One of max or min must be given.Refer to numpy.clip for full documentation.
See also
numpy.clip
equivalent function
- compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
numpy.compress
equivalent function
- conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugate
equivalent function
- conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugate
equivalent function
- copy(order='C')
Return a copy of the array.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and
numpy.copy()
are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
numpy.copy
Similar function with different default behavior
numpy.copyto
Notes
This function is the preferred method for creating an array copy. The function
numpy.copy()
is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.Examples
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x array([[0, 0, 0], [0, 0, 0]])
>>> y array([[1, 2, 3], [4, 5, 6]])
>>> y.flags['C_CONTIGUOUS'] True
- ctypes
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
- Parameters:
None –
- Returns:
c – Possessing attributes data, shape, strides, etc.
- Return type:
Python object
See also
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
- _ctypes.data
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as
self._array_interface_['data'][0]
.Note that unlike
data_as
, a reference will not be kept to the array: code likectypes.c_void_p((a + b).ctypes.data)
will result in a pointer to a deallocated array, and should be spelt(a + b).ctypes.data_as(ctypes.c_void_p)
- _ctypes.shape
A ctypes array of length self.ndim where the basetype is the C-integer corresponding to
dtype('p')
on this platform (see ~numpy.ctypeslib.c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.- Type:
(c_intp*self.ndim)
- _ctypes.strides
A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
- Type:
(c_intp*self.ndim)
- _ctypes.data_as(obj)
Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_
is equivalent toself.data_as(ctypes.c_void_p)
. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data:self.data_as(ctypes.POINTER(ctypes.c_double))
.The returned pointer will keep a reference to the array.
- _ctypes.shape_as(obj)
Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short)
.
- _ctypes.strides_as(obj)
Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong)
.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the
as_parameter
attribute which will return an integer equal to the data attribute.Examples
>>> import ctypes >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) >>> x array([[0, 1], [2, 3]], dtype=int32) >>> x.ctypes.data 31962608 # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents c_uint(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents c_ulong(4294967296) >>> x.ctypes.shape <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary >>> x.ctypes.strides <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
- cumprod(axis=None, dtype=None, out=None)
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
See also
numpy.cumprod
equivalent function
- cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis.
Refer to numpy.cumsum for full documentation.
See also
numpy.cumsum
equivalent function
- data
Python buffer object pointing to the start of the array’s data.
- diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to
numpy.diagonal()
for full documentation.See also
numpy.diagonal
equivalent function
- dot()
- dtype
Data-type of the array’s elements.
Warning
Setting
arr.dtype
is discouraged and may be deprecated in the future. Setting will replace thedtype
without modifying the memory (see also ndarray.view and ndarray.astype).- Parameters:
None –
- Returns:
d
- Return type:
numpy dtype object
See also
ndarray.astype
Cast the values contained in the array to a new data-type.
ndarray.view
Create a view of the same data but a different data-type.
numpy.dtype
Examples
>>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int32') >>> type(x.dtype) <type 'numpy.dtype'>
- dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
- Parameters:
file (str or Path) –
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
- dumps()
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.
- Parameters:
None –
- fill(value)
Fill the array with a scalar value.
- Parameters:
value (scalar) – All elements of a will be assigned this value.
Examples
>>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([1., 1.])
Fill expects a scalar value and always behaves the same as assigning to a single array element. The following is a rare example where this distinction is important:
>>> a = np.array([None, None], dtype=object) >>> a[0] = np.array(3) >>> a array([array(3), None], dtype=object) >>> a.fill(np.array(3)) >>> a array([array(3), array(3)], dtype=object)
Where other forms of assignments will unpack the array being assigned:
>>> a[...] = np.array(3) >>> a array([3, 3], dtype=object)
- flags
Information about the memory layout of the array.
- C_CONTIGUOUS(C)
The data is in a single, C-style contiguous segment.
- F_CONTIGUOUS(F)
The data is in a single, Fortran-style contiguous segment.
- OWNDATA(O)
The array owns the memory it uses or borrows it from another object.
- WRITEABLE(W)
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
- ALIGNED(A)
The data and all elements are aligned appropriately for the hardware.
- WRITEBACKIFCOPY(X)
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
- FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
- FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
- BEHAVED(B)
ALIGNED and WRITEABLE.
- CARRAY(CA)
BEHAVED and C_CONTIGUOUS.
- FARRAY(FA)
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
Notes
The flags object can be accessed dictionary-like (as in
a.flags['WRITEABLE']
), or by using lowercased attribute names (as ina.flags.writeable
). Short flag names are only supported in dictionary access.Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
WRITEBACKIFCOPY can only be set
False
.ALIGNED can only be set
True
if the data is truly aligned.WRITEABLE can only be set
True
if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string.
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension
arr.strides[dim]
may be arbitrary ifarr.shape[dim] == 1
or the array has no elements. It does not generally hold thatself.strides[-1] == self.itemsize
for C-style contiguous arrays orself.strides[0] == self.itemsize
for Fortran-style contiguous arrays is true.
- flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
Examples
>>> x = np.arange(1, 7).reshape(2, 3) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> x.flat[3] 4 >>> x.T array([[1, 4], [2, 5], [3, 6]]) >>> x.T.flat[3] 5 >>> type(x.flat) <class 'numpy.flatiter'>
An assignment example:
>>> x.flat = 3; x array([[3, 3, 3], [3, 3, 3]]) >>> x.flat[[1,4]] = 1; x array([[3, 1, 3], [3, 1, 3]])
- flatten(order='C')
Return a copy of the array collapsed into one dimension.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
- Returns:
y – A copy of the input array, flattened to one dimension.
- Return type:
ndarray
Examples
>>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4])
- getfield(dtype, offset=0)
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
- Parameters:
dtype (str or dtype) – The data type of the view. The dtype size of the view can not be larger than that of the array itself.
offset (int) – Number of bytes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2) >>> x[1, 1] = 2 + 4.j >>> x array([[1.+1.j, 0.+0.j], [0.+0.j, 2.+4.j]]) >>> x.getfield(np.float64) array([[1., 0.], [0., 2.]])
By choosing an offset of 8 bytes we can select the complex part of the array for our view:
>>> x.getfield(np.float64, offset=8) array([[1., 0.], [0., 4.]])
- imag
The imaginary part of the array.
Examples
>>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64')
- item(*args)
Copy an element of an array to a standard Python scalar and return it.
- Parameters:
*args (Arguments (variable number and type)) –
none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.
- Returns:
z – A copy of the specified element of the array as a suitable Python scalar
- Return type:
Standard Python scalar object
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.
Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.item(3) 1 >>> x.item(7) 0 >>> x.item((0, 1)) 2 >>> x.item((2, 2)) 1
- itemset(*args)
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then,
a.itemset(*args)
is equivalent to but faster thana[args] = item
. The item should be a scalar value and args must select a single item in the array a.- Parameters:
*args (Arguments) – If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.
Notes
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.
Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[2, 2, 6], [1, 0, 6], [1, 0, 9]])
- itemsize
Length of one array element in bytes.
Examples
>>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16
- max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See also
numpy.amax
equivalent function
- mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
Returns the average of the array elements along given axis.
Refer to numpy.mean for full documentation.
See also
numpy.mean
equivalent function
- min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See also
numpy.amin
equivalent function
- nbytes
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
See also
sys.getsizeof
Memory consumed by the object itself without parents in case view. This does include memory consumed by non-element attributes.
Examples
>>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480
- ndim
Number of array dimensions.
Examples
>>> x = np.array([1, 2, 3]) >>> x.ndim 1 >>> y = np.zeros((2, 3, 4)) >>> y.ndim 3
- newbyteorder(new_order='S', /)
Return the array with the same data viewed with a different byte order.
Equivalent to:
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data type.
- Parameters:
new_order (string, optional) –
Byte order to force; a value from the byte order specifications below. new_order codes can be any of:
’S’ - swap dtype from current to opposite endian
{‘<’, ‘little’} - little endian
{‘>’, ‘big’} - big endian
{‘=’, ‘native’} - native order, equivalent to sys.byteorder
{‘|’, ‘I’} - ignore (no change to byte order)
The default value (‘S’) results in swapping the current byte order.
- Returns:
new_arr – New array object with the dtype reflecting given change to the byte order.
- Return type:
array
- nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See also
numpy.nonzero
equivalent function
- partition(kth, axis=-1, kind='introselect', order=None)
Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.
New in version 1.8.0.
- Parameters:
kth (int or sequence of ints) –
Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.
Deprecated since version 1.22.0: Passing booleans as index is deprecated.
axis (int, optional) – Axis along which to sort. Default is -1, which means sort along the last axis.
kind ({'introselect'}, optional) – Selection algorithm. Default is ‘introselect’.
order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
numpy.partition
Return a partitioned copy of an array.
argpartition
Indirect partition.
sort
Full sort.
Notes
See
np.partition
for notes on the different algorithms.Examples
>>> a = np.array([3, 4, 2, 1]) >>> a.partition(3) >>> a array([2, 1, 3, 4])
>>> a.partition((1, 3)) >>> a array([1, 2, 3, 4])
- prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)
Return the product of the array elements over the given axis
Refer to numpy.prod for full documentation.
See also
numpy.prod
equivalent function
- ptp(axis=None, out=None, keepdims=False)
Peak to peak (maximum - minimum) value along a given axis.
Refer to numpy.ptp for full documentation.
See also
numpy.ptp
equivalent function
- put(indices, values, mode='raise')
Set
a.flat[n] = values[n]
for all n in indices.Refer to numpy.put for full documentation.
See also
numpy.put
equivalent function
- ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
- real
The real part of the array.
Examples
>>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64')
See also
numpy.real
equivalent function
- repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
numpy.repeat
equivalent function
- reshape(shape, order='C')
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
numpy.reshape
equivalent function
Notes
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example,
a.reshape(10, 11)
is equivalent toa.reshape((10, 11))
.
- resize(new_shape, refcheck=True)
Change shape and size of array in-place.
- Parameters:
new_shape (tuple of ints, or n ints) – Shape of resized array.
refcheck (bool, optional) – If False, reference count will not be checked. Default is True.
- Return type:
None
- Raises:
ValueError – If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.
SystemError – If the order keyword argument is specified. This behaviour is a bug in NumPy.
See also
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
>>> a = np.array([[0, 1], [2, 3]], order='C') >>> a.resize((2, 1)) >>> a array([[0], [1]])
>>> a = np.array([[0, 1], [2, 3]], order='F') >>> a.resize((2, 1)) >>> a array([[0], [2]])
Enlarging an array: as above, but missing entries are filled with zeros:
>>> b = np.array([[0, 1], [2, 3]]) >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple >>> b array([[0, 1, 2], [3, 0, 0]])
Referencing an array prevents resizing…
>>> c = a >>> a.resize((1, 1)) Traceback (most recent call last): ... ValueError: cannot resize an array that references or is referenced ...
Unless refcheck is False:
>>> a.resize((1, 1), refcheck=False) >>> a array([[0]]) >>> c array([[0]])
- round(decimals=0, out=None)
Return a with each element rounded to the given number of decimals.
Refer to numpy.around for full documentation.
See also
numpy.around
equivalent function
- searchsorted(v, side='left', sorter=None)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See also
numpy.searchsorted
equivalent function
- setfield(val, dtype, offset=0)
Put a value into a specified place in a field defined by a data-type.
Place val into a’s field defined by dtype and beginning offset bytes into the field.
- Parameters:
val (object) – Value to be placed in field.
dtype (dtype object) – Data-type of the field in which to place val.
offset (int, optional) – The number of bytes into the field at which to place val.
- Return type:
None
See also
Examples
>>> x = np.eye(3) >>> x.getfield(np.float64) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) >>> x.setfield(3, np.int32) >>> x.getfield(np.int32) array([[3, 3, 3], [3, 3, 3], [3, 3, 3]], dtype=int32) >>> x array([[1.0e+000, 1.5e-323, 1.5e-323], [1.5e-323, 1.0e+000, 1.5e-323], [1.5e-323, 1.5e-323, 1.0e+000]]) >>> x.setfield(np.eye(3), np.int32) >>> x array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
- setflags(write=None, align=None, uic=None)
Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and flag can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
- Parameters:
write (bool, optional) – Describes whether or not a can be written to.
align (bool, optional) – Describes whether or not a is aligned properly for its type.
uic (bool, optional) – Describes whether or not a is a copy of another “base” array.
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.
Examples
>>> y = np.array([[3, 1, 7], ... [2, 0, 0], ... [8, 5, 9]]) >>> y array([[3, 1, 7], [2, 0, 0], [8, 5, 9]]) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False >>> y.setflags(write=0, align=0) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False WRITEBACKIFCOPY : False >>> y.setflags(uic=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot set WRITEBACKIFCOPY flag to True
- shape
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
Warning
Setting
arr.shape
is discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.Examples
>>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: total size of new array must be unchanged >>> np.zeros((4,2))[::2].shape = (-1,) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Incompatible shape for in-place modification. Use `.reshape()` to make a copy with the desired shape.
See also
numpy.shape
Equivalent getter function.
numpy.reshape
Function similar to setting
shape
.ndarray.reshape
Method similar to setting
shape
.
- size
Number of elements in the array.
Equal to
np.prod(a.shape)
, i.e., the product of the array’s dimensions.Notes
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested
np.prod(a.shape)
, which returns an instance ofnp.int_
), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.Examples
>>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30
- sort(axis=-1, kind=None, order=None)
Sort an array in-place. Refer to numpy.sort for full documentation.
- Parameters:
axis (int, optional) – Axis along which to sort. Default is -1, which means sort along the last axis.
kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) –
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0: The ‘stable’ option was added.
order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
numpy.sort
Return a sorted copy of an array.
numpy.argsort
Indirect sort.
numpy.lexsort
Indirect stable sort on multiple keys.
numpy.searchsorted
Find elements in sorted array.
numpy.partition
Partial sort.
Notes
See numpy.sort for notes on the different sorting algorithms.
Examples
>>> a = np.array([[1,4], [3,1]]) >>> a.sort(axis=1) >>> a array([[1, 4], [1, 3]]) >>> a.sort(axis=0) >>> a array([[1, 3], [1, 4]])
Use the order keyword to specify a field to use when sorting a structured array:
>>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) >>> a.sort(order='y') >>> a array([(b'c', 1), (b'a', 2)], dtype=[('x', 'S1'), ('y', '<i8')])
- squeeze(axis=None)
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
numpy.squeeze
equivalent function
- std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
Returns the standard deviation of the array elements along given axis.
Refer to numpy.std for full documentation.
See also
numpy.std
equivalent function
- strides
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element
(i[0], i[1], ..., i[n])
in an array a is:offset = sum(np.array(i) * a.strides)
A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide.
Warning
Setting
arr.strides
is discouraged and may be deprecated in the future. numpy.lib.stride_tricks.as_strided should be preferred to create a new view of the same data in a safer way.Notes
Imagine an array of 32-bit integers (each 4 bytes):
x = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be
(20, 4)
.See also
numpy.lib.stride_tricks.as_strided
Examples
>>> y = np.reshape(np.arange(2*3*4), (2,3,4)) >>> y array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) >>> y.strides (48, 16, 4) >>> y[1,1,1] 17 >>> offset=sum(y.strides * np.array((1,1,1))) >>> offset/y.itemsize 17
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3,5,2,2]) >>> offset = sum(i * x.strides) >>> x[3,5,2,2] 813 >>> offset / x.itemsize 813
- sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
Return the sum of the array elements over the given axis.
Refer to numpy.sum for full documentation.
See also
numpy.sum
equivalent function
- swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
numpy.swapaxes
equivalent function
- take(indices, axis=None, out=None, mode='raise')
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See also
numpy.take
equivalent function
- tobytes(order='C')
Construct Python bytes containing the raw data bytes in the array.
Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the
order
parameter.New in version 1.9.0.
- Parameters:
order ({'C', 'F', 'A'}, optional) – Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.
- Returns:
s – Python bytes exhibiting a copy of a’s raw data.
- Return type:
bytes
See also
frombuffer
Inverse of this operation, construct a 1-dimensional array from Python bytes.
Examples
>>> x = np.array([[0, 1], [2, 3]], dtype='<u2') >>> x.tobytes() b'\x00\x00\x01\x00\x02\x00\x03\x00' >>> x.tobytes('C') == x.tobytes() True >>> x.tobytes('F') b'\x00\x00\x02\x00\x01\x00\x03\x00'
- tofile(fid, sep='', format='%s')
Write array to a file as text or binary (default).
Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().
- Parameters:
fid (file or str or Path) –
An open file object, or a string containing a filename.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
sep (str) – Separator between array items for text output. If “” (empty), a binary file is written, equivalent to
file.write(a.tobytes())
.format (str) – Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.
When fid is a file object, array contents are directly written to the file, bypassing the file object’s
write
method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not supportfileno()
(e.g., BytesIO).
- tolist()
Return the array as an
a.ndim
-levels deep nested list of Python scalars.Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the ~numpy.ndarray.item function.
If
a.ndim
is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.- Parameters:
none –
- Returns:
y – The possibly nested list of array elements.
- Return type:
object, or list of object, or list of list of object, or …
Notes
The array may be recreated via
a = np.array(a.tolist())
, although this may sometimes lose precision.Examples
For a 1D array,
a.tolist()
is almost the same aslist(a)
, except thattolist
changes numpy scalars to Python scalars:>>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [1, 2] >>> type(a_list[0]) <class 'numpy.uint32'> >>> a_tolist = a.tolist() >>> a_tolist [1, 2] >>> type(a_tolist[0]) <class 'int'>
Additionally, for a 2D array,
tolist
applies recursively:>>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]]
The base case for this recursion is a 0D array:
>>> a = np.array(1) >>> list(a) Traceback (most recent call last): ... TypeError: iteration over a 0-d array >>> a.tolist() 1
- tostring(order='C')
A compatibility alias for tobytes, with exactly the same behavior.
Despite its name, it returns bytes not strs.
Deprecated since version 1.19.0.
- trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to numpy.trace for full documentation.
See also
numpy.trace
equivalent function
- transpose(*axes)
Returns a view of the array with axes transposed.
Refer to numpy.transpose for full documentation.
- Parameters:
axes (None, tuple of ints, or n ints) –
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means that the array’s i-th axis becomes the transposed array’s j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form).
- Returns:
p – View of the array with its axes suitably permuted.
- Return type:
ndarray
See also
transpose
Equivalent function.
ndarray.T
Array property returning the array transposed.
ndarray.reshape
Give a new shape to an array without changing its data.
Examples
>>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.transpose() array([1, 2, 3, 4])
- var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
Returns the variance of the array elements, along given axis.
Refer to numpy.var for full documentation.
See also
numpy.var
equivalent function
- view([dtype][, type])
New view of array with the same data.
Note
Passing None for
dtype
is different from omitting the parameter, since the former invokesdtype(None)
which is an alias fordtype('float_')
.- Parameters:
dtype (data-type or ndarray sub-class, optional) – Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the
type
parameter).type (Python type, optional) – Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
Notes
a.view()
is used two different ways:a.view(some_dtype)
ora.view(dtype=some_dtype)
constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.a.view(ndarray_subclass)
ora.view(type=ndarray_subclass)
just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.For
a.view(some_dtype)
, ifsome_dtype
has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the last axis ofa
must be contiguous. This axis will be resized in the result.Changed in version 1.23.0: Only the last axis needs to be contiguous. Previously, the entire array had to be C-contiguous.
Examples
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
Viewing array data using a different type and dtype:
>>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print(type(y)) <class 'numpy.matrix'>
Creating a view on a structured array so it can be used in calculations
>>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.])
Making changes to the view changes the underlying array
>>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
Using a view to convert an array to a recarray:
>>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8)
Views share data:
>>> x[0] = (9, 10) >>> z[0] (9, 10)
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) >>> y = x[:, ::2] >>> y array([[1, 3], [4, 6]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the last axis must be contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 3)], [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
However, views that change dtype are totally fine for arrays with a contiguous last axis, even if the rest of the axes are not C-contiguous:
>>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) >>> x.transpose(1, 0, 2).view(np.int16) array([[[ 256, 770], [3340, 3854]], [[1284, 1798], [4368, 4882]], [[2312, 2826], [5396, 5910]]], dtype=int16)
- matscipy.surface.MillerPlane(v)
Special case of
MillerIndex
withtype="plane"
- matscipy.surface.MillerDirection(v)
Special case of
MillerIndex
withtype="direction"
(the default)
- matscipy.surface.angle_between(a, b)
Angle between crystallographic directions between a=[ijk] and b=[lmn], in radians.
- matscipy.surface.make_unit_slab(unit_cell, axes)
General purpose unit slab creation routine
Only tested with cubic unit cells.
- Code translated from quippy.structures.unit_slab()
https://github.com/libAtoms/QUIP/blob/public/src/libAtoms/Structures.f95
- Parameters:
unit_cell (Atoms) – Atoms object containing primitive unit cell
axes (3x3 array) – Miller indices of desired slab, as columns
- Returns:
slab – Output slab, with axes aligned with x, y, z.
- Return type:
Atoms
Module contents
- matscipy.has_parameter(name)
Test if a parameter has been provided in params.py.
- Parameters:
name (str) – Name of the parameter.
- Returns:
value – Returns True if parameter exists.
- Return type:
bool
- matscipy.parameter(name, default=None, logger=<matscipy.logger.Logger object>)
Read parameter from params.py control file.
- Parameters:
name (str) – Name of the parameter.
default (optional) – Default value. Will be returned if parameter is not present.
- Returns:
Value of the parameter.
- Return type:
value