Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def load_molecule(name, format=None): '''Read a `~chemlab.core.Molecule` from a file. .. seealso:: `chemlab.io.datafile` ''' mol = datafile(name, format=format).read('molecule') display_system(System([mol]))
[]
Please provide a description of the function:def load_remote_trajectory(url, format=None): '''Load a trajectory file from a remote location specified by *url*. .. seealso:: load_remote_system ''' from urllib import urlretrieve filename, headers = urlretrieve(url) load_trajectory(filename, ...
[]
Please provide a description of the function:def write_system(filename, format=None): '''Write the system currently displayed to a file.''' datafile(filename, format=format, mode='w').write('system', current_system())
[]
Please provide a description of the function:def write_molecule(filename, format=None): '''Write the system displayed in a file as a molecule.''' datafile(filename, format=format, mode='w').write('molecule',current_system())
[]
Please provide a description of the function:def goto_time(timeval): '''Go to a specific time (in nanoseconds) in the current trajectory. ''' i = bisect.bisect(viewer.frame_times, timeval * 1000) goto_frame(i)
[]
Please provide a description of the function:def load_trajectory(name, skip=1, format=None): '''Load a trajectory file into chemlab. You should call this command after you load a `~chemlab.core.System` through load_system or load_remote_system. ''' df = datafile(name, format=format) dt, coords ...
[]
Please provide a description of the function:def merge_systems(sysa, sysb, bounding=0.2): '''Generate a system by merging *sysa* and *sysb*. Overlapping molecules are removed by cutting the molecules of *sysa* that have atoms near the atoms of *sysb*. The cutoff distance is defined by the *bounding* pa...
[]
Please provide a description of the function:def minimum_image(self): if self.box_vectors is None: raise ValueError('No periodic vectors defined') else: self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal()) return self
[ "Align the system according to the minimum image convention" ]
Please provide a description of the function:def remove_atoms(self, indices): mol_indices = self.atom_to_molecule_indices(indices) self.copy_from(self.sub(molecule_index=mol_indices))
[ "Remove the atoms positioned at *indices*. The molecule\n containing the atom is removed as well.\n\n If you have a system of 10 water molecules (and 30 atoms), if\n you remove the atoms at indices 0, 1 and 29 you will remove\n the first and last water molecules.\n\n **Parameters*...
Please provide a description of the function: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 ...
[ "Return indices that met the conditions" ]
Please provide a description of the function:def cartesian_to_spherical(cartesian): xyz = cartesian xy = xyz[:,0]**2 + xyz[:,1]**2 r = np.sqrt(xy + xyz[:,2]**2) phi = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down #ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)...
[ "Convert cartesian to spherical coordinates passed as (N,3) shaped arrays." ]
Please provide a description of the function:def binomial(n,k): if n==k: return 1 assert n>k, "Attempting to call binomial(%d,%d)" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k))
[ "\n Binomial coefficient\n >>> binomial(5,2)\n 10\n >>> binomial(10,5)\n 252\n " ]
Please provide a description of the function:def Fgamma(m,x): SMALL=1e-12 x = max(x,SMALL) return 0.5*pow(x,-m-0.5)*gamm_inc(m+0.5,x)
[ "\n Incomplete gamma function\n >>> np.isclose(Fgamma(0,0),1.0)\n True\n " ]
Please provide a description of the function:def gamm_inc(a,x): assert (x > 0 and a >= 0), "Invalid arguments in routine gamm_inc: %s,%s" % (x,a) if x < (a+1.0): #Use the series representation gam,gln = _gser(a,x) else: #Use continued fractions gamc,gln = _gcf(a,x) gam = 1-gamc...
[ "\n Incomple gamma function \\gamma; computed from NumRec routine gammp.\n >>> np.isclose(gamm_inc(0.5,1),1.49365)\n True\n >>> np.isclose(gamm_inc(1.5,2),0.6545103)\n True\n >>> np.isclose(gamm_inc(2.5,1e-12),0)\n True\n " ]
Please provide a description of the function: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...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function:def dmat(c,nocc): "Form the density matrix from the first nocc orbitals of c" return np.dot(c[:,:nocc],c[:,:nocc].T)
[]
Please provide a description of the function:def symorth(S): "Symmetric orthogonalization" E,U = np.linalg.eigh(S) n = len(E) Shalf = np.identity(n,'d') for i in range(n): Shalf[i,i] /= np.sqrt(E[i]) return simx(Shalf,U,True)
[]
Please provide a description of the function:def canorth(S): "Canonical orthogonalization U/sqrt(lambda)" E,U = np.linalg.eigh(S) for i in range(len(E)): U[:,i] = U[:,i] / np.sqrt(E[i]) return U
[]
Please provide a description of the function:def cholorth(S): "Cholesky orthogonalization" return np.linalg.inv(np.linalg.cholesky(S)).T
[]
Please provide a description of the function:def simx(A,B,transpose=False): "Similarity transform B^T(AB) or B(AB^T) (if transpose)" if transpose: return np.dot(B,np.dot(A,B.T)) return np.dot(B.T,np.dot(A,B))
[]
Please provide a description of the function: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)
[]
Please provide a description of the function:def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [] words = line.split() for i in range(len(format)): f = format[i] trans = xlat.get(f,None) if trans: result.append(trans(words[i])) if l...
[ "\\\n Given a line (a string actually) and a short string telling\n how to format it, return a list of python objects that result.\n\n The format string maps words (as split by line.split()) into\n python code:\n x -> Nothing; skip this word\n s -> Return this word as a string\n i -...
Please provide a description of the function:def colorscale(mag, cmin, cmax): # Normalize to 0-1 try: x = float(mag-cmin)/(cmax-cmin) except ZeroDivisionError: x = 0.5 # cmax == cmin blue = min((max((4*(0.75-x), 0.)), 1.)) red = min((max((4*(x-0.25), 0.)), 1.)) green = min(...
[ "\n Return a tuple of floats between 0 and 1 for R, G, and B.\n From Python Cookbook (9.11?)\n " ]
Please provide a description of the function:def from_fields(cls, **kwargs): ''' Create an `Atom` instance from a set of fields. This is a slightly faster way to initialize an Atom. **Example** >>> Atom.from_fields(type='Ar', r_array=np.arra...
[]
Please provide a description of the function: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' ret...
[]
Please provide a description of the function:def nearest_neighbors(coordinates_a, coordinates_b, periodic, r=None, n=None): '''Nearest neighbor search between two arrays of coordinates. Notice that you can control the result by selecting neighbors either by radius *r* or by number *n*. The algorithm uses a ...
[]
Please provide a description of the function: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,) :para...
[]
Please provide a description of the function:def change_background(color): viewer.widget.background_color = colors.any_to_rgb(color) viewer.update()
[ "Setup the background color to *color*. \n \n Example::\n\n change_background('black')\n change_background('white')\n change_background('#ffffff')\n \n You can call this function interactively by using::\n\n change_color.interactive()\n \n A new dialog will popup with a color...
Please provide a description of the function:def scale_atoms(fac): '''Scale the currently selected atoms atoms by a certain factor *fac*. Use the value *fac=1.0* to reset the scale. ''' rep = current_representation() atms = selected_atoms() rep.scale_factors[atms] = fac rep.update...
[]
Please provide a description of the function:def change_color(color): rep = current_representation() # Let's parse the color first if isinstance(color, str): # The color should be a string col = color_from_string(color) if isinstance(color, tuple): col = color ...
[ "Change the color of the currently selected objects. *color* is\n represented as a string. Otherwise color can be passed as an rgba\n tuple of values between 0, 255\n\n Reset the color by passing *color=None*.\n \n You can call this function interactively by using::\n\n change_color.interactiv...
Please provide a description of the function: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\n " ]
Please provide a description of the function:def screenshot(filename, width=None, height=None): '''Make a screenshot of the current view. You can tweak the resolution up to what your GPU memory supports. By defaults it uses the current window resolution. Example:: screenshot('screen.png...
[]
Please provide a description of the function:def add_post_processing(effect, **options): from chemlab.graphics.postprocessing import SSAOEffect, OutlineEffect, FXAAEffect, GammaCorrectionEffect pp_map = {'ssao': SSAOEffect, 'outline': OutlineEffect, 'fxaa': FXAAEffect, ...
[ "Apply a post processing effect.\n\n **Parameters**\n \n effect: string\n The effect to be applied, choose between ``ssao``,\n ``outline``, ``fxaa``, ``gamma``.\n \n **options:\n Options used to initialize the effect, check the\n :doc:`chemlab.graphics.postprocessing` for ...
Please provide a description of the function:def greplines(pattern, lines): res = [] for line in lines: match = re.search(pattern, line) if match is not None: res.append(line) return res
[ "Given a list of strings *lines* return the lines that match\n pattern.\n\n " ]
Please provide a description of the function:def sections(start, end, text, line=True): if not line: return re.findall(start+"(.*?)"+end, text, re.DOTALL) lines = text.splitlines() # This is a state-machine with the states MATCHING = True/False MATCHING = False section_list = ...
[ "Given the *text* to analyze return the section the start and\n end matchers. If line=True return the lines between the line that\n matches *start* and the line that matches *end* regexps.\n\n If line=False return the text between the matching start and end\n \n The match is in the regexp lingo *ungr...
Please provide a description of the function:def grep_split(pattern, text): '''Take the lines in *text* and split them each time the pattern matches a line. ''' lines = text.splitlines() indices = [i for i, line in enumerate(lines) if re.search(pattern, line)] return ['\n'.j...
[]
Please provide a description of the function:def unit_vector(x): y = np.array(x, dtype='float') return y/norm(y)
[ "Return a unit vector in the same direction as x." ]
Please provide a description of the function: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." ]
Please provide a description of the function:def cell_to_cellpar(cell): va, vb, vc = cell a = np.linalg.norm(va) b = np.linalg.norm(vb) c = np.linalg.norm(vc) alpha = 180.0/pi*arccos(dot(vb, vc)/(b*c)) beta = 180.0/pi*arccos(dot(vc, va)/(c*a)) gamma = 180.0/pi*arccos(dot(va, vb)/(a*b))...
[ "Returns the cell parameters [a, b, c, alpha, beta, gamma] as a\n numpy array." ]
Please provide a description of the function:def cellpar_to_cell(cellpar, ab_normal=(0,0,1), a_direction=None): if a_direction is None: if np.linalg.norm(np.cross(ab_normal, (1,0,0))) < 1e-5: a_direction = (0,0,1) else: a_direction = (1,0,0) # Define rotated X,Y,Z-s...
[ "Return a 3x3 cell matrix from `cellpar` = [a, b, c, alpha,\n beta, gamma]. The returned cell is orientated such that a and b\n are normal to `ab_normal` and a is parallel to the projection of\n `a_direction` in the a-b plane.\n\n Default `a_direction` is (1,0,0), unless this is parallel to\n `ab_no...
Please provide a description of the function: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\n Cartesian system." ]
Please provide a description of the function: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 {} al...
[ "Register a new data handler for a given format in\n the default handler list.\n\n This is a convenience function used internally to setup the\n default handlers. It can be used to add other handlers at\n runtime even if this isn't a suggested practice.\n\n **Parameters**\n\n ioc...
Please provide a description of the function:def get_handler_class(ext): if ext in _extensions_map: format = _extensions_map[ext] else: raise ValueError("Unknown format for %s extension." % ext) if format in _handler_map: hc = _handler_map[format] return hc else: ...
[ "Get the IOHandler that can handle the extension *ext*." ]
Please provide a description of the function:def datafile(filename, mode="rb", format=None): filename = os.path.expanduser(filename) base, ext = os.path.splitext(filename) if format is None: hc = get_handler_class(ext) else: hc = _handler_map.get(format) if hc is None: ...
[ "Initialize the appropriate\n :py:class:`~chemlab.io.iohandler.IOHandler` for a given file\n extension or file format.\n\n The *datafile* function can be conveniently used to quickly read\n or write data in a certain format::\n\n >>> handler = datafile(\"molecule.pdb\")\n >>> mol = handler...
Please provide a description of the function:def remotefile(url, format=None): if format is None: res = urlparse(url) filename, ext = os.path.splitext(res.path) hc = get_handler_class(ext) else: hc = _handler_map.get(format) if hc is None: raise ValueEr...
[ "The usage of *remotefile* is equivalent to\n :func:`chemlab.io.datafile` except you can download a file from a\n remote url.\n\n **Example**\n\n mol = remotefile(\"https://github.com/chemlab/chemlab-testdata/blob/master/3ZJE.pdb\").read(\"molecule\")\n\n " ]
Please provide a description of the function: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_num...
[ "\n Wraps a vector collection of atom positions into the central periodic\n image or primary simulation cell.\n\n Parameters\n ----------\n pos : :class:`numpy.ndarray`, (Nx3)\n Vector collection of atom positions.\n\n Returns\n -------\n wrap : :class:`numpy.ndarray`, (Nx3)\n Returns ...
Please provide a description of the function:def noperiodic(r_array, periodic, reference=None): '''Rearrange the array of coordinates *r_array* in a way that doensn't cross the periodic boundary. Parameters ---------- r_array : :class:`numpy.ndarray`, (Nx3) Array of 3D coordinate...
[]
Please provide a description of the function: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 * (periodi...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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)
[]
Please provide a description of the function:def periodic_distance(a, b, periodic): ''' Periodic distance between two arrays. Periodic is a 3 dimensional array containing the 3 box sizes. ''' a = np.array(a) b = np.array(b) periodic = np.array(periodic) delta = np.abs(a - b) delta ...
[]
Please provide a description of the function: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) ...
[]
Please provide a description of the function: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)
[]
Please provide a description of the function: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(resp...
[ " Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds " ]
Please provide a description of the function: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 " ]
Please provide a description of the function: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.ch...
[ " Load extended compound info from the Mass Spec API " ]
Please provide a description of the function: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...
[ " Return string containing PNG binary image data of 2D structure image " ]
Please provide a description of the function: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) sel...
[ " Return record in MOL format " ]
Please provide a description of the function: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) ...
[ " Return record in MOL format with 3D coordinates calculated " ]
Please provide a description of the function: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)
[]
Please provide a description of the function:def write(self, feature, value, *args, **kwargs): if 'w' not in self.fd.mode and 'x' not in self.fd.mode: raise Exception("The file is not opened in writing mode. If you're using datafile, add the 'w' option.\ndatafile(filename, 'w')") ...
[ "Same as :py:meth:`~chemlab.io.iohandler.IOHandler.read`. You have to pass\n also a *value* to write and you may pass any additional \n arguments.\n \n **Example**\n \n ::\n \n class XyzIO(IOHandler):\n can_write = ['molecule']\n \n ...
Please provide a description of the function:def check_feature(self, feature, readwrite): if readwrite == "read": features = self.can_read if readwrite == "write": features = self.can_write if feature not in features: matches = difflib.g...
[ "Check if the *feature* is supported in the handler and\n raise an exception otherwise.\n\n **Parameters**\n \n feature: str\n Identifier for a certain feature.\n readwrite: \"read\" or \"write\"\n Check if the feature is available for reading or writing.\n ...
Please provide a description of the function: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) #...
[]
Please provide a description of the function: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 Value...
[]
Please provide a description of the function: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...
[ "normalize numpy index" ]
Please provide a description of the function:def has_attribute(self, name, alias=False): prop_dict = merge_dicts(self.__attributes__, self.__fields__, self.__relations__) if alias: prop_dict.update({v.alias : v for v in...
[ "Check if the entity contains the attribute *name*" ]
Please provide a description of the function: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\n using from_dict.\n \n " ]
Please provide a description of the function: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: ...
[ "Create a ChemicalEntity from a json string \n " ]
Please provide a description of the function: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: ...
[ "Create a copy of this ChemicalEntity\n \n " ]
Please provide a description of the function: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.__rela...
[ "Copy properties from another ChemicalEntity\n \n " ]
Please provide a description of the function: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_...
[ "Update the current chemical entity from a dictionary of attributes" ]
Please provide a description of the function: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 {})' .f...
[ "Return child entity" ]
Please provide a description of the function: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.\n \n If other dimensions depend on this one those are updated accordingly.\n " ]
Please provide a description of the function: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 == dimens...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function:def where(self, inplace=False, **kwargs): masks = {k: np.ones(v, dtype='bool') for k,v in self.dimensions.items()} def index_to_mask(index, n): val = np.zeros(n, dtype='bool') val[index] = True return val...
[ "Return indices over every dimension that met the conditions. \n \n Condition syntax:\n \n *attribute* = value\n \n Return indices that satisfy the condition where the attribute is equal\n to the value\n \n e.g. type_array = 'H'\n \n *attr...
Please provide a description of the function:def sub(self, inplace=False, **kwargs): filter_ = self.where(**kwargs) return self.subindex(filter_, inplace)
[ "Return a entity where the conditions are met" ]
Please provide a description of the function:def batch(self): _batch = [] yield _batch if _batch: new_part = super(type(self), type(self)).empty() new_part._from_entities(_batch, _batch[0].__dimension__) self.concat(new_part, inplace=True)
[ "Batch initialization" ]
Please provide a description of the function: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 ele...
[ "Return a sub-attribute" ]
Please provide a description of the function: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 " ]
Please provide a description of the function: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 = [...
[ " Get all results for resolving input to the specified output representation " ]
Please provide a description of the function: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: ...
[ " Resolve and download structure as a file " ]
Please provide a description of the function: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 " ]
Please provide a description of the function:def guess_bonds(r_array, type_array, threshold=0.1, maxradius=0.3, radii_dict=None): '''Detect bonds given the coordinates (r_array) and types of the atoms involved (type_array), based on their covalent radii. To fine-tune the detection, it is possible to s...
[]
Please provide a description of the function:def move_to(self, r): '''Translate the molecule to a new position *r*. ''' dx = r - self.r_array[0] self.r_array += dx
[]
Please provide a description of the function:def periodic_distance(a, b, periodic): '''Periodic distance between two arrays. Periodic is a 3 dimensional array containing the 3 box sizes. ''' delta = np.abs(a - b) delta = np.where(delta > 0.5 * periodic, periodic - delta, delta) return np.sqrt((...
[]
Please provide a description of the function: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)
[]
Please provide a description of the function:def parse_gro_lines(lines): '''Reusable parsing''' title = lines.pop(0) natoms = int(lines.pop(0)) atomlist = [] # I need r_array, type_array datalist = [] for l in lines: fields = l.split() line_length = len(l) if line_l...
[]
Please provide a description of the function:def distances_within(coords_a, coords_b, cutoff, periodic=False, method="simple"): mat = distance_matrix(coords_a, coords_b, cutoff, periodic, method) return mat[mat.nonzero()]
[ "Calculate distances between the array of coordinates *coord_a*\n and *coord_b* within a certain cutoff.\n \n This function is a wrapper around different routines and data structures\n for distance searches. It return a np.ndarray containing the distances.\n \n **Parameters**\n\n coords_a: np.n...
Please provide a description of the function:def distance_matrix(coords_a, coords_b, cutoff, periodic=False, method="simple"): coords_a = np.array(coords_a) coords_b = np.array(coords_b) if method=="simple": if periodic is not False: return distance_array(coords_...
[ "Calculate distances matrix the array of coordinates *coord_a*\n and *coord_b* within a certain cutoff.\n \n This function is a wrapper around different routines and data structures\n for distance searches. It return a np.ndarray containing the distances.\n \n Returns a matrix with all the compute...
Please provide a description of the function:def overlapping_points(coords_a, coords_b, cutoff, periodic=False): '''Return the indices of *coords_b* points that overlap with *coords_a* points. The overlap is calculated based on *cutoff*. **Parameters** coords_a: np.ndarray((NA, 3)) coords...
[]
Please provide a description of the function:def random_lattice_box(mol_list, mol_number, size, spacing=np.array([0.3, 0.3, 0.3])): '''Make a box by placing the molecules specified in *mol_list* on random points of an evenly spaced lattice. Using a lattice automatically ensures that ...
[]
Please provide a description of the function:def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100): '''Create a System made of a series of random molecules. Parameters: total: molecules: proportions: ''' # Setup proportions to be right if p...
[]
Please provide a description of the function: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:: ...
[]
Please provide a description of the function:def add_renderer(self, klass, *args, **kwargs): '''Add a renderer to the current scene. **Parameter** klass: renderer class The renderer class to be added args, kwargs: Arguments used by the renderer c...
[]
Please provide a description of the function:def remove_renderer(self, rend): '''Remove a renderer from the current view. **Example** :: rend = v.add_renderer(AtomRenderer) v.remove_renderer(rend) .. versionadded:: 0.3 ''' if re...
[]
Please provide a description of the function: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.widge...
[]
Please provide a description of the function:def add_post_processing(self, klass, *args, **kwargs): '''Add a post processing effect to the current scene. The usage is as following:: from chemlab.graphics.qt import QtViewer from chemlab.graphics.postprocessing im...
[]
Please provide a description of the function:def crystal(positions, molecules, group, cellpar=[1.0, 1.0, 1.0, 90, 90, 90], repetitions=[1, 1, 1]): '''Build a crystal from atomic positions, space group and cell parameters. **Parameters** positions: list of coordinates A list of ...
[]