id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,300
chemlab/chemlab
chemlab/core/system.py
System.where
def where(self, within_of=None, inplace=False, **kwargs): """Return indices that met the conditions""" masks = super(System, self).where(inplace=inplace, **kwargs) def index_to_mask(index, n): val = np.zeros(n, dtype='bool') val[index] = True return val def masks_and(dict1, dict2): return {k: dict1[k] & index_to_mask(dict2[k], len(dict1[k])) for k in dict1 } if within_of is not None: if self.box_vectors is None: raise Exception('Only periodic distance supported') thr, ref = within_of if isinstance(ref, int): a = self.r_array[ref][np.newaxis, np.newaxis, :] # (1, 1, 3,) elif len(ref) == 1: a = self.r_array[ref][np.newaxis, :] # (1, 1, 3) else: a = self.r_array[ref][:, np.newaxis, :] # (2, 1, 3) b = self.r_array[np.newaxis, :, :] dist = periodic_distance(a, b, periodic=self.box_vectors.diagonal()) atoms = (dist <= thr).sum(axis=0, dtype='bool') m = self._propagate_dim(atoms, 'atom') masks = masks_and(masks, m) return masks
python
def where(self, within_of=None, inplace=False, **kwargs): """Return indices that met the conditions""" masks = super(System, self).where(inplace=inplace, **kwargs) def index_to_mask(index, n): val = np.zeros(n, dtype='bool') val[index] = True return val def masks_and(dict1, dict2): return {k: dict1[k] & index_to_mask(dict2[k], len(dict1[k])) for k in dict1 } if within_of is not None: if self.box_vectors is None: raise Exception('Only periodic distance supported') thr, ref = within_of if isinstance(ref, int): a = self.r_array[ref][np.newaxis, np.newaxis, :] # (1, 1, 3,) elif len(ref) == 1: a = self.r_array[ref][np.newaxis, :] # (1, 1, 3) else: a = self.r_array[ref][:, np.newaxis, :] # (2, 1, 3) b = self.r_array[np.newaxis, :, :] dist = periodic_distance(a, b, periodic=self.box_vectors.diagonal()) atoms = (dist <= thr).sum(axis=0, dtype='bool') m = self._propagate_dim(atoms, 'atom') masks = masks_and(masks, m) return masks
[ "def", "where", "(", "self", ",", "within_of", "=", "None", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "masks", "=", "super", "(", "System", ",", "self", ")", ".", "where", "(", "inplace", "=", "inplace", ",", "*", "*", "kwargs", ")", "def", "index_to_mask", "(", "index", ",", "n", ")", ":", "val", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "'bool'", ")", "val", "[", "index", "]", "=", "True", "return", "val", "def", "masks_and", "(", "dict1", ",", "dict2", ")", ":", "return", "{", "k", ":", "dict1", "[", "k", "]", "&", "index_to_mask", "(", "dict2", "[", "k", "]", ",", "len", "(", "dict1", "[", "k", "]", ")", ")", "for", "k", "in", "dict1", "}", "if", "within_of", "is", "not", "None", ":", "if", "self", ".", "box_vectors", "is", "None", ":", "raise", "Exception", "(", "'Only periodic distance supported'", ")", "thr", ",", "ref", "=", "within_of", "if", "isinstance", "(", "ref", ",", "int", ")", ":", "a", "=", "self", ".", "r_array", "[", "ref", "]", "[", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", ":", "]", "# (1, 1, 3,)", "elif", "len", "(", "ref", ")", "==", "1", ":", "a", "=", "self", ".", "r_array", "[", "ref", "]", "[", "np", ".", "newaxis", ",", ":", "]", "# (1, 1, 3)", "else", ":", "a", "=", "self", ".", "r_array", "[", "ref", "]", "[", ":", ",", "np", ".", "newaxis", ",", ":", "]", "# (2, 1, 3)", "b", "=", "self", ".", "r_array", "[", "np", ".", "newaxis", ",", ":", ",", ":", "]", "dist", "=", "periodic_distance", "(", "a", ",", "b", ",", "periodic", "=", "self", ".", "box_vectors", ".", "diagonal", "(", ")", ")", "atoms", "=", "(", "dist", "<=", "thr", ")", ".", "sum", "(", "axis", "=", "0", ",", "dtype", "=", "'bool'", ")", "m", "=", "self", ".", "_propagate_dim", "(", "atoms", ",", "'atom'", ")", "masks", "=", "masks_and", "(", "masks", ",", "m", ")", "return", "masks" ]
Return indices that met the conditions
[ "Return", "indices", "that", "met", "the", "conditions" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L252-L284
16,301
chemlab/chemlab
chemlab/qc/utils.py
_gser
def _gser(a,x): "Series representation of Gamma. NumRec sect 6.1." ITMAX=100 EPS=3.e-7 gln=lgamma(a) assert(x>=0),'x < 0 in gser' if x == 0 : return 0,gln ap = a delt = sum = 1./a for i in range(ITMAX): ap=ap+1. delt=delt*x/ap sum=sum+delt if abs(delt) < abs(sum)*EPS: break else: print('a too large, ITMAX too small in gser') gamser=sum*np.exp(-x+a*np.log(x)-gln) return gamser,gln
python
def _gser(a,x): "Series representation of Gamma. NumRec sect 6.1." ITMAX=100 EPS=3.e-7 gln=lgamma(a) assert(x>=0),'x < 0 in gser' if x == 0 : return 0,gln ap = a delt = sum = 1./a for i in range(ITMAX): ap=ap+1. delt=delt*x/ap sum=sum+delt if abs(delt) < abs(sum)*EPS: break else: print('a too large, ITMAX too small in gser') gamser=sum*np.exp(-x+a*np.log(x)-gln) return gamser,gln
[ "def", "_gser", "(", "a", ",", "x", ")", ":", "ITMAX", "=", "100", "EPS", "=", "3.e-7", "gln", "=", "lgamma", "(", "a", ")", "assert", "(", "x", ">=", "0", ")", ",", "'x < 0 in gser'", "if", "x", "==", "0", ":", "return", "0", ",", "gln", "ap", "=", "a", "delt", "=", "sum", "=", "1.", "/", "a", "for", "i", "in", "range", "(", "ITMAX", ")", ":", "ap", "=", "ap", "+", "1.", "delt", "=", "delt", "*", "x", "/", "ap", "sum", "=", "sum", "+", "delt", "if", "abs", "(", "delt", ")", "<", "abs", "(", "sum", ")", "*", "EPS", ":", "break", "else", ":", "print", "(", "'a too large, ITMAX too small in gser'", ")", "gamser", "=", "sum", "*", "np", ".", "exp", "(", "-", "x", "+", "a", "*", "np", ".", "log", "(", "x", ")", "-", "gln", ")", "return", "gamser", ",", "gln" ]
Series representation of Gamma. NumRec sect 6.1.
[ "Series", "representation", "of", "Gamma", ".", "NumRec", "sect", "6", ".", "1", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L86-L105
16,302
chemlab/chemlab
chemlab/qc/utils.py
_gcf
def _gcf(a,x): "Continued fraction representation of Gamma. NumRec sect 6.1" ITMAX=100 EPS=3.e-7 FPMIN=1.e-30 gln=lgamma(a) b=x+1.-a c=1./FPMIN d=1./b h=d for i in range(1,ITMAX+1): an=-i*(i-a) b=b+2. d=an*d+b if abs(d) < FPMIN: d=FPMIN c=b+an/c if abs(c) < FPMIN: c=FPMIN d=1./d delt=d*c h=h*delt if abs(delt-1.) < EPS: break else: print('a too large, ITMAX too small in gcf') gammcf=np.exp(-x+a*np.log(x)-gln)*h return gammcf,gln
python
def _gcf(a,x): "Continued fraction representation of Gamma. NumRec sect 6.1" ITMAX=100 EPS=3.e-7 FPMIN=1.e-30 gln=lgamma(a) b=x+1.-a c=1./FPMIN d=1./b h=d for i in range(1,ITMAX+1): an=-i*(i-a) b=b+2. d=an*d+b if abs(d) < FPMIN: d=FPMIN c=b+an/c if abs(c) < FPMIN: c=FPMIN d=1./d delt=d*c h=h*delt if abs(delt-1.) < EPS: break else: print('a too large, ITMAX too small in gcf') gammcf=np.exp(-x+a*np.log(x)-gln)*h return gammcf,gln
[ "def", "_gcf", "(", "a", ",", "x", ")", ":", "ITMAX", "=", "100", "EPS", "=", "3.e-7", "FPMIN", "=", "1.e-30", "gln", "=", "lgamma", "(", "a", ")", "b", "=", "x", "+", "1.", "-", "a", "c", "=", "1.", "/", "FPMIN", "d", "=", "1.", "/", "b", "h", "=", "d", "for", "i", "in", "range", "(", "1", ",", "ITMAX", "+", "1", ")", ":", "an", "=", "-", "i", "*", "(", "i", "-", "a", ")", "b", "=", "b", "+", "2.", "d", "=", "an", "*", "d", "+", "b", "if", "abs", "(", "d", ")", "<", "FPMIN", ":", "d", "=", "FPMIN", "c", "=", "b", "+", "an", "/", "c", "if", "abs", "(", "c", ")", "<", "FPMIN", ":", "c", "=", "FPMIN", "d", "=", "1.", "/", "d", "delt", "=", "d", "*", "c", "h", "=", "h", "*", "delt", "if", "abs", "(", "delt", "-", "1.", ")", "<", "EPS", ":", "break", "else", ":", "print", "(", "'a too large, ITMAX too small in gcf'", ")", "gammcf", "=", "np", ".", "exp", "(", "-", "x", "+", "a", "*", "np", ".", "log", "(", "x", ")", "-", "gln", ")", "*", "h", "return", "gammcf", ",", "gln" ]
Continued fraction representation of Gamma. NumRec sect 6.1
[ "Continued", "fraction", "representation", "of", "Gamma", ".", "NumRec", "sect", "6", ".", "1" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L107-L132
16,303
chemlab/chemlab
chemlab/qc/utils.py
dmat
def dmat(c,nocc): "Form the density matrix from the first nocc orbitals of c" return np.dot(c[:,:nocc],c[:,:nocc].T)
python
def dmat(c,nocc): "Form the density matrix from the first nocc orbitals of c" return np.dot(c[:,:nocc],c[:,:nocc].T)
[ "def", "dmat", "(", "c", ",", "nocc", ")", ":", "return", "np", ".", "dot", "(", "c", "[", ":", ",", ":", "nocc", "]", ",", "c", "[", ":", ",", ":", "nocc", "]", ".", "T", ")" ]
Form the density matrix from the first nocc orbitals of c
[ "Form", "the", "density", "matrix", "from", "the", "first", "nocc", "orbitals", "of", "c" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L138-L140
16,304
chemlab/chemlab
chemlab/qc/utils.py
geigh
def geigh(H,S): "Solve the generalized eigensystem Hc = ESc" A = cholorth(S) E,U = np.linalg.eigh(simx(H,A)) return E,np.dot(A,U)
python
def geigh(H,S): "Solve the generalized eigensystem Hc = ESc" A = cholorth(S) E,U = np.linalg.eigh(simx(H,A)) return E,np.dot(A,U)
[ "def", "geigh", "(", "H", ",", "S", ")", ":", "A", "=", "cholorth", "(", "S", ")", "E", ",", "U", "=", "np", ".", "linalg", ".", "eigh", "(", "simx", "(", "H", ",", "A", ")", ")", "return", "E", ",", "np", ".", "dot", "(", "A", ",", "U", ")" ]
Solve the generalized eigensystem Hc = ESc
[ "Solve", "the", "generalized", "eigensystem", "Hc", "=", "ESc" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L168-L172
16,305
chemlab/chemlab
chemlab/utils/neighbors.py
_check_periodic
def _check_periodic(periodic): '''Validate periodic input''' periodic = np.array(periodic) # If it is a matrix if len(periodic.shape) == 2: assert periodic.shape[0] == periodic.shape[1], 'periodic shoud be a square matrix or a flat array' return np.diag(periodic) elif len(periodic.shape) == 1: return periodic else: raise ValueError("periodic argument can be either a 3x3 matrix or a shape 3 array.")
python
def _check_periodic(periodic): '''Validate periodic input''' periodic = np.array(periodic) # If it is a matrix if len(periodic.shape) == 2: assert periodic.shape[0] == periodic.shape[1], 'periodic shoud be a square matrix or a flat array' return np.diag(periodic) elif len(periodic.shape) == 1: return periodic else: raise ValueError("periodic argument can be either a 3x3 matrix or a shape 3 array.")
[ "def", "_check_periodic", "(", "periodic", ")", ":", "periodic", "=", "np", ".", "array", "(", "periodic", ")", "# If it is a matrix", "if", "len", "(", "periodic", ".", "shape", ")", "==", "2", ":", "assert", "periodic", ".", "shape", "[", "0", "]", "==", "periodic", ".", "shape", "[", "1", "]", ",", "'periodic shoud be a square matrix or a flat array'", "return", "np", ".", "diag", "(", "periodic", ")", "elif", "len", "(", "periodic", ".", "shape", ")", "==", "1", ":", "return", "periodic", "else", ":", "raise", "ValueError", "(", "\"periodic argument can be either a 3x3 matrix or a shape 3 array.\"", ")" ]
Validate periodic input
[ "Validate", "periodic", "input" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/neighbors.py#L19-L30
16,306
chemlab/chemlab
chemlab/utils/neighbors.py
count_neighbors
def count_neighbors(coordinates_a, coordinates_b, periodic, r): '''Count the neighbours number of neighbors. :param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3) or a single point of shape (3,) :param np.ndarray coordinates_b: Same as coordinates_a :param np.ndarray periodic: Either a matrix of box vectors (3, 3) or an array of box lengths of shape (3,). Only orthogonal boxes are supported. :param float r: Radius of neighbor search ''' indices = nearest_neighbors(coordinates_a, coordinates_b, periodic, r=r)[0] if len(indices) == 0: return 0 if isinstance(indices[0], collections.Iterable): return [len(ix) for ix in indices] else: return len(indices)
python
def count_neighbors(coordinates_a, coordinates_b, periodic, r): '''Count the neighbours number of neighbors. :param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3) or a single point of shape (3,) :param np.ndarray coordinates_b: Same as coordinates_a :param np.ndarray periodic: Either a matrix of box vectors (3, 3) or an array of box lengths of shape (3,). Only orthogonal boxes are supported. :param float r: Radius of neighbor search ''' indices = nearest_neighbors(coordinates_a, coordinates_b, periodic, r=r)[0] if len(indices) == 0: return 0 if isinstance(indices[0], collections.Iterable): return [len(ix) for ix in indices] else: return len(indices)
[ "def", "count_neighbors", "(", "coordinates_a", ",", "coordinates_b", ",", "periodic", ",", "r", ")", ":", "indices", "=", "nearest_neighbors", "(", "coordinates_a", ",", "coordinates_b", ",", "periodic", ",", "r", "=", "r", ")", "[", "0", "]", "if", "len", "(", "indices", ")", "==", "0", ":", "return", "0", "if", "isinstance", "(", "indices", "[", "0", "]", ",", "collections", ".", "Iterable", ")", ":", "return", "[", "len", "(", "ix", ")", "for", "ix", "in", "indices", "]", "else", ":", "return", "len", "(", "indices", ")" ]
Count the neighbours number of neighbors. :param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3) or a single point of shape (3,) :param np.ndarray coordinates_b: Same as coordinates_a :param np.ndarray periodic: Either a matrix of box vectors (3, 3) or an array of box lengths of shape (3,). Only orthogonal boxes are supported. :param float r: Radius of neighbor search
[ "Count", "the", "neighbours", "number", "of", "neighbors", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/neighbors.py#L77-L97
16,307
chemlab/chemlab
chemlab/mviewer/api/appeareance.py
change_default_radii
def change_default_radii(def_map): """Change the default radii """ s = current_system() rep = current_representation() rep.radii_state.default = [def_map[t] for t in s.type_array] rep.radii_state.reset()
python
def change_default_radii(def_map): """Change the default radii """ s = current_system() rep = current_representation() rep.radii_state.default = [def_map[t] for t in s.type_array] rep.radii_state.reset()
[ "def", "change_default_radii", "(", "def_map", ")", ":", "s", "=", "current_system", "(", ")", "rep", "=", "current_representation", "(", ")", "rep", ".", "radii_state", ".", "default", "=", "[", "def_map", "[", "t", "]", "for", "t", "in", "s", ".", "type_array", "]", "rep", ".", "radii_state", ".", "reset", "(", ")" ]
Change the default radii
[ "Change", "the", "default", "radii" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/appeareance.py#L128-L134
16,308
chemlab/chemlab
chemlab/mviewer/api/appeareance.py
add_post_processing
def add_post_processing(effect, **options): """Apply a post processing effect. **Parameters** effect: string The effect to be applied, choose between ``ssao``, ``outline``, ``fxaa``, ``gamma``. **options: Options used to initialize the effect, check the :doc:`chemlab.graphics.postprocessing` for a complete reference of all the options. **Returns** A string identifier that can be used to reference the applied effect. """ from chemlab.graphics.postprocessing import SSAOEffect, OutlineEffect, FXAAEffect, GammaCorrectionEffect pp_map = {'ssao': SSAOEffect, 'outline': OutlineEffect, 'fxaa': FXAAEffect, 'gamma': GammaCorrectionEffect} pp = viewer.add_post_processing(pp_map[effect], **options) viewer.update() global _counter _counter += 1 str_id = effect + str(_counter) _effect_map[str_id] = pp # saving it for removal for later... return str_id
python
def add_post_processing(effect, **options): """Apply a post processing effect. **Parameters** effect: string The effect to be applied, choose between ``ssao``, ``outline``, ``fxaa``, ``gamma``. **options: Options used to initialize the effect, check the :doc:`chemlab.graphics.postprocessing` for a complete reference of all the options. **Returns** A string identifier that can be used to reference the applied effect. """ from chemlab.graphics.postprocessing import SSAOEffect, OutlineEffect, FXAAEffect, GammaCorrectionEffect pp_map = {'ssao': SSAOEffect, 'outline': OutlineEffect, 'fxaa': FXAAEffect, 'gamma': GammaCorrectionEffect} pp = viewer.add_post_processing(pp_map[effect], **options) viewer.update() global _counter _counter += 1 str_id = effect + str(_counter) _effect_map[str_id] = pp # saving it for removal for later... return str_id
[ "def", "add_post_processing", "(", "effect", ",", "*", "*", "options", ")", ":", "from", "chemlab", ".", "graphics", ".", "postprocessing", "import", "SSAOEffect", ",", "OutlineEffect", ",", "FXAAEffect", ",", "GammaCorrectionEffect", "pp_map", "=", "{", "'ssao'", ":", "SSAOEffect", ",", "'outline'", ":", "OutlineEffect", ",", "'fxaa'", ":", "FXAAEffect", ",", "'gamma'", ":", "GammaCorrectionEffect", "}", "pp", "=", "viewer", ".", "add_post_processing", "(", "pp_map", "[", "effect", "]", ",", "*", "*", "options", ")", "viewer", ".", "update", "(", ")", "global", "_counter", "_counter", "+=", "1", "str_id", "=", "effect", "+", "str", "(", "_counter", ")", "_effect_map", "[", "str_id", "]", "=", "pp", "# saving it for removal for later...", "return", "str_id" ]
Apply a post processing effect. **Parameters** effect: string The effect to be applied, choose between ``ssao``, ``outline``, ``fxaa``, ``gamma``. **options: Options used to initialize the effect, check the :doc:`chemlab.graphics.postprocessing` for a complete reference of all the options. **Returns** A string identifier that can be used to reference the applied effect.
[ "Apply", "a", "post", "processing", "effect", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/appeareance.py#L192-L229
16,309
chemlab/chemlab
chemlab/core/spacegroup/cell.py
unit_vector
def unit_vector(x): """Return a unit vector in the same direction as x.""" y = np.array(x, dtype='float') return y/norm(y)
python
def unit_vector(x): """Return a unit vector in the same direction as x.""" y = np.array(x, dtype='float') return y/norm(y)
[ "def", "unit_vector", "(", "x", ")", ":", "y", "=", "np", ".", "array", "(", "x", ",", "dtype", "=", "'float'", ")", "return", "y", "/", "norm", "(", "y", ")" ]
Return a unit vector in the same direction as x.
[ "Return", "a", "unit", "vector", "in", "the", "same", "direction", "as", "x", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L13-L16
16,310
chemlab/chemlab
chemlab/core/spacegroup/cell.py
angle
def angle(x, y): """Return the angle between vectors a and b in degrees.""" return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi
python
def angle(x, y): """Return the angle between vectors a and b in degrees.""" return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi
[ "def", "angle", "(", "x", ",", "y", ")", ":", "return", "arccos", "(", "dot", "(", "x", ",", "y", ")", "/", "(", "norm", "(", "x", ")", "*", "norm", "(", "y", ")", ")", ")", "*", "180.", "/", "pi" ]
Return the angle between vectors a and b in degrees.
[ "Return", "the", "angle", "between", "vectors", "a", "and", "b", "in", "degrees", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L19-L21
16,311
chemlab/chemlab
chemlab/core/spacegroup/cell.py
metric_from_cell
def metric_from_cell(cell): """Calculates the metric matrix from cell, which is given in the Cartesian system.""" cell = np.asarray(cell, dtype=float) return np.dot(cell, cell.T)
python
def metric_from_cell(cell): """Calculates the metric matrix from cell, which is given in the Cartesian system.""" cell = np.asarray(cell, dtype=float) return np.dot(cell, cell.T)
[ "def", "metric_from_cell", "(", "cell", ")", ":", "cell", "=", "np", ".", "asarray", "(", "cell", ",", "dtype", "=", "float", ")", "return", "np", ".", "dot", "(", "cell", ",", "cell", ".", "T", ")" ]
Calculates the metric matrix from cell, which is given in the Cartesian system.
[ "Calculates", "the", "metric", "matrix", "from", "cell", "which", "is", "given", "in", "the", "Cartesian", "system", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L101-L105
16,312
chemlab/chemlab
chemlab/io/datafile.py
add_default_handler
def add_default_handler(ioclass, format, extension=None): """Register a new data handler for a given format in the default handler list. This is a convenience function used internally to setup the default handlers. It can be used to add other handlers at runtime even if this isn't a suggested practice. **Parameters** ioclass: IOHandler subclass format: str A string identifier representing the format extension: str, optional The file extension associated with the format. """ if format in _handler_map: print("Warning: format {} already present.".format(format)) _handler_map[format] = ioclass if extension in _extensions_map: print("Warning: extension {} already handled by {} handler." .format(extension, _extensions_map[extension])) if extension is not None: _extensions_map[extension] = format
python
def add_default_handler(ioclass, format, extension=None): """Register a new data handler for a given format in the default handler list. This is a convenience function used internally to setup the default handlers. It can be used to add other handlers at runtime even if this isn't a suggested practice. **Parameters** ioclass: IOHandler subclass format: str A string identifier representing the format extension: str, optional The file extension associated with the format. """ if format in _handler_map: print("Warning: format {} already present.".format(format)) _handler_map[format] = ioclass if extension in _extensions_map: print("Warning: extension {} already handled by {} handler." .format(extension, _extensions_map[extension])) if extension is not None: _extensions_map[extension] = format
[ "def", "add_default_handler", "(", "ioclass", ",", "format", ",", "extension", "=", "None", ")", ":", "if", "format", "in", "_handler_map", ":", "print", "(", "\"Warning: format {} already present.\"", ".", "format", "(", "format", ")", ")", "_handler_map", "[", "format", "]", "=", "ioclass", "if", "extension", "in", "_extensions_map", ":", "print", "(", "\"Warning: extension {} already handled by {} handler.\"", ".", "format", "(", "extension", ",", "_extensions_map", "[", "extension", "]", ")", ")", "if", "extension", "is", "not", "None", ":", "_extensions_map", "[", "extension", "]", "=", "format" ]
Register a new data handler for a given format in the default handler list. This is a convenience function used internally to setup the default handlers. It can be used to add other handlers at runtime even if this isn't a suggested practice. **Parameters** ioclass: IOHandler subclass format: str A string identifier representing the format extension: str, optional The file extension associated with the format.
[ "Register", "a", "new", "data", "handler", "for", "a", "given", "format", "in", "the", "default", "handler", "list", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/datafile.py#L39-L66
16,313
chemlab/chemlab
chemlab/utils/pbc.py
minimum_image
def minimum_image(coords, pbc): """ Wraps a vector collection of atom positions into the central periodic image or primary simulation cell. Parameters ---------- pos : :class:`numpy.ndarray`, (Nx3) Vector collection of atom positions. Returns ------- wrap : :class:`numpy.ndarray`, (Nx3) Returns atomic positions wrapped into the primary simulation cell, or periodic image. """ # This will do the broadcasting coords = np.array(coords) pbc = np.array(pbc) # For each coordinate this number represents which box we are in image_number = np.floor(coords / pbc) wrap = coords - pbc * image_number return wrap
python
def minimum_image(coords, pbc): """ Wraps a vector collection of atom positions into the central periodic image or primary simulation cell. Parameters ---------- pos : :class:`numpy.ndarray`, (Nx3) Vector collection of atom positions. Returns ------- wrap : :class:`numpy.ndarray`, (Nx3) Returns atomic positions wrapped into the primary simulation cell, or periodic image. """ # This will do the broadcasting coords = np.array(coords) pbc = np.array(pbc) # For each coordinate this number represents which box we are in image_number = np.floor(coords / pbc) wrap = coords - pbc * image_number return wrap
[ "def", "minimum_image", "(", "coords", ",", "pbc", ")", ":", "# This will do the broadcasting", "coords", "=", "np", ".", "array", "(", "coords", ")", "pbc", "=", "np", ".", "array", "(", "pbc", ")", "# For each coordinate this number represents which box we are in", "image_number", "=", "np", ".", "floor", "(", "coords", "/", "pbc", ")", "wrap", "=", "coords", "-", "pbc", "*", "image_number", "return", "wrap" ]
Wraps a vector collection of atom positions into the central periodic image or primary simulation cell. Parameters ---------- pos : :class:`numpy.ndarray`, (Nx3) Vector collection of atom positions. Returns ------- wrap : :class:`numpy.ndarray`, (Nx3) Returns atomic positions wrapped into the primary simulation cell, or periodic image.
[ "Wraps", "a", "vector", "collection", "of", "atom", "positions", "into", "the", "central", "periodic", "image", "or", "primary", "simulation", "cell", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L6-L31
16,314
chemlab/chemlab
chemlab/utils/pbc.py
subtract_vectors
def subtract_vectors(a, b, periodic): '''Returns the difference of the points vec_a - vec_b subject to the periodic boundary conditions. ''' r = a - b delta = np.abs(r) sign = np.sign(r) return np.where(delta > 0.5 * periodic, sign * (periodic - delta), r)
python
def subtract_vectors(a, b, periodic): '''Returns the difference of the points vec_a - vec_b subject to the periodic boundary conditions. ''' r = a - b delta = np.abs(r) sign = np.sign(r) return np.where(delta > 0.5 * periodic, sign * (periodic - delta), r)
[ "def", "subtract_vectors", "(", "a", ",", "b", ",", "periodic", ")", ":", "r", "=", "a", "-", "b", "delta", "=", "np", ".", "abs", "(", "r", ")", "sign", "=", "np", ".", "sign", "(", "r", ")", "return", "np", ".", "where", "(", "delta", ">", "0.5", "*", "periodic", ",", "sign", "*", "(", "periodic", "-", "delta", ")", ",", "r", ")" ]
Returns the difference of the points vec_a - vec_b subject to the periodic boundary conditions.
[ "Returns", "the", "difference", "of", "the", "points", "vec_a", "-", "vec_b", "subject", "to", "the", "periodic", "boundary", "conditions", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L80-L88
16,315
chemlab/chemlab
chemlab/utils/pbc.py
add_vectors
def add_vectors(vec_a, vec_b, periodic): '''Returns the sum of the points vec_a - vec_b subject to the periodic boundary conditions. ''' moved = noperiodic(np.array([vec_a, vec_b]), periodic) return vec_a + vec_b
python
def add_vectors(vec_a, vec_b, periodic): '''Returns the sum of the points vec_a - vec_b subject to the periodic boundary conditions. ''' moved = noperiodic(np.array([vec_a, vec_b]), periodic) return vec_a + vec_b
[ "def", "add_vectors", "(", "vec_a", ",", "vec_b", ",", "periodic", ")", ":", "moved", "=", "noperiodic", "(", "np", ".", "array", "(", "[", "vec_a", ",", "vec_b", "]", ")", ",", "periodic", ")", "return", "vec_a", "+", "vec_b" ]
Returns the sum of the points vec_a - vec_b subject to the periodic boundary conditions.
[ "Returns", "the", "sum", "of", "the", "points", "vec_a", "-", "vec_b", "subject", "to", "the", "periodic", "boundary", "conditions", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L91-L97
16,316
chemlab/chemlab
chemlab/utils/pbc.py
distance_matrix
def distance_matrix(a, b, periodic): '''Calculate a distrance matrix between coordinates sets a and b ''' a = a b = b[:, np.newaxis] return periodic_distance(a, b, periodic)
python
def distance_matrix(a, b, periodic): '''Calculate a distrance matrix between coordinates sets a and b ''' a = a b = b[:, np.newaxis] return periodic_distance(a, b, periodic)
[ "def", "distance_matrix", "(", "a", ",", "b", ",", "periodic", ")", ":", "a", "=", "a", "b", "=", "b", "[", ":", ",", "np", ".", "newaxis", "]", "return", "periodic_distance", "(", "a", ",", "b", ",", "periodic", ")" ]
Calculate a distrance matrix between coordinates sets a and b
[ "Calculate", "a", "distrance", "matrix", "between", "coordinates", "sets", "a", "and", "b" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L100-L105
16,317
chemlab/chemlab
chemlab/utils/pbc.py
geometric_center
def geometric_center(coords, periodic): '''Geometric center taking into account periodic boundaries''' max_vals = periodic theta = 2 * np.pi * (coords / max_vals) eps = np.cos(theta) * max_vals / (2 * np.pi) zeta = np.sin(theta) * max_vals / (2 * np.pi) eps_avg = eps.sum(axis=0) zeta_avg = zeta.sum(axis=0) theta_avg = np.arctan2(-zeta_avg, -eps_avg) + np.pi return theta_avg * max_vals / (2 * np.pi)
python
def geometric_center(coords, periodic): '''Geometric center taking into account periodic boundaries''' max_vals = periodic theta = 2 * np.pi * (coords / max_vals) eps = np.cos(theta) * max_vals / (2 * np.pi) zeta = np.sin(theta) * max_vals / (2 * np.pi) eps_avg = eps.sum(axis=0) zeta_avg = zeta.sum(axis=0) theta_avg = np.arctan2(-zeta_avg, -eps_avg) + np.pi return theta_avg * max_vals / (2 * np.pi)
[ "def", "geometric_center", "(", "coords", ",", "periodic", ")", ":", "max_vals", "=", "periodic", "theta", "=", "2", "*", "np", ".", "pi", "*", "(", "coords", "/", "max_vals", ")", "eps", "=", "np", ".", "cos", "(", "theta", ")", "*", "max_vals", "/", "(", "2", "*", "np", ".", "pi", ")", "zeta", "=", "np", ".", "sin", "(", "theta", ")", "*", "max_vals", "/", "(", "2", "*", "np", ".", "pi", ")", "eps_avg", "=", "eps", ".", "sum", "(", "axis", "=", "0", ")", "zeta_avg", "=", "zeta", ".", "sum", "(", "axis", "=", "0", ")", "theta_avg", "=", "np", ".", "arctan2", "(", "-", "zeta_avg", ",", "-", "eps_avg", ")", "+", "np", ".", "pi", "return", "theta_avg", "*", "max_vals", "/", "(", "2", "*", "np", ".", "pi", ")" ]
Geometric center taking into account periodic boundaries
[ "Geometric", "center", "taking", "into", "account", "periodic", "boundaries" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L123-L134
16,318
chemlab/chemlab
chemlab/utils/pbc.py
radius_of_gyration
def radius_of_gyration(coords, periodic): '''Calculate the square root of the mean distance squared from the center of gravity. ''' gc = geometric_center(coords, periodic) return (periodic_distance(coords, gc, periodic) ** 2).sum() / len(coords)
python
def radius_of_gyration(coords, periodic): '''Calculate the square root of the mean distance squared from the center of gravity. ''' gc = geometric_center(coords, periodic) return (periodic_distance(coords, gc, periodic) ** 2).sum() / len(coords)
[ "def", "radius_of_gyration", "(", "coords", ",", "periodic", ")", ":", "gc", "=", "geometric_center", "(", "coords", ",", "periodic", ")", "return", "(", "periodic_distance", "(", "coords", ",", "gc", ",", "periodic", ")", "**", "2", ")", ".", "sum", "(", ")", "/", "len", "(", "coords", ")" ]
Calculate the square root of the mean distance squared from the center of gravity.
[ "Calculate", "the", "square", "root", "of", "the", "mean", "distance", "squared", "from", "the", "center", "of", "gravity", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L137-L142
16,319
chemlab/chemlab
chemlab/libs/chemspipy.py
find
def find(query): """ Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds """ assert type(query) == str or type(query) == str, 'query not a string object' searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % (urlquote(query), TOKEN) response = urlopen(searchurl) tree = ET.parse(response) elem = tree.getroot() csid_tags = elem.getiterator('{http://www.chemspider.com/}int') compoundlist = [] for tag in csid_tags: compoundlist.append(Compound(tag.text)) return compoundlist if compoundlist else None
python
def find(query): """ Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds """ assert type(query) == str or type(query) == str, 'query not a string object' searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % (urlquote(query), TOKEN) response = urlopen(searchurl) tree = ET.parse(response) elem = tree.getroot() csid_tags = elem.getiterator('{http://www.chemspider.com/}int') compoundlist = [] for tag in csid_tags: compoundlist.append(Compound(tag.text)) return compoundlist if compoundlist else None
[ "def", "find", "(", "query", ")", ":", "assert", "type", "(", "query", ")", "==", "str", "or", "type", "(", "query", ")", "==", "str", ",", "'query not a string object'", "searchurl", "=", "'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s'", "%", "(", "urlquote", "(", "query", ")", ",", "TOKEN", ")", "response", "=", "urlopen", "(", "searchurl", ")", "tree", "=", "ET", ".", "parse", "(", "response", ")", "elem", "=", "tree", ".", "getroot", "(", ")", "csid_tags", "=", "elem", ".", "getiterator", "(", "'{http://www.chemspider.com/}int'", ")", "compoundlist", "=", "[", "]", "for", "tag", "in", "csid_tags", ":", "compoundlist", ".", "append", "(", "Compound", "(", "tag", ".", "text", ")", ")", "return", "compoundlist", "if", "compoundlist", "else", "None" ]
Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds
[ "Search", "by", "Name", "SMILES", "InChI", "InChIKey", "etc", ".", "Returns", "first", "100", "Compounds" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L213-L224
16,320
chemlab/chemlab
chemlab/libs/chemspipy.py
Compound.imageurl
def imageurl(self): """ Return the URL of a png image of the 2D structure """ if self._imageurl is None: self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid return self._imageurl
python
def imageurl(self): """ Return the URL of a png image of the 2D structure """ if self._imageurl is None: self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid return self._imageurl
[ "def", "imageurl", "(", "self", ")", ":", "if", "self", ".", "_imageurl", "is", "None", ":", "self", ".", "_imageurl", "=", "'http://www.chemspider.com/ImagesHandler.ashx?id=%s'", "%", "self", ".", "csid", "return", "self", ".", "_imageurl" ]
Return the URL of a png image of the 2D structure
[ "Return", "the", "URL", "of", "a", "png", "image", "of", "the", "2D", "structure" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L71-L75
16,321
chemlab/chemlab
chemlab/libs/chemspipy.py
Compound.loadextendedcompoundinfo
def loadextendedcompoundinfo(self): """ Load extended compound info from the Mass Spec API """ apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) mf = tree.find('{http://www.chemspider.com/}MF') self._mf = mf.text if mf is not None else None smiles = tree.find('{http://www.chemspider.com/}SMILES') self._smiles = smiles.text if smiles is not None else None inchi = tree.find('{http://www.chemspider.com/}InChI') self._inchi = inchi.text if inchi is not None else None inchikey = tree.find('{http://www.chemspider.com/}InChIKey') self._inchikey = inchikey.text if inchikey is not None else None averagemass = tree.find('{http://www.chemspider.com/}AverageMass') self._averagemass = float(averagemass.text) if averagemass is not None else None molecularweight = tree.find('{http://www.chemspider.com/}MolecularWeight') self._molecularweight = float(molecularweight.text) if molecularweight is not None else None monoisotopicmass = tree.find('{http://www.chemspider.com/}MonoisotopicMass') self._monoisotopicmass = float(monoisotopicmass.text) if monoisotopicmass is not None else None nominalmass = tree.find('{http://www.chemspider.com/}NominalMass') self._nominalmass = float(nominalmass.text) if nominalmass is not None else None alogp = tree.find('{http://www.chemspider.com/}ALogP') self._alogp = float(alogp.text) if alogp is not None else None xlogp = tree.find('{http://www.chemspider.com/}XLogP') self._xlogp = float(xlogp.text) if xlogp is not None else None commonname = tree.find('{http://www.chemspider.com/}CommonName') self._commonname = commonname.text if commonname is not None else None
python
def loadextendedcompoundinfo(self): """ Load extended compound info from the Mass Spec API """ apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) mf = tree.find('{http://www.chemspider.com/}MF') self._mf = mf.text if mf is not None else None smiles = tree.find('{http://www.chemspider.com/}SMILES') self._smiles = smiles.text if smiles is not None else None inchi = tree.find('{http://www.chemspider.com/}InChI') self._inchi = inchi.text if inchi is not None else None inchikey = tree.find('{http://www.chemspider.com/}InChIKey') self._inchikey = inchikey.text if inchikey is not None else None averagemass = tree.find('{http://www.chemspider.com/}AverageMass') self._averagemass = float(averagemass.text) if averagemass is not None else None molecularweight = tree.find('{http://www.chemspider.com/}MolecularWeight') self._molecularweight = float(molecularweight.text) if molecularweight is not None else None monoisotopicmass = tree.find('{http://www.chemspider.com/}MonoisotopicMass') self._monoisotopicmass = float(monoisotopicmass.text) if monoisotopicmass is not None else None nominalmass = tree.find('{http://www.chemspider.com/}NominalMass') self._nominalmass = float(nominalmass.text) if nominalmass is not None else None alogp = tree.find('{http://www.chemspider.com/}ALogP') self._alogp = float(alogp.text) if alogp is not None else None xlogp = tree.find('{http://www.chemspider.com/}XLogP') self._xlogp = float(xlogp.text) if xlogp is not None else None commonname = tree.find('{http://www.chemspider.com/}CommonName') self._commonname = commonname.text if commonname is not None else None
[ "def", "loadextendedcompoundinfo", "(", "self", ")", ":", "apiurl", "=", "'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s'", "%", "(", "self", ".", "csid", ",", "TOKEN", ")", "response", "=", "urlopen", "(", "apiurl", ")", "tree", "=", "ET", ".", "parse", "(", "response", ")", "mf", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}MF'", ")", "self", ".", "_mf", "=", "mf", ".", "text", "if", "mf", "is", "not", "None", "else", "None", "smiles", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}SMILES'", ")", "self", ".", "_smiles", "=", "smiles", ".", "text", "if", "smiles", "is", "not", "None", "else", "None", "inchi", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}InChI'", ")", "self", ".", "_inchi", "=", "inchi", ".", "text", "if", "inchi", "is", "not", "None", "else", "None", "inchikey", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}InChIKey'", ")", "self", ".", "_inchikey", "=", "inchikey", ".", "text", "if", "inchikey", "is", "not", "None", "else", "None", "averagemass", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}AverageMass'", ")", "self", ".", "_averagemass", "=", "float", "(", "averagemass", ".", "text", ")", "if", "averagemass", "is", "not", "None", "else", "None", "molecularweight", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}MolecularWeight'", ")", "self", ".", "_molecularweight", "=", "float", "(", "molecularweight", ".", "text", ")", "if", "molecularweight", "is", "not", "None", "else", "None", "monoisotopicmass", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}MonoisotopicMass'", ")", "self", ".", "_monoisotopicmass", "=", "float", "(", "monoisotopicmass", ".", "text", ")", "if", "monoisotopicmass", "is", "not", "None", "else", "None", "nominalmass", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}NominalMass'", ")", "self", ".", "_nominalmass", "=", "float", "(", "nominalmass", ".", "text", ")", "if", "nominalmass", "is", "not", "None", "else", "None", "alogp", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}ALogP'", ")", "self", ".", "_alogp", "=", "float", "(", "alogp", ".", "text", ")", "if", "alogp", "is", "not", "None", "else", "None", "xlogp", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}XLogP'", ")", "self", ".", "_xlogp", "=", "float", "(", "xlogp", ".", "text", ")", "if", "xlogp", "is", "not", "None", "else", "None", "commonname", "=", "tree", ".", "find", "(", "'{http://www.chemspider.com/}CommonName'", ")", "self", ".", "_commonname", "=", "commonname", ".", "text", "if", "commonname", "is", "not", "None", "else", "None" ]
Load extended compound info from the Mass Spec API
[ "Load", "extended", "compound", "info", "from", "the", "Mass", "Spec", "API" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L154-L180
16,322
chemlab/chemlab
chemlab/libs/chemspipy.py
Compound.image
def image(self): """ Return string containing PNG binary image data of 2D structure image """ if self._image is None: apiurl = 'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._image = tree.getroot().text return self._image
python
def image(self): """ Return string containing PNG binary image data of 2D structure image """ if self._image is None: apiurl = 'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._image = tree.getroot().text return self._image
[ "def", "image", "(", "self", ")", ":", "if", "self", ".", "_image", "is", "None", ":", "apiurl", "=", "'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s'", "%", "(", "self", ".", "csid", ",", "TOKEN", ")", "response", "=", "urlopen", "(", "apiurl", ")", "tree", "=", "ET", ".", "parse", "(", "response", ")", "self", ".", "_image", "=", "tree", ".", "getroot", "(", ")", ".", "text", "return", "self", ".", "_image" ]
Return string containing PNG binary image data of 2D structure image
[ "Return", "string", "containing", "PNG", "binary", "image", "data", "of", "2D", "structure", "image" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L183-L190
16,323
chemlab/chemlab
chemlab/libs/chemspipy.py
Compound.mol
def mol(self): """ Return record in MOL format """ if self._mol is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol = tree.getroot().text return self._mol
python
def mol(self): """ Return record in MOL format """ if self._mol is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol = tree.getroot().text return self._mol
[ "def", "mol", "(", "self", ")", ":", "if", "self", ".", "_mol", "is", "None", ":", "apiurl", "=", "'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s'", "%", "(", "self", ".", "csid", ",", "TOKEN", ")", "response", "=", "urlopen", "(", "apiurl", ")", "tree", "=", "ET", ".", "parse", "(", "response", ")", "self", ".", "_mol", "=", "tree", ".", "getroot", "(", ")", ".", "text", "return", "self", ".", "_mol" ]
Return record in MOL format
[ "Return", "record", "in", "MOL", "format" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L193-L200
16,324
chemlab/chemlab
chemlab/libs/chemspipy.py
Compound.mol3d
def mol3d(self): """ Return record in MOL format with 3D coordinates calculated """ if self._mol3d is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol3d = tree.getroot().text return self._mol3d
python
def mol3d(self): """ Return record in MOL format with 3D coordinates calculated """ if self._mol3d is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol3d = tree.getroot().text return self._mol3d
[ "def", "mol3d", "(", "self", ")", ":", "if", "self", ".", "_mol3d", "is", "None", ":", "apiurl", "=", "'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s'", "%", "(", "self", ".", "csid", ",", "TOKEN", ")", "response", "=", "urlopen", "(", "apiurl", ")", "tree", "=", "ET", ".", "parse", "(", "response", ")", "self", ".", "_mol3d", "=", "tree", ".", "getroot", "(", ")", ".", "text", "return", "self", ".", "_mol3d" ]
Return record in MOL format with 3D coordinates calculated
[ "Return", "record", "in", "MOL", "format", "with", "3D", "coordinates", "calculated" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L203-L210
16,325
chemlab/chemlab
chemlab/graphics/renderers/ballandstick.py
BallAndStickRenderer.update_positions
def update_positions(self, r_array): '''Update the coordinate array r_array''' self.ar.update_positions(r_array) if self.has_bonds: self.br.update_positions(r_array)
python
def update_positions(self, r_array): '''Update the coordinate array r_array''' self.ar.update_positions(r_array) if self.has_bonds: self.br.update_positions(r_array)
[ "def", "update_positions", "(", "self", ",", "r_array", ")", ":", "self", ".", "ar", ".", "update_positions", "(", "r_array", ")", "if", "self", ".", "has_bonds", ":", "self", ".", "br", ".", "update_positions", "(", "r_array", ")" ]
Update the coordinate array r_array
[ "Update", "the", "coordinate", "array", "r_array" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/ballandstick.py#L52-L57
16,326
chemlab/chemlab
chemlab/core/base.py
concatenate_attributes
def concatenate_attributes(attributes): '''Concatenate InstanceAttribute to return a bigger one.''' # We get a template/ tpl = attributes[0] attr = InstanceAttribute(tpl.name, tpl.shape, tpl.dtype, tpl.dim, alias=None) # Special case, not a single array has size bigger than 0 if all(a.size == 0 for a in attributes): return attr else: attr.value = np.concatenate([a.value for a in attributes if a.size > 0], axis=0) return attr
python
def concatenate_attributes(attributes): '''Concatenate InstanceAttribute to return a bigger one.''' # We get a template/ tpl = attributes[0] attr = InstanceAttribute(tpl.name, tpl.shape, tpl.dtype, tpl.dim, alias=None) # Special case, not a single array has size bigger than 0 if all(a.size == 0 for a in attributes): return attr else: attr.value = np.concatenate([a.value for a in attributes if a.size > 0], axis=0) return attr
[ "def", "concatenate_attributes", "(", "attributes", ")", ":", "# We get a template/", "tpl", "=", "attributes", "[", "0", "]", "attr", "=", "InstanceAttribute", "(", "tpl", ".", "name", ",", "tpl", ".", "shape", ",", "tpl", ".", "dtype", ",", "tpl", ".", "dim", ",", "alias", "=", "None", ")", "# Special case, not a single array has size bigger than 0", "if", "all", "(", "a", ".", "size", "==", "0", "for", "a", "in", "attributes", ")", ":", "return", "attr", "else", ":", "attr", ".", "value", "=", "np", ".", "concatenate", "(", "[", "a", ".", "value", "for", "a", "in", "attributes", "if", "a", ".", "size", ">", "0", "]", ",", "axis", "=", "0", ")", "return", "attr" ]
Concatenate InstanceAttribute to return a bigger one.
[ "Concatenate", "InstanceAttribute", "to", "return", "a", "bigger", "one", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L700-L712
16,327
chemlab/chemlab
chemlab/core/base.py
concatenate_fields
def concatenate_fields(fields, dim): 'Create an INstanceAttribute from a list of InstnaceFields' if len(fields) == 0: raise ValueError('fields cannot be an empty list') if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1: raise ValueError('fields should have homogeneous name, shape and dtype') tpl = fields[0] attr = InstanceAttribute(tpl.name, shape=tpl.shape, dtype=tpl.dtype, dim=dim, alias=None) attr.value = np.array([f.value for f in fields], dtype=tpl.dtype) return attr
python
def concatenate_fields(fields, dim): 'Create an INstanceAttribute from a list of InstnaceFields' if len(fields) == 0: raise ValueError('fields cannot be an empty list') if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1: raise ValueError('fields should have homogeneous name, shape and dtype') tpl = fields[0] attr = InstanceAttribute(tpl.name, shape=tpl.shape, dtype=tpl.dtype, dim=dim, alias=None) attr.value = np.array([f.value for f in fields], dtype=tpl.dtype) return attr
[ "def", "concatenate_fields", "(", "fields", ",", "dim", ")", ":", "if", "len", "(", "fields", ")", "==", "0", ":", "raise", "ValueError", "(", "'fields cannot be an empty list'", ")", "if", "len", "(", "set", "(", "(", "f", ".", "name", ",", "f", ".", "shape", ",", "f", ".", "dtype", ")", "for", "f", "in", "fields", ")", ")", "!=", "1", ":", "raise", "ValueError", "(", "'fields should have homogeneous name, shape and dtype'", ")", "tpl", "=", "fields", "[", "0", "]", "attr", "=", "InstanceAttribute", "(", "tpl", ".", "name", ",", "shape", "=", "tpl", ".", "shape", ",", "dtype", "=", "tpl", ".", "dtype", ",", "dim", "=", "dim", ",", "alias", "=", "None", ")", "attr", ".", "value", "=", "np", ".", "array", "(", "[", "f", ".", "value", "for", "f", "in", "fields", "]", ",", "dtype", "=", "tpl", ".", "dtype", ")", "return", "attr" ]
Create an INstanceAttribute from a list of InstnaceFields
[ "Create", "an", "INstanceAttribute", "from", "a", "list", "of", "InstnaceFields" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L714-L726
16,328
chemlab/chemlab
chemlab/core/base.py
normalize_index
def normalize_index(index): """normalize numpy index""" index = np.asarray(index) if len(index) == 0: return index.astype('int') if index.dtype == 'bool': index = index.nonzero()[0] elif index.dtype == 'int': pass else: raise ValueError('Index should be either integer or bool') return index
python
def normalize_index(index): """normalize numpy index""" index = np.asarray(index) if len(index) == 0: return index.astype('int') if index.dtype == 'bool': index = index.nonzero()[0] elif index.dtype == 'int': pass else: raise ValueError('Index should be either integer or bool') return index
[ "def", "normalize_index", "(", "index", ")", ":", "index", "=", "np", ".", "asarray", "(", "index", ")", "if", "len", "(", "index", ")", "==", "0", ":", "return", "index", ".", "astype", "(", "'int'", ")", "if", "index", ".", "dtype", "==", "'bool'", ":", "index", "=", "index", ".", "nonzero", "(", ")", "[", "0", "]", "elif", "index", ".", "dtype", "==", "'int'", ":", "pass", "else", ":", "raise", "ValueError", "(", "'Index should be either integer or bool'", ")", "return", "index" ]
normalize numpy index
[ "normalize", "numpy", "index" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L745-L758
16,329
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.to_dict
def to_dict(self): """Return a dict representing the ChemicalEntity that can be read back using from_dict. """ ret = merge_dicts(self.__attributes__, self.__relations__, self.__fields__) ret = {k : v.value for k,v in ret.items()} ret['maps'] = {k : v.value for k,v in self.maps.items()} return ret
python
def to_dict(self): """Return a dict representing the ChemicalEntity that can be read back using from_dict. """ ret = merge_dicts(self.__attributes__, self.__relations__, self.__fields__) ret = {k : v.value for k,v in ret.items()} ret['maps'] = {k : v.value for k,v in self.maps.items()} return ret
[ "def", "to_dict", "(", "self", ")", ":", "ret", "=", "merge_dicts", "(", "self", ".", "__attributes__", ",", "self", ".", "__relations__", ",", "self", ".", "__fields__", ")", "ret", "=", "{", "k", ":", "v", ".", "value", "for", "k", ",", "v", "in", "ret", ".", "items", "(", ")", "}", "ret", "[", "'maps'", "]", "=", "{", "k", ":", "v", ".", "value", "for", "k", ",", "v", "in", "self", ".", "maps", ".", "items", "(", ")", "}", "return", "ret" ]
Return a dict representing the ChemicalEntity that can be read back using from_dict.
[ "Return", "a", "dict", "representing", "the", "ChemicalEntity", "that", "can", "be", "read", "back", "using", "from_dict", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L105-L114
16,330
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.from_json
def from_json(cls, string): """Create a ChemicalEntity from a json string """ exp_dict = json_to_data(string) version = exp_dict.get('version', 0) if version == 0: return cls.from_dict(exp_dict) elif version == 1: return cls.from_dict(exp_dict) else: raise ValueError("Version %d not supported" % version)
python
def from_json(cls, string): """Create a ChemicalEntity from a json string """ exp_dict = json_to_data(string) version = exp_dict.get('version', 0) if version == 0: return cls.from_dict(exp_dict) elif version == 1: return cls.from_dict(exp_dict) else: raise ValueError("Version %d not supported" % version)
[ "def", "from_json", "(", "cls", ",", "string", ")", ":", "exp_dict", "=", "json_to_data", "(", "string", ")", "version", "=", "exp_dict", ".", "get", "(", "'version'", ",", "0", ")", "if", "version", "==", "0", ":", "return", "cls", ".", "from_dict", "(", "exp_dict", ")", "elif", "version", "==", "1", ":", "return", "cls", ".", "from_dict", "(", "exp_dict", ")", "else", ":", "raise", "ValueError", "(", "\"Version %d not supported\"", "%", "version", ")" ]
Create a ChemicalEntity from a json string
[ "Create", "a", "ChemicalEntity", "from", "a", "json", "string" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L117-L127
16,331
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.copy
def copy(self): """Create a copy of this ChemicalEntity """ inst = super(type(self), type(self)).empty(**self.dimensions) # Need to copy all attributes, fields, relations inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()} inst.__fields__ = {k: v.copy() for k, v in self.__fields__.items()} inst.__relations__ = {k: v.copy() for k, v in self.__relations__.items()} inst.maps = {k: m.copy() for k, m in self.maps.items()} inst.dimensions = self.dimensions.copy() return inst
python
def copy(self): """Create a copy of this ChemicalEntity """ inst = super(type(self), type(self)).empty(**self.dimensions) # Need to copy all attributes, fields, relations inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()} inst.__fields__ = {k: v.copy() for k, v in self.__fields__.items()} inst.__relations__ = {k: v.copy() for k, v in self.__relations__.items()} inst.maps = {k: m.copy() for k, m in self.maps.items()} inst.dimensions = self.dimensions.copy() return inst
[ "def", "copy", "(", "self", ")", ":", "inst", "=", "super", "(", "type", "(", "self", ")", ",", "type", "(", "self", ")", ")", ".", "empty", "(", "*", "*", "self", ".", "dimensions", ")", "# Need to copy all attributes, fields, relations", "inst", ".", "__attributes__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "self", ".", "__attributes__", ".", "items", "(", ")", "}", "inst", ".", "__fields__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "self", ".", "__fields__", ".", "items", "(", ")", "}", "inst", ".", "__relations__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "self", ".", "__relations__", ".", "items", "(", ")", "}", "inst", ".", "maps", "=", "{", "k", ":", "m", ".", "copy", "(", ")", "for", "k", ",", "m", "in", "self", ".", "maps", ".", "items", "(", ")", "}", "inst", ".", "dimensions", "=", "self", ".", "dimensions", ".", "copy", "(", ")", "return", "inst" ]
Create a copy of this ChemicalEntity
[ "Create", "a", "copy", "of", "this", "ChemicalEntity" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L138-L151
16,332
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.copy_from
def copy_from(self, other): """Copy properties from another ChemicalEntity """ # Need to copy all attributes, fields, relations self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()} self.__fields__ = {k: v.copy() for k, v in other.__fields__.items()} self.__relations__ = {k: v.copy() for k, v in other.__relations__.items()} self.maps = {k: m.copy() for k, m in other.maps.items()} self.dimensions = other.dimensions.copy()
python
def copy_from(self, other): """Copy properties from another ChemicalEntity """ # Need to copy all attributes, fields, relations self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()} self.__fields__ = {k: v.copy() for k, v in other.__fields__.items()} self.__relations__ = {k: v.copy() for k, v in other.__relations__.items()} self.maps = {k: m.copy() for k, m in other.maps.items()} self.dimensions = other.dimensions.copy()
[ "def", "copy_from", "(", "self", ",", "other", ")", ":", "# Need to copy all attributes, fields, relations", "self", ".", "__attributes__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "other", ".", "__attributes__", ".", "items", "(", ")", "}", "self", ".", "__fields__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "other", ".", "__fields__", ".", "items", "(", ")", "}", "self", ".", "__relations__", "=", "{", "k", ":", "v", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "other", ".", "__relations__", ".", "items", "(", ")", "}", "self", ".", "maps", "=", "{", "k", ":", "m", ".", "copy", "(", ")", "for", "k", ",", "m", "in", "other", ".", "maps", ".", "items", "(", ")", "}", "self", ".", "dimensions", "=", "other", ".", "dimensions", ".", "copy", "(", ")" ]
Copy properties from another ChemicalEntity
[ "Copy", "properties", "from", "another", "ChemicalEntity" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L153-L162
16,333
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.update
def update(self, dictionary): """Update the current chemical entity from a dictionary of attributes""" allowed_attrs = list(self.__attributes__.keys()) allowed_attrs += [a.alias for a in self.__attributes__.values()] for k in dictionary: # We only update existing attributes if k in allowed_attrs: setattr(self, k, dictionary[k]) return self
python
def update(self, dictionary): """Update the current chemical entity from a dictionary of attributes""" allowed_attrs = list(self.__attributes__.keys()) allowed_attrs += [a.alias for a in self.__attributes__.values()] for k in dictionary: # We only update existing attributes if k in allowed_attrs: setattr(self, k, dictionary[k]) return self
[ "def", "update", "(", "self", ",", "dictionary", ")", ":", "allowed_attrs", "=", "list", "(", "self", ".", "__attributes__", ".", "keys", "(", ")", ")", "allowed_attrs", "+=", "[", "a", ".", "alias", "for", "a", "in", "self", ".", "__attributes__", ".", "values", "(", ")", "]", "for", "k", "in", "dictionary", ":", "# We only update existing attributes", "if", "k", "in", "allowed_attrs", ":", "setattr", "(", "self", ",", "k", ",", "dictionary", "[", "k", "]", ")", "return", "self" ]
Update the current chemical entity from a dictionary of attributes
[ "Update", "the", "current", "chemical", "entity", "from", "a", "dictionary", "of", "attributes" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L164-L172
16,334
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.subentity
def subentity(self, Entity, index): """Return child entity""" dim = Entity.__dimension__ entity = Entity.empty() if index >= self.dimensions[dim]: raise ValueError('index {} out of bounds for dimension {} (size {})' .format(index, dim, self.dimensions[dim])) for name, attr in self.__attributes__.items(): if attr.dim == dim: # If the dimension of the attributes is the same of the # dimension of the entity, we generate a field entity.__fields__[name] = attr.field(index) elif attr.dim in entity.dimensions: # Special case, we don't need to do anything if self.dimensions[attr.dim] == 0: continue # Else, we generate a subattribute mapped_index = self.maps[attr.dim, dim].value == index entity.__attributes__[name] = attr.sub(mapped_index) entity.dimensions[attr.dim] = np.count_nonzero(mapped_index) for name, rel in self.__relations__.items(): if rel.map == dim: # The relation is between entities we need to return # which means the entity doesn't know about that pass if rel.map in entity.dimensions: # Special case, we don't need to do anything if self.dimensions[rel.dim] == 0: continue mapped_index = self.maps[rel.dim, dim].value == index entity.__relations__[name] = rel.sub(mapped_index) entity.dimensions[rel.dim] = np.count_nonzero(mapped_index) # We need to remap values convert_index = self.maps[rel.map, dim].value == index entity.__relations__[name].remap(convert_index.nonzero()[0], range(entity.dimensions[rel.map])) return entity
python
def subentity(self, Entity, index): """Return child entity""" dim = Entity.__dimension__ entity = Entity.empty() if index >= self.dimensions[dim]: raise ValueError('index {} out of bounds for dimension {} (size {})' .format(index, dim, self.dimensions[dim])) for name, attr in self.__attributes__.items(): if attr.dim == dim: # If the dimension of the attributes is the same of the # dimension of the entity, we generate a field entity.__fields__[name] = attr.field(index) elif attr.dim in entity.dimensions: # Special case, we don't need to do anything if self.dimensions[attr.dim] == 0: continue # Else, we generate a subattribute mapped_index = self.maps[attr.dim, dim].value == index entity.__attributes__[name] = attr.sub(mapped_index) entity.dimensions[attr.dim] = np.count_nonzero(mapped_index) for name, rel in self.__relations__.items(): if rel.map == dim: # The relation is between entities we need to return # which means the entity doesn't know about that pass if rel.map in entity.dimensions: # Special case, we don't need to do anything if self.dimensions[rel.dim] == 0: continue mapped_index = self.maps[rel.dim, dim].value == index entity.__relations__[name] = rel.sub(mapped_index) entity.dimensions[rel.dim] = np.count_nonzero(mapped_index) # We need to remap values convert_index = self.maps[rel.map, dim].value == index entity.__relations__[name].remap(convert_index.nonzero()[0], range(entity.dimensions[rel.map])) return entity
[ "def", "subentity", "(", "self", ",", "Entity", ",", "index", ")", ":", "dim", "=", "Entity", ".", "__dimension__", "entity", "=", "Entity", ".", "empty", "(", ")", "if", "index", ">=", "self", ".", "dimensions", "[", "dim", "]", ":", "raise", "ValueError", "(", "'index {} out of bounds for dimension {} (size {})'", ".", "format", "(", "index", ",", "dim", ",", "self", ".", "dimensions", "[", "dim", "]", ")", ")", "for", "name", ",", "attr", "in", "self", ".", "__attributes__", ".", "items", "(", ")", ":", "if", "attr", ".", "dim", "==", "dim", ":", "# If the dimension of the attributes is the same of the", "# dimension of the entity, we generate a field", "entity", ".", "__fields__", "[", "name", "]", "=", "attr", ".", "field", "(", "index", ")", "elif", "attr", ".", "dim", "in", "entity", ".", "dimensions", ":", "# Special case, we don't need to do anything", "if", "self", ".", "dimensions", "[", "attr", ".", "dim", "]", "==", "0", ":", "continue", "# Else, we generate a subattribute", "mapped_index", "=", "self", ".", "maps", "[", "attr", ".", "dim", ",", "dim", "]", ".", "value", "==", "index", "entity", ".", "__attributes__", "[", "name", "]", "=", "attr", ".", "sub", "(", "mapped_index", ")", "entity", ".", "dimensions", "[", "attr", ".", "dim", "]", "=", "np", ".", "count_nonzero", "(", "mapped_index", ")", "for", "name", ",", "rel", "in", "self", ".", "__relations__", ".", "items", "(", ")", ":", "if", "rel", ".", "map", "==", "dim", ":", "# The relation is between entities we need to return", "# which means the entity doesn't know about that", "pass", "if", "rel", ".", "map", "in", "entity", ".", "dimensions", ":", "# Special case, we don't need to do anything", "if", "self", ".", "dimensions", "[", "rel", ".", "dim", "]", "==", "0", ":", "continue", "mapped_index", "=", "self", ".", "maps", "[", "rel", ".", "dim", ",", "dim", "]", ".", "value", "==", "index", "entity", ".", "__relations__", "[", "name", "]", "=", "rel", ".", "sub", "(", "mapped_index", ")", "entity", ".", "dimensions", "[", "rel", ".", "dim", "]", "=", "np", ".", "count_nonzero", "(", "mapped_index", ")", "# We need to remap values", "convert_index", "=", "self", ".", "maps", "[", "rel", ".", "map", ",", "dim", "]", ".", "value", "==", "index", "entity", ".", "__relations__", "[", "name", "]", ".", "remap", "(", "convert_index", ".", "nonzero", "(", ")", "[", "0", "]", ",", "range", "(", "entity", ".", "dimensions", "[", "rel", ".", "map", "]", ")", ")", "return", "entity" ]
Return child entity
[ "Return", "child", "entity" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L343-L386
16,335
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.sub_dimension
def sub_dimension(self, index, dimension, propagate=True, inplace=False): """Return a ChemicalEntity sliced through a dimension. If other dimensions depend on this one those are updated accordingly. """ filter_ = self._propagate_dim(index, dimension, propagate) return self.subindex(filter_, inplace)
python
def sub_dimension(self, index, dimension, propagate=True, inplace=False): """Return a ChemicalEntity sliced through a dimension. If other dimensions depend on this one those are updated accordingly. """ filter_ = self._propagate_dim(index, dimension, propagate) return self.subindex(filter_, inplace)
[ "def", "sub_dimension", "(", "self", ",", "index", ",", "dimension", ",", "propagate", "=", "True", ",", "inplace", "=", "False", ")", ":", "filter_", "=", "self", ".", "_propagate_dim", "(", "index", ",", "dimension", ",", "propagate", ")", "return", "self", ".", "subindex", "(", "filter_", ",", "inplace", ")" ]
Return a ChemicalEntity sliced through a dimension. If other dimensions depend on this one those are updated accordingly.
[ "Return", "a", "ChemicalEntity", "sliced", "through", "a", "dimension", ".", "If", "other", "dimensions", "depend", "on", "this", "one", "those", "are", "updated", "accordingly", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L446-L452
16,336
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.expand_dimension
def expand_dimension(self, newdim, dimension, maps={}, relations={}): ''' When we expand we need to provide new maps and relations as those can't be inferred ''' for name, attr in self.__attributes__.items(): if attr.dim == dimension: newattr = attr.copy() newattr.empty(newdim - attr.size) self.__attributes__[name] = concatenate_attributes([attr, newattr]) for name, rel in self.__relations__.items(): if dimension == rel.dim: # We need the new relation from the user if not rel.name in relations: raise ValueError('You need to provide the relation {} for this resize'.format(rel.name)) else: if len(relations[name]) != newdim: raise ValueError('New relation {} should be of size {}'.format(rel.name, newdim)) else: self.__relations__[name].value = relations[name] elif dimension == rel.map: # Extend the index rel.index = range(newdim) for (a, b), rel in self.maps.items(): if dimension == rel.dim: # We need the new relation from the user if not (a, b) in maps: raise ValueError('You need to provide the map {}->{} for this resize'.format(a, b)) else: if len(maps[a, b]) != newdim: raise ValueError('New map {} should be of size {}'.format(rel.name, newdim)) else: rel.value = maps[a, b] elif dimension == rel.map: # Extend the index rel.index = range(newdim) # Update dimensions self.dimensions[dimension] = newdim return self
python
def expand_dimension(self, newdim, dimension, maps={}, relations={}): ''' When we expand we need to provide new maps and relations as those can't be inferred ''' for name, attr in self.__attributes__.items(): if attr.dim == dimension: newattr = attr.copy() newattr.empty(newdim - attr.size) self.__attributes__[name] = concatenate_attributes([attr, newattr]) for name, rel in self.__relations__.items(): if dimension == rel.dim: # We need the new relation from the user if not rel.name in relations: raise ValueError('You need to provide the relation {} for this resize'.format(rel.name)) else: if len(relations[name]) != newdim: raise ValueError('New relation {} should be of size {}'.format(rel.name, newdim)) else: self.__relations__[name].value = relations[name] elif dimension == rel.map: # Extend the index rel.index = range(newdim) for (a, b), rel in self.maps.items(): if dimension == rel.dim: # We need the new relation from the user if not (a, b) in maps: raise ValueError('You need to provide the map {}->{} for this resize'.format(a, b)) else: if len(maps[a, b]) != newdim: raise ValueError('New map {} should be of size {}'.format(rel.name, newdim)) else: rel.value = maps[a, b] elif dimension == rel.map: # Extend the index rel.index = range(newdim) # Update dimensions self.dimensions[dimension] = newdim return self
[ "def", "expand_dimension", "(", "self", ",", "newdim", ",", "dimension", ",", "maps", "=", "{", "}", ",", "relations", "=", "{", "}", ")", ":", "for", "name", ",", "attr", "in", "self", ".", "__attributes__", ".", "items", "(", ")", ":", "if", "attr", ".", "dim", "==", "dimension", ":", "newattr", "=", "attr", ".", "copy", "(", ")", "newattr", ".", "empty", "(", "newdim", "-", "attr", ".", "size", ")", "self", ".", "__attributes__", "[", "name", "]", "=", "concatenate_attributes", "(", "[", "attr", ",", "newattr", "]", ")", "for", "name", ",", "rel", "in", "self", ".", "__relations__", ".", "items", "(", ")", ":", "if", "dimension", "==", "rel", ".", "dim", ":", "# We need the new relation from the user", "if", "not", "rel", ".", "name", "in", "relations", ":", "raise", "ValueError", "(", "'You need to provide the relation {} for this resize'", ".", "format", "(", "rel", ".", "name", ")", ")", "else", ":", "if", "len", "(", "relations", "[", "name", "]", ")", "!=", "newdim", ":", "raise", "ValueError", "(", "'New relation {} should be of size {}'", ".", "format", "(", "rel", ".", "name", ",", "newdim", ")", ")", "else", ":", "self", ".", "__relations__", "[", "name", "]", ".", "value", "=", "relations", "[", "name", "]", "elif", "dimension", "==", "rel", ".", "map", ":", "# Extend the index", "rel", ".", "index", "=", "range", "(", "newdim", ")", "for", "(", "a", ",", "b", ")", ",", "rel", "in", "self", ".", "maps", ".", "items", "(", ")", ":", "if", "dimension", "==", "rel", ".", "dim", ":", "# We need the new relation from the user", "if", "not", "(", "a", ",", "b", ")", "in", "maps", ":", "raise", "ValueError", "(", "'You need to provide the map {}->{} for this resize'", ".", "format", "(", "a", ",", "b", ")", ")", "else", ":", "if", "len", "(", "maps", "[", "a", ",", "b", "]", ")", "!=", "newdim", ":", "raise", "ValueError", "(", "'New map {} should be of size {}'", ".", "format", "(", "rel", ".", "name", ",", "newdim", ")", ")", "else", ":", "rel", ".", "value", "=", "maps", "[", "a", ",", "b", "]", "elif", "dimension", "==", "rel", ".", "map", ":", "# Extend the index", "rel", ".", "index", "=", "range", "(", "newdim", ")", "# Update dimensions", "self", ".", "dimensions", "[", "dimension", "]", "=", "newdim", "return", "self" ]
When we expand we need to provide new maps and relations as those can't be inferred
[ "When", "we", "expand", "we", "need", "to", "provide", "new", "maps", "and", "relations", "as", "those", "can", "t", "be", "inferred" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L461-L504
16,337
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.concat
def concat(self, other, inplace=False): '''Concatenate two ChemicalEntity of the same kind''' # Create new entity if inplace: obj = self else: obj = self.copy() # Stitch every attribute for name, attr in obj.__attributes__.items(): attr.append(other.__attributes__[name]) # Stitch every relation for name, rel in obj.__relations__.items(): rel.append(other.__relations__[name]) # Update maps # Update dimensions if obj.is_empty(): obj.maps = {k: m.copy() for k, m in other.maps.items()} obj.dimensions = other.dimensions.copy() else: for (a, b), rel in obj.maps.items(): rel.append(other.maps[a, b]) for d in obj.dimensions: obj.dimensions[d] += other.dimensions[d] return obj
python
def concat(self, other, inplace=False): '''Concatenate two ChemicalEntity of the same kind''' # Create new entity if inplace: obj = self else: obj = self.copy() # Stitch every attribute for name, attr in obj.__attributes__.items(): attr.append(other.__attributes__[name]) # Stitch every relation for name, rel in obj.__relations__.items(): rel.append(other.__relations__[name]) # Update maps # Update dimensions if obj.is_empty(): obj.maps = {k: m.copy() for k, m in other.maps.items()} obj.dimensions = other.dimensions.copy() else: for (a, b), rel in obj.maps.items(): rel.append(other.maps[a, b]) for d in obj.dimensions: obj.dimensions[d] += other.dimensions[d] return obj
[ "def", "concat", "(", "self", ",", "other", ",", "inplace", "=", "False", ")", ":", "# Create new entity", "if", "inplace", ":", "obj", "=", "self", "else", ":", "obj", "=", "self", ".", "copy", "(", ")", "# Stitch every attribute", "for", "name", ",", "attr", "in", "obj", ".", "__attributes__", ".", "items", "(", ")", ":", "attr", ".", "append", "(", "other", ".", "__attributes__", "[", "name", "]", ")", "# Stitch every relation", "for", "name", ",", "rel", "in", "obj", ".", "__relations__", ".", "items", "(", ")", ":", "rel", ".", "append", "(", "other", ".", "__relations__", "[", "name", "]", ")", "# Update maps", "# Update dimensions", "if", "obj", ".", "is_empty", "(", ")", ":", "obj", ".", "maps", "=", "{", "k", ":", "m", ".", "copy", "(", ")", "for", "k", ",", "m", "in", "other", ".", "maps", ".", "items", "(", ")", "}", "obj", ".", "dimensions", "=", "other", ".", "dimensions", ".", "copy", "(", ")", "else", ":", "for", "(", "a", ",", "b", ")", ",", "rel", "in", "obj", ".", "maps", ".", "items", "(", ")", ":", "rel", ".", "append", "(", "other", ".", "maps", "[", "a", ",", "b", "]", ")", "for", "d", "in", "obj", ".", "dimensions", ":", "obj", ".", "dimensions", "[", "d", "]", "+=", "other", ".", "dimensions", "[", "d", "]", "return", "obj" ]
Concatenate two ChemicalEntity of the same kind
[ "Concatenate", "two", "ChemicalEntity", "of", "the", "same", "kind" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L544-L573
16,338
chemlab/chemlab
chemlab/core/base.py
ChemicalEntity.sub
def sub(self, inplace=False, **kwargs): """Return a entity where the conditions are met""" filter_ = self.where(**kwargs) return self.subindex(filter_, inplace)
python
def sub(self, inplace=False, **kwargs): """Return a entity where the conditions are met""" filter_ = self.where(**kwargs) return self.subindex(filter_, inplace)
[ "def", "sub", "(", "self", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "filter_", "=", "self", ".", "where", "(", "*", "*", "kwargs", ")", "return", "self", ".", "subindex", "(", "filter_", ",", "inplace", ")" ]
Return a entity where the conditions are met
[ "Return", "a", "entity", "where", "the", "conditions", "are", "met" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L636-L639
16,339
chemlab/chemlab
chemlab/core/attributes.py
InstanceArray.sub
def sub(self, index): """Return a sub-attribute""" index = np.asarray(index) if index.dtype == 'bool': index = index.nonzero()[0] if self.size < len(index): raise ValueError('Can\'t subset "{}": index ({}) is bigger than the number of elements ({})'.format(self.name, len(index), self.size)) inst = self.copy() size = len(index) inst.empty(size) if len(index) > 0: inst.value = self.value.take(index, axis=0) return inst
python
def sub(self, index): """Return a sub-attribute""" index = np.asarray(index) if index.dtype == 'bool': index = index.nonzero()[0] if self.size < len(index): raise ValueError('Can\'t subset "{}": index ({}) is bigger than the number of elements ({})'.format(self.name, len(index), self.size)) inst = self.copy() size = len(index) inst.empty(size) if len(index) > 0: inst.value = self.value.take(index, axis=0) return inst
[ "def", "sub", "(", "self", ",", "index", ")", ":", "index", "=", "np", ".", "asarray", "(", "index", ")", "if", "index", ".", "dtype", "==", "'bool'", ":", "index", "=", "index", ".", "nonzero", "(", ")", "[", "0", "]", "if", "self", ".", "size", "<", "len", "(", "index", ")", ":", "raise", "ValueError", "(", "'Can\\'t subset \"{}\": index ({}) is bigger than the number of elements ({})'", ".", "format", "(", "self", ".", "name", ",", "len", "(", "index", ")", ",", "self", ".", "size", ")", ")", "inst", "=", "self", ".", "copy", "(", ")", "size", "=", "len", "(", "index", ")", "inst", ".", "empty", "(", "size", ")", "if", "len", "(", "index", ")", ">", "0", ":", "inst", ".", "value", "=", "self", ".", "value", ".", "take", "(", "index", ",", "axis", "=", "0", ")", "return", "inst" ]
Return a sub-attribute
[ "Return", "a", "sub", "-", "attribute" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/attributes.py#L119-L135
16,340
chemlab/chemlab
chemlab/libs/cirpy.py
resolve
def resolve(input, representation, resolvers=None, **kwargs): """ Resolve input to the specified output representation """ resultdict = query(input, representation, resolvers, **kwargs) result = resultdict[0]['value'] if resultdict else None if result and len(result) == 1: result = result[0] return result
python
def resolve(input, representation, resolvers=None, **kwargs): """ Resolve input to the specified output representation """ resultdict = query(input, representation, resolvers, **kwargs) result = resultdict[0]['value'] if resultdict else None if result and len(result) == 1: result = result[0] return result
[ "def", "resolve", "(", "input", ",", "representation", ",", "resolvers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "resultdict", "=", "query", "(", "input", ",", "representation", ",", "resolvers", ",", "*", "*", "kwargs", ")", "result", "=", "resultdict", "[", "0", "]", "[", "'value'", "]", "if", "resultdict", "else", "None", "if", "result", "and", "len", "(", "result", ")", "==", "1", ":", "result", "=", "result", "[", "0", "]", "return", "result" ]
Resolve input to the specified output representation
[ "Resolve", "input", "to", "the", "specified", "output", "representation" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L33-L39
16,341
chemlab/chemlab
chemlab/libs/cirpy.py
query
def query(input, representation, resolvers=None, **kwargs): """ Get all results for resolving input to the specified output representation """ apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation) if resolvers: kwargs['resolver'] = ",".join(resolvers) if kwargs: apiurl+= '?%s' % urlencode(kwargs) result = [] try: tree = ET.parse(urlopen(apiurl)) for data in tree.findall(".//data"): datadict = {'resolver':data.attrib['resolver'], 'notation':data.attrib['notation'], 'value':[]} for item in data.findall("item"): datadict['value'].append(item.text) if len(datadict['value']) == 1: datadict['value'] = datadict['value'][0] result.append(datadict) except HTTPError: # TODO: Proper handling of 404, for now just returns None pass return result if result else None
python
def query(input, representation, resolvers=None, **kwargs): """ Get all results for resolving input to the specified output representation """ apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation) if resolvers: kwargs['resolver'] = ",".join(resolvers) if kwargs: apiurl+= '?%s' % urlencode(kwargs) result = [] try: tree = ET.parse(urlopen(apiurl)) for data in tree.findall(".//data"): datadict = {'resolver':data.attrib['resolver'], 'notation':data.attrib['notation'], 'value':[]} for item in data.findall("item"): datadict['value'].append(item.text) if len(datadict['value']) == 1: datadict['value'] = datadict['value'][0] result.append(datadict) except HTTPError: # TODO: Proper handling of 404, for now just returns None pass return result if result else None
[ "def", "query", "(", "input", ",", "representation", ",", "resolvers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "apiurl", "=", "API_BASE", "+", "'/%s/%s/xml'", "%", "(", "urlquote", "(", "input", ")", ",", "representation", ")", "if", "resolvers", ":", "kwargs", "[", "'resolver'", "]", "=", "\",\"", ".", "join", "(", "resolvers", ")", "if", "kwargs", ":", "apiurl", "+=", "'?%s'", "%", "urlencode", "(", "kwargs", ")", "result", "=", "[", "]", "try", ":", "tree", "=", "ET", ".", "parse", "(", "urlopen", "(", "apiurl", ")", ")", "for", "data", "in", "tree", ".", "findall", "(", "\".//data\"", ")", ":", "datadict", "=", "{", "'resolver'", ":", "data", ".", "attrib", "[", "'resolver'", "]", ",", "'notation'", ":", "data", ".", "attrib", "[", "'notation'", "]", ",", "'value'", ":", "[", "]", "}", "for", "item", "in", "data", ".", "findall", "(", "\"item\"", ")", ":", "datadict", "[", "'value'", "]", ".", "append", "(", "item", ".", "text", ")", "if", "len", "(", "datadict", "[", "'value'", "]", ")", "==", "1", ":", "datadict", "[", "'value'", "]", "=", "datadict", "[", "'value'", "]", "[", "0", "]", "result", ".", "append", "(", "datadict", ")", "except", "HTTPError", ":", "# TODO: Proper handling of 404, for now just returns None", "pass", "return", "result", "if", "result", "else", "None" ]
Get all results for resolving input to the specified output representation
[ "Get", "all", "results", "for", "resolving", "input", "to", "the", "specified", "output", "representation" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L42-L64
16,342
chemlab/chemlab
chemlab/libs/cirpy.py
download
def download(input, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): """ Resolve and download structure as a file """ kwargs['format'] = format if resolvers: kwargs['resolver'] = ",".join(resolvers) url = API_BASE+'/%s/file?%s' % (urlquote(input), urlencode(kwargs)) try: servefile = urlopen(url) if not overwrite and os.path.isfile(filename): raise IOError("%s already exists. Use 'overwrite=True' to overwrite it." % filename) file = open(filename, "w") file.write(servefile.read()) file.close() except urllib.error.HTTPError: # TODO: Proper handling of 404, for now just does nothing pass
python
def download(input, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): """ Resolve and download structure as a file """ kwargs['format'] = format if resolvers: kwargs['resolver'] = ",".join(resolvers) url = API_BASE+'/%s/file?%s' % (urlquote(input), urlencode(kwargs)) try: servefile = urlopen(url) if not overwrite and os.path.isfile(filename): raise IOError("%s already exists. Use 'overwrite=True' to overwrite it." % filename) file = open(filename, "w") file.write(servefile.read()) file.close() except urllib.error.HTTPError: # TODO: Proper handling of 404, for now just does nothing pass
[ "def", "download", "(", "input", ",", "filename", ",", "format", "=", "'sdf'", ",", "overwrite", "=", "False", ",", "resolvers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'format'", "]", "=", "format", "if", "resolvers", ":", "kwargs", "[", "'resolver'", "]", "=", "\",\"", ".", "join", "(", "resolvers", ")", "url", "=", "API_BASE", "+", "'/%s/file?%s'", "%", "(", "urlquote", "(", "input", ")", ",", "urlencode", "(", "kwargs", ")", ")", "try", ":", "servefile", "=", "urlopen", "(", "url", ")", "if", "not", "overwrite", "and", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "IOError", "(", "\"%s already exists. Use 'overwrite=True' to overwrite it.\"", "%", "filename", ")", "file", "=", "open", "(", "filename", ",", "\"w\"", ")", "file", ".", "write", "(", "servefile", ".", "read", "(", ")", ")", "file", ".", "close", "(", ")", "except", "urllib", ".", "error", ".", "HTTPError", ":", "# TODO: Proper handling of 404, for now just does nothing", "pass" ]
Resolve and download structure as a file
[ "Resolve", "and", "download", "structure", "as", "a", "file" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L66-L81
16,343
chemlab/chemlab
chemlab/libs/cirpy.py
Molecule.download
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): """ Download the resolved structure as a file """ download(self.input, filename, format, overwrite, resolvers, **kwargs)
python
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): """ Download the resolved structure as a file """ download(self.input, filename, format, overwrite, resolvers, **kwargs)
[ "def", "download", "(", "self", ",", "filename", ",", "format", "=", "'sdf'", ",", "overwrite", "=", "False", ",", "resolvers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "download", "(", "self", ".", "input", ",", "filename", ",", "format", ",", "overwrite", ",", "resolvers", ",", "*", "*", "kwargs", ")" ]
Download the resolved structure as a file
[ "Download", "the", "resolved", "structure", "as", "a", "file" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L196-L198
16,344
chemlab/chemlab
chemlab/utils/__init__.py
dipole_moment
def dipole_moment(r_array, charge_array): '''Return the dipole moment of a neutral system. ''' return np.sum(r_array * charge_array[:, np.newaxis], axis=0)
python
def dipole_moment(r_array, charge_array): '''Return the dipole moment of a neutral system. ''' return np.sum(r_array * charge_array[:, np.newaxis], axis=0)
[ "def", "dipole_moment", "(", "r_array", ",", "charge_array", ")", ":", "return", "np", ".", "sum", "(", "r_array", "*", "charge_array", "[", ":", ",", "np", ".", "newaxis", "]", ",", "axis", "=", "0", ")" ]
Return the dipole moment of a neutral system.
[ "Return", "the", "dipole", "moment", "of", "a", "neutral", "system", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/__init__.py#L90-L93
16,345
chemlab/chemlab
chemlab/graphics/qt/qtviewer.py
QtViewer.schedule
def schedule(self, callback, timeout=100): '''Schedule a function to be called repeated time. This method can be used to perform animations. **Example** This is a typical way to perform an animation, just:: from chemlab.graphics.qt import QtViewer from chemlab.graphics.renderers import SphereRenderer v = QtViewer() sr = v.add_renderer(SphereRenderer, centers, radii, colors) def update(): # calculate new_positions sr.update_positions(new_positions) v.widget.repaint() v.schedule(update) v.run() .. note:: remember to call QtViewer.widget.repaint() each once you want to update the display. **Parameters** callback: function() A function that takes no arguments that will be called at intervals. timeout: int Time in milliseconds between calls of the *callback* function. **Returns** a `QTimer`, to stop the animation you can use `Qtimer.stop` ''' timer = QTimer(self) timer.timeout.connect(callback) timer.start(timeout) return timer
python
def schedule(self, callback, timeout=100): '''Schedule a function to be called repeated time. This method can be used to perform animations. **Example** This is a typical way to perform an animation, just:: from chemlab.graphics.qt import QtViewer from chemlab.graphics.renderers import SphereRenderer v = QtViewer() sr = v.add_renderer(SphereRenderer, centers, radii, colors) def update(): # calculate new_positions sr.update_positions(new_positions) v.widget.repaint() v.schedule(update) v.run() .. note:: remember to call QtViewer.widget.repaint() each once you want to update the display. **Parameters** callback: function() A function that takes no arguments that will be called at intervals. timeout: int Time in milliseconds between calls of the *callback* function. **Returns** a `QTimer`, to stop the animation you can use `Qtimer.stop` ''' timer = QTimer(self) timer.timeout.connect(callback) timer.start(timeout) return timer
[ "def", "schedule", "(", "self", ",", "callback", ",", "timeout", "=", "100", ")", ":", "timer", "=", "QTimer", "(", "self", ")", "timer", ".", "timeout", ".", "connect", "(", "callback", ")", "timer", ".", "start", "(", "timeout", ")", "return", "timer" ]
Schedule a function to be called repeated time. This method can be used to perform animations. **Example** This is a typical way to perform an animation, just:: from chemlab.graphics.qt import QtViewer from chemlab.graphics.renderers import SphereRenderer v = QtViewer() sr = v.add_renderer(SphereRenderer, centers, radii, colors) def update(): # calculate new_positions sr.update_positions(new_positions) v.widget.repaint() v.schedule(update) v.run() .. note:: remember to call QtViewer.widget.repaint() each once you want to update the display. **Parameters** callback: function() A function that takes no arguments that will be called at intervals. timeout: int Time in milliseconds between calls of the *callback* function. **Returns** a `QTimer`, to stop the animation you can use `Qtimer.stop`
[ "Schedule", "a", "function", "to", "be", "called", "repeated", "time", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qtviewer.py#L87-L129
16,346
chemlab/chemlab
chemlab/graphics/qt/qtviewer.py
QtViewer.add_ui
def add_ui(self, klass, *args, **kwargs): '''Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized ''' ui = klass(self.widget, *args, **kwargs) self.widget.uis.append(ui) return ui
python
def add_ui(self, klass, *args, **kwargs): '''Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized ''' ui = klass(self.widget, *args, **kwargs) self.widget.uis.append(ui) return ui
[ "def", "add_ui", "(", "self", ",", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ui", "=", "klass", "(", "self", ".", "widget", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "widget", ".", "uis", ".", "append", "(", "ui", ")", "return", "ui" ]
Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized
[ "Add", "an", "UI", "element", "for", "the", "current", "scene", ".", "The", "approach", "is", "the", "same", "as", "renderers", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qtviewer.py#L182-L191
16,347
chemlab/chemlab
chemlab/io/handlers/gamess.py
parse_card
def parse_card(card, text, default=None): """Parse a card from an input string """ match = re.search(card.lower() + r"\s*=\s*(\w+)", text.lower()) return match.group(1) if match else default
python
def parse_card(card, text, default=None): """Parse a card from an input string """ match = re.search(card.lower() + r"\s*=\s*(\w+)", text.lower()) return match.group(1) if match else default
[ "def", "parse_card", "(", "card", ",", "text", ",", "default", "=", "None", ")", ":", "match", "=", "re", ".", "search", "(", "card", ".", "lower", "(", ")", "+", "r\"\\s*=\\s*(\\w+)\"", ",", "text", ".", "lower", "(", ")", ")", "return", "match", ".", "group", "(", "1", ")", "if", "match", "else", "default" ]
Parse a card from an input string
[ "Parse", "a", "card", "from", "an", "input", "string" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L143-L148
16,348
chemlab/chemlab
chemlab/io/handlers/gamess.py
GamessDataParser._parse_geometry
def _parse_geometry(self, geom): """Parse a geometry string and return Molecule object from it. """ atoms = [] for i, line in enumerate(geom.splitlines()): sym, atno, x, y, z = line.split() atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i)) return Molecule(atoms)
python
def _parse_geometry(self, geom): """Parse a geometry string and return Molecule object from it. """ atoms = [] for i, line in enumerate(geom.splitlines()): sym, atno, x, y, z = line.split() atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i)) return Molecule(atoms)
[ "def", "_parse_geometry", "(", "self", ",", "geom", ")", ":", "atoms", "=", "[", "]", "for", "i", ",", "line", "in", "enumerate", "(", "geom", ".", "splitlines", "(", ")", ")", ":", "sym", ",", "atno", ",", "x", ",", "y", ",", "z", "=", "line", ".", "split", "(", ")", "atoms", ".", "append", "(", "Atom", "(", "sym", ",", "[", "float", "(", "x", ")", ",", "float", "(", "y", ")", ",", "float", "(", "z", ")", "]", ",", "id", "=", "i", ")", ")", "return", "Molecule", "(", "atoms", ")" ]
Parse a geometry string and return Molecule object from it.
[ "Parse", "a", "geometry", "string", "and", "return", "Molecule", "object", "from", "it", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L67-L77
16,349
chemlab/chemlab
chemlab/io/handlers/gamess.py
GamessDataParser.parse_optimize
def parse_optimize(self): """Parse the ouput resulted of a geometry optimization. Or a saddle point. """ match = re.search("EQUILIBRIUM GEOMETRY LOCATED", self.text) spmatch = "SADDLE POINT LOCATED" in self.text located = True if match or spmatch else False points = grep_split(" BEGINNING GEOMETRY SEARCH POINT NSERCH=", self.text) if self.tddft == "excite": points = [self.parse_energy(point) for point in points[1:]] else: regex = re.compile(r'NSERCH:\s+\d+\s+E=\s+([+-]?\d+\.\d+)') points = [Energy(states=[State(0,None,float(m.group(1)), 0.0, 0.0)]) for m in regex.finditer(self.text)] # Error handling if "FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN" in self.text: self.errcode = GEOM_NOT_LOCATED self.errmsg = "too many steps taken: %i"%len(points) if located: self.errcode = OK return Optimize(points=points)
python
def parse_optimize(self): """Parse the ouput resulted of a geometry optimization. Or a saddle point. """ match = re.search("EQUILIBRIUM GEOMETRY LOCATED", self.text) spmatch = "SADDLE POINT LOCATED" in self.text located = True if match or spmatch else False points = grep_split(" BEGINNING GEOMETRY SEARCH POINT NSERCH=", self.text) if self.tddft == "excite": points = [self.parse_energy(point) for point in points[1:]] else: regex = re.compile(r'NSERCH:\s+\d+\s+E=\s+([+-]?\d+\.\d+)') points = [Energy(states=[State(0,None,float(m.group(1)), 0.0, 0.0)]) for m in regex.finditer(self.text)] # Error handling if "FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN" in self.text: self.errcode = GEOM_NOT_LOCATED self.errmsg = "too many steps taken: %i"%len(points) if located: self.errcode = OK return Optimize(points=points)
[ "def", "parse_optimize", "(", "self", ")", ":", "match", "=", "re", ".", "search", "(", "\"EQUILIBRIUM GEOMETRY LOCATED\"", ",", "self", ".", "text", ")", "spmatch", "=", "\"SADDLE POINT LOCATED\"", "in", "self", ".", "text", "located", "=", "True", "if", "match", "or", "spmatch", "else", "False", "points", "=", "grep_split", "(", "\" BEGINNING GEOMETRY SEARCH POINT NSERCH=\"", ",", "self", ".", "text", ")", "if", "self", ".", "tddft", "==", "\"excite\"", ":", "points", "=", "[", "self", ".", "parse_energy", "(", "point", ")", "for", "point", "in", "points", "[", "1", ":", "]", "]", "else", ":", "regex", "=", "re", ".", "compile", "(", "r'NSERCH:\\s+\\d+\\s+E=\\s+([+-]?\\d+\\.\\d+)'", ")", "points", "=", "[", "Energy", "(", "states", "=", "[", "State", "(", "0", ",", "None", ",", "float", "(", "m", ".", "group", "(", "1", ")", ")", ",", "0.0", ",", "0.0", ")", "]", ")", "for", "m", "in", "regex", ".", "finditer", "(", "self", ".", "text", ")", "]", "# Error handling", "if", "\"FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN\"", "in", "self", ".", "text", ":", "self", ".", "errcode", "=", "GEOM_NOT_LOCATED", "self", ".", "errmsg", "=", "\"too many steps taken: %i\"", "%", "len", "(", "points", ")", "if", "located", ":", "self", ".", "errcode", "=", "OK", "return", "Optimize", "(", "points", "=", "points", ")" ]
Parse the ouput resulted of a geometry optimization. Or a saddle point.
[ "Parse", "the", "ouput", "resulted", "of", "a", "geometry", "optimization", ".", "Or", "a", "saddle", "point", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L79-L104
16,350
chemlab/chemlab
chemlab/graphics/renderers/cylinder_imp.py
CylinderImpostorRenderer.change_attributes
def change_attributes(self, bounds, radii, colors): """Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed. """ self.n_cylinders = len(bounds) self.is_empty = True if self.n_cylinders == 0 else False if self.is_empty: self.bounds = bounds self.radii = radii self.colors = colors return # Do nothing # We pass the starting position 8 times, and each of these has # a mapping to the bounding box corner. self.bounds = np.array(bounds, dtype='float32') vertices, directions = self._gen_bounds(self.bounds) self.radii = np.array(radii, dtype='float32') prim_radii = self._gen_radii(self.radii) self.colors = np.array(colors, dtype='uint8') prim_colors = self._gen_colors(self.colors) local = np.array([ # First face -- front 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, # Second face -- back 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, # Third face -- left 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, # Fourth face -- right 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, # Fifth face -- up 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, # Sixth face -- down 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, ]).astype('float32') local = np.tile(local, self.n_cylinders) self._verts_vbo = VertexBuffer(vertices,GL_DYNAMIC_DRAW) self._directions_vbo = VertexBuffer(directions, GL_DYNAMIC_DRAW) self._local_vbo = VertexBuffer(local,GL_DYNAMIC_DRAW) self._color_vbo = VertexBuffer(prim_colors, GL_DYNAMIC_DRAW) self._radii_vbo = VertexBuffer(prim_radii, GL_DYNAMIC_DRAW)
python
def change_attributes(self, bounds, radii, colors): """Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed. """ self.n_cylinders = len(bounds) self.is_empty = True if self.n_cylinders == 0 else False if self.is_empty: self.bounds = bounds self.radii = radii self.colors = colors return # Do nothing # We pass the starting position 8 times, and each of these has # a mapping to the bounding box corner. self.bounds = np.array(bounds, dtype='float32') vertices, directions = self._gen_bounds(self.bounds) self.radii = np.array(radii, dtype='float32') prim_radii = self._gen_radii(self.radii) self.colors = np.array(colors, dtype='uint8') prim_colors = self._gen_colors(self.colors) local = np.array([ # First face -- front 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, # Second face -- back 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, # Third face -- left 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, # Fourth face -- right 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, # Fifth face -- up 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, # Sixth face -- down 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, ]).astype('float32') local = np.tile(local, self.n_cylinders) self._verts_vbo = VertexBuffer(vertices,GL_DYNAMIC_DRAW) self._directions_vbo = VertexBuffer(directions, GL_DYNAMIC_DRAW) self._local_vbo = VertexBuffer(local,GL_DYNAMIC_DRAW) self._color_vbo = VertexBuffer(prim_colors, GL_DYNAMIC_DRAW) self._radii_vbo = VertexBuffer(prim_radii, GL_DYNAMIC_DRAW)
[ "def", "change_attributes", "(", "self", ",", "bounds", ",", "radii", ",", "colors", ")", ":", "self", ".", "n_cylinders", "=", "len", "(", "bounds", ")", "self", ".", "is_empty", "=", "True", "if", "self", ".", "n_cylinders", "==", "0", "else", "False", "if", "self", ".", "is_empty", ":", "self", ".", "bounds", "=", "bounds", "self", ".", "radii", "=", "radii", "self", ".", "colors", "=", "colors", "return", "# Do nothing", "# We pass the starting position 8 times, and each of these has", "# a mapping to the bounding box corner.", "self", ".", "bounds", "=", "np", ".", "array", "(", "bounds", ",", "dtype", "=", "'float32'", ")", "vertices", ",", "directions", "=", "self", ".", "_gen_bounds", "(", "self", ".", "bounds", ")", "self", ".", "radii", "=", "np", ".", "array", "(", "radii", ",", "dtype", "=", "'float32'", ")", "prim_radii", "=", "self", ".", "_gen_radii", "(", "self", ".", "radii", ")", "self", ".", "colors", "=", "np", ".", "array", "(", "colors", ",", "dtype", "=", "'uint8'", ")", "prim_colors", "=", "self", ".", "_gen_colors", "(", "self", ".", "colors", ")", "local", "=", "np", ".", "array", "(", "[", "# First face -- front", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "# Second face -- back", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "# Third face -- left", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "# Fourth face -- right", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "# Fifth face -- up", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "# Sixth face -- down", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "0.0", ",", "0.0", ",", "]", ")", ".", "astype", "(", "'float32'", ")", "local", "=", "np", ".", "tile", "(", "local", ",", "self", ".", "n_cylinders", ")", "self", ".", "_verts_vbo", "=", "VertexBuffer", "(", "vertices", ",", "GL_DYNAMIC_DRAW", ")", "self", ".", "_directions_vbo", "=", "VertexBuffer", "(", "directions", ",", "GL_DYNAMIC_DRAW", ")", "self", ".", "_local_vbo", "=", "VertexBuffer", "(", "local", ",", "GL_DYNAMIC_DRAW", ")", "self", ".", "_color_vbo", "=", "VertexBuffer", "(", "prim_colors", ",", "GL_DYNAMIC_DRAW", ")", "self", ".", "_radii_vbo", "=", "VertexBuffer", "(", "prim_radii", ",", "GL_DYNAMIC_DRAW", ")" ]
Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed.
[ "Reinitialize", "the", "buffers", "to", "accomodate", "the", "new", "attributes", ".", "This", "is", "used", "to", "change", "the", "number", "of", "cylinders", "to", "be", "displayed", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L32-L123
16,351
chemlab/chemlab
chemlab/graphics/renderers/cylinder_imp.py
CylinderImpostorRenderer.update_bounds
def update_bounds(self, bounds): '''Update the bounds inplace''' self.bounds = np.array(bounds, dtype='float32') vertices, directions = self._gen_bounds(self.bounds) self._verts_vbo.set_data(vertices) self._directions_vbo.set_data(directions) self.widget.update()
python
def update_bounds(self, bounds): '''Update the bounds inplace''' self.bounds = np.array(bounds, dtype='float32') vertices, directions = self._gen_bounds(self.bounds) self._verts_vbo.set_data(vertices) self._directions_vbo.set_data(directions) self.widget.update()
[ "def", "update_bounds", "(", "self", ",", "bounds", ")", ":", "self", ".", "bounds", "=", "np", ".", "array", "(", "bounds", ",", "dtype", "=", "'float32'", ")", "vertices", ",", "directions", "=", "self", ".", "_gen_bounds", "(", "self", ".", "bounds", ")", "self", ".", "_verts_vbo", ".", "set_data", "(", "vertices", ")", "self", ".", "_directions_vbo", ".", "set_data", "(", "directions", ")", "self", ".", "widget", ".", "update", "(", ")" ]
Update the bounds inplace
[ "Update", "the", "bounds", "inplace" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L209-L216
16,352
chemlab/chemlab
chemlab/graphics/renderers/cylinder_imp.py
CylinderImpostorRenderer.update_radii
def update_radii(self, radii): '''Update the radii inplace''' self.radii = np.array(radii, dtype='float32') prim_radii = self._gen_radii(self.radii) self._radii_vbo.set_data(prim_radii) self.widget.update()
python
def update_radii(self, radii): '''Update the radii inplace''' self.radii = np.array(radii, dtype='float32') prim_radii = self._gen_radii(self.radii) self._radii_vbo.set_data(prim_radii) self.widget.update()
[ "def", "update_radii", "(", "self", ",", "radii", ")", ":", "self", ".", "radii", "=", "np", ".", "array", "(", "radii", ",", "dtype", "=", "'float32'", ")", "prim_radii", "=", "self", ".", "_gen_radii", "(", "self", ".", "radii", ")", "self", ".", "_radii_vbo", ".", "set_data", "(", "prim_radii", ")", "self", ".", "widget", ".", "update", "(", ")" ]
Update the radii inplace
[ "Update", "the", "radii", "inplace" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L218-L224
16,353
chemlab/chemlab
chemlab/graphics/renderers/cylinder_imp.py
CylinderImpostorRenderer.update_colors
def update_colors(self, colors): '''Update the colors inplace''' self.colors = np.array(colors, dtype='uint8') prim_colors = self._gen_colors(self.colors) self._color_vbo.set_data(prim_colors) self.widget.update()
python
def update_colors(self, colors): '''Update the colors inplace''' self.colors = np.array(colors, dtype='uint8') prim_colors = self._gen_colors(self.colors) self._color_vbo.set_data(prim_colors) self.widget.update()
[ "def", "update_colors", "(", "self", ",", "colors", ")", ":", "self", ".", "colors", "=", "np", ".", "array", "(", "colors", ",", "dtype", "=", "'uint8'", ")", "prim_colors", "=", "self", ".", "_gen_colors", "(", "self", ".", "colors", ")", "self", ".", "_color_vbo", ".", "set_data", "(", "prim_colors", ")", "self", ".", "widget", ".", "update", "(", ")" ]
Update the colors inplace
[ "Update", "the", "colors", "inplace" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L226-L232
16,354
chemlab/chemlab
chemlab/notebook/display.py
Display.system
def system(self, object, highlight=None, alpha=1.0, color=None, transparent=None): '''Display System object''' if self.backend == 'povray': kwargs = {} if color is not None: kwargs['color'] = color else: kwargs['color'] = default_colormap[object.type_array] self.plotter.camera.autozoom(object.r_array) self.plotter.points(object.r_array, alpha=alpha, **kwargs) return self
python
def system(self, object, highlight=None, alpha=1.0, color=None, transparent=None): '''Display System object''' if self.backend == 'povray': kwargs = {} if color is not None: kwargs['color'] = color else: kwargs['color'] = default_colormap[object.type_array] self.plotter.camera.autozoom(object.r_array) self.plotter.points(object.r_array, alpha=alpha, **kwargs) return self
[ "def", "system", "(", "self", ",", "object", ",", "highlight", "=", "None", ",", "alpha", "=", "1.0", ",", "color", "=", "None", ",", "transparent", "=", "None", ")", ":", "if", "self", ".", "backend", "==", "'povray'", ":", "kwargs", "=", "{", "}", "if", "color", "is", "not", "None", ":", "kwargs", "[", "'color'", "]", "=", "color", "else", ":", "kwargs", "[", "'color'", "]", "=", "default_colormap", "[", "object", ".", "type_array", "]", "self", ".", "plotter", ".", "camera", ".", "autozoom", "(", "object", ".", "r_array", ")", "self", ".", "plotter", ".", "points", "(", "object", ".", "r_array", ",", "alpha", "=", "alpha", ",", "*", "*", "kwargs", ")", "return", "self" ]
Display System object
[ "Display", "System", "object" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/notebook/display.py#L17-L29
16,355
chemlab/chemlab
chemlab/contrib/gromacs.py
make_gromacs
def make_gromacs(simulation, directory, clean=False): """Create gromacs directory structure""" if clean is False and os.path.exists(directory): raise ValueError( 'Cannot override {}, use option clean=True'.format(directory)) else: shutil.rmtree(directory, ignore_errors=True) os.mkdir(directory) # Check custom simulation potential if simulation.potential.intermolecular.type == 'custom': for pair in simulation.potential.intermolecular.special_pairs: table = to_table(simulation.potential.intermolecular.pair_interaction(*pair), simulation.cutoff) fname1 = os.path.join(directory, 'table_{}_{}.xvg'.format(pair[0], pair[1])) fname2 = os.path.join(directory, 'table_{}_{}.xvg'.format(pair[1], pair[0])) with open(fname1, 'w') as fd: fd.write(table) with open(fname2, 'w') as fd: fd.write(table) ndx = {'System' : np.arange(simulation.system.n_atoms, dtype='int')} for particle in simulation.potential.intermolecular.particles: idx = simulation.system.where(atom_name=particle)['atom'].nonzero()[0] ndx[particle] = idx with open(os.path.join(directory, 'index.ndx'), 'w') as fd: fd.write(to_ndx(ndx)) # Parameter file mdpfile = to_mdp(simulation) with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd: fd.write(mdpfile) # Topology file topfile = to_top(simulation.system, simulation.potential) with open(os.path.join(directory, 'topol.top'), 'w') as fd: fd.write(topfile) # Simulation file datafile(os.path.join(directory, 'conf.gro'), 'w').write('system', simulation.system) return directory
python
def make_gromacs(simulation, directory, clean=False): """Create gromacs directory structure""" if clean is False and os.path.exists(directory): raise ValueError( 'Cannot override {}, use option clean=True'.format(directory)) else: shutil.rmtree(directory, ignore_errors=True) os.mkdir(directory) # Check custom simulation potential if simulation.potential.intermolecular.type == 'custom': for pair in simulation.potential.intermolecular.special_pairs: table = to_table(simulation.potential.intermolecular.pair_interaction(*pair), simulation.cutoff) fname1 = os.path.join(directory, 'table_{}_{}.xvg'.format(pair[0], pair[1])) fname2 = os.path.join(directory, 'table_{}_{}.xvg'.format(pair[1], pair[0])) with open(fname1, 'w') as fd: fd.write(table) with open(fname2, 'w') as fd: fd.write(table) ndx = {'System' : np.arange(simulation.system.n_atoms, dtype='int')} for particle in simulation.potential.intermolecular.particles: idx = simulation.system.where(atom_name=particle)['atom'].nonzero()[0] ndx[particle] = idx with open(os.path.join(directory, 'index.ndx'), 'w') as fd: fd.write(to_ndx(ndx)) # Parameter file mdpfile = to_mdp(simulation) with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd: fd.write(mdpfile) # Topology file topfile = to_top(simulation.system, simulation.potential) with open(os.path.join(directory, 'topol.top'), 'w') as fd: fd.write(topfile) # Simulation file datafile(os.path.join(directory, 'conf.gro'), 'w').write('system', simulation.system) return directory
[ "def", "make_gromacs", "(", "simulation", ",", "directory", ",", "clean", "=", "False", ")", ":", "if", "clean", "is", "False", "and", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "raise", "ValueError", "(", "'Cannot override {}, use option clean=True'", ".", "format", "(", "directory", ")", ")", "else", ":", "shutil", ".", "rmtree", "(", "directory", ",", "ignore_errors", "=", "True", ")", "os", ".", "mkdir", "(", "directory", ")", "# Check custom simulation potential", "if", "simulation", ".", "potential", ".", "intermolecular", ".", "type", "==", "'custom'", ":", "for", "pair", "in", "simulation", ".", "potential", ".", "intermolecular", ".", "special_pairs", ":", "table", "=", "to_table", "(", "simulation", ".", "potential", ".", "intermolecular", ".", "pair_interaction", "(", "*", "pair", ")", ",", "simulation", ".", "cutoff", ")", "fname1", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "'table_{}_{}.xvg'", ".", "format", "(", "pair", "[", "0", "]", ",", "pair", "[", "1", "]", ")", ")", "fname2", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "'table_{}_{}.xvg'", ".", "format", "(", "pair", "[", "1", "]", ",", "pair", "[", "0", "]", ")", ")", "with", "open", "(", "fname1", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "table", ")", "with", "open", "(", "fname2", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "table", ")", "ndx", "=", "{", "'System'", ":", "np", ".", "arange", "(", "simulation", ".", "system", ".", "n_atoms", ",", "dtype", "=", "'int'", ")", "}", "for", "particle", "in", "simulation", ".", "potential", ".", "intermolecular", ".", "particles", ":", "idx", "=", "simulation", ".", "system", ".", "where", "(", "atom_name", "=", "particle", ")", "[", "'atom'", "]", ".", "nonzero", "(", ")", "[", "0", "]", "ndx", "[", "particle", "]", "=", "idx", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'index.ndx'", ")", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "to_ndx", "(", "ndx", ")", ")", "# Parameter file", "mdpfile", "=", "to_mdp", "(", "simulation", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'grompp.mdp'", ")", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "mdpfile", ")", "# Topology file", "topfile", "=", "to_top", "(", "simulation", ".", "system", ",", "simulation", ".", "potential", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'topol.top'", ")", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "topfile", ")", "# Simulation file", "datafile", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'conf.gro'", ")", ",", "'w'", ")", ".", "write", "(", "'system'", ",", "simulation", ".", "system", ")", "return", "directory" ]
Create gromacs directory structure
[ "Create", "gromacs", "directory", "structure" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/contrib/gromacs.py#L125-L175
16,356
chemlab/chemlab
chemlab/graphics/renderers/triangles.py
TriangleRenderer.update_vertices
def update_vertices(self, vertices): """ Update the triangle vertices. """ vertices = np.array(vertices, dtype=np.float32) self._vbo_v.set_data(vertices)
python
def update_vertices(self, vertices): """ Update the triangle vertices. """ vertices = np.array(vertices, dtype=np.float32) self._vbo_v.set_data(vertices)
[ "def", "update_vertices", "(", "self", ",", "vertices", ")", ":", "vertices", "=", "np", ".", "array", "(", "vertices", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "_vbo_v", ".", "set_data", "(", "vertices", ")" ]
Update the triangle vertices.
[ "Update", "the", "triangle", "vertices", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/triangles.py#L86-L92
16,357
chemlab/chemlab
chemlab/graphics/renderers/triangles.py
TriangleRenderer.update_normals
def update_normals(self, normals): """ Update the triangle normals. """ normals = np.array(normals, dtype=np.float32) self._vbo_n.set_data(normals)
python
def update_normals(self, normals): """ Update the triangle normals. """ normals = np.array(normals, dtype=np.float32) self._vbo_n.set_data(normals)
[ "def", "update_normals", "(", "self", ",", "normals", ")", ":", "normals", "=", "np", ".", "array", "(", "normals", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "_vbo_n", ".", "set_data", "(", "normals", ")" ]
Update the triangle normals.
[ "Update", "the", "triangle", "normals", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/triangles.py#L94-L100
16,358
chemlab/chemlab
chemlab/graphics/qt/qttrajectory.py
TrajectoryControls.set_ticks
def set_ticks(self, number): '''Set the number of frames to animate. ''' self.max_index = number self.current_index = 0 self.slider.setMaximum(self.max_index-1) self.slider.setMinimum(0) self.slider.setPageStep(1)
python
def set_ticks(self, number): '''Set the number of frames to animate. ''' self.max_index = number self.current_index = 0 self.slider.setMaximum(self.max_index-1) self.slider.setMinimum(0) self.slider.setPageStep(1)
[ "def", "set_ticks", "(", "self", ",", "number", ")", ":", "self", ".", "max_index", "=", "number", "self", ".", "current_index", "=", "0", "self", ".", "slider", ".", "setMaximum", "(", "self", ".", "max_index", "-", "1", ")", "self", ".", "slider", ".", "setMinimum", "(", "0", ")", "self", ".", "slider", ".", "setPageStep", "(", "1", ")" ]
Set the number of frames to animate.
[ "Set", "the", "number", "of", "frames", "to", "animate", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L229-L237
16,359
chemlab/chemlab
chemlab/graphics/qt/qttrajectory.py
QtTrajectoryViewer.set_text
def set_text(self, text): '''Update the time indicator in the interface. ''' self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text))
python
def set_text(self, text): '''Update the time indicator in the interface. ''' self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text))
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "self", ".", "traj_controls", ".", "timelabel", ".", "setText", "(", "self", ".", "traj_controls", ".", "_label_tmp", ".", "format", "(", "text", ")", ")" ]
Update the time indicator in the interface.
[ "Update", "the", "time", "indicator", "in", "the", "interface", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L316-L320
16,360
chemlab/chemlab
chemlab/graphics/qt/qttrajectory.py
QtTrajectoryViewer.update_function
def update_function(self, func, frames=None): '''Set the function to be called when it's time to display a frame. *func* should be a function that takes one integer argument that represents the frame that has to be played:: def func(index): # Update the renderers to match the # current animation index ''' # Back-compatibility if frames is not None: self.traj_controls.set_ticks(frames) self._update_function = func
python
def update_function(self, func, frames=None): '''Set the function to be called when it's time to display a frame. *func* should be a function that takes one integer argument that represents the frame that has to be played:: def func(index): # Update the renderers to match the # current animation index ''' # Back-compatibility if frames is not None: self.traj_controls.set_ticks(frames) self._update_function = func
[ "def", "update_function", "(", "self", ",", "func", ",", "frames", "=", "None", ")", ":", "# Back-compatibility", "if", "frames", "is", "not", "None", ":", "self", ".", "traj_controls", ".", "set_ticks", "(", "frames", ")", "self", ".", "_update_function", "=", "func" ]
Set the function to be called when it's time to display a frame. *func* should be a function that takes one integer argument that represents the frame that has to be played:: def func(index): # Update the renderers to match the # current animation index
[ "Set", "the", "function", "to", "be", "called", "when", "it", "s", "time", "to", "display", "a", "frame", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L371-L386
16,361
chemlab/chemlab
chemlab/graphics/transformations.py
rotation_matrix
def rotation_matrix(angle, direction): """ Create a rotation matrix corresponding to the rotation around a general axis by a specified angle. R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d) Parameters: angle : float a direction : array d """ d = numpy.array(direction, dtype=numpy.float64) d /= numpy.linalg.norm(d) eye = numpy.eye(3, dtype=numpy.float64) ddt = numpy.outer(d, d) skew = numpy.array([[ 0, d[2], -d[1]], [-d[2], 0, d[0]], [d[1], -d[0], 0]], dtype=numpy.float64) mtx = ddt + numpy.cos(angle) * (eye - ddt) + numpy.sin(angle) * skew M = numpy.eye(4) M[:3,:3] = mtx return M
python
def rotation_matrix(angle, direction): """ Create a rotation matrix corresponding to the rotation around a general axis by a specified angle. R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d) Parameters: angle : float a direction : array d """ d = numpy.array(direction, dtype=numpy.float64) d /= numpy.linalg.norm(d) eye = numpy.eye(3, dtype=numpy.float64) ddt = numpy.outer(d, d) skew = numpy.array([[ 0, d[2], -d[1]], [-d[2], 0, d[0]], [d[1], -d[0], 0]], dtype=numpy.float64) mtx = ddt + numpy.cos(angle) * (eye - ddt) + numpy.sin(angle) * skew M = numpy.eye(4) M[:3,:3] = mtx return M
[ "def", "rotation_matrix", "(", "angle", ",", "direction", ")", ":", "d", "=", "numpy", ".", "array", "(", "direction", ",", "dtype", "=", "numpy", ".", "float64", ")", "d", "/=", "numpy", ".", "linalg", ".", "norm", "(", "d", ")", "eye", "=", "numpy", ".", "eye", "(", "3", ",", "dtype", "=", "numpy", ".", "float64", ")", "ddt", "=", "numpy", ".", "outer", "(", "d", ",", "d", ")", "skew", "=", "numpy", ".", "array", "(", "[", "[", "0", ",", "d", "[", "2", "]", ",", "-", "d", "[", "1", "]", "]", ",", "[", "-", "d", "[", "2", "]", ",", "0", ",", "d", "[", "0", "]", "]", ",", "[", "d", "[", "1", "]", ",", "-", "d", "[", "0", "]", ",", "0", "]", "]", ",", "dtype", "=", "numpy", ".", "float64", ")", "mtx", "=", "ddt", "+", "numpy", ".", "cos", "(", "angle", ")", "*", "(", "eye", "-", "ddt", ")", "+", "numpy", ".", "sin", "(", "angle", ")", "*", "skew", "M", "=", "numpy", ".", "eye", "(", "4", ")", "M", "[", ":", "3", ",", ":", "3", "]", "=", "mtx", "return", "M" ]
Create a rotation matrix corresponding to the rotation around a general axis by a specified angle. R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d) Parameters: angle : float a direction : array d
[ "Create", "a", "rotation", "matrix", "corresponding", "to", "the", "rotation", "around", "a", "general", "axis", "by", "a", "specified", "angle", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L341-L366
16,362
chemlab/chemlab
chemlab/graphics/transformations.py
rotation_from_matrix
def rotation_from_matrix(matrix): """Return rotation angle and axis from rotation matrix. >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> angle, direc, point = rotation_from_matrix(R0) >>> R1 = rotation_matrix(angle, direc, point) >>> is_same_transform(R0, R1) True """ R = numpy.array(matrix, dtype=numpy.float64, copy=False) R33 = R[:3, :3] # direction: unit eigenvector of R33 corresponding to eigenvalue of 1 w, W = numpy.linalg.eig(R33.T) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") direction = numpy.real(W[:, i[-1]]).squeeze() # point: unit eigenvector of R33 corresponding to eigenvalue of 1 w, Q = numpy.linalg.eig(R) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") point = numpy.real(Q[:, i[-1]]).squeeze() point /= point[3] # rotation angle depending on direction cosa = (numpy.trace(R33) - 1.0) / 2.0 if abs(direction[2]) > 1e-8: sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2] elif abs(direction[1]) > 1e-8: sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1] else: sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0] angle = math.atan2(sina, cosa) return angle, direction, point
python
def rotation_from_matrix(matrix): """Return rotation angle and axis from rotation matrix. >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> angle, direc, point = rotation_from_matrix(R0) >>> R1 = rotation_matrix(angle, direc, point) >>> is_same_transform(R0, R1) True """ R = numpy.array(matrix, dtype=numpy.float64, copy=False) R33 = R[:3, :3] # direction: unit eigenvector of R33 corresponding to eigenvalue of 1 w, W = numpy.linalg.eig(R33.T) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") direction = numpy.real(W[:, i[-1]]).squeeze() # point: unit eigenvector of R33 corresponding to eigenvalue of 1 w, Q = numpy.linalg.eig(R) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") point = numpy.real(Q[:, i[-1]]).squeeze() point /= point[3] # rotation angle depending on direction cosa = (numpy.trace(R33) - 1.0) / 2.0 if abs(direction[2]) > 1e-8: sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2] elif abs(direction[1]) > 1e-8: sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1] else: sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0] angle = math.atan2(sina, cosa) return angle, direction, point
[ "def", "rotation_from_matrix", "(", "matrix", ")", ":", "R", "=", "numpy", ".", "array", "(", "matrix", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "R33", "=", "R", "[", ":", "3", ",", ":", "3", "]", "# direction: unit eigenvector of R33 corresponding to eigenvalue of 1", "w", ",", "W", "=", "numpy", ".", "linalg", ".", "eig", "(", "R33", ".", "T", ")", "i", "=", "numpy", ".", "where", "(", "abs", "(", "numpy", ".", "real", "(", "w", ")", "-", "1.0", ")", "<", "1e-8", ")", "[", "0", "]", "if", "not", "len", "(", "i", ")", ":", "raise", "ValueError", "(", "\"no unit eigenvector corresponding to eigenvalue 1\"", ")", "direction", "=", "numpy", ".", "real", "(", "W", "[", ":", ",", "i", "[", "-", "1", "]", "]", ")", ".", "squeeze", "(", ")", "# point: unit eigenvector of R33 corresponding to eigenvalue of 1", "w", ",", "Q", "=", "numpy", ".", "linalg", ".", "eig", "(", "R", ")", "i", "=", "numpy", ".", "where", "(", "abs", "(", "numpy", ".", "real", "(", "w", ")", "-", "1.0", ")", "<", "1e-8", ")", "[", "0", "]", "if", "not", "len", "(", "i", ")", ":", "raise", "ValueError", "(", "\"no unit eigenvector corresponding to eigenvalue 1\"", ")", "point", "=", "numpy", ".", "real", "(", "Q", "[", ":", ",", "i", "[", "-", "1", "]", "]", ")", ".", "squeeze", "(", ")", "point", "/=", "point", "[", "3", "]", "# rotation angle depending on direction", "cosa", "=", "(", "numpy", ".", "trace", "(", "R33", ")", "-", "1.0", ")", "/", "2.0", "if", "abs", "(", "direction", "[", "2", "]", ")", ">", "1e-8", ":", "sina", "=", "(", "R", "[", "1", ",", "0", "]", "+", "(", "cosa", "-", "1.0", ")", "*", "direction", "[", "0", "]", "*", "direction", "[", "1", "]", ")", "/", "direction", "[", "2", "]", "elif", "abs", "(", "direction", "[", "1", "]", ")", ">", "1e-8", ":", "sina", "=", "(", "R", "[", "0", ",", "2", "]", "+", "(", "cosa", "-", "1.0", ")", "*", "direction", "[", "0", "]", "*", "direction", "[", "2", "]", ")", "/", "direction", "[", "1", "]", "else", ":", "sina", "=", "(", "R", "[", "2", ",", "1", "]", "+", "(", "cosa", "-", "1.0", ")", "*", "direction", "[", "1", "]", "*", "direction", "[", "2", "]", ")", "/", "direction", "[", "0", "]", "angle", "=", "math", ".", "atan2", "(", "sina", ",", "cosa", ")", "return", "angle", ",", "direction", ",", "point" ]
Return rotation angle and axis from rotation matrix. >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> angle, direc, point = rotation_from_matrix(R0) >>> R1 = rotation_matrix(angle, direc, point) >>> is_same_transform(R0, R1) True
[ "Return", "rotation", "angle", "and", "axis", "from", "rotation", "matrix", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L369-L406
16,363
chemlab/chemlab
chemlab/graphics/transformations.py
scale_from_matrix
def scale_from_matrix(matrix): """Return scaling factor, origin and direction from scaling matrix. >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S0 = scale_matrix(factor, origin) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True >>> S0 = scale_matrix(factor, origin, direct) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] factor = numpy.trace(M33) - 2.0 try: # direction: unit eigenvector corresponding to eigenvalue factor w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0] direction = numpy.real(V[:, i]).squeeze() direction /= vector_norm(direction) except IndexError: # uniform scaling factor = (factor + 2.0) / 3.0 direction = None # origin: any eigenvector corresponding to eigenvalue 1 w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 1") origin = numpy.real(V[:, i[-1]]).squeeze() origin /= origin[3] return factor, origin, direction
python
def scale_from_matrix(matrix): """Return scaling factor, origin and direction from scaling matrix. >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S0 = scale_matrix(factor, origin) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True >>> S0 = scale_matrix(factor, origin, direct) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] factor = numpy.trace(M33) - 2.0 try: # direction: unit eigenvector corresponding to eigenvalue factor w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0] direction = numpy.real(V[:, i]).squeeze() direction /= vector_norm(direction) except IndexError: # uniform scaling factor = (factor + 2.0) / 3.0 direction = None # origin: any eigenvector corresponding to eigenvalue 1 w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 1") origin = numpy.real(V[:, i[-1]]).squeeze() origin /= origin[3] return factor, origin, direction
[ "def", "scale_from_matrix", "(", "matrix", ")", ":", "M", "=", "numpy", ".", "array", "(", "matrix", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "M33", "=", "M", "[", ":", "3", ",", ":", "3", "]", "factor", "=", "numpy", ".", "trace", "(", "M33", ")", "-", "2.0", "try", ":", "# direction: unit eigenvector corresponding to eigenvalue factor", "w", ",", "V", "=", "numpy", ".", "linalg", ".", "eig", "(", "M33", ")", "i", "=", "numpy", ".", "where", "(", "abs", "(", "numpy", ".", "real", "(", "w", ")", "-", "factor", ")", "<", "1e-8", ")", "[", "0", "]", "[", "0", "]", "direction", "=", "numpy", ".", "real", "(", "V", "[", ":", ",", "i", "]", ")", ".", "squeeze", "(", ")", "direction", "/=", "vector_norm", "(", "direction", ")", "except", "IndexError", ":", "# uniform scaling", "factor", "=", "(", "factor", "+", "2.0", ")", "/", "3.0", "direction", "=", "None", "# origin: any eigenvector corresponding to eigenvalue 1", "w", ",", "V", "=", "numpy", ".", "linalg", ".", "eig", "(", "M", ")", "i", "=", "numpy", ".", "where", "(", "abs", "(", "numpy", ".", "real", "(", "w", ")", "-", "1.0", ")", "<", "1e-8", ")", "[", "0", "]", "if", "not", "len", "(", "i", ")", ":", "raise", "ValueError", "(", "\"no eigenvector corresponding to eigenvalue 1\"", ")", "origin", "=", "numpy", ".", "real", "(", "V", "[", ":", ",", "i", "[", "-", "1", "]", "]", ")", ".", "squeeze", "(", ")", "origin", "/=", "origin", "[", "3", "]", "return", "factor", ",", "origin", ",", "direction" ]
Return scaling factor, origin and direction from scaling matrix. >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S0 = scale_matrix(factor, origin) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True >>> S0 = scale_matrix(factor, origin, direct) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True
[ "Return", "scaling", "factor", "origin", "and", "direction", "from", "scaling", "matrix", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L443-L481
16,364
chemlab/chemlab
chemlab/graphics/transformations.py
orthogonalization_matrix
def orthogonalization_matrix(lengths, angles): """Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True """ a, b, c = lengths angles = numpy.radians(angles) sina, sinb, _ = numpy.sin(angles) cosa, cosb, cosg = numpy.cos(angles) co = (cosa * cosb - cosg) / (sina * sinb) return numpy.array([ [ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0], [-a*sinb*co, b*sina, 0.0, 0.0], [ a*cosb, b*cosa, c, 0.0], [ 0.0, 0.0, 0.0, 1.0]])
python
def orthogonalization_matrix(lengths, angles): """Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True """ a, b, c = lengths angles = numpy.radians(angles) sina, sinb, _ = numpy.sin(angles) cosa, cosb, cosg = numpy.cos(angles) co = (cosa * cosb - cosg) / (sina * sinb) return numpy.array([ [ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0], [-a*sinb*co, b*sina, 0.0, 0.0], [ a*cosb, b*cosa, c, 0.0], [ 0.0, 0.0, 0.0, 1.0]])
[ "def", "orthogonalization_matrix", "(", "lengths", ",", "angles", ")", ":", "a", ",", "b", ",", "c", "=", "lengths", "angles", "=", "numpy", ".", "radians", "(", "angles", ")", "sina", ",", "sinb", ",", "_", "=", "numpy", ".", "sin", "(", "angles", ")", "cosa", ",", "cosb", ",", "cosg", "=", "numpy", ".", "cos", "(", "angles", ")", "co", "=", "(", "cosa", "*", "cosb", "-", "cosg", ")", "/", "(", "sina", "*", "sinb", ")", "return", "numpy", ".", "array", "(", "[", "[", "a", "*", "sinb", "*", "math", ".", "sqrt", "(", "1.0", "-", "co", "*", "co", ")", ",", "0.0", ",", "0.0", ",", "0.0", "]", ",", "[", "-", "a", "*", "sinb", "*", "co", ",", "b", "*", "sina", ",", "0.0", ",", "0.0", "]", ",", "[", "a", "*", "cosb", ",", "b", "*", "cosa", ",", "c", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")" ]
Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True
[ "Return", "orthogonalization", "matrix", "for", "crystallographic", "cell", "coordinates", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L903-L927
16,365
chemlab/chemlab
chemlab/graphics/transformations.py
superimposition_matrix
def superimposition_matrix(v0, v1, scale=False, usesvd=True): """Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Eucledian transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd)
python
def superimposition_matrix(v0, v1, scale=False, usesvd=True): """Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Eucledian transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd)
[ "def", "superimposition_matrix", "(", "v0", ",", "v1", ",", "scale", "=", "False", ",", "usesvd", "=", "True", ")", ":", "v0", "=", "numpy", ".", "array", "(", "v0", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "[", ":", "3", "]", "v1", "=", "numpy", ".", "array", "(", "v1", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "[", ":", "3", "]", "return", "affine_matrix_from_points", "(", "v0", ",", "v1", ",", "shear", "=", "False", ",", "scale", "=", "scale", ",", "usesvd", "=", "usesvd", ")" ]
Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Eucledian transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True
[ "Return", "matrix", "to", "transform", "given", "3D", "point", "set", "into", "second", "point", "set", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1039-L1087
16,366
chemlab/chemlab
chemlab/graphics/transformations.py
quaternion_matrix
def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion. >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0]) >>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0])) True >>> M = quaternion_matrix([1, 0, 0, 0]) >>> numpy.allclose(M, numpy.identity(4)) True >>> M = quaternion_matrix([0, 1, 0, 0]) >>> numpy.allclose(M, numpy.diag([1, -1, -1, 1])) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) n = numpy.dot(q, q) if n < _EPS: return numpy.identity(4) q *= math.sqrt(2.0 / n) q = numpy.outer(q, q) return numpy.array([ [1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0], [ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0], [ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0], [ 0.0, 0.0, 0.0, 1.0]])
python
def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion. >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0]) >>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0])) True >>> M = quaternion_matrix([1, 0, 0, 0]) >>> numpy.allclose(M, numpy.identity(4)) True >>> M = quaternion_matrix([0, 1, 0, 0]) >>> numpy.allclose(M, numpy.diag([1, -1, -1, 1])) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) n = numpy.dot(q, q) if n < _EPS: return numpy.identity(4) q *= math.sqrt(2.0 / n) q = numpy.outer(q, q) return numpy.array([ [1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0], [ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0], [ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0], [ 0.0, 0.0, 0.0, 1.0]])
[ "def", "quaternion_matrix", "(", "quaternion", ")", ":", "q", "=", "numpy", ".", "array", "(", "quaternion", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "n", "=", "numpy", ".", "dot", "(", "q", ",", "q", ")", "if", "n", "<", "_EPS", ":", "return", "numpy", ".", "identity", "(", "4", ")", "q", "*=", "math", ".", "sqrt", "(", "2.0", "/", "n", ")", "q", "=", "numpy", ".", "outer", "(", "q", ",", "q", ")", "return", "numpy", ".", "array", "(", "[", "[", "1.0", "-", "q", "[", "2", ",", "2", "]", "-", "q", "[", "3", ",", "3", "]", ",", "q", "[", "1", ",", "2", "]", "-", "q", "[", "3", ",", "0", "]", ",", "q", "[", "1", ",", "3", "]", "+", "q", "[", "2", ",", "0", "]", ",", "0.0", "]", ",", "[", "q", "[", "1", ",", "2", "]", "+", "q", "[", "3", ",", "0", "]", ",", "1.0", "-", "q", "[", "1", ",", "1", "]", "-", "q", "[", "3", ",", "3", "]", ",", "q", "[", "2", ",", "3", "]", "-", "q", "[", "1", ",", "0", "]", ",", "0.0", "]", ",", "[", "q", "[", "1", ",", "3", "]", "-", "q", "[", "2", ",", "0", "]", ",", "q", "[", "2", ",", "3", "]", "+", "q", "[", "1", ",", "0", "]", ",", "1.0", "-", "q", "[", "1", ",", "1", "]", "-", "q", "[", "2", ",", "2", "]", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")" ]
Return homogeneous rotation matrix from quaternion. >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0]) >>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0])) True >>> M = quaternion_matrix([1, 0, 0, 0]) >>> numpy.allclose(M, numpy.identity(4)) True >>> M = quaternion_matrix([0, 1, 0, 0]) >>> numpy.allclose(M, numpy.diag([1, -1, -1, 1])) True
[ "Return", "homogeneous", "rotation", "matrix", "from", "quaternion", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1295-L1319
16,367
chemlab/chemlab
chemlab/graphics/transformations.py
quaternion_multiply
def quaternion_multiply(quaternion1, quaternion0): """Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True """ w0, x0, y0, z0 = quaternion0 w1, x1, y1, z1 = quaternion1 return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0, x1*w0 + y1*z0 - z1*y0 + w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64)
python
def quaternion_multiply(quaternion1, quaternion0): """Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True """ w0, x0, y0, z0 = quaternion0 w1, x1, y1, z1 = quaternion1 return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0, x1*w0 + y1*z0 - z1*y0 + w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64)
[ "def", "quaternion_multiply", "(", "quaternion1", ",", "quaternion0", ")", ":", "w0", ",", "x0", ",", "y0", ",", "z0", "=", "quaternion0", "w1", ",", "x1", ",", "y1", ",", "z1", "=", "quaternion1", "return", "numpy", ".", "array", "(", "[", "-", "x1", "*", "x0", "-", "y1", "*", "y0", "-", "z1", "*", "z0", "+", "w1", "*", "w0", ",", "x1", "*", "w0", "+", "y1", "*", "z0", "-", "z1", "*", "y0", "+", "w1", "*", "x0", ",", "-", "x1", "*", "z0", "+", "y1", "*", "w0", "+", "z1", "*", "x0", "+", "w1", "*", "y0", ",", "x1", "*", "y0", "-", "y1", "*", "x0", "+", "z1", "*", "w0", "+", "w1", "*", "z0", "]", ",", "dtype", "=", "numpy", ".", "float64", ")" ]
Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True
[ "Return", "multiplication", "of", "two", "quaternions", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1399-L1412
16,368
chemlab/chemlab
chemlab/graphics/transformations.py
angle_between_vectors
def angle_between_vectors(v0, v1, directed=True, axis=0): """Return angle between vectors. If directed is False, the input vectors are interpreted as undirected axes, i.e. the maximum angle is pi/2. >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3]) >>> numpy.allclose(a, math.pi) True >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False) >>> numpy.allclose(a, 0) True >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]] >>> v1 = [[3], [0], [0]] >>> a = angle_between_vectors(v0, v1) >>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532]) True >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]] >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]] >>> a = angle_between_vectors(v0, v1, axis=1) >>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532]) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False) v1 = numpy.array(v1, dtype=numpy.float64, copy=False) dot = numpy.sum(v0 * v1, axis=axis) dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis) return numpy.arccos(dot if directed else numpy.fabs(dot))
python
def angle_between_vectors(v0, v1, directed=True, axis=0): """Return angle between vectors. If directed is False, the input vectors are interpreted as undirected axes, i.e. the maximum angle is pi/2. >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3]) >>> numpy.allclose(a, math.pi) True >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False) >>> numpy.allclose(a, 0) True >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]] >>> v1 = [[3], [0], [0]] >>> a = angle_between_vectors(v0, v1) >>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532]) True >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]] >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]] >>> a = angle_between_vectors(v0, v1, axis=1) >>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532]) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False) v1 = numpy.array(v1, dtype=numpy.float64, copy=False) dot = numpy.sum(v0 * v1, axis=axis) dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis) return numpy.arccos(dot if directed else numpy.fabs(dot))
[ "def", "angle_between_vectors", "(", "v0", ",", "v1", ",", "directed", "=", "True", ",", "axis", "=", "0", ")", ":", "v0", "=", "numpy", ".", "array", "(", "v0", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "v1", "=", "numpy", ".", "array", "(", "v1", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "dot", "=", "numpy", ".", "sum", "(", "v0", "*", "v1", ",", "axis", "=", "axis", ")", "dot", "/=", "vector_norm", "(", "v0", ",", "axis", "=", "axis", ")", "*", "vector_norm", "(", "v1", ",", "axis", "=", "axis", ")", "return", "numpy", ".", "arccos", "(", "dot", "if", "directed", "else", "numpy", ".", "fabs", "(", "dot", ")", ")" ]
Return angle between vectors. If directed is False, the input vectors are interpreted as undirected axes, i.e. the maximum angle is pi/2. >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3]) >>> numpy.allclose(a, math.pi) True >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False) >>> numpy.allclose(a, 0) True >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]] >>> v1 = [[3], [0], [0]] >>> a = angle_between_vectors(v0, v1) >>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532]) True >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]] >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]] >>> a = angle_between_vectors(v0, v1, axis=1) >>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532]) True
[ "Return", "angle", "between", "vectors", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1846-L1874
16,369
chemlab/chemlab
chemlab/graphics/transformations.py
Arcball.drag
def drag(self, point): """Update current cursor window coordinates.""" vnow = arcball_map_to_sphere(point, self._center, self._radius) if self._axis is not None: vnow = arcball_constrain_to_axis(vnow, self._axis) self._qpre = self._qnow t = numpy.cross(self._vdown, vnow) if numpy.dot(t, t) < _EPS: self._qnow = self._qdown else: q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]] self._qnow = quaternion_multiply(q, self._qdown)
python
def drag(self, point): """Update current cursor window coordinates.""" vnow = arcball_map_to_sphere(point, self._center, self._radius) if self._axis is not None: vnow = arcball_constrain_to_axis(vnow, self._axis) self._qpre = self._qnow t = numpy.cross(self._vdown, vnow) if numpy.dot(t, t) < _EPS: self._qnow = self._qdown else: q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]] self._qnow = quaternion_multiply(q, self._qdown)
[ "def", "drag", "(", "self", ",", "point", ")", ":", "vnow", "=", "arcball_map_to_sphere", "(", "point", ",", "self", ".", "_center", ",", "self", ".", "_radius", ")", "if", "self", ".", "_axis", "is", "not", "None", ":", "vnow", "=", "arcball_constrain_to_axis", "(", "vnow", ",", "self", ".", "_axis", ")", "self", ".", "_qpre", "=", "self", ".", "_qnow", "t", "=", "numpy", ".", "cross", "(", "self", ".", "_vdown", ",", "vnow", ")", "if", "numpy", ".", "dot", "(", "t", ",", "t", ")", "<", "_EPS", ":", "self", ".", "_qnow", "=", "self", ".", "_qdown", "else", ":", "q", "=", "[", "numpy", ".", "dot", "(", "self", ".", "_vdown", ",", "vnow", ")", ",", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", "]", "self", ".", "_qnow", "=", "quaternion_multiply", "(", "q", ",", "self", ".", "_qdown", ")" ]
Update current cursor window coordinates.
[ "Update", "current", "cursor", "window", "coordinates", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1633-L1644
16,370
chemlab/chemlab
chemlab/notebook/__init__.py
load_trajectory
def load_trajectory(name, format=None, skip=1): '''Read a trajectory from a file. .. seealso:: `chemlab.io.datafile` ''' df = datafile(name, format=format) ret = {} t, coords = df.read('trajectory', skip=skip) boxes = df.read('boxes') ret['t'] = t ret['coords'] = coords ret['boxes'] = boxes return ret
python
def load_trajectory(name, format=None, skip=1): '''Read a trajectory from a file. .. seealso:: `chemlab.io.datafile` ''' df = datafile(name, format=format) ret = {} t, coords = df.read('trajectory', skip=skip) boxes = df.read('boxes') ret['t'] = t ret['coords'] = coords ret['boxes'] = boxes return ret
[ "def", "load_trajectory", "(", "name", ",", "format", "=", "None", ",", "skip", "=", "1", ")", ":", "df", "=", "datafile", "(", "name", ",", "format", "=", "format", ")", "ret", "=", "{", "}", "t", ",", "coords", "=", "df", ".", "read", "(", "'trajectory'", ",", "skip", "=", "skip", ")", "boxes", "=", "df", ".", "read", "(", "'boxes'", ")", "ret", "[", "'t'", "]", "=", "t", "ret", "[", "'coords'", "]", "=", "coords", "ret", "[", "'boxes'", "]", "=", "boxes", "return", "ret" ]
Read a trajectory from a file. .. seealso:: `chemlab.io.datafile`
[ "Read", "a", "trajectory", "from", "a", "file", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/notebook/__init__.py#L78-L93
16,371
chemlab/chemlab
chemlab/mviewer/api/selections.py
select_atoms
def select_atoms(indices): '''Select atoms by their indices. You can select the first 3 atoms as follows:: select_atoms([0, 1, 2]) Return the current selection dictionary. ''' rep = current_representation() rep.select({'atoms': Selection(indices, current_system().n_atoms)}) return rep.selection_state
python
def select_atoms(indices): '''Select atoms by their indices. You can select the first 3 atoms as follows:: select_atoms([0, 1, 2]) Return the current selection dictionary. ''' rep = current_representation() rep.select({'atoms': Selection(indices, current_system().n_atoms)}) return rep.selection_state
[ "def", "select_atoms", "(", "indices", ")", ":", "rep", "=", "current_representation", "(", ")", "rep", ".", "select", "(", "{", "'atoms'", ":", "Selection", "(", "indices", ",", "current_system", "(", ")", ".", "n_atoms", ")", "}", ")", "return", "rep", ".", "selection_state" ]
Select atoms by their indices. You can select the first 3 atoms as follows:: select_atoms([0, 1, 2]) Return the current selection dictionary.
[ "Select", "atoms", "by", "their", "indices", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L20-L32
16,372
chemlab/chemlab
chemlab/mviewer/api/selections.py
select_connected_bonds
def select_connected_bonds(): '''Select the bonds connected to the currently selected atoms.''' s = current_system() start, end = s.bonds.transpose() selected = np.zeros(s.n_bonds, 'bool') for i in selected_atoms(): selected |= (i == start) | (i == end) csel = current_selection() bsel = csel['bonds'].add( Selection(selected.nonzero()[0], s.n_bonds)) ret = csel.copy() ret['bonds'] = bsel return select_selection(ret)
python
def select_connected_bonds(): '''Select the bonds connected to the currently selected atoms.''' s = current_system() start, end = s.bonds.transpose() selected = np.zeros(s.n_bonds, 'bool') for i in selected_atoms(): selected |= (i == start) | (i == end) csel = current_selection() bsel = csel['bonds'].add( Selection(selected.nonzero()[0], s.n_bonds)) ret = csel.copy() ret['bonds'] = bsel return select_selection(ret)
[ "def", "select_connected_bonds", "(", ")", ":", "s", "=", "current_system", "(", ")", "start", ",", "end", "=", "s", ".", "bonds", ".", "transpose", "(", ")", "selected", "=", "np", ".", "zeros", "(", "s", ".", "n_bonds", ",", "'bool'", ")", "for", "i", "in", "selected_atoms", "(", ")", ":", "selected", "|=", "(", "i", "==", "start", ")", "|", "(", "i", "==", "end", ")", "csel", "=", "current_selection", "(", ")", "bsel", "=", "csel", "[", "'bonds'", "]", ".", "add", "(", "Selection", "(", "selected", ".", "nonzero", "(", ")", "[", "0", "]", ",", "s", ".", "n_bonds", ")", ")", "ret", "=", "csel", ".", "copy", "(", ")", "ret", "[", "'bonds'", "]", "=", "bsel", "return", "select_selection", "(", "ret", ")" ]
Select the bonds connected to the currently selected atoms.
[ "Select", "the", "bonds", "connected", "to", "the", "currently", "selected", "atoms", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L54-L69
16,373
chemlab/chemlab
chemlab/mviewer/api/selections.py
select_molecules
def select_molecules(name): '''Select all the molecules corresponding to the formulas.''' mol_formula = current_system().get_derived_molecule_array('formula') mask = mol_formula == name ind = current_system().mol_to_atom_indices(mask.nonzero()[0]) selection = {'atoms': Selection(ind, current_system().n_atoms)} # Need to find the bonds between the atoms b = current_system().bonds if len(b) == 0: selection['bonds'] = Selection([], 0) else: molbonds = np.zeros(len(b), 'bool') for i in ind: matching = (i == b).sum(axis=1).astype('bool') molbonds[matching] = True selection['bonds'] = Selection(molbonds.nonzero()[0], len(b)) return select_selection(selection)
python
def select_molecules(name): '''Select all the molecules corresponding to the formulas.''' mol_formula = current_system().get_derived_molecule_array('formula') mask = mol_formula == name ind = current_system().mol_to_atom_indices(mask.nonzero()[0]) selection = {'atoms': Selection(ind, current_system().n_atoms)} # Need to find the bonds between the atoms b = current_system().bonds if len(b) == 0: selection['bonds'] = Selection([], 0) else: molbonds = np.zeros(len(b), 'bool') for i in ind: matching = (i == b).sum(axis=1).astype('bool') molbonds[matching] = True selection['bonds'] = Selection(molbonds.nonzero()[0], len(b)) return select_selection(selection)
[ "def", "select_molecules", "(", "name", ")", ":", "mol_formula", "=", "current_system", "(", ")", ".", "get_derived_molecule_array", "(", "'formula'", ")", "mask", "=", "mol_formula", "==", "name", "ind", "=", "current_system", "(", ")", ".", "mol_to_atom_indices", "(", "mask", ".", "nonzero", "(", ")", "[", "0", "]", ")", "selection", "=", "{", "'atoms'", ":", "Selection", "(", "ind", ",", "current_system", "(", ")", ".", "n_atoms", ")", "}", "# Need to find the bonds between the atoms", "b", "=", "current_system", "(", ")", ".", "bonds", "if", "len", "(", "b", ")", "==", "0", ":", "selection", "[", "'bonds'", "]", "=", "Selection", "(", "[", "]", ",", "0", ")", "else", ":", "molbonds", "=", "np", ".", "zeros", "(", "len", "(", "b", ")", ",", "'bool'", ")", "for", "i", "in", "ind", ":", "matching", "=", "(", "i", "==", "b", ")", ".", "sum", "(", "axis", "=", "1", ")", ".", "astype", "(", "'bool'", ")", "molbonds", "[", "matching", "]", "=", "True", "selection", "[", "'bonds'", "]", "=", "Selection", "(", "molbonds", ".", "nonzero", "(", ")", "[", "0", "]", ",", "len", "(", "b", ")", ")", "return", "select_selection", "(", "selection", ")" ]
Select all the molecules corresponding to the formulas.
[ "Select", "all", "the", "molecules", "corresponding", "to", "the", "formulas", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L85-L105
16,374
chemlab/chemlab
chemlab/mviewer/api/selections.py
hide_selected
def hide_selected(): '''Hide the selected objects.''' ss = current_representation().selection_state hs = current_representation().hidden_state res = {} for k in ss: res[k] = hs[k].add(ss[k]) current_representation().hide(res)
python
def hide_selected(): '''Hide the selected objects.''' ss = current_representation().selection_state hs = current_representation().hidden_state res = {} for k in ss: res[k] = hs[k].add(ss[k]) current_representation().hide(res)
[ "def", "hide_selected", "(", ")", ":", "ss", "=", "current_representation", "(", ")", ".", "selection_state", "hs", "=", "current_representation", "(", ")", ".", "hidden_state", "res", "=", "{", "}", "for", "k", "in", "ss", ":", "res", "[", "k", "]", "=", "hs", "[", "k", "]", ".", "add", "(", "ss", "[", "k", "]", ")", "current_representation", "(", ")", ".", "hide", "(", "res", ")" ]
Hide the selected objects.
[ "Hide", "the", "selected", "objects", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L113-L122
16,375
chemlab/chemlab
chemlab/mviewer/api/selections.py
unhide_selected
def unhide_selected(): '''Unhide the selected objects''' hidden_state = current_representation().hidden_state selection_state = current_representation().selection_state res = {} # Take the hidden state and flip the selected atoms bits. for k in selection_state: visible = hidden_state[k].invert() visible_and_selected = visible.add(selection_state[k]) # Add some atoms to be visible res[k] = visible_and_selected.invert() current_representation().hide(res)
python
def unhide_selected(): '''Unhide the selected objects''' hidden_state = current_representation().hidden_state selection_state = current_representation().selection_state res = {} # Take the hidden state and flip the selected atoms bits. for k in selection_state: visible = hidden_state[k].invert() visible_and_selected = visible.add(selection_state[k]) # Add some atoms to be visible res[k] = visible_and_selected.invert() current_representation().hide(res)
[ "def", "unhide_selected", "(", ")", ":", "hidden_state", "=", "current_representation", "(", ")", ".", "hidden_state", "selection_state", "=", "current_representation", "(", ")", ".", "selection_state", "res", "=", "{", "}", "# Take the hidden state and flip the selected atoms bits.", "for", "k", "in", "selection_state", ":", "visible", "=", "hidden_state", "[", "k", "]", ".", "invert", "(", ")", "visible_and_selected", "=", "visible", ".", "add", "(", "selection_state", "[", "k", "]", ")", "# Add some atoms to be visible", "res", "[", "k", "]", "=", "visible_and_selected", ".", "invert", "(", ")", "current_representation", "(", ")", ".", "hide", "(", "res", ")" ]
Unhide the selected objects
[ "Unhide", "the", "selected", "objects" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L137-L150
16,376
chemlab/chemlab
chemlab/graphics/camera.py
Camera.mouse_rotate
def mouse_rotate(self, dx, dy): '''Convenience function to implement the mouse rotation by giving two displacements in the x and y directions. ''' fact = 1.5 self.orbit_y(-dx*fact) self.orbit_x(dy*fact)
python
def mouse_rotate(self, dx, dy): '''Convenience function to implement the mouse rotation by giving two displacements in the x and y directions. ''' fact = 1.5 self.orbit_y(-dx*fact) self.orbit_x(dy*fact)
[ "def", "mouse_rotate", "(", "self", ",", "dx", ",", "dy", ")", ":", "fact", "=", "1.5", "self", ".", "orbit_y", "(", "-", "dx", "*", "fact", ")", "self", ".", "orbit_x", "(", "dy", "*", "fact", ")" ]
Convenience function to implement the mouse rotation by giving two displacements in the x and y directions.
[ "Convenience", "function", "to", "implement", "the", "mouse", "rotation", "by", "giving", "two", "displacements", "in", "the", "x", "and", "y", "directions", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L148-L155
16,377
chemlab/chemlab
chemlab/graphics/camera.py
Camera.mouse_zoom
def mouse_zoom(self, inc): '''Convenience function to implement a zoom function. This is achieved by moving ``Camera.position`` in the direction of the ``Camera.c`` vector. ''' # Square Distance from pivot dsq = np.linalg.norm(self.position - self.pivot) minsq = 1.0**2 # How near can we be to the pivot maxsq = 7.0**2 # How far can we go scalefac = 0.25 if dsq > maxsq and inc < 0: # We're going too far pass elif dsq < minsq and inc > 0: # We're going too close pass else: # We're golden self.position += self.c*inc*scalefac
python
def mouse_zoom(self, inc): '''Convenience function to implement a zoom function. This is achieved by moving ``Camera.position`` in the direction of the ``Camera.c`` vector. ''' # Square Distance from pivot dsq = np.linalg.norm(self.position - self.pivot) minsq = 1.0**2 # How near can we be to the pivot maxsq = 7.0**2 # How far can we go scalefac = 0.25 if dsq > maxsq and inc < 0: # We're going too far pass elif dsq < minsq and inc > 0: # We're going too close pass else: # We're golden self.position += self.c*inc*scalefac
[ "def", "mouse_zoom", "(", "self", ",", "inc", ")", ":", "# Square Distance from pivot", "dsq", "=", "np", ".", "linalg", ".", "norm", "(", "self", ".", "position", "-", "self", ".", "pivot", ")", "minsq", "=", "1.0", "**", "2", "# How near can we be to the pivot", "maxsq", "=", "7.0", "**", "2", "# How far can we go ", "scalefac", "=", "0.25", "if", "dsq", ">", "maxsq", "and", "inc", "<", "0", ":", "# We're going too far", "pass", "elif", "dsq", "<", "minsq", "and", "inc", ">", "0", ":", "# We're going too close", "pass", "else", ":", "# We're golden", "self", ".", "position", "+=", "self", ".", "c", "*", "inc", "*", "scalefac" ]
Convenience function to implement a zoom function. This is achieved by moving ``Camera.position`` in the direction of the ``Camera.c`` vector.
[ "Convenience", "function", "to", "implement", "a", "zoom", "function", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L157-L179
16,378
chemlab/chemlab
chemlab/graphics/camera.py
Camera.unproject
def unproject(self, x, y, z=-1.0): """Receive x and y as screen coordinates and returns a point in world coordinates. This function comes in handy each time we have to convert a 2d mouse click to a 3d point in our space. **Parameters** x: float in the interval [-1.0, 1.0] Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost. y: float in the interval [1.0, -1.0] Vertical coordinate, -1.0 is down, 1.0 is up. z: float in the interval [1.0, -1.0] Depth, -1.0 is the near plane, that is exactly behind our screen, 1.0 is the far clipping plane. :rtype: np.ndarray(3,dtype=float) :return: The point in 3d coordinates (world coordinates). """ source = np.array([x,y,z,1.0]) # Invert the combined matrix matrix = self.projection.dot(self.matrix) IM = LA.inv(matrix) res = np.dot(IM, source) return res[0:3]/res[3]
python
def unproject(self, x, y, z=-1.0): """Receive x and y as screen coordinates and returns a point in world coordinates. This function comes in handy each time we have to convert a 2d mouse click to a 3d point in our space. **Parameters** x: float in the interval [-1.0, 1.0] Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost. y: float in the interval [1.0, -1.0] Vertical coordinate, -1.0 is down, 1.0 is up. z: float in the interval [1.0, -1.0] Depth, -1.0 is the near plane, that is exactly behind our screen, 1.0 is the far clipping plane. :rtype: np.ndarray(3,dtype=float) :return: The point in 3d coordinates (world coordinates). """ source = np.array([x,y,z,1.0]) # Invert the combined matrix matrix = self.projection.dot(self.matrix) IM = LA.inv(matrix) res = np.dot(IM, source) return res[0:3]/res[3]
[ "def", "unproject", "(", "self", ",", "x", ",", "y", ",", "z", "=", "-", "1.0", ")", ":", "source", "=", "np", ".", "array", "(", "[", "x", ",", "y", ",", "z", ",", "1.0", "]", ")", "# Invert the combined matrix", "matrix", "=", "self", ".", "projection", ".", "dot", "(", "self", ".", "matrix", ")", "IM", "=", "LA", ".", "inv", "(", "matrix", ")", "res", "=", "np", ".", "dot", "(", "IM", ",", "source", ")", "return", "res", "[", "0", ":", "3", "]", "/", "res", "[", "3", "]" ]
Receive x and y as screen coordinates and returns a point in world coordinates. This function comes in handy each time we have to convert a 2d mouse click to a 3d point in our space. **Parameters** x: float in the interval [-1.0, 1.0] Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost. y: float in the interval [1.0, -1.0] Vertical coordinate, -1.0 is down, 1.0 is up. z: float in the interval [1.0, -1.0] Depth, -1.0 is the near plane, that is exactly behind our screen, 1.0 is the far clipping plane. :rtype: np.ndarray(3,dtype=float) :return: The point in 3d coordinates (world coordinates).
[ "Receive", "x", "and", "y", "as", "screen", "coordinates", "and", "returns", "a", "point", "in", "world", "coordinates", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L230-L261
16,379
chemlab/chemlab
chemlab/graphics/camera.py
Camera.state
def state(self): '''Return the current camera state as a dictionary, it can be restored with `Camera.restore`. ''' return dict(a=self.a.tolist(), b=self.b.tolist(), c=self.c.tolist(), pivot=self.pivot.tolist(), position=self.position.tolist())
python
def state(self): '''Return the current camera state as a dictionary, it can be restored with `Camera.restore`. ''' return dict(a=self.a.tolist(), b=self.b.tolist(), c=self.c.tolist(), pivot=self.pivot.tolist(), position=self.position.tolist())
[ "def", "state", "(", "self", ")", ":", "return", "dict", "(", "a", "=", "self", ".", "a", ".", "tolist", "(", ")", ",", "b", "=", "self", ".", "b", ".", "tolist", "(", ")", ",", "c", "=", "self", ".", "c", ".", "tolist", "(", ")", ",", "pivot", "=", "self", ".", "pivot", ".", "tolist", "(", ")", ",", "position", "=", "self", ".", "position", ".", "tolist", "(", ")", ")" ]
Return the current camera state as a dictionary, it can be restored with `Camera.restore`.
[ "Return", "the", "current", "camera", "state", "as", "a", "dictionary", "it", "can", "be", "restored", "with", "Camera", ".", "restore", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L316-L322
16,380
chemlab/chemlab
chemlab/graphics/pickers.py
ray_spheres_intersection
def ray_spheres_intersection(origin, direction, centers, radii): """Calculate the intersection points between a ray and multiple spheres. **Returns** intersections distances Ordered by closest to farther """ b_v = 2.0 * ((origin - centers) * direction).sum(axis=1) c_v = ((origin - centers)**2).sum(axis=1) - radii ** 2 det_v = b_v * b_v - 4.0 * c_v inters_mask = det_v >= 0 intersections = (inters_mask).nonzero()[0] distances = (-b_v[inters_mask] - np.sqrt(det_v[inters_mask])) / 2.0 # We need only the thing in front of us, that corresponts to # positive distances. dist_mask = distances > 0.0 # We correct this aspect to get an absolute distance distances = distances[dist_mask] intersections = intersections[dist_mask].tolist() if intersections: distances, intersections = zip(*sorted(zip(distances, intersections))) return list(intersections), list(distances) else: return [], []
python
def ray_spheres_intersection(origin, direction, centers, radii): """Calculate the intersection points between a ray and multiple spheres. **Returns** intersections distances Ordered by closest to farther """ b_v = 2.0 * ((origin - centers) * direction).sum(axis=1) c_v = ((origin - centers)**2).sum(axis=1) - radii ** 2 det_v = b_v * b_v - 4.0 * c_v inters_mask = det_v >= 0 intersections = (inters_mask).nonzero()[0] distances = (-b_v[inters_mask] - np.sqrt(det_v[inters_mask])) / 2.0 # We need only the thing in front of us, that corresponts to # positive distances. dist_mask = distances > 0.0 # We correct this aspect to get an absolute distance distances = distances[dist_mask] intersections = intersections[dist_mask].tolist() if intersections: distances, intersections = zip(*sorted(zip(distances, intersections))) return list(intersections), list(distances) else: return [], []
[ "def", "ray_spheres_intersection", "(", "origin", ",", "direction", ",", "centers", ",", "radii", ")", ":", "b_v", "=", "2.0", "*", "(", "(", "origin", "-", "centers", ")", "*", "direction", ")", ".", "sum", "(", "axis", "=", "1", ")", "c_v", "=", "(", "(", "origin", "-", "centers", ")", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", "-", "radii", "**", "2", "det_v", "=", "b_v", "*", "b_v", "-", "4.0", "*", "c_v", "inters_mask", "=", "det_v", ">=", "0", "intersections", "=", "(", "inters_mask", ")", ".", "nonzero", "(", ")", "[", "0", "]", "distances", "=", "(", "-", "b_v", "[", "inters_mask", "]", "-", "np", ".", "sqrt", "(", "det_v", "[", "inters_mask", "]", ")", ")", "/", "2.0", "# We need only the thing in front of us, that corresponts to", "# positive distances.", "dist_mask", "=", "distances", ">", "0.0", "# We correct this aspect to get an absolute distance", "distances", "=", "distances", "[", "dist_mask", "]", "intersections", "=", "intersections", "[", "dist_mask", "]", ".", "tolist", "(", ")", "if", "intersections", ":", "distances", ",", "intersections", "=", "zip", "(", "*", "sorted", "(", "zip", "(", "distances", ",", "intersections", ")", ")", ")", "return", "list", "(", "intersections", ")", ",", "list", "(", "distances", ")", "else", ":", "return", "[", "]", ",", "[", "]" ]
Calculate the intersection points between a ray and multiple spheres. **Returns** intersections distances Ordered by closest to farther
[ "Calculate", "the", "intersection", "points", "between", "a", "ray", "and", "multiple", "spheres", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/pickers.py#L8-L40
16,381
chemlab/chemlab
chemlab/graphics/colors.py
any_to_rgb
def any_to_rgb(color): '''If color is an rgb tuple return it, if it is a string, parse it and return the respective rgb tuple. ''' if isinstance(color, tuple): if len(color) == 3: color = color + (255,) return color if isinstance(color, str): return parse_color(color) raise ValueError("Color not recognized: {}".format(color))
python
def any_to_rgb(color): '''If color is an rgb tuple return it, if it is a string, parse it and return the respective rgb tuple. ''' if isinstance(color, tuple): if len(color) == 3: color = color + (255,) return color if isinstance(color, str): return parse_color(color) raise ValueError("Color not recognized: {}".format(color))
[ "def", "any_to_rgb", "(", "color", ")", ":", "if", "isinstance", "(", "color", ",", "tuple", ")", ":", "if", "len", "(", "color", ")", "==", "3", ":", "color", "=", "color", "+", "(", "255", ",", ")", "return", "color", "if", "isinstance", "(", "color", ",", "str", ")", ":", "return", "parse_color", "(", "color", ")", "raise", "ValueError", "(", "\"Color not recognized: {}\"", ".", "format", "(", "color", ")", ")" ]
If color is an rgb tuple return it, if it is a string, parse it and return the respective rgb tuple.
[ "If", "color", "is", "an", "rgb", "tuple", "return", "it", "if", "it", "is", "a", "string", "parse", "it", "and", "return", "the", "respective", "rgb", "tuple", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L167-L180
16,382
chemlab/chemlab
chemlab/graphics/colors.py
parse_color
def parse_color(color): '''Return the RGB 0-255 representation of the current string passed. It first tries to match the string with DVI color names. ''' # Let's parse the color string if isinstance(color, str): # Try dvi names try: col = get(color) except ValueError: # String is not present pass # Try html names try: col = html_to_rgb(color) except ValueError: raise ValueError("Can't parse color string: {}'".format(color)) return col
python
def parse_color(color): '''Return the RGB 0-255 representation of the current string passed. It first tries to match the string with DVI color names. ''' # Let's parse the color string if isinstance(color, str): # Try dvi names try: col = get(color) except ValueError: # String is not present pass # Try html names try: col = html_to_rgb(color) except ValueError: raise ValueError("Can't parse color string: {}'".format(color)) return col
[ "def", "parse_color", "(", "color", ")", ":", "# Let's parse the color string", "if", "isinstance", "(", "color", ",", "str", ")", ":", "# Try dvi names", "try", ":", "col", "=", "get", "(", "color", ")", "except", "ValueError", ":", "# String is not present", "pass", "# Try html names", "try", ":", "col", "=", "html_to_rgb", "(", "color", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Can't parse color string: {}'\"", ".", "format", "(", "color", ")", ")", "return", "col" ]
Return the RGB 0-255 representation of the current string passed. It first tries to match the string with DVI color names.
[ "Return", "the", "RGB", "0", "-", "255", "representation", "of", "the", "current", "string", "passed", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L197-L220
16,383
chemlab/chemlab
chemlab/graphics/colors.py
hsl_to_rgb
def hsl_to_rgb(arr): """ Converts HSL color array to RGB array H = [0..360] S = [0..1] l = [0..1] http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL Returns R,G,B in [0..255] """ H, S, L = arr.T H = (H.copy()/255.0) * 360 S = S.copy()/255.0 L = L.copy()/255.0 C = (1 - np.absolute(2 * L - 1)) * S Hp = H / 60.0 X = C * (1 - np.absolute(np.mod(Hp, 2) - 1)) # initilize with zero R = np.zeros(H.shape, float) G = np.zeros(H.shape, float) B = np.zeros(H.shape, float) # handle each case: mask = (Hp >= 0) == ( Hp < 1) R[mask] = C[mask] G[mask] = X[mask] mask = (Hp >= 1) == ( Hp < 2) R[mask] = X[mask] G[mask] = C[mask] mask = (Hp >= 2) == ( Hp < 3) G[mask] = C[mask] B[mask] = X[mask] mask = (Hp >= 3) == ( Hp < 4) G[mask] = X[mask] B[mask] = C[mask] mask = (Hp >= 4) == ( Hp < 5) R[mask] = X[mask] B[mask] = C[mask] mask = (Hp >= 5) == ( Hp < 6) R[mask] = C[mask] B[mask] = X[mask] m = L - 0.5*C R += m G += m B += m R *= 255.0 G *= 255.0 B *= 255.0 return np.array((R.astype(int),G.astype(int),B.astype(int))).T
python
def hsl_to_rgb(arr): """ Converts HSL color array to RGB array H = [0..360] S = [0..1] l = [0..1] http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL Returns R,G,B in [0..255] """ H, S, L = arr.T H = (H.copy()/255.0) * 360 S = S.copy()/255.0 L = L.copy()/255.0 C = (1 - np.absolute(2 * L - 1)) * S Hp = H / 60.0 X = C * (1 - np.absolute(np.mod(Hp, 2) - 1)) # initilize with zero R = np.zeros(H.shape, float) G = np.zeros(H.shape, float) B = np.zeros(H.shape, float) # handle each case: mask = (Hp >= 0) == ( Hp < 1) R[mask] = C[mask] G[mask] = X[mask] mask = (Hp >= 1) == ( Hp < 2) R[mask] = X[mask] G[mask] = C[mask] mask = (Hp >= 2) == ( Hp < 3) G[mask] = C[mask] B[mask] = X[mask] mask = (Hp >= 3) == ( Hp < 4) G[mask] = X[mask] B[mask] = C[mask] mask = (Hp >= 4) == ( Hp < 5) R[mask] = X[mask] B[mask] = C[mask] mask = (Hp >= 5) == ( Hp < 6) R[mask] = C[mask] B[mask] = X[mask] m = L - 0.5*C R += m G += m B += m R *= 255.0 G *= 255.0 B *= 255.0 return np.array((R.astype(int),G.astype(int),B.astype(int))).T
[ "def", "hsl_to_rgb", "(", "arr", ")", ":", "H", ",", "S", ",", "L", "=", "arr", ".", "T", "H", "=", "(", "H", ".", "copy", "(", ")", "/", "255.0", ")", "*", "360", "S", "=", "S", ".", "copy", "(", ")", "/", "255.0", "L", "=", "L", ".", "copy", "(", ")", "/", "255.0", "C", "=", "(", "1", "-", "np", ".", "absolute", "(", "2", "*", "L", "-", "1", ")", ")", "*", "S", "Hp", "=", "H", "/", "60.0", "X", "=", "C", "*", "(", "1", "-", "np", ".", "absolute", "(", "np", ".", "mod", "(", "Hp", ",", "2", ")", "-", "1", ")", ")", "# initilize with zero", "R", "=", "np", ".", "zeros", "(", "H", ".", "shape", ",", "float", ")", "G", "=", "np", ".", "zeros", "(", "H", ".", "shape", ",", "float", ")", "B", "=", "np", ".", "zeros", "(", "H", ".", "shape", ",", "float", ")", "# handle each case:", "mask", "=", "(", "Hp", ">=", "0", ")", "==", "(", "Hp", "<", "1", ")", "R", "[", "mask", "]", "=", "C", "[", "mask", "]", "G", "[", "mask", "]", "=", "X", "[", "mask", "]", "mask", "=", "(", "Hp", ">=", "1", ")", "==", "(", "Hp", "<", "2", ")", "R", "[", "mask", "]", "=", "X", "[", "mask", "]", "G", "[", "mask", "]", "=", "C", "[", "mask", "]", "mask", "=", "(", "Hp", ">=", "2", ")", "==", "(", "Hp", "<", "3", ")", "G", "[", "mask", "]", "=", "C", "[", "mask", "]", "B", "[", "mask", "]", "=", "X", "[", "mask", "]", "mask", "=", "(", "Hp", ">=", "3", ")", "==", "(", "Hp", "<", "4", ")", "G", "[", "mask", "]", "=", "X", "[", "mask", "]", "B", "[", "mask", "]", "=", "C", "[", "mask", "]", "mask", "=", "(", "Hp", ">=", "4", ")", "==", "(", "Hp", "<", "5", ")", "R", "[", "mask", "]", "=", "X", "[", "mask", "]", "B", "[", "mask", "]", "=", "C", "[", "mask", "]", "mask", "=", "(", "Hp", ">=", "5", ")", "==", "(", "Hp", "<", "6", ")", "R", "[", "mask", "]", "=", "C", "[", "mask", "]", "B", "[", "mask", "]", "=", "X", "[", "mask", "]", "m", "=", "L", "-", "0.5", "*", "C", "R", "+=", "m", "G", "+=", "m", "B", "+=", "m", "R", "*=", "255.0", "G", "*=", "255.0", "B", "*=", "255.0", "return", "np", ".", "array", "(", "(", "R", ".", "astype", "(", "int", ")", ",", "G", ".", "astype", "(", "int", ")", ",", "B", ".", "astype", "(", "int", ")", ")", ")", ".", "T" ]
Converts HSL color array to RGB array H = [0..360] S = [0..1] l = [0..1] http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL Returns R,G,B in [0..255]
[ "Converts", "HSL", "color", "array", "to", "RGB", "array" ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L309-L372
16,384
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
format_symbol
def format_symbol(symbol): """Returns well formatted Hermann-Mauguin symbol as extected by the database, by correcting the case and adding missing or removing dublicated spaces.""" fixed = [] s = symbol.strip() s = s[0].upper() + s[1:].lower() for c in s: if c.isalpha(): fixed.append(' ' + c + ' ') elif c.isspace(): fixed.append(' ') elif c.isdigit(): fixed.append(c) elif c == '-': fixed.append(' ' + c) elif c == '/': fixed.append(' ' + c) s = ''.join(fixed).strip() return ' '.join(s.split())
python
def format_symbol(symbol): """Returns well formatted Hermann-Mauguin symbol as extected by the database, by correcting the case and adding missing or removing dublicated spaces.""" fixed = [] s = symbol.strip() s = s[0].upper() + s[1:].lower() for c in s: if c.isalpha(): fixed.append(' ' + c + ' ') elif c.isspace(): fixed.append(' ') elif c.isdigit(): fixed.append(c) elif c == '-': fixed.append(' ' + c) elif c == '/': fixed.append(' ' + c) s = ''.join(fixed).strip() return ' '.join(s.split())
[ "def", "format_symbol", "(", "symbol", ")", ":", "fixed", "=", "[", "]", "s", "=", "symbol", ".", "strip", "(", ")", "s", "=", "s", "[", "0", "]", ".", "upper", "(", ")", "+", "s", "[", "1", ":", "]", ".", "lower", "(", ")", "for", "c", "in", "s", ":", "if", "c", ".", "isalpha", "(", ")", ":", "fixed", ".", "append", "(", "' '", "+", "c", "+", "' '", ")", "elif", "c", ".", "isspace", "(", ")", ":", "fixed", ".", "append", "(", "' '", ")", "elif", "c", ".", "isdigit", "(", ")", ":", "fixed", ".", "append", "(", "c", ")", "elif", "c", "==", "'-'", ":", "fixed", ".", "append", "(", "' '", "+", "c", ")", "elif", "c", "==", "'/'", ":", "fixed", ".", "append", "(", "' '", "+", "c", ")", "s", "=", "''", ".", "join", "(", "fixed", ")", ".", "strip", "(", ")", "return", "' '", ".", "join", "(", "s", ".", "split", "(", ")", ")" ]
Returns well formatted Hermann-Mauguin symbol as extected by the database, by correcting the case and adding missing or removing dublicated spaces.
[ "Returns", "well", "formatted", "Hermann", "-", "Mauguin", "symbol", "as", "extected", "by", "the", "database", "by", "correcting", "the", "case", "and", "adding", "missing", "or", "removing", "dublicated", "spaces", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L484-L503
16,385
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
_skip_to_blank
def _skip_to_blank(f, spacegroup, setting): """Read lines from f until a blank line is encountered.""" while True: line = f.readline() if not line: raise SpacegroupNotFoundError( 'invalid spacegroup %s, setting %i not found in data base' % ( spacegroup, setting ) ) if not line.strip(): break
python
def _skip_to_blank(f, spacegroup, setting): """Read lines from f until a blank line is encountered.""" while True: line = f.readline() if not line: raise SpacegroupNotFoundError( 'invalid spacegroup %s, setting %i not found in data base' % ( spacegroup, setting ) ) if not line.strip(): break
[ "def", "_skip_to_blank", "(", "f", ",", "spacegroup", ",", "setting", ")", ":", "while", "True", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ":", "raise", "SpacegroupNotFoundError", "(", "'invalid spacegroup %s, setting %i not found in data base'", "%", "(", "spacegroup", ",", "setting", ")", ")", "if", "not", "line", ".", "strip", "(", ")", ":", "break" ]
Read lines from f until a blank line is encountered.
[ "Read", "lines", "from", "f", "until", "a", "blank", "line", "is", "encountered", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L513-L522
16,386
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
_read_datafile_entry
def _read_datafile_entry(spg, no, symbol, setting, f): """Read space group data from f to spg.""" spg._no = no spg._symbol = symbol.strip() spg._setting = setting spg._centrosymmetric = bool(int(f.readline().split()[1])) # primitive vectors f.readline() spg._scaled_primitive_cell = np.array([ list(map(float, f.readline().split())) for i in range(3)], dtype='float') # primitive reciprocal vectors f.readline() spg._reciprocal_cell = np.array([list(map(int, f.readline().split())) for i in range(3)], dtype=np.int) # subtranslations spg._nsubtrans = int(f.readline().split()[0]) spg._subtrans = np.array([list(map(float, f.readline().split())) for i in range(spg._nsubtrans)], dtype=np.float) # symmetry operations nsym = int(f.readline().split()[0]) symop = np.array([list(map(float, f.readline().split())) for i in range(nsym)], dtype=np.float) spg._nsymop = nsym spg._rotations = np.array(symop[:,:9].reshape((nsym,3,3)), dtype=np.int) spg._translations = symop[:,9:]
python
def _read_datafile_entry(spg, no, symbol, setting, f): """Read space group data from f to spg.""" spg._no = no spg._symbol = symbol.strip() spg._setting = setting spg._centrosymmetric = bool(int(f.readline().split()[1])) # primitive vectors f.readline() spg._scaled_primitive_cell = np.array([ list(map(float, f.readline().split())) for i in range(3)], dtype='float') # primitive reciprocal vectors f.readline() spg._reciprocal_cell = np.array([list(map(int, f.readline().split())) for i in range(3)], dtype=np.int) # subtranslations spg._nsubtrans = int(f.readline().split()[0]) spg._subtrans = np.array([list(map(float, f.readline().split())) for i in range(spg._nsubtrans)], dtype=np.float) # symmetry operations nsym = int(f.readline().split()[0]) symop = np.array([list(map(float, f.readline().split())) for i in range(nsym)], dtype=np.float) spg._nsymop = nsym spg._rotations = np.array(symop[:,:9].reshape((nsym,3,3)), dtype=np.int) spg._translations = symop[:,9:]
[ "def", "_read_datafile_entry", "(", "spg", ",", "no", ",", "symbol", ",", "setting", ",", "f", ")", ":", "spg", ".", "_no", "=", "no", "spg", ".", "_symbol", "=", "symbol", ".", "strip", "(", ")", "spg", ".", "_setting", "=", "setting", "spg", ".", "_centrosymmetric", "=", "bool", "(", "int", "(", "f", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "1", "]", ")", ")", "# primitive vectors", "f", ".", "readline", "(", ")", "spg", ".", "_scaled_primitive_cell", "=", "np", ".", "array", "(", "[", "list", "(", "map", "(", "float", ",", "f", ".", "readline", "(", ")", ".", "split", "(", ")", ")", ")", "for", "i", "in", "range", "(", "3", ")", "]", ",", "dtype", "=", "'float'", ")", "# primitive reciprocal vectors", "f", ".", "readline", "(", ")", "spg", ".", "_reciprocal_cell", "=", "np", ".", "array", "(", "[", "list", "(", "map", "(", "int", ",", "f", ".", "readline", "(", ")", ".", "split", "(", ")", ")", ")", "for", "i", "in", "range", "(", "3", ")", "]", ",", "dtype", "=", "np", ".", "int", ")", "# subtranslations", "spg", ".", "_nsubtrans", "=", "int", "(", "f", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "spg", ".", "_subtrans", "=", "np", ".", "array", "(", "[", "list", "(", "map", "(", "float", ",", "f", ".", "readline", "(", ")", ".", "split", "(", ")", ")", ")", "for", "i", "in", "range", "(", "spg", ".", "_nsubtrans", ")", "]", ",", "dtype", "=", "np", ".", "float", ")", "# symmetry operations", "nsym", "=", "int", "(", "f", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "symop", "=", "np", ".", "array", "(", "[", "list", "(", "map", "(", "float", ",", "f", ".", "readline", "(", ")", ".", "split", "(", ")", ")", ")", "for", "i", "in", "range", "(", "nsym", ")", "]", ",", "dtype", "=", "np", ".", "float", ")", "spg", ".", "_nsymop", "=", "nsym", "spg", ".", "_rotations", "=", "np", ".", "array", "(", "symop", "[", ":", ",", ":", "9", "]", ".", "reshape", "(", "(", "nsym", ",", "3", ",", "3", ")", ")", ",", "dtype", "=", "np", ".", "int", ")", "spg", ".", "_translations", "=", "symop", "[", ":", ",", "9", ":", "]" ]
Read space group data from f to spg.
[ "Read", "space", "group", "data", "from", "f", "to", "spg", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L541-L570
16,387
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
parse_sitesym
def parse_sitesym(symlist, sep=','): """Parses a sequence of site symmetries in the form used by International Tables and returns corresponding rotation and translation arrays. Example: >>> symlist = [ ... 'x,y,z', ... '-y+1/2,x+1/2,z', ... '-y,-x,-z', ... ] >>> rot, trans = parse_sitesym(symlist) >>> rot array([[[ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [ 1, 0, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [-1, 0, 0], [ 0, 0, -1]]]) >>> trans array([[ 0. , 0. , 0. ], [ 0.5, 0.5, 0. ], [ 0. , 0. , 0. ]]) """ nsym = len(symlist) rot = np.zeros((nsym, 3, 3), dtype='int') trans = np.zeros((nsym, 3)) for i, sym in enumerate(symlist): for j, s in enumerate (sym.split(sep)): s = s.lower().strip() while s: sign = 1 if s[0] in '+-': if s[0] == '-': sign = -1 s = s[1:] if s[0] in 'xyz': k = ord(s[0]) - ord('x') rot[i, j, k] = sign s = s[1:] elif s[0].isdigit() or s[0] == '.': n = 0 while n < len(s) and (s[n].isdigit() or s[n] in '/.'): n += 1 t = s[:n] s = s[n:] if '/' in t: q, r = t.split('/') trans[i,j] = float(q)/float(r) else: trans[i,j] = float(t) else: raise SpacegroupValueError( 'Error parsing %r. Invalid site symmetry: %s' % (s, sym)) return rot, trans
python
def parse_sitesym(symlist, sep=','): """Parses a sequence of site symmetries in the form used by International Tables and returns corresponding rotation and translation arrays. Example: >>> symlist = [ ... 'x,y,z', ... '-y+1/2,x+1/2,z', ... '-y,-x,-z', ... ] >>> rot, trans = parse_sitesym(symlist) >>> rot array([[[ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [ 1, 0, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [-1, 0, 0], [ 0, 0, -1]]]) >>> trans array([[ 0. , 0. , 0. ], [ 0.5, 0.5, 0. ], [ 0. , 0. , 0. ]]) """ nsym = len(symlist) rot = np.zeros((nsym, 3, 3), dtype='int') trans = np.zeros((nsym, 3)) for i, sym in enumerate(symlist): for j, s in enumerate (sym.split(sep)): s = s.lower().strip() while s: sign = 1 if s[0] in '+-': if s[0] == '-': sign = -1 s = s[1:] if s[0] in 'xyz': k = ord(s[0]) - ord('x') rot[i, j, k] = sign s = s[1:] elif s[0].isdigit() or s[0] == '.': n = 0 while n < len(s) and (s[n].isdigit() or s[n] in '/.'): n += 1 t = s[:n] s = s[n:] if '/' in t: q, r = t.split('/') trans[i,j] = float(q)/float(r) else: trans[i,j] = float(t) else: raise SpacegroupValueError( 'Error parsing %r. Invalid site symmetry: %s' % (s, sym)) return rot, trans
[ "def", "parse_sitesym", "(", "symlist", ",", "sep", "=", "','", ")", ":", "nsym", "=", "len", "(", "symlist", ")", "rot", "=", "np", ".", "zeros", "(", "(", "nsym", ",", "3", ",", "3", ")", ",", "dtype", "=", "'int'", ")", "trans", "=", "np", ".", "zeros", "(", "(", "nsym", ",", "3", ")", ")", "for", "i", ",", "sym", "in", "enumerate", "(", "symlist", ")", ":", "for", "j", ",", "s", "in", "enumerate", "(", "sym", ".", "split", "(", "sep", ")", ")", ":", "s", "=", "s", ".", "lower", "(", ")", ".", "strip", "(", ")", "while", "s", ":", "sign", "=", "1", "if", "s", "[", "0", "]", "in", "'+-'", ":", "if", "s", "[", "0", "]", "==", "'-'", ":", "sign", "=", "-", "1", "s", "=", "s", "[", "1", ":", "]", "if", "s", "[", "0", "]", "in", "'xyz'", ":", "k", "=", "ord", "(", "s", "[", "0", "]", ")", "-", "ord", "(", "'x'", ")", "rot", "[", "i", ",", "j", ",", "k", "]", "=", "sign", "s", "=", "s", "[", "1", ":", "]", "elif", "s", "[", "0", "]", ".", "isdigit", "(", ")", "or", "s", "[", "0", "]", "==", "'.'", ":", "n", "=", "0", "while", "n", "<", "len", "(", "s", ")", "and", "(", "s", "[", "n", "]", ".", "isdigit", "(", ")", "or", "s", "[", "n", "]", "in", "'/.'", ")", ":", "n", "+=", "1", "t", "=", "s", "[", ":", "n", "]", "s", "=", "s", "[", "n", ":", "]", "if", "'/'", "in", "t", ":", "q", ",", "r", "=", "t", ".", "split", "(", "'/'", ")", "trans", "[", "i", ",", "j", "]", "=", "float", "(", "q", ")", "/", "float", "(", "r", ")", "else", ":", "trans", "[", "i", ",", "j", "]", "=", "float", "(", "t", ")", "else", ":", "raise", "SpacegroupValueError", "(", "'Error parsing %r. Invalid site symmetry: %s'", "%", "(", "s", ",", "sym", ")", ")", "return", "rot", ",", "trans" ]
Parses a sequence of site symmetries in the form used by International Tables and returns corresponding rotation and translation arrays. Example: >>> symlist = [ ... 'x,y,z', ... '-y+1/2,x+1/2,z', ... '-y,-x,-z', ... ] >>> rot, trans = parse_sitesym(symlist) >>> rot array([[[ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [ 1, 0, 0], [ 0, 0, 1]], <BLANKLINE> [[ 0, -1, 0], [-1, 0, 0], [ 0, 0, -1]]]) >>> trans array([[ 0. , 0. , 0. ], [ 0.5, 0.5, 0. ], [ 0. , 0. , 0. ]])
[ "Parses", "a", "sequence", "of", "site", "symmetries", "in", "the", "form", "used", "by", "International", "Tables", "and", "returns", "corresponding", "rotation", "and", "translation", "arrays", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L596-L657
16,388
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
spacegroup_from_data
def spacegroup_from_data(no=None, symbol=None, setting=1, centrosymmetric=None, scaled_primitive_cell=None, reciprocal_cell=None, subtrans=None, sitesym=None, rotations=None, translations=None, datafile=None): """Manually create a new space group instance. This might be usefull when reading crystal data with its own spacegroup definitions.""" if no is not None: spg = Spacegroup(no, setting, datafile) elif symbol is not None: spg = Spacegroup(symbol, setting, datafile) else: raise SpacegroupValueError('either *no* or *symbol* must be given') have_sym = False if centrosymmetric is not None: spg._centrosymmetric = bool(centrosymmetric) if scaled_primitive_cell is not None: spg._scaled_primitive_cell = np.array(scaled_primitive_cell) if reciprocal_cell is not None: spg._reciprocal_cell = np.array(reciprocal_cell) if subtrans is not None: spg._subtrans = np.atleast_2d(subtrans) spg._nsubtrans = spg._subtrans.shape[0] if sitesym is not None: spg._rotations, spg._translations = parse_sitesym(sitesym) have_sym = True if rotations is not None: spg._rotations = np.atleast_3d(rotations) have_sym = True if translations is not None: spg._translations = np.atleast_2d(translations) have_sym = True if have_sym: if spg._rotations.shape[0] != spg._translations.shape[0]: raise SpacegroupValueError('inconsistent number of rotations and ' 'translations') spg._nsymop = spg._rotations.shape[0] return spg
python
def spacegroup_from_data(no=None, symbol=None, setting=1, centrosymmetric=None, scaled_primitive_cell=None, reciprocal_cell=None, subtrans=None, sitesym=None, rotations=None, translations=None, datafile=None): """Manually create a new space group instance. This might be usefull when reading crystal data with its own spacegroup definitions.""" if no is not None: spg = Spacegroup(no, setting, datafile) elif symbol is not None: spg = Spacegroup(symbol, setting, datafile) else: raise SpacegroupValueError('either *no* or *symbol* must be given') have_sym = False if centrosymmetric is not None: spg._centrosymmetric = bool(centrosymmetric) if scaled_primitive_cell is not None: spg._scaled_primitive_cell = np.array(scaled_primitive_cell) if reciprocal_cell is not None: spg._reciprocal_cell = np.array(reciprocal_cell) if subtrans is not None: spg._subtrans = np.atleast_2d(subtrans) spg._nsubtrans = spg._subtrans.shape[0] if sitesym is not None: spg._rotations, spg._translations = parse_sitesym(sitesym) have_sym = True if rotations is not None: spg._rotations = np.atleast_3d(rotations) have_sym = True if translations is not None: spg._translations = np.atleast_2d(translations) have_sym = True if have_sym: if spg._rotations.shape[0] != spg._translations.shape[0]: raise SpacegroupValueError('inconsistent number of rotations and ' 'translations') spg._nsymop = spg._rotations.shape[0] return spg
[ "def", "spacegroup_from_data", "(", "no", "=", "None", ",", "symbol", "=", "None", ",", "setting", "=", "1", ",", "centrosymmetric", "=", "None", ",", "scaled_primitive_cell", "=", "None", ",", "reciprocal_cell", "=", "None", ",", "subtrans", "=", "None", ",", "sitesym", "=", "None", ",", "rotations", "=", "None", ",", "translations", "=", "None", ",", "datafile", "=", "None", ")", ":", "if", "no", "is", "not", "None", ":", "spg", "=", "Spacegroup", "(", "no", ",", "setting", ",", "datafile", ")", "elif", "symbol", "is", "not", "None", ":", "spg", "=", "Spacegroup", "(", "symbol", ",", "setting", ",", "datafile", ")", "else", ":", "raise", "SpacegroupValueError", "(", "'either *no* or *symbol* must be given'", ")", "have_sym", "=", "False", "if", "centrosymmetric", "is", "not", "None", ":", "spg", ".", "_centrosymmetric", "=", "bool", "(", "centrosymmetric", ")", "if", "scaled_primitive_cell", "is", "not", "None", ":", "spg", ".", "_scaled_primitive_cell", "=", "np", ".", "array", "(", "scaled_primitive_cell", ")", "if", "reciprocal_cell", "is", "not", "None", ":", "spg", ".", "_reciprocal_cell", "=", "np", ".", "array", "(", "reciprocal_cell", ")", "if", "subtrans", "is", "not", "None", ":", "spg", ".", "_subtrans", "=", "np", ".", "atleast_2d", "(", "subtrans", ")", "spg", ".", "_nsubtrans", "=", "spg", ".", "_subtrans", ".", "shape", "[", "0", "]", "if", "sitesym", "is", "not", "None", ":", "spg", ".", "_rotations", ",", "spg", ".", "_translations", "=", "parse_sitesym", "(", "sitesym", ")", "have_sym", "=", "True", "if", "rotations", "is", "not", "None", ":", "spg", ".", "_rotations", "=", "np", ".", "atleast_3d", "(", "rotations", ")", "have_sym", "=", "True", "if", "translations", "is", "not", "None", ":", "spg", ".", "_translations", "=", "np", ".", "atleast_2d", "(", "translations", ")", "have_sym", "=", "True", "if", "have_sym", ":", "if", "spg", ".", "_rotations", ".", "shape", "[", "0", "]", "!=", "spg", ".", "_translations", ".", "shape", "[", "0", "]", ":", "raise", "SpacegroupValueError", "(", "'inconsistent number of rotations and '", "'translations'", ")", "spg", ".", "_nsymop", "=", "spg", ".", "_rotations", ".", "shape", "[", "0", "]", "return", "spg" ]
Manually create a new space group instance. This might be usefull when reading crystal data with its own spacegroup definitions.
[ "Manually", "create", "a", "new", "space", "group", "instance", ".", "This", "might", "be", "usefull", "when", "reading", "crystal", "data", "with", "its", "own", "spacegroup", "definitions", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L660-L698
16,389
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
Spacegroup._get_nsymop
def _get_nsymop(self): """Returns total number of symmetry operations.""" if self.centrosymmetric: return 2 * len(self._rotations) * len(self._subtrans) else: return len(self._rotations) * len(self._subtrans)
python
def _get_nsymop(self): """Returns total number of symmetry operations.""" if self.centrosymmetric: return 2 * len(self._rotations) * len(self._subtrans) else: return len(self._rotations) * len(self._subtrans)
[ "def", "_get_nsymop", "(", "self", ")", ":", "if", "self", ".", "centrosymmetric", ":", "return", "2", "*", "len", "(", "self", ".", "_rotations", ")", "*", "len", "(", "self", ".", "_subtrans", ")", "else", ":", "return", "len", "(", "self", ".", "_rotations", ")", "*", "len", "(", "self", ".", "_subtrans", ")" ]
Returns total number of symmetry operations.
[ "Returns", "total", "number", "of", "symmetry", "operations", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L86-L91
16,390
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
Spacegroup.get_rotations
def get_rotations(self): """Return all rotations, including inversions for centrosymmetric crystals.""" if self.centrosymmetric: return np.vstack((self.rotations, -self.rotations)) else: return self.rotations
python
def get_rotations(self): """Return all rotations, including inversions for centrosymmetric crystals.""" if self.centrosymmetric: return np.vstack((self.rotations, -self.rotations)) else: return self.rotations
[ "def", "get_rotations", "(", "self", ")", ":", "if", "self", ".", "centrosymmetric", ":", "return", "np", ".", "vstack", "(", "(", "self", ".", "rotations", ",", "-", "self", ".", "rotations", ")", ")", "else", ":", "return", "self", ".", "rotations" ]
Return all rotations, including inversions for centrosymmetric crystals.
[ "Return", "all", "rotations", "including", "inversions", "for", "centrosymmetric", "crystals", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L221-L227
16,391
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
Spacegroup.equivalent_reflections
def equivalent_reflections(self, hkl): """Return all equivalent reflections to the list of Miller indices in hkl. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sg.equivalent_reflections([[0, 0, 2]]) array([[ 0, 0, -2], [ 0, -2, 0], [-2, 0, 0], [ 2, 0, 0], [ 0, 2, 0], [ 0, 0, 2]]) """ hkl = np.array(hkl, dtype='int', ndmin=2) rot = self.get_rotations() n, nrot = len(hkl), len(rot) R = rot.transpose(0, 2, 1).reshape((3*nrot, 3)).T refl = np.dot(hkl, R).reshape((n*nrot, 3)) ind = np.lexsort(refl.T) refl = refl[ind] diff = np.diff(refl, axis=0) mask = np.any(diff, axis=1) return np.vstack((refl[mask], refl[-1,:]))
python
def equivalent_reflections(self, hkl): """Return all equivalent reflections to the list of Miller indices in hkl. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sg.equivalent_reflections([[0, 0, 2]]) array([[ 0, 0, -2], [ 0, -2, 0], [-2, 0, 0], [ 2, 0, 0], [ 0, 2, 0], [ 0, 0, 2]]) """ hkl = np.array(hkl, dtype='int', ndmin=2) rot = self.get_rotations() n, nrot = len(hkl), len(rot) R = rot.transpose(0, 2, 1).reshape((3*nrot, 3)).T refl = np.dot(hkl, R).reshape((n*nrot, 3)) ind = np.lexsort(refl.T) refl = refl[ind] diff = np.diff(refl, axis=0) mask = np.any(diff, axis=1) return np.vstack((refl[mask], refl[-1,:]))
[ "def", "equivalent_reflections", "(", "self", ",", "hkl", ")", ":", "hkl", "=", "np", ".", "array", "(", "hkl", ",", "dtype", "=", "'int'", ",", "ndmin", "=", "2", ")", "rot", "=", "self", ".", "get_rotations", "(", ")", "n", ",", "nrot", "=", "len", "(", "hkl", ")", ",", "len", "(", "rot", ")", "R", "=", "rot", ".", "transpose", "(", "0", ",", "2", ",", "1", ")", ".", "reshape", "(", "(", "3", "*", "nrot", ",", "3", ")", ")", ".", "T", "refl", "=", "np", ".", "dot", "(", "hkl", ",", "R", ")", ".", "reshape", "(", "(", "n", "*", "nrot", ",", "3", ")", ")", "ind", "=", "np", ".", "lexsort", "(", "refl", ".", "T", ")", "refl", "=", "refl", "[", "ind", "]", "diff", "=", "np", ".", "diff", "(", "refl", ",", "axis", "=", "0", ")", "mask", "=", "np", ".", "any", "(", "diff", ",", "axis", "=", "1", ")", "return", "np", ".", "vstack", "(", "(", "refl", "[", "mask", "]", ",", "refl", "[", "-", "1", ",", ":", "]", ")", ")" ]
Return all equivalent reflections to the list of Miller indices in hkl. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sg.equivalent_reflections([[0, 0, 2]]) array([[ 0, 0, -2], [ 0, -2, 0], [-2, 0, 0], [ 2, 0, 0], [ 0, 2, 0], [ 0, 0, 2]])
[ "Return", "all", "equivalent", "reflections", "to", "the", "list", "of", "Miller", "indices", "in", "hkl", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L229-L254
16,392
chemlab/chemlab
chemlab/core/spacegroup/spacegroup.py
Spacegroup.equivalent_sites
def equivalent_sites(self, scaled_positions, ondublicates='error', symprec=1e-3): """Returns the scaled positions and all their equivalent sites. Parameters: scaled_positions: list | array List of non-equivalent sites given in unit cell coordinates. ondublicates : 'keep' | 'replace' | 'warn' | 'error' Action if `scaled_positions` contain symmetry-equivalent positions: 'keep' ignore additional symmetry-equivalent positions 'replace' replace 'warn' like 'keep', but issue an UserWarning 'error' raises a SpacegroupValueError symprec: float Minimum "distance" betweed two sites in scaled coordinates before they are counted as the same site. Returns: sites: array A NumPy array of equivalent sites. kinds: list A list of integer indices specifying which input site is equivalent to the corresponding returned site. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]]) >>> sites array([[ 0. , 0. , 0. ], [ 0. , 0.5, 0.5], [ 0.5, 0. , 0.5], [ 0.5, 0.5, 0. ], [ 0.5, 0. , 0. ], [ 0. , 0.5, 0. ], [ 0. , 0. , 0.5], [ 0.5, 0.5, 0.5]]) >>> kinds [0, 0, 0, 0, 1, 1, 1, 1] """ kinds = [] sites = [] symprec2 = symprec**2 scaled = np.array(scaled_positions, ndmin=2) for kind, pos in enumerate(scaled): for rot, trans in self.get_symop(): site = np.mod(np.dot(rot, pos) + trans, 1.) if not sites: sites.append(site) kinds.append(kind) continue t = site - sites mask = np.sum(t*t, 1) < symprec2 if np.any(mask): ind = np.argwhere(mask)[0][0] if kinds[ind] == kind: pass elif ondublicates == 'keep': pass elif ondublicates == 'replace': kinds[ind] = kind elif ondublicates == 'warn': warnings.warn('scaled_positions %d and %d ' 'are equivalent'%(kinds[ind], kind)) elif ondublicates == 'error': raise SpacegroupValueError( 'scaled_positions %d and %d are equivalent'%( kinds[ind], kind)) else: raise SpacegroupValueError( 'Argument "ondublicates" must be one of: ' '"keep", "replace", "warn" or "error".') else: sites.append(site) kinds.append(kind) return np.array(sites), kinds
python
def equivalent_sites(self, scaled_positions, ondublicates='error', symprec=1e-3): """Returns the scaled positions and all their equivalent sites. Parameters: scaled_positions: list | array List of non-equivalent sites given in unit cell coordinates. ondublicates : 'keep' | 'replace' | 'warn' | 'error' Action if `scaled_positions` contain symmetry-equivalent positions: 'keep' ignore additional symmetry-equivalent positions 'replace' replace 'warn' like 'keep', but issue an UserWarning 'error' raises a SpacegroupValueError symprec: float Minimum "distance" betweed two sites in scaled coordinates before they are counted as the same site. Returns: sites: array A NumPy array of equivalent sites. kinds: list A list of integer indices specifying which input site is equivalent to the corresponding returned site. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]]) >>> sites array([[ 0. , 0. , 0. ], [ 0. , 0.5, 0.5], [ 0.5, 0. , 0.5], [ 0.5, 0.5, 0. ], [ 0.5, 0. , 0. ], [ 0. , 0.5, 0. ], [ 0. , 0. , 0.5], [ 0.5, 0.5, 0.5]]) >>> kinds [0, 0, 0, 0, 1, 1, 1, 1] """ kinds = [] sites = [] symprec2 = symprec**2 scaled = np.array(scaled_positions, ndmin=2) for kind, pos in enumerate(scaled): for rot, trans in self.get_symop(): site = np.mod(np.dot(rot, pos) + trans, 1.) if not sites: sites.append(site) kinds.append(kind) continue t = site - sites mask = np.sum(t*t, 1) < symprec2 if np.any(mask): ind = np.argwhere(mask)[0][0] if kinds[ind] == kind: pass elif ondublicates == 'keep': pass elif ondublicates == 'replace': kinds[ind] = kind elif ondublicates == 'warn': warnings.warn('scaled_positions %d and %d ' 'are equivalent'%(kinds[ind], kind)) elif ondublicates == 'error': raise SpacegroupValueError( 'scaled_positions %d and %d are equivalent'%( kinds[ind], kind)) else: raise SpacegroupValueError( 'Argument "ondublicates" must be one of: ' '"keep", "replace", "warn" or "error".') else: sites.append(site) kinds.append(kind) return np.array(sites), kinds
[ "def", "equivalent_sites", "(", "self", ",", "scaled_positions", ",", "ondublicates", "=", "'error'", ",", "symprec", "=", "1e-3", ")", ":", "kinds", "=", "[", "]", "sites", "=", "[", "]", "symprec2", "=", "symprec", "**", "2", "scaled", "=", "np", ".", "array", "(", "scaled_positions", ",", "ndmin", "=", "2", ")", "for", "kind", ",", "pos", "in", "enumerate", "(", "scaled", ")", ":", "for", "rot", ",", "trans", "in", "self", ".", "get_symop", "(", ")", ":", "site", "=", "np", ".", "mod", "(", "np", ".", "dot", "(", "rot", ",", "pos", ")", "+", "trans", ",", "1.", ")", "if", "not", "sites", ":", "sites", ".", "append", "(", "site", ")", "kinds", ".", "append", "(", "kind", ")", "continue", "t", "=", "site", "-", "sites", "mask", "=", "np", ".", "sum", "(", "t", "*", "t", ",", "1", ")", "<", "symprec2", "if", "np", ".", "any", "(", "mask", ")", ":", "ind", "=", "np", ".", "argwhere", "(", "mask", ")", "[", "0", "]", "[", "0", "]", "if", "kinds", "[", "ind", "]", "==", "kind", ":", "pass", "elif", "ondublicates", "==", "'keep'", ":", "pass", "elif", "ondublicates", "==", "'replace'", ":", "kinds", "[", "ind", "]", "=", "kind", "elif", "ondublicates", "==", "'warn'", ":", "warnings", ".", "warn", "(", "'scaled_positions %d and %d '", "'are equivalent'", "%", "(", "kinds", "[", "ind", "]", ",", "kind", ")", ")", "elif", "ondublicates", "==", "'error'", ":", "raise", "SpacegroupValueError", "(", "'scaled_positions %d and %d are equivalent'", "%", "(", "kinds", "[", "ind", "]", ",", "kind", ")", ")", "else", ":", "raise", "SpacegroupValueError", "(", "'Argument \"ondublicates\" must be one of: '", "'\"keep\", \"replace\", \"warn\" or \"error\".'", ")", "else", ":", "sites", ".", "append", "(", "site", ")", "kinds", ".", "append", "(", "kind", ")", "return", "np", ".", "array", "(", "sites", ")", ",", "kinds" ]
Returns the scaled positions and all their equivalent sites. Parameters: scaled_positions: list | array List of non-equivalent sites given in unit cell coordinates. ondublicates : 'keep' | 'replace' | 'warn' | 'error' Action if `scaled_positions` contain symmetry-equivalent positions: 'keep' ignore additional symmetry-equivalent positions 'replace' replace 'warn' like 'keep', but issue an UserWarning 'error' raises a SpacegroupValueError symprec: float Minimum "distance" betweed two sites in scaled coordinates before they are counted as the same site. Returns: sites: array A NumPy array of equivalent sites. kinds: list A list of integer indices specifying which input site is equivalent to the corresponding returned site. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]]) >>> sites array([[ 0. , 0. , 0. ], [ 0. , 0.5, 0.5], [ 0.5, 0. , 0.5], [ 0.5, 0.5, 0. ], [ 0.5, 0. , 0. ], [ 0. , 0.5, 0. ], [ 0. , 0. , 0.5], [ 0.5, 0.5, 0.5]]) >>> kinds [0, 0, 0, 0, 1, 1, 1, 1]
[ "Returns", "the", "scaled", "positions", "and", "all", "their", "equivalent", "sites", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L302-L387
16,393
chemlab/chemlab
chemlab/io/handlers/utils.py
guess_type
def guess_type(typ): '''Guess the atom type from purely heuristic considerations.''' # Strip useless numbers match = re.match("([a-zA-Z]+)\d*", typ) if match: typ = match.groups()[0] return typ
python
def guess_type(typ): '''Guess the atom type from purely heuristic considerations.''' # Strip useless numbers match = re.match("([a-zA-Z]+)\d*", typ) if match: typ = match.groups()[0] return typ
[ "def", "guess_type", "(", "typ", ")", ":", "# Strip useless numbers", "match", "=", "re", ".", "match", "(", "\"([a-zA-Z]+)\\d*\"", ",", "typ", ")", "if", "match", ":", "typ", "=", "match", ".", "groups", "(", ")", "[", "0", "]", "return", "typ" ]
Guess the atom type from purely heuristic considerations.
[ "Guess", "the", "atom", "type", "from", "purely", "heuristic", "considerations", "." ]
c8730966316d101e24f39ac3b96b51282aba0abe
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/utils.py#L3-L9
16,394
janpipek/physt
physt/plotting/matplotlib.py
register
def register(*dim: List[int], use_3d: bool = False, use_polar: bool = False, collection: bool = False): """Decorator to wrap common plotting functionality. Parameters ---------- dim : Dimensionality of histogram for which it is applicable use_3d : If True, the figure will be 3D. use_polar : If True, the figure will be in polar coordinates. collection : Whether to allow histogram collections to be used """ if use_3d and use_polar: raise RuntimeError("Cannot have polar and 3d coordinates simultaneously.") # TODO: Add some kind of class parameter def decorate(function): types.append(function.__name__) dims[function.__name__] = dim @wraps(function) def f(hist, write_to: Optional[str] = None, dpi:Optional[float] = None, **kwargs): fig, ax = _get_axes(kwargs, use_3d=use_3d, use_polar=use_polar) from physt.histogram_collection import HistogramCollection if collection and isinstance(hist, HistogramCollection): title = kwargs.pop("title", hist.title) if not hist: raise ValueError("Cannot plot empty histogram collection") for i, h in enumerate(hist): # TODO: Add some mechanism for argument maps (like sklearn?) function(h, ax=ax, **kwargs) ax.legend() ax.set_title(title) else: function(hist, ax=ax, **kwargs) if write_to: fig = ax.figure fig.tight_layout() fig.savefig(write_to, dpi=dpi or default_dpi) return ax return f return decorate
python
def register(*dim: List[int], use_3d: bool = False, use_polar: bool = False, collection: bool = False): """Decorator to wrap common plotting functionality. Parameters ---------- dim : Dimensionality of histogram for which it is applicable use_3d : If True, the figure will be 3D. use_polar : If True, the figure will be in polar coordinates. collection : Whether to allow histogram collections to be used """ if use_3d and use_polar: raise RuntimeError("Cannot have polar and 3d coordinates simultaneously.") # TODO: Add some kind of class parameter def decorate(function): types.append(function.__name__) dims[function.__name__] = dim @wraps(function) def f(hist, write_to: Optional[str] = None, dpi:Optional[float] = None, **kwargs): fig, ax = _get_axes(kwargs, use_3d=use_3d, use_polar=use_polar) from physt.histogram_collection import HistogramCollection if collection and isinstance(hist, HistogramCollection): title = kwargs.pop("title", hist.title) if not hist: raise ValueError("Cannot plot empty histogram collection") for i, h in enumerate(hist): # TODO: Add some mechanism for argument maps (like sklearn?) function(h, ax=ax, **kwargs) ax.legend() ax.set_title(title) else: function(hist, ax=ax, **kwargs) if write_to: fig = ax.figure fig.tight_layout() fig.savefig(write_to, dpi=dpi or default_dpi) return ax return f return decorate
[ "def", "register", "(", "*", "dim", ":", "List", "[", "int", "]", ",", "use_3d", ":", "bool", "=", "False", ",", "use_polar", ":", "bool", "=", "False", ",", "collection", ":", "bool", "=", "False", ")", ":", "if", "use_3d", "and", "use_polar", ":", "raise", "RuntimeError", "(", "\"Cannot have polar and 3d coordinates simultaneously.\"", ")", "# TODO: Add some kind of class parameter", "def", "decorate", "(", "function", ")", ":", "types", ".", "append", "(", "function", ".", "__name__", ")", "dims", "[", "function", ".", "__name__", "]", "=", "dim", "@", "wraps", "(", "function", ")", "def", "f", "(", "hist", ",", "write_to", ":", "Optional", "[", "str", "]", "=", "None", ",", "dpi", ":", "Optional", "[", "float", "]", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fig", ",", "ax", "=", "_get_axes", "(", "kwargs", ",", "use_3d", "=", "use_3d", ",", "use_polar", "=", "use_polar", ")", "from", "physt", ".", "histogram_collection", "import", "HistogramCollection", "if", "collection", "and", "isinstance", "(", "hist", ",", "HistogramCollection", ")", ":", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "hist", ".", "title", ")", "if", "not", "hist", ":", "raise", "ValueError", "(", "\"Cannot plot empty histogram collection\"", ")", "for", "i", ",", "h", "in", "enumerate", "(", "hist", ")", ":", "# TODO: Add some mechanism for argument maps (like sklearn?)", "function", "(", "h", ",", "ax", "=", "ax", ",", "*", "*", "kwargs", ")", "ax", ".", "legend", "(", ")", "ax", ".", "set_title", "(", "title", ")", "else", ":", "function", "(", "hist", ",", "ax", "=", "ax", ",", "*", "*", "kwargs", ")", "if", "write_to", ":", "fig", "=", "ax", ".", "figure", "fig", ".", "tight_layout", "(", ")", "fig", ".", "savefig", "(", "write_to", ",", "dpi", "=", "dpi", "or", "default_dpi", ")", "return", "ax", "return", "f", "return", "decorate" ]
Decorator to wrap common plotting functionality. Parameters ---------- dim : Dimensionality of histogram for which it is applicable use_3d : If True, the figure will be 3D. use_polar : If True, the figure will be in polar coordinates. collection : Whether to allow histogram collections to be used
[ "Decorator", "to", "wrap", "common", "plotting", "functionality", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L63-L105
16,395
janpipek/physt
physt/plotting/matplotlib.py
bar
def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Bar plot of 1D histograms.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) value_format = kwargs.pop("value_format", None) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) label = kwargs.pop("label", h1.name) lw = kwargs.pop("linewidth", kwargs.pop("lw", 0.5)) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", None) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) kwargs["yerr"] = err_data if "ecolor" not in kwargs: kwargs["ecolor"] = "black" _add_labels(ax, h1, kwargs) ax.bar(h1.bin_left_edges, data, h1.bin_widths, align="edge", label=label, color=colors, linewidth=lw, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
python
def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Bar plot of 1D histograms.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) value_format = kwargs.pop("value_format", None) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) label = kwargs.pop("label", h1.name) lw = kwargs.pop("linewidth", kwargs.pop("lw", 0.5)) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", None) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) kwargs["yerr"] = err_data if "ecolor" not in kwargs: kwargs["ecolor"] = "black" _add_labels(ax, h1, kwargs) ax.bar(h1.bin_left_edges, data, h1.bin_widths, align="edge", label=label, color=colors, linewidth=lw, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
[ "def", "bar", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "*", ",", "errors", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "show_values", "=", "kwargs", ".", "pop", "(", "\"show_values\"", ",", "False", ")", "value_format", "=", "kwargs", ".", "pop", "(", "\"value_format\"", ",", "None", ")", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "cumulative", "=", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "False", ")", "label", "=", "kwargs", ".", "pop", "(", "\"label\"", ",", "h1", ".", "name", ")", "lw", "=", "kwargs", ".", "pop", "(", "\"linewidth\"", ",", "kwargs", ".", "pop", "(", "\"lw\"", ",", "0.5", ")", ")", "text_kwargs", "=", "pop_kwargs_with_prefix", "(", "\"text_\"", ",", "kwargs", ")", "data", "=", "get_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "if", "\"cmap\"", "in", "kwargs", ":", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "_", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "colors", "=", "cmap", "(", "cmap_data", ")", "else", ":", "colors", "=", "kwargs", ".", "pop", "(", "\"color\"", ",", "None", ")", "_apply_xy_lims", "(", "ax", ",", "h1", ",", "data", ",", "kwargs", ")", "_add_ticks", "(", "ax", ",", "h1", ",", "kwargs", ")", "if", "errors", ":", "err_data", "=", "get_err_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "kwargs", "[", "\"yerr\"", "]", "=", "err_data", "if", "\"ecolor\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"ecolor\"", "]", "=", "\"black\"", "_add_labels", "(", "ax", ",", "h1", ",", "kwargs", ")", "ax", ".", "bar", "(", "h1", ".", "bin_left_edges", ",", "data", ",", "h1", ".", "bin_widths", ",", "align", "=", "\"edge\"", ",", "label", "=", "label", ",", "color", "=", "colors", ",", "linewidth", "=", "lw", ",", "*", "*", "kwargs", ")", "if", "show_values", ":", "_add_values", "(", "ax", ",", "h1", ",", "data", ",", "value_format", "=", "value_format", ",", "*", "*", "text_kwargs", ")", "if", "show_stats", ":", "_add_stats_box", "(", "h1", ",", "ax", ",", "stats", "=", "show_stats", ")" ]
Bar plot of 1D histograms.
[ "Bar", "plot", "of", "1D", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L109-L145
16,396
janpipek/physt
physt/plotting/matplotlib.py
scatter
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Scatter plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) kwargs["color"] = cmap(cmap_data) else: kwargs["color"] = kwargs.pop("color", "blue") _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"), ecolor=kwargs.pop("ecolor", "black"), ms=0) ax.scatter(h1.bin_centers, data, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
python
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Scatter plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) kwargs["color"] = cmap(cmap_data) else: kwargs["color"] = kwargs.pop("color", "blue") _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"), ecolor=kwargs.pop("ecolor", "black"), ms=0) ax.scatter(h1.bin_centers, data, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
[ "def", "scatter", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "*", ",", "errors", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "show_values", "=", "kwargs", ".", "pop", "(", "\"show_values\"", ",", "False", ")", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "cumulative", "=", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "False", ")", "value_format", "=", "kwargs", ".", "pop", "(", "\"value_format\"", ",", "None", ")", "text_kwargs", "=", "pop_kwargs_with_prefix", "(", "\"text_\"", ",", "kwargs", ")", "data", "=", "get_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "if", "\"cmap\"", "in", "kwargs", ":", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "_", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "kwargs", "[", "\"color\"", "]", "=", "cmap", "(", "cmap_data", ")", "else", ":", "kwargs", "[", "\"color\"", "]", "=", "kwargs", ".", "pop", "(", "\"color\"", ",", "\"blue\"", ")", "_apply_xy_lims", "(", "ax", ",", "h1", ",", "data", ",", "kwargs", ")", "_add_ticks", "(", "ax", ",", "h1", ",", "kwargs", ")", "_add_labels", "(", "ax", ",", "h1", ",", "kwargs", ")", "if", "errors", ":", "err_data", "=", "get_err_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "ax", ".", "errorbar", "(", "h1", ".", "bin_centers", ",", "data", ",", "yerr", "=", "err_data", ",", "fmt", "=", "kwargs", ".", "pop", "(", "\"fmt\"", ",", "\"o\"", ")", ",", "ecolor", "=", "kwargs", ".", "pop", "(", "\"ecolor\"", ",", "\"black\"", ")", ",", "ms", "=", "0", ")", "ax", ".", "scatter", "(", "h1", ".", "bin_centers", ",", "data", ",", "*", "*", "kwargs", ")", "if", "show_values", ":", "_add_values", "(", "ax", ",", "h1", ",", "data", ",", "value_format", "=", "value_format", ",", "*", "*", "text_kwargs", ")", "if", "show_stats", ":", "_add_stats_box", "(", "h1", ",", "ax", ",", "stats", "=", "show_stats", ")" ]
Scatter plot of 1D histogram.
[ "Scatter", "plot", "of", "1D", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L149-L180
16,397
janpipek/physt
physt/plotting/matplotlib.py
line
def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs): """Line plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop( "fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs) else: ax.plot(h1.bin_centers, data, **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
python
def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs): """Line plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop( "fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs) else: ax.plot(h1.bin_centers, data, **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
[ "def", "line", "(", "h1", ":", "Union", "[", "Histogram1D", ",", "\"HistogramCollection\"", "]", ",", "ax", ":", "Axes", ",", "*", ",", "errors", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "show_values", "=", "kwargs", ".", "pop", "(", "\"show_values\"", ",", "False", ")", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "cumulative", "=", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "False", ")", "value_format", "=", "kwargs", ".", "pop", "(", "\"value_format\"", ",", "None", ")", "text_kwargs", "=", "pop_kwargs_with_prefix", "(", "\"text_\"", ",", "kwargs", ")", "kwargs", "[", "\"label\"", "]", "=", "kwargs", ".", "get", "(", "\"label\"", ",", "h1", ".", "name", ")", "data", "=", "get_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "_apply_xy_lims", "(", "ax", ",", "h1", ",", "data", ",", "kwargs", ")", "_add_ticks", "(", "ax", ",", "h1", ",", "kwargs", ")", "_add_labels", "(", "ax", ",", "h1", ",", "kwargs", ")", "if", "errors", ":", "err_data", "=", "get_err_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "ax", ".", "errorbar", "(", "h1", ".", "bin_centers", ",", "data", ",", "yerr", "=", "err_data", ",", "fmt", "=", "kwargs", ".", "pop", "(", "\"fmt\"", ",", "\"-\"", ")", ",", "ecolor", "=", "kwargs", ".", "pop", "(", "\"ecolor\"", ",", "\"black\"", ")", ",", "*", "*", "kwargs", ")", "else", ":", "ax", ".", "plot", "(", "h1", ".", "bin_centers", ",", "data", ",", "*", "*", "kwargs", ")", "if", "show_stats", ":", "_add_stats_box", "(", "h1", ",", "ax", ",", "stats", "=", "show_stats", ")", "if", "show_values", ":", "_add_values", "(", "ax", ",", "h1", ",", "data", ",", "value_format", "=", "value_format", ",", "*", "*", "text_kwargs", ")" ]
Line plot of 1D histogram.
[ "Line", "plot", "of", "1D", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L184-L211
16,398
janpipek/physt
physt/plotting/matplotlib.py
fill
def fill(h1: Histogram1D, ax: Axes, **kwargs): """Fill plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) # show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) ax.fill_between(h1.bin_centers, 0, data, **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) # if show_values: # _add_values(ax, h1, data) return ax
python
def fill(h1: Histogram1D, ax: Axes, **kwargs): """Fill plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) # show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) ax.fill_between(h1.bin_centers, 0, data, **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) # if show_values: # _add_values(ax, h1, data) return ax
[ "def", "fill", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "# show_values = kwargs.pop(\"show_values\", False)", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "cumulative", "=", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "False", ")", "kwargs", "[", "\"label\"", "]", "=", "kwargs", ".", "get", "(", "\"label\"", ",", "h1", ".", "name", ")", "data", "=", "get_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "_apply_xy_lims", "(", "ax", ",", "h1", ",", "data", ",", "kwargs", ")", "_add_ticks", "(", "ax", ",", "h1", ",", "kwargs", ")", "_add_labels", "(", "ax", ",", "h1", ",", "kwargs", ")", "ax", ".", "fill_between", "(", "h1", ".", "bin_centers", ",", "0", ",", "data", ",", "*", "*", "kwargs", ")", "if", "show_stats", ":", "_add_stats_box", "(", "h1", ",", "ax", ",", "stats", "=", "show_stats", ")", "# if show_values:", "# _add_values(ax, h1, data)", "return", "ax" ]
Fill plot of 1D histogram.
[ "Fill", "plot", "of", "1D", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L215-L234
16,399
janpipek/physt
physt/plotting/matplotlib.py
step
def step(h1: Histogram1D, ax: Axes, **kwargs): """Step line-plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) ax.step(h1.numpy_bins, np.concatenate([data[:1], data]), **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
python
def step(h1: Histogram1D, ax: Axes, **kwargs): """Step line-plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) ax.step(h1.numpy_bins, np.concatenate([data[:1], data]), **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
[ "def", "step", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "show_values", "=", "kwargs", ".", "pop", "(", "\"show_values\"", ",", "False", ")", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "cumulative", "=", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "False", ")", "value_format", "=", "kwargs", ".", "pop", "(", "\"value_format\"", ",", "None", ")", "text_kwargs", "=", "pop_kwargs_with_prefix", "(", "\"text_\"", ",", "kwargs", ")", "kwargs", "[", "\"label\"", "]", "=", "kwargs", ".", "get", "(", "\"label\"", ",", "h1", ".", "name", ")", "data", "=", "get_data", "(", "h1", ",", "cumulative", "=", "cumulative", ",", "density", "=", "density", ")", "_apply_xy_lims", "(", "ax", ",", "h1", ",", "data", ",", "kwargs", ")", "_add_ticks", "(", "ax", ",", "h1", ",", "kwargs", ")", "_add_labels", "(", "ax", ",", "h1", ",", "kwargs", ")", "ax", ".", "step", "(", "h1", ".", "numpy_bins", ",", "np", ".", "concatenate", "(", "[", "data", "[", ":", "1", "]", ",", "data", "]", ")", ",", "*", "*", "kwargs", ")", "if", "show_stats", ":", "_add_stats_box", "(", "h1", ",", "ax", ",", "stats", "=", "show_stats", ")", "if", "show_values", ":", "_add_values", "(", "ax", ",", "h1", ",", "data", ",", "value_format", "=", "value_format", ",", "*", "*", "text_kwargs", ")" ]
Step line-plot of 1D histogram.
[ "Step", "line", "-", "plot", "of", "1D", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L238-L258