idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
249,200 | def download ( input , filename , format = 'sdf' , overwrite = False , resolvers = None , ** kwargs ) : kwargs [ 'format' ] = format if resolvers : kwargs [ 'resolver' ] = "," . join ( resolvers ) url = API_BASE + '/%s/file?%s' % ( urlquote ( input ) , urlencode ( kwargs ) ) try : servefile = urlopen ( url ) if not ove... | Resolve and download structure as a file |
249,201 | 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 |
249,202 | 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 . |
249,203 | 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 . |
249,204 | 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 . |
249,205 | 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 |
249,206 | 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 . |
249,207 | 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 . |
249,208 | def change_attributes ( self , bounds , radii , colors ) : self . n_cylinders = len ( bounds ) self . is_empty = True if self . n_cylinders == 0 else False if self . is_empty : self . bounds = bounds self . radii = radii self . colors = colors return self . bounds = np . array ( bounds , dtype = 'float32' ) vertices , ... | Reinitialize the buffers to accomodate the new attributes . This is used to change the number of cylinders to be displayed . |
249,209 | 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 |
249,210 | 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 |
249,211 | 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 |
249,212 | 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 |
249,213 | def make_gromacs ( simulation , directory , clean = False ) : if clean is False and os . path . exists ( directory ) : raise ValueError ( 'Cannot override {}, use option clean=True' . format ( directory ) ) else : shutil . rmtree ( directory , ignore_errors = True ) os . mkdir ( directory ) if simulation . potential . ... | Create gromacs directory structure |
249,214 | def update_vertices ( self , vertices ) : vertices = np . array ( vertices , dtype = np . float32 ) self . _vbo_v . set_data ( vertices ) | Update the triangle vertices . |
249,215 | def update_normals ( self , normals ) : normals = np . array ( normals , dtype = np . float32 ) self . _vbo_n . set_data ( normals ) | Update the triangle normals . |
249,216 | 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 . |
249,217 | def set_text ( self , text ) : self . traj_controls . timelabel . setText ( self . traj_controls . _label_tmp . format ( text ) ) | Update the time indicator in the interface . |
249,218 | def update_function ( self , func , frames = None ) : if frames is not None : self . traj_controls . set_ticks ( frames ) self . _update_function = func | Set the function to be called when it s time to display a frame . |
249,219 | 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 . |
249,220 | def rotation_from_matrix ( matrix ) : R = numpy . array ( matrix , dtype = numpy . float64 , copy = False ) R33 = R [ : 3 , : 3 ] w , W = numpy . linalg . eig ( R33 . T ) i = numpy . where ( abs ( numpy . real ( w ) - 1.0 ) < 1e-8 ) [ 0 ] if not len ( i ) : raise ValueError ( "no unit eigenvector corresponding to eigen... | Return rotation angle and axis from rotation matrix . |
249,221 | def scale_from_matrix ( matrix ) : M = numpy . array ( matrix , dtype = numpy . float64 , copy = False ) M33 = M [ : 3 , : 3 ] factor = numpy . trace ( M33 ) - 2.0 try : w , V = numpy . linalg . eig ( M33 ) i = numpy . where ( abs ( numpy . real ( w ) - factor ) < 1e-8 ) [ 0 ] [ 0 ] direction = numpy . real ( V [ : , i... | Return scaling factor origin and direction from scaling matrix . |
249,222 | 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 . |
249,223 | 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 . |
249,224 | 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 . |
249,225 | 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 . |
249,226 | 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 . |
249,227 | 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 . |
249,228 | 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 . |
249,229 | 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 . |
249,230 | 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 . |
249,231 | def select_molecules ( name ) : mol_formula = current_system ( ) . get_derived_molecule_array ( 'formula' ) mask = mol_formula == name ind = current_system ( ) . mol_to_atom_indices ( mask . nonzero ( ) [ 0 ] ) selection = { 'atoms' : Selection ( ind , current_system ( ) . n_atoms ) } b = current_system ( ) . bonds if ... | Select all the molecules corresponding to the formulas . |
249,232 | 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 . |
249,233 | def unhide_selected ( ) : hidden_state = current_representation ( ) . hidden_state selection_state = current_representation ( ) . selection_state res = { } for k in selection_state : visible = hidden_state [ k ] . invert ( ) visible_and_selected = visible . add ( selection_state [ k ] ) res [ k ] = visible_and_selected... | Unhide the selected objects |
249,234 | 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 . |
249,235 | def mouse_zoom ( self , inc ) : dsq = np . linalg . norm ( self . position - self . pivot ) minsq = 1.0 ** 2 maxsq = 7.0 ** 2 scalefac = 0.25 if dsq > maxsq and inc < 0 : pass elif dsq < minsq and inc > 0 : pass else : self . position += self . c * inc * scalefac | Convenience function to implement a zoom function . |
249,236 | def unproject ( self , x , y , z = - 1.0 ) : source = np . array ( [ x , y , z , 1.0 ] ) matrix = self . projection . dot ( self . matrix ) IM = LA . inv ( matrix ) res = np . dot ( IM , source ) return res [ 0 : 3 ] / res [ 3 ] | Receive x and y as screen coordinates and returns a point in world coordinates . |
249,237 | 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 . |
249,238 | 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 . |
249,239 | 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 . |
249,240 | def parse_color ( color ) : if isinstance ( color , str ) : try : col = get ( color ) except ValueError : pass try : col = html_to_rgb ( color ) except ValueError : raise ValueError ( "Can't parse color string: {}'" . format ( color ) ) return col | Return the RGB 0 - 255 representation of the current string passed . |
249,241 | def hsl_to_rgb ( arr ) : H , S , L = arr . T H = ( H . copy ( ) / 255.0 ) * 360 S = S . copy ( ) / 255.0 L = L . copy ( ) / 255.0 C = ( 1 - np . absolute ( 2 * L - 1 ) ) * S Hp = H / 60.0 X = C * ( 1 - np . absolute ( np . mod ( Hp , 2 ) - 1 ) ) R = np . zeros ( H . shape , float ) G = np . zeros ( H . shape , float ) ... | Converts HSL color array to RGB array |
249,242 | 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 . |
249,243 | 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 . |
249,244 | def _read_datafile_entry ( spg , no , symbol , setting , f ) : spg . _no = no spg . _symbol = symbol . strip ( ) spg . _setting = setting spg . _centrosymmetric = bool ( int ( f . readline ( ) . split ( ) [ 1 ] ) ) f . readline ( ) spg . _scaled_primitive_cell = np . array ( [ list ( map ( float , f . readline ( ) . sp... | Read space group data from f to spg . |
249,245 | 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 . |
249,246 | 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 . |
249,247 | 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 . |
249,248 | 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 . |
249,249 | 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 . |
249,250 | 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 . |
249,251 | def guess_type ( typ ) : match = re . match ( "([a-zA-Z]+)\d*" , typ ) if match : typ = match . groups ( ) [ 0 ] return typ | Guess the atom type from purely heuristic considerations . |
249,252 | def register ( * dim : List [ int ] , use_3d : bool = False , use_polar : bool = False , collection : bool = False ) : if use_3d and use_polar : raise RuntimeError ( "Cannot have polar and 3d coordinates simultaneously." ) def decorate ( function ) : types . append ( function . __name__ ) dims [ function . __name__ ] =... | Decorator to wrap common plotting functionality . |
249,253 | def bar ( h1 : Histogram1D , ax : Axes , * , errors : bool = False , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) show_values = kwargs . pop ( "show_values" , False ) value_format = kwargs . pop ( "value_format" , None ) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumul... | Bar plot of 1D histograms . |
249,254 | def scatter ( h1 : Histogram1D , ax : Axes , * , errors : bool = False , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) show_values = kwargs . pop ( "show_values" , False ) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumulative" , False ) value_format = kwargs . pop ( "va... | Scatter plot of 1D histogram . |
249,255 | def line ( h1 : Union [ Histogram1D , "HistogramCollection" ] , ax : Axes , * , errors : bool = False , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) show_values = kwargs . pop ( "show_values" , False ) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumulative" , False ) va... | Line plot of 1D histogram . |
249,256 | def fill ( h1 : Histogram1D , ax : Axes , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumulative" , False ) kwargs [ "label" ] = kwargs . get ( "label" , h1 . name ) data = get_data ( h1 , cumulative = cumulative , density = ... | Fill plot of 1D histogram . |
249,257 | def step ( h1 : Histogram1D , ax : Axes , ** kwargs ) : show_stats = kwargs . pop ( "show_stats" , False ) show_values = kwargs . pop ( "show_values" , False ) density = kwargs . pop ( "density" , False ) cumulative = kwargs . pop ( "cumulative" , False ) value_format = kwargs . pop ( "value_format" , None ) text_kwarg... | Step line - plot of 1D histogram . |
249,258 | def bar3d ( h2 : Histogram2D , ax : Axes3D , ** kwargs ) : density = kwargs . pop ( "density" , False ) data = get_data ( h2 , cumulative = False , flatten = True , density = density ) if "cmap" in kwargs : cmap = _get_cmap ( kwargs ) _ , cmap_data = _get_cmap_data ( data , kwargs ) colors = cmap ( cmap_data ) else : c... | Plot of 2D histograms as 3D boxes . |
249,259 | def image ( h2 : Histogram2D , ax : Axes , * , show_colorbar : bool = True , interpolation : str = "nearest" , ** kwargs ) : cmap = _get_cmap ( kwargs ) data = get_data ( h2 , cumulative = False , density = kwargs . pop ( "density" , False ) ) norm , cmap_data = _get_cmap_data ( data , kwargs ) for binning in h2 . _bin... | Plot of 2D histograms based on pixmaps . |
249,260 | 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 . |
249,261 | def globe_map ( hist : Union [ Histogram2D , DirectionalHistogram ] , ax : Axes3D , * , show_zero : bool = True , ** kwargs ) : data = get_data ( hist , cumulative = False , flatten = False , density = kwargs . pop ( "density" , False ) ) cmap = _get_cmap ( kwargs ) norm , cmap_data = _get_cmap_data ( data , kwargs ) c... | Heat map plotted on the surface of a sphere . |
249,262 | def pair_bars ( first : Histogram1D , second : Histogram2D , * , orientation : str = "vertical" , kind : str = "bar" , ** kwargs ) : _ , ax = _get_axes ( kwargs ) color1 = kwargs . pop ( "color1" , "red" ) color2 = kwargs . pop ( "color2" , "blue" ) title = kwargs . pop ( "title" , "{0} - {1}" . format ( first . name ,... | Draw two different histograms mirrored in one figure . |
249,263 | 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 . |
249,264 | def _get_cmap ( kwargs : dict ) -> colors . Colormap : from matplotlib . colors import ListedColormap cmap = kwargs . pop ( "cmap" , default_cmap ) if isinstance ( cmap , list ) : return ListedColormap ( cmap ) if isinstance ( cmap , str ) : try : cmap = plt . get_cmap ( cmap ) except BaseException as exc : try : impor... | Get the colour map for plots that support it . |
249,265 | 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 . |
249,266 | 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 . |
249,267 | 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 . bi... | Show values next to each bin in a 1D plot . |
249,268 | 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 ) fig . colorbar ( mappable , ax = ax ) | Show a colorbar right of the plot . |
249,269 | def _add_stats_box ( h1 : Histogram1D , ax : Axes , stats : Union [ str , bool ] = "all" ) : 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 ValueEr... | Insert a small legend - like box with statistical information . |
249,270 | 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 . |
249,271 | 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 . |
249,272 | 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 . |
249,273 | 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 . |
249,274 | 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 . |
249,275 | def save_json ( histogram : Union [ HistogramBase , HistogramCollection ] , path : Optional [ str ] = None , ** kwargs ) -> str : data = histogram . to_dict ( ) data [ "physt_version" ] = CURRENT_VERSION if isinstance ( histogram , HistogramBase ) : data [ "physt_compatible" ] = COMPATIBLE_VERSION elif isinstance ( his... | Save histogram to JSON format . |
249,276 | 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 . |
249,277 | 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 . |
249,278 | 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 . |
249,279 | def histogram2d ( data1 , data2 , bins = 10 , * args , ** kwargs ) : import numpy as np 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 ) dat... | Facade function to create 2D histograms . |
249,280 | 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 . |
249,281 | 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 . concaten... | Facade function to create 3D histograms . |
249,282 | 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 . |
249,283 | def write_root ( histogram : HistogramBase , hfile : uproot . write . TFile . TFileUpdate , name : str ) : hfile [ name ] = histogram | Write histogram to an open ROOT file . |
249,284 | def write ( histogram ) : histogram_dict = histogram . to_dict ( ) message = Histogram ( ) for field in SIMPLE_CONVERSION_FIELDS : setattr ( message , field , histogram_dict [ field ] ) message . frequencies . extend ( histogram . frequencies . flatten ( ) ) message . errors2 . extend ( histogram . errors2 . flatten ( ... | Convert a histogram to a protobuf message . |
249,285 | def read ( message ) : require_compatible_version ( message . physt_compatible ) a_dict = _dict_from_v0342 ( message ) return create_from_dict ( a_dict , "Message" ) | Convert a parsed protobuf message into a histogram . |
249,286 | def make_bin_array ( bins ) -> np . ndarray : bins = np . asarray ( bins ) if bins . ndim == 1 : 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" ) return bin... | Turn bin data into array understood by HistogramXX classes . |
249,287 | def to_numpy_bins ( bins ) -> np . ndarray : bins = np . asarray ( bins ) if bins . ndim == 1 : 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 . |
249,288 | 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 . |
249,289 | def is_rising ( bins ) -> bool : 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 . |
249,290 | 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 . |
249,291 | 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 . |
249,292 | 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 . |
249,293 | 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 . |
249,294 | def bins ( self ) -> List [ np . ndarray ] : return [ binning . bins for binning in self . _binnings ] | List of bin matrices . |
249,295 | 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 . |
249,296 | def accumulate ( self , axis : AxisIdentifier ) -> HistogramBase : 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 . |
249,297 | 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 . |
249,298 | def partial_normalize ( self , axis : AxisIdentifier = 0 , inplace : bool = False ) : 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 = ... | Normalize in rows or columns . |
249,299 | def numpy_binning ( data , bins = 10 , range = None , * args , ** kwargs ) -> NumpyBinning : if isinstance ( bins , int ) : if range : bins = np . linspace ( range [ 0 ] , range [ 1 ] , bins + 1 ) else : start = data . min ( ) stop = data . max ( ) bins = np . linspace ( start , stop , bins + 1 ) elif np . iterable ( b... | Construct binning schema compatible with numpy . histogram |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.