idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
248,200 | def query ( input , representation , resolvers = None , * * kwargs ) : apiurl = API_BASE + '/%s/%s/xml' % ( urlquote ( input ) , representation ) if resolvers : kwargs [ 'resolver' ] = "," . join ( resolvers ) if kwargs : apiurl += '?%s' % urlencode ( kwargs ) result = [ ] try : tree = ET . parse ( urlopen ( apiurl ) ) for data in tree . findall ( ".//data" ) : datadict = { 'resolver' : data . attrib [ 'resolver' ] , 'notation' : data . attrib [ 'notation' ] , 'value' : [ ] } for item in data . findall ( "item" ) : datadict [ 'value' ] . append ( item . text ) if len ( datadict [ 'value' ] ) == 1 : datadict [ 'value' ] = datadict [ 'value' ] [ 0 ] result . append ( datadict ) except HTTPError : # TODO: Proper handling of 404, for now just returns None pass return result if result else None | Get all results for resolving input to the specified output representation | 264 | 11 |
248,201 | def download ( input , filename , format = 'sdf' , overwrite = False , resolvers = None , * * kwargs ) : kwargs [ 'format' ] = format if resolvers : kwargs [ 'resolver' ] = "," . join ( resolvers ) url = API_BASE + '/%s/file?%s' % ( urlquote ( input ) , urlencode ( kwargs ) ) try : servefile = urlopen ( url ) if not overwrite and os . path . isfile ( filename ) : raise IOError ( "%s already exists. Use 'overwrite=True' to overwrite it." % filename ) file = open ( filename , "w" ) file . write ( servefile . read ( ) ) file . close ( ) except urllib . error . HTTPError : # TODO: Proper handling of 404, for now just does nothing pass | Resolve and download structure as a file | 196 | 8 |
248,202 | 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 | 53 | 7 |
248,203 | 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 . | 41 | 10 |
248,204 | 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 . | 35 | 10 |
248,205 | 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 . | 54 | 18 |
248,206 | 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 | 57 | 8 |
248,207 | 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 . | 86 | 13 |
248,208 | def parse_optimize ( self ) : match = re . search ( "EQUILIBRIUM GEOMETRY LOCATED" , self . text ) spmatch = "SADDLE POINT LOCATED" in self . text located = True if match or spmatch else False points = grep_split ( " BEGINNING GEOMETRY SEARCH POINT NSERCH=" , self . text ) if self . tddft == "excite" : points = [ self . parse_energy ( point ) for point in points [ 1 : ] ] else : regex = re . compile ( r'NSERCH:\s+\d+\s+E=\s+([+-]?\d+\.\d+)' ) points = [ Energy ( states = [ State ( 0 , None , float ( m . group ( 1 ) ) , 0.0 , 0.0 ) ] ) for m in regex . finditer ( self . text ) ] # Error handling if "FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN" in self . text : self . errcode = GEOM_NOT_LOCATED self . errmsg = "too many steps taken: %i" % len ( points ) if located : self . errcode = OK return Optimize ( points = points ) | Parse the ouput resulted of a geometry optimization . Or a saddle point . | 289 | 17 |
248,209 | def change_attributes ( self , bounds , radii , colors ) : self . n_cylinders = len ( bounds ) self . is_empty = True if self . n_cylinders == 0 else False if self . is_empty : self . bounds = bounds self . radii = radii self . colors = colors return # Do nothing # We pass the starting position 8 times, and each of these has # a mapping to the bounding box corner. self . bounds = np . array ( bounds , dtype = 'float32' ) vertices , directions = self . _gen_bounds ( self . bounds ) self . radii = np . array ( radii , dtype = 'float32' ) prim_radii = self . _gen_radii ( self . radii ) self . colors = np . array ( colors , dtype = 'uint8' ) prim_colors = self . _gen_colors ( self . colors ) local = np . array ( [ # First face -- front 0.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.0 , 1.0 , 0.0 , 1.0 , 0.0 , 0.0 , # Second face -- back 0.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , 1.0 , # Third face -- left 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.0 , 1.0 , 0.0 , 1.0 , 0.0 , # Fourth face -- right 1.0 , 0.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , # Fifth face -- up 0.0 , 1.0 , 0.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , 0.0 , # Sixth face -- down 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.0 , 1.0 , 0.0 , 1.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 1.0 , 1.0 , 0.0 , 0.0 , ] ) . astype ( 'float32' ) local = np . tile ( local , self . n_cylinders ) self . _verts_vbo = VertexBuffer ( vertices , GL_DYNAMIC_DRAW ) self . _directions_vbo = VertexBuffer ( directions , GL_DYNAMIC_DRAW ) self . _local_vbo = VertexBuffer ( local , GL_DYNAMIC_DRAW ) self . _color_vbo = VertexBuffer ( prim_colors , GL_DYNAMIC_DRAW ) self . _radii_vbo = VertexBuffer ( prim_radii , GL_DYNAMIC_DRAW ) | Reinitialize the buffers to accomodate the new attributes . This is used to change the number of cylinders to be displayed . | 829 | 27 |
248,210 | 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 | 83 | 5 |
248,211 | 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 | 75 | 6 |
248,212 | 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 | 70 | 5 |
248,213 | 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 | 124 | 3 |
248,214 | def make_gromacs ( simulation , directory , clean = False ) : if clean is False and os . path . exists ( directory ) : raise ValueError ( 'Cannot override {}, use option clean=True' . format ( directory ) ) else : shutil . rmtree ( directory , ignore_errors = True ) os . mkdir ( directory ) # Check custom simulation potential if simulation . potential . intermolecular . type == 'custom' : for pair in simulation . potential . intermolecular . special_pairs : table = to_table ( simulation . potential . intermolecular . pair_interaction ( * pair ) , simulation . cutoff ) fname1 = os . path . join ( directory , 'table_{}_{}.xvg' . format ( pair [ 0 ] , pair [ 1 ] ) ) fname2 = os . path . join ( directory , 'table_{}_{}.xvg' . format ( pair [ 1 ] , pair [ 0 ] ) ) with open ( fname1 , 'w' ) as fd : fd . write ( table ) with open ( fname2 , 'w' ) as fd : fd . write ( table ) ndx = { 'System' : np . arange ( simulation . system . n_atoms , dtype = 'int' ) } for particle in simulation . potential . intermolecular . particles : idx = simulation . system . where ( atom_name = particle ) [ 'atom' ] . nonzero ( ) [ 0 ] ndx [ particle ] = idx with open ( os . path . join ( directory , 'index.ndx' ) , 'w' ) as fd : fd . write ( to_ndx ( ndx ) ) # Parameter file mdpfile = to_mdp ( simulation ) with open ( os . path . join ( directory , 'grompp.mdp' ) , 'w' ) as fd : fd . write ( mdpfile ) # Topology file topfile = to_top ( simulation . system , simulation . potential ) with open ( os . path . join ( directory , 'topol.top' ) , 'w' ) as fd : fd . write ( topfile ) # Simulation file datafile ( os . path . join ( directory , 'conf.gro' ) , 'w' ) . write ( 'system' , simulation . system ) return directory | Create gromacs directory structure | 522 | 6 |
248,215 | def update_vertices ( self , vertices ) : vertices = np . array ( vertices , dtype = np . float32 ) self . _vbo_v . set_data ( vertices ) | Update the triangle vertices . | 45 | 6 |
248,216 | def update_normals ( self , normals ) : normals = np . array ( normals , dtype = np . float32 ) self . _vbo_n . set_data ( normals ) | Update the triangle normals . | 45 | 6 |
248,217 | 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 . | 59 | 8 |
248,218 | def set_text ( self , text ) : self . traj_controls . timelabel . setText ( self . traj_controls . _label_tmp . format ( text ) ) | Update the time indicator in the interface . | 43 | 8 |
248,219 | def update_function ( self , func , frames = None ) : # Back-compatibility if frames is not None : self . traj_controls . set_ticks ( frames ) self . _update_function = func | Set the function to be called when it s time to display a frame . | 48 | 15 |
248,220 | 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 . | 188 | 17 |
248,221 | def rotation_from_matrix ( matrix ) : R = numpy . array ( matrix , dtype = numpy . float64 , copy = False ) R33 = R [ : 3 , : 3 ] # direction: unit eigenvector of R33 corresponding to eigenvalue of 1 w , W = numpy . linalg . eig ( R33 . T ) i = numpy . where ( abs ( numpy . real ( w ) - 1.0 ) < 1e-8 ) [ 0 ] if not len ( i ) : raise ValueError ( "no unit eigenvector corresponding to eigenvalue 1" ) direction = numpy . real ( W [ : , i [ - 1 ] ] ) . squeeze ( ) # point: unit eigenvector of R33 corresponding to eigenvalue of 1 w , Q = numpy . linalg . eig ( R ) i = numpy . where ( abs ( numpy . real ( w ) - 1.0 ) < 1e-8 ) [ 0 ] if not len ( i ) : raise ValueError ( "no unit eigenvector corresponding to eigenvalue 1" ) point = numpy . real ( Q [ : , i [ - 1 ] ] ) . squeeze ( ) point /= point [ 3 ] # rotation angle depending on direction cosa = ( numpy . trace ( R33 ) - 1.0 ) / 2.0 if abs ( direction [ 2 ] ) > 1e-8 : sina = ( R [ 1 , 0 ] + ( cosa - 1.0 ) * direction [ 0 ] * direction [ 1 ] ) / direction [ 2 ] elif abs ( direction [ 1 ] ) > 1e-8 : sina = ( R [ 0 , 2 ] + ( cosa - 1.0 ) * direction [ 0 ] * direction [ 2 ] ) / direction [ 1 ] else : sina = ( R [ 2 , 1 ] + ( cosa - 1.0 ) * direction [ 1 ] * direction [ 2 ] ) / direction [ 0 ] angle = math . atan2 ( sina , cosa ) return angle , direction , point | Return rotation angle and axis from rotation matrix . | 457 | 9 |
248,222 | def scale_from_matrix ( matrix ) : M = numpy . array ( matrix , dtype = numpy . float64 , copy = False ) M33 = M [ : 3 , : 3 ] factor = numpy . trace ( M33 ) - 2.0 try : # direction: unit eigenvector corresponding to eigenvalue factor w , V = numpy . linalg . eig ( M33 ) i = numpy . where ( abs ( numpy . real ( w ) - factor ) < 1e-8 ) [ 0 ] [ 0 ] direction = numpy . real ( V [ : , i ] ) . squeeze ( ) direction /= vector_norm ( direction ) except IndexError : # uniform scaling factor = ( factor + 2.0 ) / 3.0 direction = None # origin: any eigenvector corresponding to eigenvalue 1 w , V = numpy . linalg . eig ( M ) i = numpy . where ( abs ( numpy . real ( w ) - 1.0 ) < 1e-8 ) [ 0 ] if not len ( i ) : raise ValueError ( "no eigenvector corresponding to eigenvalue 1" ) origin = numpy . real ( V [ : , i [ - 1 ] ] ) . squeeze ( ) origin /= origin [ 3 ] return factor , origin , direction | Return scaling factor origin and direction from scaling matrix . | 289 | 10 |
248,223 | 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 . | 182 | 12 |
248,224 | 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 . | 112 | 14 |
248,225 | 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 . | 270 | 10 |
248,226 | 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 . | 167 | 8 |
248,227 | 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 . | 135 | 5 |
248,228 | 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 . | 174 | 6 |
248,229 | 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 . | 90 | 7 |
248,230 | 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 . | 50 | 6 |
248,231 | 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 . | 138 | 10 |
248,232 | def select_molecules ( name ) : mol_formula = current_system ( ) . get_derived_molecule_array ( 'formula' ) mask = mol_formula == name ind = current_system ( ) . mol_to_atom_indices ( mask . nonzero ( ) [ 0 ] ) selection = { 'atoms' : Selection ( ind , current_system ( ) . n_atoms ) } # Need to find the bonds between the atoms b = current_system ( ) . bonds if len ( b ) == 0 : selection [ 'bonds' ] = Selection ( [ ] , 0 ) else : molbonds = np . zeros ( len ( b ) , 'bool' ) for i in ind : matching = ( i == b ) . sum ( axis = 1 ) . astype ( 'bool' ) molbonds [ matching ] = True selection [ 'bonds' ] = Selection ( molbonds . nonzero ( ) [ 0 ] , len ( b ) ) return select_selection ( selection ) | Select all the molecules corresponding to the formulas . | 225 | 9 |
248,233 | 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 . | 70 | 5 |
248,234 | def unhide_selected ( ) : hidden_state = current_representation ( ) . hidden_state selection_state = current_representation ( ) . selection_state res = { } # Take the hidden state and flip the selected atoms bits. for k in selection_state : visible = hidden_state [ k ] . invert ( ) visible_and_selected = visible . add ( selection_state [ k ] ) # Add some atoms to be visible res [ k ] = visible_and_selected . invert ( ) current_representation ( ) . hide ( res ) | Unhide the selected objects | 122 | 5 |
248,235 | 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 . | 39 | 21 |
248,236 | def mouse_zoom ( self , inc ) : # Square Distance from pivot dsq = np . linalg . norm ( self . position - self . pivot ) minsq = 1.0 ** 2 # How near can we be to the pivot maxsq = 7.0 ** 2 # How far can we go scalefac = 0.25 if dsq > maxsq and inc < 0 : # We're going too far pass elif dsq < minsq and inc > 0 : # We're going too close pass else : # We're golden self . position += self . c * inc * scalefac | Convenience function to implement a zoom function . | 129 | 10 |
248,237 | def unproject ( self , x , y , z = - 1.0 ) : source = np . array ( [ x , y , z , 1.0 ] ) # Invert the combined matrix matrix = self . projection . dot ( self . matrix ) IM = LA . inv ( matrix ) res = np . dot ( IM , source ) return res [ 0 : 3 ] / res [ 3 ] | Receive x and y as screen coordinates and returns a point in world coordinates . | 84 | 16 |
248,238 | 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 . | 64 | 17 |
248,239 | def ray_spheres_intersection ( origin , direction , centers , radii ) : b_v = 2.0 * ( ( origin - centers ) * direction ) . sum ( axis = 1 ) c_v = ( ( origin - centers ) ** 2 ) . sum ( axis = 1 ) - radii ** 2 det_v = b_v * b_v - 4.0 * c_v inters_mask = det_v >= 0 intersections = ( inters_mask ) . nonzero ( ) [ 0 ] distances = ( - b_v [ inters_mask ] - np . sqrt ( det_v [ inters_mask ] ) ) / 2.0 # We need only the thing in front of us, that corresponts to # positive distances. dist_mask = distances > 0.0 # We correct this aspect to get an absolute distance distances = distances [ dist_mask ] intersections = intersections [ dist_mask ] . tolist ( ) if intersections : distances , intersections = zip ( * sorted ( zip ( distances , intersections ) ) ) return list ( intersections ) , list ( distances ) else : return [ ] , [ ] | Calculate the intersection points between a ray and multiple spheres . | 246 | 13 |
248,240 | 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 . | 71 | 22 |
248,241 | def parse_color ( color ) : # Let's parse the color string if isinstance ( color , str ) : # Try dvi names try : col = get ( color ) except ValueError : # String is not present pass # Try html names try : col = html_to_rgb ( color ) except ValueError : raise ValueError ( "Can't parse color string: {}'" . format ( color ) ) return col | Return the RGB 0 - 255 representation of the current string passed . | 89 | 13 |
248,242 | def hsl_to_rgb ( arr ) : H , S , L = arr . T H = ( H . copy ( ) / 255.0 ) * 360 S = S . copy ( ) / 255.0 L = L . copy ( ) / 255.0 C = ( 1 - np . absolute ( 2 * L - 1 ) ) * S Hp = H / 60.0 X = C * ( 1 - np . absolute ( np . mod ( Hp , 2 ) - 1 ) ) # initilize with zero R = np . zeros ( H . shape , float ) G = np . zeros ( H . shape , float ) B = np . zeros ( H . shape , float ) # handle each case: mask = ( Hp >= 0 ) == ( Hp < 1 ) R [ mask ] = C [ mask ] G [ mask ] = X [ mask ] mask = ( Hp >= 1 ) == ( Hp < 2 ) R [ mask ] = X [ mask ] G [ mask ] = C [ mask ] mask = ( Hp >= 2 ) == ( Hp < 3 ) G [ mask ] = C [ mask ] B [ mask ] = X [ mask ] mask = ( Hp >= 3 ) == ( Hp < 4 ) G [ mask ] = X [ mask ] B [ mask ] = C [ mask ] mask = ( Hp >= 4 ) == ( Hp < 5 ) R [ mask ] = X [ mask ] B [ mask ] = C [ mask ] mask = ( Hp >= 5 ) == ( Hp < 6 ) R [ mask ] = C [ mask ] B [ mask ] = X [ mask ] m = L - 0.5 * C R += m G += m B += m R *= 255.0 G *= 255.0 B *= 255.0 return np . array ( ( R . astype ( int ) , G . astype ( int ) , B . astype ( int ) ) ) . T | Converts HSL color array to RGB array | 425 | 9 |
248,243 | 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 . | 152 | 30 |
248,244 | 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 . | 72 | 11 |
248,245 | def _read_datafile_entry ( spg , no , symbol , setting , f ) : spg . _no = no spg . _symbol = symbol . strip ( ) spg . _setting = setting spg . _centrosymmetric = bool ( int ( f . readline ( ) . split ( ) [ 1 ] ) ) # primitive vectors f . readline ( ) spg . _scaled_primitive_cell = np . array ( [ list ( map ( float , f . readline ( ) . split ( ) ) ) for i in range ( 3 ) ] , dtype = 'float' ) # primitive reciprocal vectors f . readline ( ) spg . _reciprocal_cell = np . array ( [ list ( map ( int , f . readline ( ) . split ( ) ) ) for i in range ( 3 ) ] , dtype = np . int ) # subtranslations spg . _nsubtrans = int ( f . readline ( ) . split ( ) [ 0 ] ) spg . _subtrans = np . array ( [ list ( map ( float , f . readline ( ) . split ( ) ) ) for i in range ( spg . _nsubtrans ) ] , dtype = np . float ) # symmetry operations nsym = int ( f . readline ( ) . split ( ) [ 0 ] ) symop = np . array ( [ list ( map ( float , f . readline ( ) . split ( ) ) ) for i in range ( nsym ) ] , dtype = np . float ) spg . _nsymop = nsym spg . _rotations = np . array ( symop [ : , : 9 ] . reshape ( ( nsym , 3 , 3 ) ) , dtype = np . int ) spg . _translations = symop [ : , 9 : ] | Read space group data from f to spg . | 405 | 10 |
248,246 | 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 . | 328 | 25 |
248,247 | 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 . | 435 | 25 |
248,248 | 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 | 7 |
248,249 | 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 . | 44 | 15 |
248,250 | 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 . | 181 | 14 |
248,251 | 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 . | 350 | 10 |
248,252 | def guess_type ( typ ) : # Strip useless numbers match = re . match ( "([a-zA-Z]+)\d*" , typ ) if match : typ = match . groups ( ) [ 0 ] return typ | Guess the atom type from purely heuristic considerations . | 49 | 11 |
248,253 | def register ( * dim : List [ int ] , use_3d : bool = False , use_polar : bool = False , collection : bool = False ) : if use_3d and use_polar : raise RuntimeError ( "Cannot have polar and 3d coordinates simultaneously." ) # TODO: Add some kind of class parameter def decorate ( function ) : types . append ( function . __name__ ) dims [ function . __name__ ] = dim @ wraps ( function ) def f ( hist , write_to : Optional [ str ] = None , dpi : Optional [ float ] = None , * * kwargs ) : fig , ax = _get_axes ( kwargs , use_3d = use_3d , use_polar = use_polar ) from physt . histogram_collection import HistogramCollection if collection and isinstance ( hist , HistogramCollection ) : title = kwargs . pop ( "title" , hist . title ) if not hist : raise ValueError ( "Cannot plot empty histogram collection" ) for i , h in enumerate ( hist ) : # TODO: Add some mechanism for argument maps (like sklearn?) function ( h , ax = ax , * * kwargs ) ax . legend ( ) ax . set_title ( title ) else : function ( hist , ax = ax , * * kwargs ) if write_to : fig = ax . figure fig . tight_layout ( ) fig . savefig ( write_to , dpi = dpi or default_dpi ) return ax return f return decorate | Decorator to wrap common plotting functionality . | 346 | 9 |
248,254 | 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 . | 488 | 8 |
248,255 | 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 . | 451 | 9 |
248,256 | 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 . | 401 | 8 |
248,257 | def fill ( h1 : Histogram1D , ax : Axes , * * kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) # show_values = kwargs.pop("show_values", False) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumulative" , False ) kwargs [ "label" ] = kwargs . get ( "label" , h1 . name ) data = get_data ( h1 , cumulative = cumulative , density = density ) _apply_xy_lims ( ax , h1 , data , kwargs ) _add_ticks ( ax , h1 , kwargs ) _add_labels ( ax , h1 , kwargs ) ax . fill_between ( h1 . bin_centers , 0 , data , * * kwargs ) if show_stats : _add_stats_box ( h1 , ax , stats = show_stats ) # if show_values: # _add_values(ax, h1, data) return ax | Fill plot of 1D histogram . | 245 | 8 |
248,258 | 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 . | 310 | 10 |
248,259 | 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 . | 265 | 11 |
248,260 | def image ( h2 : Histogram2D , ax : Axes , * , show_colorbar : bool = True , interpolation : str = "nearest" , * * kwargs ) : cmap = _get_cmap ( kwargs ) # h2 as well? data = get_data ( h2 , cumulative = False , density = kwargs . pop ( "density" , False ) ) norm , cmap_data = _get_cmap_data ( data , kwargs ) # zorder = kwargs.pop("zorder", None) 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 . | 393 | 12 |
248,261 | 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 ] # TODO: align = "edge" 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 . | 466 | 8 |
248,262 | 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 . | 613 | 10 |
248,263 | def pair_bars ( first : Histogram1D , second : Histogram2D , * , orientation : str = "vertical" , kind : str = "bar" , * * kwargs ) : # TODO: enable vertical as well as horizontal _ , 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 . | 352 | 10 |
248,264 | 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 . | 205 | 8 |
248,265 | 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 : # Try to use seaborn palette 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 . | 173 | 10 |
248,266 | def _get_cmap_data ( data , kwargs ) -> Tuple [ colors . Normalize , np . ndarray ] : norm = kwargs . pop ( "cmap_normalize" , None ) if norm == "log" : cmap_max = kwargs . pop ( "cmap_max" , data . max ( ) ) cmap_min = kwargs . pop ( "cmap_min" , data [ data > 0 ] . min ( ) ) norm = colors . LogNorm ( cmap_min , cmap_max ) elif not norm : cmap_max = kwargs . pop ( "cmap_max" , data . max ( ) ) cmap_min = kwargs . pop ( "cmap_min" , 0 ) if cmap_min == "min" : cmap_min = data . min ( ) norm = colors . Normalize ( cmap_min , cmap_max , clip = True ) return norm , norm ( data ) | Get normalized values to be used with a colormap . | 223 | 12 |
248,267 | def _get_alpha_data ( data : np . ndarray , kwargs ) -> Union [ float , np . ndarray ] : alpha = kwargs . pop ( "alpha" , 1 ) if hasattr ( alpha , "__call__" ) : return np . vectorize ( alpha ) ( data ) return alpha | Get alpha values for all data points . | 72 | 8 |
248,268 | def _add_values ( ax : Axes , h1 : Histogram1D , data , * , value_format = lambda x : x , * * kwargs ) : from . common import get_value_format value_format = get_value_format ( value_format ) text_kwargs = { "ha" : "center" , "va" : "bottom" , "clip_on" : True } text_kwargs . update ( kwargs ) for x , y in zip ( h1 . bin_centers , data ) : ax . text ( x , y , str ( value_format ( y ) ) , * * text_kwargs ) | Show values next to each bin in a 1D plot . | 146 | 12 |
248,269 | def _add_colorbar ( ax : Axes , cmap : colors . Colormap , cmap_data : np . ndarray , norm : colors . Normalize ) : fig = ax . get_figure ( ) mappable = cm . ScalarMappable ( cmap = cmap , norm = norm ) mappable . set_array ( cmap_data ) # TODO: Or what??? fig . colorbar ( mappable , ax = ax ) | Show a colorbar right of the plot . | 104 | 9 |
248,270 | def _add_stats_box ( h1 : Histogram1D , ax : Axes , stats : Union [ str , bool ] = "all" ) : # place a text box in upper left in axes coords if stats in [ "all" , True ] : text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}" . format ( h1 . total , h1 . mean ( ) , h1 . std ( ) ) elif stats == "total" : text = "Total: {0}" . format ( h1 . total ) else : raise ValueError ( "Invalid stats specification" ) ax . text ( 0.05 , 0.95 , text , transform = ax . transAxes , verticalalignment = 'top' , horizontalalignment = 'left' ) | Insert a small legend - like box with statistical information . | 186 | 11 |
248,271 | def normal_h1 ( size : int = 10000 , mean : float = 0 , sigma : float = 1 ) -> Histogram1D : data = np . random . normal ( mean , sigma , ( size , ) ) return h1 ( data , name = "normal" , axis_name = "x" , title = "1D normal distribution" ) | A simple 1D histogram with normal distribution . | 78 | 10 |
248,272 | def normal_h2 ( size : int = 10000 ) -> Histogram2D : data1 = np . random . normal ( 0 , 1 , ( size , ) ) data2 = np . random . normal ( 0 , 1 , ( size , ) ) return h2 ( data1 , data2 , name = "normal" , axis_names = tuple ( "xy" ) , title = "2D normal distribution" ) | A simple 2D histogram with normal distribution . | 90 | 10 |
248,273 | def normal_h3 ( size : int = 10000 ) -> HistogramND : data1 = np . random . normal ( 0 , 1 , ( size , ) ) data2 = np . random . normal ( 0 , 1 , ( size , ) ) data3 = np . random . normal ( 0 , 1 , ( size , ) ) return h3 ( [ data1 , data2 , data3 ] , name = "normal" , axis_names = tuple ( "xyz" ) , title = "3D normal distribution" ) | A simple 3D histogram with normal distribution . | 113 | 10 |
248,274 | def fist ( ) -> Histogram1D : import numpy as np from . . histogram1d import Histogram1D widths = [ 0 , 1.2 , 0.2 , 1 , 0.1 , 1 , 0.1 , 0.9 , 0.1 , 0.8 ] edges = np . cumsum ( widths ) heights = np . asarray ( [ 4 , 1 , 7.5 , 6 , 7.6 , 6 , 7.5 , 6 , 7.2 ] ) + 5 return Histogram1D ( edges , heights , axis_name = "Is this a fist?" , title = "Physt \"logo\"" ) | A simple histogram in the shape of a fist . | 146 | 11 |
248,275 | def require_compatible_version ( compatible_version , word = "File" ) : if isinstance ( compatible_version , str ) : compatible_version = parse_version ( compatible_version ) elif not isinstance ( compatible_version , Version ) : raise ValueError ( "Type of `compatible_version` not understood." ) current_version = parse_version ( CURRENT_VERSION ) if current_version < compatible_version : raise VersionError ( "{0} written for version >= {1}, this is {2}." . format ( word , str ( compatible_version ) , CURRENT_VERSION ) ) | Check that compatible version of input data is not too new . | 130 | 12 |
248,276 | def save_json ( histogram : Union [ HistogramBase , HistogramCollection ] , path : Optional [ str ] = None , * * kwargs ) -> str : # TODO: Implement multiple histograms in one file? data = histogram . to_dict ( ) data [ "physt_version" ] = CURRENT_VERSION if isinstance ( histogram , HistogramBase ) : data [ "physt_compatible" ] = COMPATIBLE_VERSION elif isinstance ( histogram , HistogramCollection ) : data [ "physt_compatible" ] = COLLECTION_COMPATIBLE_VERSION else : raise TypeError ( "Cannot save unknown type: {0}" . format ( type ( histogram ) ) ) text = json . dumps ( data , * * kwargs ) if path : with open ( path , "w" , encoding = "utf-8" ) as f : f . write ( text ) return text | Save histogram to JSON format . | 204 | 7 |
248,277 | def load_json ( path : str , encoding : str = "utf-8" ) -> HistogramBase : with open ( path , "r" , encoding = encoding ) as f : text = f . read ( ) return parse_json ( text ) | Load histogram from a JSON file . | 54 | 8 |
248,278 | def parse_json ( text : str , encoding : str = "utf-8" ) -> HistogramBase : data = json . loads ( text , encoding = encoding ) return create_from_dict ( data , format_name = "JSON" ) | Create histogram from a JSON string . | 53 | 8 |
248,279 | def histogram ( data , bins = None , * args , * * kwargs ) : import numpy as np from . histogram1d import Histogram1D , calculate_frequencies from . binnings import calculate_bins adaptive = kwargs . pop ( "adaptive" , False ) dtype = kwargs . pop ( "dtype" , None ) if isinstance ( data , tuple ) and isinstance ( data [ 0 ] , str ) : # Works for groupby DataSeries return histogram ( data [ 1 ] , bins , * args , name = data [ 0 ] , * * kwargs ) elif type ( data ) . __name__ == "DataFrame" : raise RuntimeError ( "Cannot create histogram from a pandas DataFrame. Use Series." ) # Collect arguments (not to send them to binning algorithms) dropna = kwargs . pop ( "dropna" , True ) weights = kwargs . pop ( "weights" , None ) keep_missed = kwargs . pop ( "keep_missed" , True ) name = kwargs . pop ( "name" , None ) axis_name = kwargs . pop ( "axis_name" , None ) title = kwargs . pop ( "title" , None ) # Convert to array if data is not None : array = np . asarray ( data ) #.flatten() if dropna : array = array [ ~ np . isnan ( array ) ] else : array = None # Get binning binning = calculate_bins ( array , bins , * args , check_nan = not dropna and array is not None , adaptive = adaptive , * * kwargs ) # bins = binning.bins # Get frequencies if array is not None : ( frequencies , errors2 , underflow , overflow , stats ) = calculate_frequencies ( array , binning = binning , weights = weights , dtype = dtype ) else : frequencies = None errors2 = None underflow = 0 overflow = 0 stats = { "sum" : 0.0 , "sum2" : 0.0 } # Construct the object if not keep_missed : underflow = 0 overflow = 0 if not axis_name : if hasattr ( data , "name" ) : axis_name = data . name elif hasattr ( data , "fields" ) and len ( data . fields ) == 1 and isinstance ( data . fields [ 0 ] , str ) : # Case of dask fields (examples) axis_name = data . fields [ 0 ] return Histogram1D ( binning = binning , frequencies = frequencies , errors2 = errors2 , overflow = overflow , underflow = underflow , stats = stats , dtype = dtype , keep_missed = keep_missed , name = name , axis_name = axis_name , title = title ) | Facade function to create 1D histograms . | 626 | 10 |
248,280 | def histogram2d ( data1 , data2 , bins = 10 , * args , * * kwargs ) : import numpy as np # guess axis names if "axis_names" not in kwargs : if hasattr ( data1 , "name" ) and hasattr ( data2 , "name" ) : kwargs [ "axis_names" ] = [ data1 . name , data2 . name ] if data1 is not None and data2 is not None : data1 = np . asarray ( data1 ) data2 = np . asarray ( data2 ) data = np . concatenate ( [ data1 [ : , np . newaxis ] , data2 [ : , np . newaxis ] ] , axis = 1 ) else : data = None return histogramdd ( data , bins , * args , dim = 2 , * * kwargs ) | Facade function to create 2D histograms . | 190 | 10 |
248,281 | def histogramdd ( data , bins = 10 , * args , * * kwargs ) : import numpy as np from . import histogram_nd from . binnings import calculate_bins_nd adaptive = kwargs . pop ( "adaptive" , False ) dropna = kwargs . pop ( "dropna" , True ) name = kwargs . pop ( "name" , None ) title = kwargs . pop ( "title" , None ) dim = kwargs . pop ( "dim" , None ) axis_names = kwargs . pop ( "axis_names" , None ) # pandas - guess axis names if not "axis_names" in kwargs : if hasattr ( data , "columns" ) : try : kwargs [ "axis_names" ] = tuple ( data . columns ) except : pass # Perhaps columns has different meaning here. # Prepare and check data # Convert to array if data is not None : data = np . asarray ( data ) if data . ndim != 2 : raise RuntimeError ( "Array must have shape (n, d)" ) if dim is not None and dim != data . shape [ 1 ] : raise RuntimeError ( "Dimension mismatch: {0}!={1}" . format ( dim , data . shape [ 1 ] ) ) _ , dim = data . shape if dropna : data = data [ ~ np . isnan ( data ) . any ( axis = 1 ) ] check_nan = not dropna else : if dim is None : raise RuntimeError ( "You have to specify either data or its dimension." ) data = np . zeros ( ( 0 , dim ) ) check_nan = False # Prepare bins bin_schemas = calculate_bins_nd ( data , bins , * args , check_nan = check_nan , adaptive = adaptive , * * kwargs ) #bins = [binning.bins for binning in bin_schemas] # Prepare remaining data weights = kwargs . pop ( "weights" , None ) frequencies , errors2 , missed = histogram_nd . calculate_frequencies ( data , ndim = dim , binnings = bin_schemas , weights = weights ) kwargs [ "name" ] = name if title : kwargs [ "title" ] = title if axis_names : kwargs [ "axis_names" ] = axis_names if dim == 2 : return histogram_nd . Histogram2D ( binnings = bin_schemas , frequencies = frequencies , errors2 = errors2 , * * kwargs ) else : return histogram_nd . HistogramND ( dimension = dim , binnings = bin_schemas , frequencies = frequencies , errors2 = errors2 , * * kwargs ) | Facade function to create n - dimensional histograms . | 611 | 11 |
248,282 | def h3 ( data , * args , * * kwargs ) : import numpy as np if data is not None and isinstance ( data , ( list , tuple ) ) and not np . isscalar ( data [ 0 ] ) : if "axis_names" not in kwargs : kwargs [ "axis_names" ] = [ ( column . name if hasattr ( column , "name" ) else None ) for column in data ] data = np . concatenate ( [ item [ : , np . newaxis ] for item in data ] , axis = 1 ) else : kwargs [ "dim" ] = 3 return histogramdd ( data , * args , * * kwargs ) | Facade function to create 3D histograms . | 154 | 10 |
248,283 | def collection ( data , bins = 10 , * args , * * kwargs ) : from physt . histogram_collection import HistogramCollection if hasattr ( data , "columns" ) : data = { column : data [ column ] for column in data . columns } return HistogramCollection . multi_h1 ( data , bins , * * kwargs ) | Create histogram collection with shared binnning . | 80 | 10 |
248,284 | def write_root ( histogram : HistogramBase , hfile : uproot . write . TFile . TFileUpdate , name : str ) : hfile [ name ] = histogram | Write histogram to an open ROOT file . | 40 | 10 |
248,285 | def write ( histogram ) : histogram_dict = histogram . to_dict ( ) message = Histogram ( ) for field in SIMPLE_CONVERSION_FIELDS : setattr ( message , field , histogram_dict [ field ] ) # Main numerical data - TODO: Optimize! message . frequencies . extend ( histogram . frequencies . flatten ( ) ) message . errors2 . extend ( histogram . errors2 . flatten ( ) ) # Binnings for binning in histogram . _binnings : binning_message = message . binnings . add ( ) for edges in binning . bins : limits = binning_message . bins . add ( ) limits . lower = edges [ 0 ] limits . upper = edges [ 1 ] # All meta data meta_message = message . meta # user_defined = {} # for key, value in histogram.meta_data.items(): # if key not in PREDEFINED: # user_defined[str(key)] = str(value) for key in SIMPLE_META_KEYS : if key in histogram . meta_data : setattr ( meta_message , key , str ( histogram . meta_data [ key ] ) ) if "axis_names" in histogram . meta_data : meta_message . axis_names . extend ( histogram . meta_data [ "axis_names" ] ) message . physt_version = CURRENT_VERSION message . physt_compatible = COMPATIBLE_VERSION return message | Convert a histogram to a protobuf message . | 331 | 12 |
248,286 | def read ( message ) : require_compatible_version ( message . physt_compatible ) # Currently the only implementation a_dict = _dict_from_v0342 ( message ) return create_from_dict ( a_dict , "Message" ) | Convert a parsed protobuf message into a histogram . | 55 | 13 |
248,287 | def make_bin_array ( bins ) -> np . ndarray : bins = np . asarray ( bins ) if bins . ndim == 1 : # if bins.shape[0] == 0: # raise RuntimeError("Needs at least one bin") return np . hstack ( ( bins [ : - 1 , np . newaxis ] , bins [ 1 : , np . newaxis ] ) ) elif bins . ndim == 2 : if bins . shape [ 1 ] != 2 : raise RuntimeError ( "Binning schema with ndim==2 must have 2 columns" ) # if bins.shape[0] == 0: # raise RuntimeError("Needs at least one bin") return bins # Already correct, just pass else : raise RuntimeError ( "Binning schema must have ndim==1 or ndim==2" ) | Turn bin data into array understood by HistogramXX classes . | 179 | 12 |
248,288 | def to_numpy_bins ( bins ) -> np . ndarray : bins = np . asarray ( bins ) if bins . ndim == 1 : # Already in the proper format return bins if not is_consecutive ( bins ) : raise RuntimeError ( "Cannot create numpy bins from inconsecutive edges" ) return np . concatenate ( [ bins [ : 1 , 0 ] , bins [ : , 1 ] ] ) | Convert physt bin format to numpy edges . | 96 | 12 |
248,289 | def to_numpy_bins_with_mask ( bins ) -> Tuple [ np . ndarray , np . ndarray ] : bins = np . asarray ( bins ) if bins . ndim == 1 : edges = bins if bins . shape [ 0 ] > 1 : mask = np . arange ( bins . shape [ 0 ] - 1 ) else : mask = [ ] elif bins . ndim == 2 : edges = [ ] mask = [ ] j = 0 if bins . shape [ 0 ] > 0 : edges . append ( bins [ 0 , 0 ] ) for i in range ( bins . shape [ 0 ] - 1 ) : mask . append ( j ) edges . append ( bins [ i , 1 ] ) if bins [ i , 1 ] != bins [ i + 1 , 0 ] : edges . append ( bins [ i + 1 , 0 ] ) j += 1 j += 1 mask . append ( j ) edges . append ( bins [ - 1 , 1 ] ) else : raise RuntimeError ( "to_numpy_bins_with_mask: array with dim=1 or 2 expected" ) if not np . all ( np . diff ( edges ) > 0 ) : raise RuntimeError ( "to_numpy_bins_with_mask: edges array not monotone." ) return edges , mask | Numpy binning edges including gaps . | 285 | 8 |
248,290 | def is_rising ( bins ) -> bool : # TODO: Optimize for numpy bins bins = make_bin_array ( bins ) if np . any ( bins [ : , 0 ] >= bins [ : , 1 ] ) : return False if np . any ( bins [ 1 : , 0 ] < bins [ : - 1 , 1 ] ) : return False return True | Check whether the bins are in raising order . | 79 | 9 |
248,291 | def get_data ( histogram : HistogramBase , density : bool = False , cumulative : bool = False , flatten : bool = False ) -> np . ndarray : if density : if cumulative : data = ( histogram / histogram . total ) . cumulative_frequencies else : data = histogram . densities else : if cumulative : data = histogram . cumulative_frequencies else : data = histogram . frequencies if flatten : data = data . flatten ( ) return data | Get histogram data based on plotting parameters . | 107 | 9 |
248,292 | def get_err_data ( histogram : HistogramBase , density : bool = False , cumulative : bool = False , flatten : bool = False ) -> np . ndarray : if cumulative : raise RuntimeError ( "Error bars not supported for cumulative plots." ) if density : data = histogram . errors / histogram . bin_sizes else : data = histogram . errors if flatten : data = data . flatten ( ) return data | Get histogram error data based on plotting parameters . | 96 | 10 |
248,293 | def get_value_format ( value_format : Union [ Callable , str ] = str ) -> Callable [ [ float ] , str ] : if value_format is None : value_format = "" if isinstance ( value_format , str ) : format_str = "{0:" + value_format + "}" def value_format ( x ) : return format_str . format ( x ) return value_format | Create a formatting function from a generic value_format argument . | 90 | 12 |
248,294 | def pop_kwargs_with_prefix ( prefix : str , kwargs : dict ) -> dict : keys = [ key for key in kwargs if key . startswith ( prefix ) ] return { key [ len ( prefix ) : ] : kwargs . pop ( key ) for key in keys } | Pop all items from a dictionary that have keys beginning with a prefix . | 67 | 14 |
248,295 | def bins ( self ) -> List [ np . ndarray ] : return [ binning . bins for binning in self . _binnings ] | List of bin matrices . | 32 | 6 |
248,296 | def select ( self , axis : AxisIdentifier , index , force_copy : bool = False ) -> HistogramBase : if index == slice ( None ) and not force_copy : return self axis_id = self . _get_axis ( axis ) array_index = [ slice ( None , None , None ) for i in range ( self . ndim ) ] array_index [ axis_id ] = index frequencies = self . _frequencies [ tuple ( array_index ) ] . copy ( ) errors2 = self . _errors2 [ tuple ( array_index ) ] . copy ( ) if isinstance ( index , int ) : return self . _reduce_dimension ( [ ax for ax in range ( self . ndim ) if ax != axis_id ] , frequencies , errors2 ) elif isinstance ( index , slice ) : if index . step is not None and index . step < 0 : raise IndexError ( "Cannot change the order of bins" ) copy = self . copy ( ) copy . _frequencies = frequencies copy . _errors2 = errors2 copy . _binnings [ axis_id ] = self . _binnings [ axis_id ] [ index ] return copy else : raise ValueError ( "Invalid index." ) | Select in an axis . | 271 | 5 |
248,297 | def accumulate ( self , axis : AxisIdentifier ) -> HistogramBase : # TODO: Merge with Histogram1D.cumulative_frequencies # TODO: Deal with errors and totals etc. # TODO: inplace new_one = self . copy ( ) axis_id = self . _get_axis ( axis ) new_one . _frequencies = np . cumsum ( new_one . frequencies , axis_id [ 0 ] ) return new_one | Calculate cumulative frequencies along a certain axis . | 104 | 10 |
248,298 | def T ( self ) -> "Histogram2D" : a_copy = self . copy ( ) a_copy . _binnings = list ( reversed ( a_copy . _binnings ) ) a_copy . axis_names = list ( reversed ( a_copy . axis_names ) ) a_copy . _frequencies = a_copy . _frequencies . T a_copy . _errors2 = a_copy . _errors2 . T return a_copy | Histogram with swapped axes . | 106 | 6 |
248,299 | def partial_normalize ( self , axis : AxisIdentifier = 0 , inplace : bool = False ) : # TODO: Is this applicable for HistogramND? axis = self . _get_axis ( axis ) if not inplace : copy = self . copy ( ) copy . partial_normalize ( axis , inplace = True ) return copy else : self . _coerce_dtype ( float ) if axis == 0 : divisor = self . _frequencies . sum ( axis = 0 ) else : divisor = self . _frequencies . sum ( axis = 1 ) [ : , np . newaxis ] divisor [ divisor == 0 ] = 1 # Prevent division errors self . _frequencies /= divisor self . _errors2 /= ( divisor * divisor ) # Has its limitations return self | Normalize in rows or columns . | 187 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.