idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
60,300 | 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 |
60,301 | 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_ma... | Apply a post processing effect . |
60,302 | def unit_vector ( x ) : y = np . array ( x , dtype = 'float' ) return y / norm ( y ) | Return a unit vector in the same direction as x . |
60,303 | 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 . |
60,304 | 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 . |
60,305 | 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 , _ext... | Register a new data handler for a given format in the default handler list . |
60,306 | def minimum_image ( coords , pbc ) : coords = np . array ( coords ) pbc = np . array ( pbc ) 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 . |
60,307 | 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 . |
60,308 | 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 . |
60,309 | 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 |
60,310 | 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_... | Geometric center taking into account periodic boundaries |
60,311 | 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 . |
60,312 | 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... | Search by Name SMILES InChI InChIKey etc . Returns first 100 Compounds |
60,313 | 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 |
60,314 | 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 els... | Load extended compound info from the Mass Spec API |
60,315 | 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 |
60,316 | 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 |
60,317 | 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 |
60,318 | 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 |
60,319 | def concatenate_attributes ( attributes ) : tpl = attributes [ 0 ] attr = InstanceAttribute ( tpl . name , tpl . shape , tpl . dtype , tpl . dim , alias = None ) 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 =... | Concatenate InstanceAttribute to return a bigger one . |
60,320 | 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, sha... | Create an INstanceAttribute from a list of InstnaceFields |
60,321 | 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 |
60,322 | 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 . |
60,323 | 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 |
60,324 | def copy ( self ) : inst = super ( type ( self ) , type ( self ) ) . empty ( ** self . dimensions ) 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 ( ) fo... | Create a copy of this ChemicalEntity |
60,325 | def copy_from ( self , other ) : 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 ... | Copy properties from another ChemicalEntity |
60,326 | def update ( self , dictionary ) : allowed_attrs = list ( self . __attributes__ . keys ( ) ) allowed_attrs += [ a . alias for a in self . __attributes__ . values ( ) ] for k in dictionary : if k in allowed_attrs : setattr ( self , k , dictionary [ k ] ) return self | Update the current chemical entity from a dictionary of attributes |
60,327 | 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 ( ) : ... | Return child entity |
60,328 | 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 . |
60,329 | 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 na... | When we expand we need to provide new maps and relations as those can t be inferred |
60,330 | def concat ( self , other , inplace = False ) : if inplace : obj = self else : obj = self . copy ( ) for name , attr in obj . __attributes__ . items ( ) : attr . append ( other . __attributes__ [ name ] ) for name , rel in obj . __relations__ . items ( ) : rel . append ( other . __relations__ [ name ] ) if obj . is_emp... | Concatenate two ChemicalEntity of the same kind |
60,331 | def sub ( self , inplace = False , ** kwargs ) : filter_ = self . where ( ** kwargs ) return self . subindex ( filter_ , inplace ) | Return a entity where the conditions are met |
60,332 | 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 . ... | Return a sub - attribute |
60,333 | 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 |
60,334 | 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 ) ) ... | Get all results for resolving input to the specified output representation |
60,335 | 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 ove... | Resolve and download structure as a file |
60,336 | 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 |
60,337 | 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 . |
60,338 | 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 . |
60,339 | 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 . |
60,340 | 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 |
60,341 | 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 . |
60,342 | 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 the ouput resulted of a geometry optimization . Or a saddle point . |
60,343 | 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 self . bounds = np . array ( bounds , dtype = 'float32' ) vertices , ... | Reinitialize the buffers to accomodate the new attributes . This is used to change the number of cylinders to be displayed . |
60,344 | 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 |
60,345 | 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 |
60,346 | 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 |
60,347 | 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 ) ... | Display System object |
60,348 | 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 ) if simulation . potential . ... | Create gromacs directory structure |
60,349 | def update_vertices ( self , vertices ) : vertices = np . array ( vertices , dtype = np . float32 ) self . _vbo_v . set_data ( vertices ) | Update the triangle vertices . |
60,350 | def update_normals ( self , normals ) : normals = np . array ( normals , dtype = np . float32 ) self . _vbo_n . set_data ( normals ) | Update the triangle normals . |
60,351 | 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 . |
60,352 | def set_text ( self , text ) : self . traj_controls . timelabel . setText ( self . traj_controls . _label_tmp . format ( text ) ) | Update the time indicator in the interface . |
60,353 | def update_function ( self , func , frames = None ) : 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 . |
60,354 | 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 ... | Create a rotation matrix corresponding to the rotation around a general axis by a specified angle . |
60,355 | def rotation_from_matrix ( matrix ) : R = numpy . array ( matrix , dtype = numpy . float64 , copy = False ) R33 = R [ : 3 , : 3 ] 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 eigen... | Return rotation angle and axis from rotation matrix . |
60,356 | 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 : w , V = numpy . linalg . eig ( M33 ) i = numpy . where ( abs ( numpy . real ( w ) - factor ) < 1e-8 ) [ 0 ] [ 0 ] direction = numpy . real ( V [ : , i... | Return scaling factor origin and direction from scaling matrix . |
60,357 | 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 ,... | Return orthogonalization matrix for crystallographic cell coordinates . |
60,358 | 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 . |
60,359 | 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 ... | Return homogeneous rotation matrix from quaternion . |
60,360 | 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 = n... | Return multiplication of two quaternions . |
60,361 | 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 angle between vectors . |
60,362 | 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 . _qdow... | Update current cursor window coordinates . |
60,363 | 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 . |
60,364 | 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 . |
60,365 | 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... | Select the bonds connected to the currently selected atoms . |
60,366 | 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 ) } b = current_system ( ) . bonds if ... | Select all the molecules corresponding to the formulas . |
60,367 | 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 . |
60,368 | def unhide_selected ( ) : hidden_state = current_representation ( ) . hidden_state selection_state = current_representation ( ) . selection_state res = { } for k in selection_state : visible = hidden_state [ k ] . invert ( ) visible_and_selected = visible . add ( selection_state [ k ] ) res [ k ] = visible_and_selected... | Unhide the selected objects |
60,369 | 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 . |
60,370 | def mouse_zoom ( self , inc ) : dsq = np . linalg . norm ( self . position - self . pivot ) minsq = 1.0 ** 2 maxsq = 7.0 ** 2 scalefac = 0.25 if dsq > maxsq and inc < 0 : pass elif dsq < minsq and inc > 0 : pass else : self . position += self . c * inc * scalefac | Convenience function to implement a zoom function . |
60,371 | def unproject ( self , x , y , z = - 1.0 ) : source = np . array ( [ x , y , z , 1.0 ] ) 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 . |
60,372 | 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 . |
60,373 | 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 ] dista... | Calculate the intersection points between a ray and multiple spheres . |
60,374 | 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 . |
60,375 | def parse_color ( color ) : if isinstance ( color , str ) : try : col = get ( color ) except ValueError : pass 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 . |
60,376 | 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 ) ) R = np . zeros ( H . shape , float ) G = np . zeros ( H . shape , float ) ... | Converts HSL color array to RGB array |
60,377 | 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... | Returns well formatted Hermann - Mauguin symbol as extected by the database by correcting the case and adding missing or removing dublicated spaces . |
60,378 | 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 . |
60,379 | 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 ] ) ) f . readline ( ) spg . _scaled_primitive_cell = np . array ( [ list ( map ( float , f . readline ( ) . sp... | Read space group data from f to spg . |
60,380 | 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 ... | Parses a sequence of site symmetries in the form used by International Tables and returns corresponding rotation and translation arrays . |
60,381 | 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 symb... | Manually create a new space group instance . This might be usefull when reading crystal data with its own spacegroup definitions . |
60,382 | 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 . |
60,383 | 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 . |
60,384 | 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 .... | Return all equivalent reflections to the list of Miller indices in hkl . |
60,385 | 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 ) + ... | Returns the scaled positions and all their equivalent sites . |
60,386 | def guess_type ( typ ) : match = re . match ( "([a-zA-Z]+)\d*" , typ ) if match : typ = match . groups ( ) [ 0 ] return typ | Guess the atom type from purely heuristic considerations . |
60,387 | 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." ) def decorate ( function ) : types . append ( function . __name__ ) dims [ function . __name__ ] =... | Decorator to wrap common plotting functionality . |
60,388 | 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 ( "cumul... | Bar plot of 1D histograms . |
60,389 | 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 ( "va... | Scatter plot of 1D histogram . |
60,390 | 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 ) va... | Line plot of 1D histogram . |
60,391 | def fill ( h1 : Histogram1D , ax : Axes , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , 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 = ... | Fill plot of 1D histogram . |
60,392 | 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_kwarg... | Step line - plot of 1D histogram . |
60,393 | def bar3d ( h2 : Histogram2D , ax : Axes3D , ** kwargs ) : density = kwargs . pop ( "density" , False ) data = get_data ( h2 , cumulative = False , flatten = True , density = density ) if "cmap" in kwargs : cmap = _get_cmap ( kwargs ) _ , cmap_data = _get_cmap_data ( data , kwargs ) colors = cmap ( cmap_data ) else : c... | Plot of 2D histograms as 3D boxes . |
60,394 | def image ( h2 : Histogram2D , ax : Axes , * , show_colorbar : bool = True , interpolation : str = "nearest" , ** kwargs ) : cmap = _get_cmap ( kwargs ) data = get_data ( h2 , cumulative = False , density = kwargs . pop ( "density" , False ) ) norm , cmap_data = _get_cmap_data ( data , kwargs ) for binning in h2 . _bin... | Plot of 2D histograms based on pixmaps . |
60,395 | def polar_map ( hist : Histogram2D , ax : Axes , * , show_zero : bool = True , show_colorbar : bool = True , ** kwargs ) : data = get_data ( hist , cumulative = False , flatten = True , density = kwargs . pop ( "density" , False ) ) cmap = _get_cmap ( kwargs ) norm , cmap_data = _get_cmap_data ( data , kwargs ) colors ... | Polar map of polar histograms . |
60,396 | def globe_map ( hist : Union [ Histogram2D , DirectionalHistogram ] , ax : Axes3D , * , show_zero : bool = True , ** kwargs ) : data = get_data ( hist , cumulative = False , flatten = False , density = kwargs . pop ( "density" , False ) ) cmap = _get_cmap ( kwargs ) norm , cmap_data = _get_cmap_data ( data , kwargs ) c... | Heat map plotted on the surface of a sphere . |
60,397 | def pair_bars ( first : Histogram1D , second : Histogram2D , * , orientation : str = "vertical" , kind : str = "bar" , ** kwargs ) : _ , ax = _get_axes ( kwargs ) color1 = kwargs . pop ( "color1" , "red" ) color2 = kwargs . pop ( "color2" , "blue" ) title = kwargs . pop ( "title" , "{0} - {1}" . format ( first . name ,... | Draw two different histograms mirrored in one figure . |
60,398 | def _get_axes ( kwargs : Dict [ str , Any ] , * , use_3d : bool = False , use_polar : bool = False ) -> Tuple [ Figure , Union [ Axes , Axes3D ] ] : figsize = kwargs . pop ( "figsize" , default_figsize ) if "ax" in kwargs : ax = kwargs . pop ( "ax" ) fig = ax . get_figure ( ) elif use_3d : fig = plt . figure ( figsize ... | Prepare the axis to draw into . |
60,399 | def _get_cmap ( kwargs : dict ) -> colors . Colormap : from matplotlib . colors import ListedColormap cmap = kwargs . pop ( "cmap" , default_cmap ) if isinstance ( cmap , list ) : return ListedColormap ( cmap ) if isinstance ( cmap , str ) : try : cmap = plt . get_cmap ( cmap ) except BaseException as exc : try : impor... | Get the colour map for plots that support it . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.