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_map [ effect ] , ** options ) viewer . update ( ) global _counter _counter += 1 str_id = effect + str ( _counter ) _effect_map [ str_id ] = pp return str_id
|
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 , _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 .
|
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_avg , - eps_avg ) + np . pi return theta_avg * max_vals / ( 2 * np . pi )
|
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 = 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
|
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 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
|
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 = 0 ) return attr
|
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, 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
|
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 ( ) 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
|
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 : m . copy ( ) for k , m in other . maps . items ( ) } self . dimensions = other . dimensions . copy ( )
|
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 ( ) : if attr . dim == dim : entity . __fields__ [ name ] = attr . field ( index ) elif attr . dim in entity . dimensions : if self . dimensions [ attr . dim ] == 0 : continue 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 : pass if rel . map in entity . dimensions : 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 ) 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
|
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 name , rel in self . __relations__ . items ( ) : if dimension == rel . dim : 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 : rel . index = range ( newdim ) for ( a , b ) , rel in self . maps . items ( ) : if dimension == rel . dim : 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 : rel . index = range ( newdim ) self . dimensions [ dimension ] = newdim return self
|
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_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
|
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 . 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
|
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 ) ) 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 : pass return result if result else None
|
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 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 : pass
|
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_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 ) ] 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 .
|
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 , 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 ( [ 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 , 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 , 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 , 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 , 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 , 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 .
|
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 ) self . plotter . points ( object . r_array , alpha = alpha , ** kwargs ) return self
|
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 . 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 ) ) mdpfile = to_mdp ( simulation ) with open ( os . path . join ( directory , 'grompp.mdp' ) , 'w' ) as fd : fd . write ( mdpfile ) topfile = to_top ( simulation . system , simulation . potential ) with open ( os . path . join ( directory , 'topol.top' ) , 'w' ) as fd : fd . write ( topfile ) datafile ( os . path . join ( directory , 'conf.gro' ) , 'w' ) . write ( 'system' , simulation . system ) return directory
|
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 ] , 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 .
|
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 eigenvalue 1" ) direction = numpy . real ( W [ : , i [ - 1 ] ] ) . squeeze ( ) 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 ] 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 .
|
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 ] ) . squeeze ( ) direction /= vector_norm ( direction ) except IndexError : factor = ( factor + 2.0 ) / 3.0 direction = None 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 .
|
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 , 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 .
|
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 , 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 .
|
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 = numpy . float64 )
|
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 numpy . arccos ( dot if directed else numpy . fabs ( dot ) )
|
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 . _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 .
|
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 . n_bonds ) ) ret = csel . copy ( ) ret [ 'bonds' ] = bsel return select_selection ( ret )
|
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 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 .
|
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 . invert ( ) current_representation ( ) . hide ( res )
|
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 ] distances = ( - b_v [ inters_mask ] - np . sqrt ( det_v [ inters_mask ] ) ) / 2.0 dist_mask = distances > 0.0 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 .
|
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 ) B = np . zeros ( H . shape , float ) 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
|
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 == '/' : 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 .
|
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 ( ) . split ( ) ) ) for i in range ( 3 ) ] , dtype = 'float' ) f . readline ( ) spg . _reciprocal_cell = np . array ( [ list ( map ( int , f . readline ( ) . split ( ) ) ) for i in range ( 3 ) ] , dtype = np . int ) 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 ) 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 .
|
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 [ 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 .
|
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 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 .
|
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 . 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 .
|
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 ) + 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 .
|
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__ ] = 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 ) : 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 .
|
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 ( "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 .
|
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 ( "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 .
|
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 ) 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 .
|
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 = 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 ) return ax
|
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_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 .
|
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 : colors = kwargs . pop ( "color" , "blue" ) xpos , ypos = ( arr . flatten ( ) for arr in h2 . get_bin_centers ( ) ) zpos = np . zeros_like ( ypos ) dx , dy = ( arr . flatten ( ) for arr in h2 . get_bin_widths ( ) ) _add_labels ( ax , h2 , kwargs ) ax . bar3d ( xpos , ypos , zpos , dx , dy , data , color = colors , ** kwargs ) ax . set_zlabel ( "density" if density else "frequency" )
|
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 . _binnings : if not binning . is_regular ( ) : raise RuntimeError ( "Histograms with irregular bins cannot be plotted using image method." ) kwargs [ "interpolation" ] = interpolation if kwargs . get ( "xscale" ) == "log" or kwargs . get ( "yscale" ) == "log" : raise RuntimeError ( "Cannot use logarithmic axes with image plots." ) _apply_xy_lims ( ax , h2 , data = data , kwargs = kwargs ) _add_labels ( ax , h2 , kwargs ) ax . imshow ( data . T [ : : - 1 , : ] , cmap = cmap , norm = norm , extent = ( h2 . bins [ 0 ] [ 0 , 0 ] , h2 . bins [ 0 ] [ - 1 , 1 ] , h2 . bins [ 1 ] [ 0 , 0 ] , h2 . bins [ 1 ] [ - 1 , 1 ] ) , aspect = "auto" , ** kwargs ) if show_colorbar : _add_colorbar ( ax , cmap , cmap_data , norm )
|
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 = cmap ( cmap_data ) rpos , phipos = ( arr . flatten ( ) for arr in hist . get_bin_left_edges ( ) ) dr , dphi = ( arr . flatten ( ) for arr in hist . get_bin_widths ( ) ) rmax , _ = ( arr . flatten ( ) for arr in hist . get_bin_right_edges ( ) ) bar_args = { } if "zorder" in kwargs : bar_args [ "zorder" ] = kwargs . pop ( "zorder" ) alphas = _get_alpha_data ( cmap_data , kwargs ) if np . isscalar ( alphas ) : alphas = np . ones_like ( data ) * alphas for i in range ( len ( rpos ) ) : if data [ i ] > 0 or show_zero : bin_color = colors [ i ] bars = ax . bar ( phipos [ i ] , dr [ i ] , width = dphi [ i ] , bottom = rpos [ i ] , align = 'edge' , color = bin_color , edgecolor = kwargs . get ( "grid_color" , cmap ( 0.5 ) ) , lw = kwargs . get ( "lw" , 0.5 ) , alpha = alphas [ i ] , ** bar_args ) ax . set_rmax ( rmax . max ( ) ) if show_colorbar : _add_colorbar ( ax , cmap , cmap_data , norm )
|
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 ) colors = cmap ( cmap_data ) lw = kwargs . pop ( "lw" , 1 ) r = 1 xs = r * np . outer ( np . sin ( hist . numpy_bins [ 0 ] ) , np . cos ( hist . numpy_bins [ 1 ] ) ) ys = r * np . outer ( np . sin ( hist . numpy_bins [ 0 ] ) , np . sin ( hist . numpy_bins [ 1 ] ) ) zs = r * np . outer ( np . cos ( hist . numpy_bins [ 0 ] ) , np . ones ( hist . shape [ 1 ] + 1 ) ) for i in range ( hist . shape [ 0 ] ) : for j in range ( hist . shape [ 1 ] ) : if not show_zero and not data [ i , j ] : continue x = xs [ i , j ] , xs [ i , j + 1 ] , xs [ i + 1 , j + 1 ] , xs [ i + 1 , j ] y = ys [ i , j ] , ys [ i , j + 1 ] , ys [ i + 1 , j + 1 ] , ys [ i + 1 , j ] z = zs [ i , j ] , zs [ i , j + 1 ] , zs [ i + 1 , j + 1 ] , zs [ i + 1 , j ] verts = [ list ( zip ( x , y , z ) ) ] col = Poly3DCollection ( verts ) col . set_facecolor ( colors [ i , j ] ) col . set_edgecolor ( "black" ) col . set_linewidth ( lw ) ax . add_collection3d ( col ) ax . set_xlabel ( "x" ) ax . set_ylabel ( "y" ) ax . set_zlabel ( "z" ) if matplotlib . __version__ < "2" : ax . plot_surface ( [ ] , [ ] , [ ] , color = "b" ) ax . set_xlim ( - 1.1 , 1.1 ) ax . set_ylim ( - 1.1 , 1.1 ) ax . set_zlim ( - 1.1 , 1.1 ) return ax
|
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 , second . name ) ) xlim = kwargs . pop ( "xlim" , ( min ( first . bin_left_edges [ 0 ] , first . bin_left_edges [ 0 ] ) , max ( first . bin_right_edges [ - 1 ] , second . bin_right_edges [ - 1 ] ) ) ) bar ( first * ( - 1 ) , color = color1 , ax = ax , ylim = "keep" , ** kwargs ) bar ( second , color = color2 , ax = ax , ylim = "keep" , ** kwargs ) ax . set_title ( title ) ticks = np . abs ( ax . get_yticks ( ) ) if np . allclose ( np . rint ( ticks ) , ticks ) : ax . set_yticklabels ( ticks . astype ( int ) ) else : ax . set_yticklabels ( ticks ) ax . set_xlim ( xlim ) ax . legend ( ) return ax
|
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 = figsize ) ax = fig . add_subplot ( 111 , projection = '3d' ) elif use_polar : fig = plt . figure ( figsize = figsize ) ax = fig . add_subplot ( 111 , projection = 'polar' ) else : fig , ax = plt . subplots ( figsize = figsize ) return fig , ax
|
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 : import seaborn as sns sns_palette = sns . color_palette ( cmap , n_colors = 256 ) cmap = ListedColormap ( sns_palette , name = cmap ) except ImportError : raise exc return cmap
|
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.