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 ) )... | 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 ov... | 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 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 the... | 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 ) ... | 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 po... | 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 ... | 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 ... | 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 ) - f... | 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 ,... | 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 ... | 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 = n... | 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 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 . _qdow... | 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... | 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 t... | 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 ... | 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 ... | 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 ] dista... | 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 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 ... | 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... | 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... | 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 ... | 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 symb... | 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 .... | 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 ) + ... | 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 . ... | 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 ( "cumu... | 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 ( "v... | 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 ) v... | 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 = ge... | 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_kwar... | 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 : ... | 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 ... | 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... | 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 ) ... | 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 ( ... | 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 ... | 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... | 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_... | 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 . b... | 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: {... | 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 di... | 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 thi... | 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 = pars... | 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_comp... | 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 ... | 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 . a... | 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 =... | 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 . concate... | 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 . e... | 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 Runti... | 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 : edg... | 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 . cumulati... | 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 . ... | 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 = s... | 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 ] ) r... | 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 : d... | 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.