idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
39,600
def export_image ( self , bbox , zoomlevel , imagepath ) : assert has_pil , _ ( "Cannot export image without python PIL" ) grid = self . grid_tiles ( bbox , zoomlevel ) width = len ( grid [ 0 ] ) height = len ( grid ) widthpix = width * self . tile_size heightpix = height * self . tile_size result = Image . new ( "RGBA" , ( widthpix , heightpix ) ) offset = ( 0 , 0 ) for i , row in enumerate ( grid ) : for j , ( x , y ) in enumerate ( row ) : offset = ( j * self . tile_size , i * self . tile_size ) img = self . _tile_image ( self . tile ( ( zoomlevel , x , y ) ) ) result . paste ( img , offset ) logger . info ( _ ( "Save resulting image to '%s'" ) % imagepath ) result . save ( imagepath )
Writes to imagepath the tiles for the specified bounding box and zoomlevel .
39,601
def _makeScriptOrder ( gpos ) : scripts = [ ] for scriptRecord in gpos . ScriptList . ScriptRecord : scripts . append ( scriptRecord . ScriptTag ) if "DFLT" in scripts : scripts . remove ( "DFLT" ) scripts . insert ( 0 , "DFLT" ) return sorted ( scripts )
Run therough GPOS and make an alphabetically ordered list of scripts . If DFLT is in the list move it to the front .
39,602
def _gatherDataFromLookups ( gpos , scriptOrder ) : lookupIndexes = _gatherLookupIndexes ( gpos ) seenLookups = set ( ) kerningDictionaries = [ ] leftClassDictionaries = [ ] rightClassDictionaries = [ ] for script in scriptOrder : kerning = [ ] leftClasses = [ ] rightClasses = [ ] for lookupIndex in lookupIndexes [ script ] : if lookupIndex in seenLookups : continue seenLookups . add ( lookupIndex ) result = _gatherKerningForLookup ( gpos , lookupIndex ) if result is None : continue k , lG , rG = result kerning . append ( k ) leftClasses . append ( lG ) rightClasses . append ( rG ) if kerning : kerningDictionaries . append ( kerning ) leftClassDictionaries . append ( leftClasses ) rightClassDictionaries . append ( rightClasses ) return kerningDictionaries , leftClassDictionaries , rightClassDictionaries
Gather kerning and classes from the applicable lookups and return them in script order .
39,603
def _handleLookupType2Format1 ( subtable ) : kerning = { } coverage = subtable . Coverage . glyphs valueFormat1 = subtable . ValueFormat1 pairSets = subtable . PairSet for index , leftGlyphName in enumerate ( coverage ) : pairSet = pairSets [ index ] for pairValueRecord in pairSet . PairValueRecord : rightGlyphName = pairValueRecord . SecondGlyph if valueFormat1 : value = pairValueRecord . Value1 else : value = pairValueRecord . Value2 if hasattr ( value , "XAdvance" ) : value = value . XAdvance kerning [ leftGlyphName , rightGlyphName ] = value return kerning
Extract a kerning dictionary from a Lookup Type 2 Format 1 .
39,604
def _handleLookupType2Format2 ( subtable , lookupIndex , subtableIndex ) : leftClasses = _extractFeatureClasses ( lookupIndex = lookupIndex , subtableIndex = subtableIndex , classDefs = subtable . ClassDef1 . classDefs , coverage = subtable . Coverage . glyphs ) rightClasses = _extractFeatureClasses ( lookupIndex = lookupIndex , subtableIndex = subtableIndex , classDefs = subtable . ClassDef2 . classDefs ) kerning = { } for class1RecordIndex , class1Record in enumerate ( subtable . Class1Record ) : for class2RecordIndex , class2Record in enumerate ( class1Record . Class2Record ) : leftClass = ( lookupIndex , subtableIndex , class1RecordIndex ) rightClass = ( lookupIndex , subtableIndex , class2RecordIndex ) valueFormat1 = subtable . ValueFormat1 if valueFormat1 : value = class2Record . Value1 else : value = class2Record . Value2 if hasattr ( value , "XAdvance" ) and value . XAdvance != 0 : value = value . XAdvance kerning [ leftClass , rightClass ] = value return kerning , leftClasses , rightClasses
Extract kerning left class and right class dictionaries from a Lookup Type 2 Format 2 .
39,605
def _mergeKerningDictionaries ( kerningDictionaries ) : kerning = { } for dictionaryGroup in reversed ( kerningDictionaries ) : for dictionary in dictionaryGroup : kerning . update ( dictionary ) return kerning
Merge all of the kerning dictionaries found into one flat dictionary .
39,606
def _findSingleMemberGroups ( classDictionaries ) : toRemove = { } for classDictionaryGroup in classDictionaries : for classDictionary in classDictionaryGroup : for name , members in list ( classDictionary . items ( ) ) : if len ( members ) == 1 : toRemove [ name ] = list ( members ) [ 0 ] del classDictionary [ name ] return toRemove
Find all classes that have only one member .
39,607
def _removeSingleMemberGroupReferences ( kerning , leftGroups , rightGroups ) : new = { } for ( left , right ) , value in kerning . items ( ) : left = leftGroups . get ( left , left ) right = rightGroups . get ( right , right ) new [ left , right ] = value return new
Translate group names into glyph names in pairs if the group only contains one glyph .
39,608
def _setGroupNames ( classes , classRename ) : groups = { } for groupName , glyphList in classes . items ( ) : groupName = classRename . get ( groupName , groupName ) if len ( glyphList ) == 1 : continue groups [ groupName ] = glyphList return groups
Set the final names into the groups .
39,609
def _validateClasses ( classes ) : glyphToClass = { } for className , glyphList in classes . items ( ) : for glyphName in glyphList : if glyphName not in glyphToClass : glyphToClass [ glyphName ] = set ( ) glyphToClass [ glyphName ] . add ( className ) for glyphName , groupList in glyphToClass . items ( ) : if len ( groupList ) > 1 : raise ExtractorError ( "Kerning classes are in an conflicting state." )
Check to make sure that a glyph is not part of more than one class . If this is found an ExtractorError is raised .
39,610
def _replaceRenamedPairMembers ( kerning , leftRename , rightRename ) : renamedKerning = { } for ( left , right ) , value in kerning . items ( ) : left = leftRename . get ( left , left ) right = rightRename . get ( right , right ) renamedKerning [ left , right ] = value return renamedKerning
Populate the renamed pair members into the kerning .
39,611
def _renameClasses ( classes , prefix ) : renameMap = { } for classID , glyphList in classes . items ( ) : if len ( glyphList ) == 0 : groupName = "%s_empty_lu.%d_st.%d_cl.%d" % ( prefix , classID [ 0 ] , classID [ 1 ] , classID [ 2 ] ) elif len ( glyphList ) == 1 : groupName = list ( glyphList ) [ 0 ] else : glyphList = list ( sorted ( glyphList ) ) groupName = prefix + glyphList [ 0 ] renameMap [ classID ] = groupName return renameMap
Replace class IDs with nice strings .
39,612
def _extractFeatureClasses ( lookupIndex , subtableIndex , classDefs , coverage = None ) : classDict = { } for glyphName , classIndex in classDefs . items ( ) : if classIndex not in classDict : classDict [ classIndex ] = set ( ) classDict [ classIndex ] . add ( glyphName ) revisedClass0 = set ( ) if coverage is not None and 0 in classDict : for glyphName in classDict [ 0 ] : if glyphName in coverage : revisedClass0 . add ( glyphName ) elif coverage is not None and 0 not in classDict : revisedClass0 = set ( coverage ) for glyphList in classDict . values ( ) : revisedClass0 = revisedClass0 - glyphList classDict [ 0 ] = revisedClass0 classes = { } for classIndex , glyphList in classDict . items ( ) : classes [ lookupIndex , subtableIndex , classIndex ] = frozenset ( glyphList ) return classes
Extract classes for a specific lookup in a specific subtable . This is relatively straightforward except for class 0 interpretation . Some fonts don t have class 0 . Some fonts have a list of class members that are clearly not all to be used in kerning pairs . In the case of a missing class 0 the coverage is used as a basis for the class and glyph names used in classed 1 + are filtered out . In the case of class 0 having glyph names that are not part of the kerning pairs the coverage is used to filter out the unnecessary glyph names .
39,613
def add_include ( self , name , module_spec ) : assert name , 'name is required' assert self . can_include if name in self . includes : raise ThriftCompilerError ( 'Cannot include module "%s" as "%s" in "%s". ' 'The name is already taken.' % ( module_spec . name , name , self . path ) ) self . includes [ name ] = module_spec self . scope . add_include ( name , module_spec . scope , module_spec . surface )
Adds a module as an included module .
39,614
def link ( self ) : if self . linked : return self self . linked = True included_modules = [ ] for include in self . includes . values ( ) : included_modules . append ( include . link ( ) . surface ) self . scope . add_surface ( '__includes__' , tuple ( included_modules ) ) self . scope . add_surface ( '__thrift_source__' , self . thrift_source ) for linker in LINKERS : linker ( self . scope ) . link ( ) self . scope . add_surface ( 'loads' , Deserializer ( self . protocol ) ) self . scope . add_surface ( 'dumps' , Serializer ( self . protocol ) ) return self
Link all the types in this module and all included modules .
39,615
def compile ( self , name , contents , path = None ) : assert name if path : path = os . path . abspath ( path ) if path in self . _module_specs : return self . _module_specs [ path ] module_spec = ModuleSpec ( name , self . protocol , path , contents ) if path : self . _module_specs [ path ] = module_spec program = self . parser . parse ( contents ) header_processor = HeaderProcessor ( self , module_spec , self . include_as ) for header in program . headers : header . apply ( header_processor ) generator = Generator ( module_spec . scope , strict = self . strict ) for definition in program . definitions : generator . process ( definition ) return module_spec
Compile the given Thrift document into a Python module .
39,616
def input ( self , data ) : self . _lexer . lineno = 1 return self . _lexer . input ( data )
Reset the lexer and feed in new input .
39,617
def get_data ( ) : y = 1.0 / ( 1.0 + 1j * ( n_x . get_value ( ) - 0.002 ) * 1000 ) + _n . random . rand ( ) * 0.1 _t . sleep ( 0.1 ) return abs ( y ) , _n . angle ( y , True )
Currently pretends to talk to an instrument and get back the magnitud and phase of the measurement .
39,618
def List ( self ) : print ( ) for key in list ( self . keys ( ) ) : print ( key , '=' , self [ key ] ) print ( )
Lists the keys and values .
39,619
def Set ( self , key , value ) : if not value == None : self . prefs [ key ] = value else : self . prefs . pop ( key ) self . Dump ( )
Sets the key - value pair and dumps to the preferences file .
39,620
def MakeDir ( self , path = "temp" ) : full_path = _os . path . join ( self . path_home , path ) if not _os . path . exists ( full_path ) : _os . makedirs ( full_path )
Creates a directory of the specified path in the . spinmob directory .
39,621
def _parse_seq ( self , p ) : if len ( p ) == 4 : p [ 3 ] . appendleft ( p [ 1 ] ) p [ 0 ] = p [ 3 ] elif len ( p ) == 3 : p [ 2 ] . appendleft ( p [ 1 ] ) p [ 0 ] = p [ 2 ] elif len ( p ) == 1 : p [ 0 ] = deque ( ) else : raise ThriftParserError ( 'Wrong number of tokens received for expression at line %d' % p . lineno ( 1 ) )
Helper to parse sequence rules .
39,622
def parse ( self , input , ** kwargs ) : return self . _parser . parse ( input , lexer = self . _lexer , ** kwargs )
Parse the given input .
39,623
def acquire_fake_data ( number_of_points = 1000 ) : t = _n . linspace ( 0 , 10 , number_of_points ) return ( t , [ _n . cos ( t ) * ( 1.0 + 0.2 * _n . random . random ( number_of_points ) ) , _n . sin ( t + 0.5 * _n . random . random ( number_of_points ) ) ] )
This function generates some fake data and returns two channels of data in the form
39,624
def load ( path = None , first_data_line = 'auto' , filters = '*.*' , text = 'Select a file, FACEHEAD.' , default_directory = 'default_directory' , quiet = True , header_only = False , transpose = False , ** kwargs ) : d = databox ( ** kwargs ) d . load_file ( path = path , first_data_line = first_data_line , filters = filters , text = text , default_directory = default_directory , header_only = header_only ) if not quiet : print ( "\nloaded" , d . path , "\n" ) if transpose : return d . transpose ( ) return d
Loads a data file into the databox data class . Returns the data object .
39,625
def more_info ( self ) : print ( "\nDatabox Instance" , self . path ) print ( "\nHeader" ) for h in self . hkeys : print ( " " + h + ":" , self . h ( h ) ) s = "\nColumns (" + str ( len ( self . ckeys ) ) + "): " for c in self . ckeys : s = s + c + ", " print ( s [ : - 2 ] )
Prints out more information about the databox .
39,626
def execute_script ( self , script , g = None ) : if not g == None : self . extra_globals . update ( g ) if not _s . fun . is_iterable ( script ) : if script is None : return None [ expression , v ] = self . _parse_script ( script ) if v is None : print ( "ERROR: Could not parse '" + script + "'" ) return None g = self . _globals ( ) g . update ( v ) return eval ( expression , g ) output = [ ] for s in script : output . append ( self . execute_script ( s ) ) return output
Runs a script returning the result .
39,627
def copy_headers ( self , source_databox ) : for k in source_databox . hkeys : self . insert_header ( k , source_databox . h ( k ) ) return self
Loops over the hkeys of the source_databox updating this databoxes header .
39,628
def copy_columns ( self , source_databox ) : for k in source_databox . ckeys : self . insert_column ( source_databox [ k ] , k ) return self
Loops over the ckeys of the source_databox updating this databoxes columns .
39,629
def copy_all ( self , source_databox ) : self . copy_headers ( source_databox ) self . copy_columns ( source_databox ) return self
Copies the header and columns from source_databox to this databox .
39,630
def insert_globals ( self , * args , ** kwargs ) : for a in args : kwargs [ a . __name__ ] = a self . extra_globals . update ( kwargs )
Appends or overwrites the supplied object in the self . extra_globals .
39,631
def pop_header ( self , hkey , ignore_error = False ) : if type ( hkey ) is not str : try : return self . headers . pop ( self . hkeys . pop ( hkey ) ) except : if not ignore_error : print ( "ERROR: pop_header() could not find hkey " + str ( hkey ) ) return None else : try : hkey = self . hkeys . index ( hkey ) return self . headers . pop ( self . hkeys . pop ( hkey ) ) except : if not ignore_error : print ( "ERROR: pop_header() could not find hkey " + str ( hkey ) ) return
This will remove and return the specified header value .
39,632
def pop_column ( self , ckey ) : if type ( ckey ) is not str : return self . columns . pop ( self . ckeys . pop ( ckey ) ) else : ckey = self . ckeys . index ( ckey ) if ckey < 0 : print ( "Column does not exist (yes, we looked)." ) return return self . columns . pop ( self . ckeys . pop ( ckey ) )
This will remove and return the data in the specified column .
39,633
def rename_header ( self , old_name , new_name ) : self . hkeys [ self . hkeys . index ( old_name ) ] = new_name self . headers [ new_name ] = self . headers . pop ( old_name ) return self
This will rename the header . The supplied names need to be strings .
39,634
def rename_column ( self , column , new_name ) : if type ( column ) is not str : column = self . ckeys [ column ] self . ckeys [ self . ckeys . index ( column ) ] = new_name self . columns [ new_name ] = self . columns . pop ( column ) return self
This will rename the column . The supplied column can be an integer or the old column name .
39,635
def transpose ( self ) : d = databox ( delimter = self . delimiter ) self . copy_headers ( d ) z = _n . array ( self [ : ] ) . transpose ( ) for n in range ( len ( z ) ) : d [ 'c' + str ( n ) ] = z [ n ] return d
Returns a copy of this databox with the columns as rows . Currently requires that the databox has equal - length columns .
39,636
def _update_functions ( self ) : self . f = [ ] self . bg = [ ] self . _fnames = [ ] self . _bgnames = [ ] self . _odr_models = [ ] f = self . _f_raw bg = self . _bg_raw if not _s . fun . is_iterable ( f ) : f = [ f ] if not _s . fun . is_iterable ( bg ) : bg = [ bg ] while len ( bg ) < len ( f ) : bg . append ( None ) pstring = 'x, ' + ', ' . join ( self . _pnames ) pstring_odr = 'x, ' for n in range ( len ( self . _pnames ) ) : pstring_odr = pstring_odr + 'p[' + str ( n ) + '], ' for cname in self . _cnames : self . _globals [ cname ] = self [ cname ] for n in range ( len ( f ) ) : if isinstance ( f [ n ] , str ) : self . f . append ( eval ( 'lambda ' + pstring + ': ' + f [ n ] , self . _globals ) ) self . _fnames . append ( f [ n ] ) self . _odr_models . append ( _odr . Model ( eval ( 'lambda p,x: self.f[n](' + pstring_odr + ')' , dict ( self = self , n = n ) ) ) ) else : self . f . append ( f [ n ] ) self . _fnames . append ( f [ n ] . __name__ ) if isinstance ( bg [ n ] , str ) : self . bg . append ( eval ( 'lambda ' + pstring + ': ' + bg [ n ] , self . _globals ) ) self . _bgnames . append ( bg [ n ] ) else : self . bg . append ( bg [ n ] ) if bg [ n ] is None : self . _bgnames . append ( "None" ) else : self . _bgnames . append ( bg [ n ] . __name__ ) for k in list ( self . _settings . keys ( ) ) : self [ k ] = self [ k ] self . clear_results ( )
Uses internal settings to update the functions .
39,637
def set_data ( self , xdata = [ 1 , 2 , 3 , 4 , 5 ] , ydata = [ 1.7 , 2 , 3 , 4 , 3 ] , eydata = None , ** kwargs ) : if type ( xdata ) is str : xdata = [ xdata ] if type ( ydata ) is str : ydata = [ ydata ] if type ( eydata ) is str or _s . fun . is_a_number ( eydata ) or eydata is None : eydata = [ eydata ] if _s . fun . is_a_number ( xdata [ 0 ] ) : xdata = [ xdata ] if _s . fun . is_a_number ( ydata [ 0 ] ) : ydata = [ ydata ] if _s . fun . is_a_number ( eydata [ 0 ] ) and len ( eydata ) == len ( ydata [ 0 ] ) : eydata = [ eydata ] while len ( xdata ) < len ( ydata ) : xdata . append ( xdata [ 0 ] ) while len ( ydata ) < len ( xdata ) : ydata . append ( ydata [ 0 ] ) while len ( eydata ) < len ( ydata ) : eydata . append ( eydata [ 0 ] ) while len ( ydata ) < len ( self . f ) : ydata . append ( ydata [ 0 ] ) while len ( xdata ) < len ( self . f ) : xdata . append ( xdata [ 0 ] ) while len ( eydata ) < len ( self . f ) : eydata . append ( eydata [ 0 ] ) self . _set_xdata = xdata self . _set_ydata = ydata self . _set_eydata = eydata self . _set_data_globals . update ( kwargs ) self [ 'scale_eydata' ] = [ 1.0 ] * len ( self . _set_xdata ) for k in self . _settings . keys ( ) : self [ k ] = self [ k ] if self [ 'autoplot' ] : self . plot ( ) return self
This will handle the different types of supplied data and put everything in a standard format for processing .
39,638
def set_guess_to_fit_result ( self ) : if self . results is None : print ( "No fit results to use! Run fit() first." ) return for n in range ( len ( self . _pguess ) ) : self . _pguess [ n ] = self . results [ 0 ] [ n ] if self [ 'autoplot' ] : self . plot ( ) return self
If you have a fit result set the guess parameters to the fit parameters .
39,639
def _massage_data ( self ) : self . _xdata_massaged , self . _ydata_massaged , self . _eydata_massaged = self . get_processed_data ( ) return self
Processes the data and stores it .
39,640
def free ( self , * args , ** kwargs ) : self . set ( ** kwargs ) cnames = list ( args ) + list ( kwargs . keys ( ) ) for cname in cnames : if not cname in self . _cnames : self . _error ( "Naughty. '" + cname + "' is not a valid constant name." ) else : n = self . _cnames . index ( cname ) if type ( self . _pnames ) is not list : self . _pnames = list ( self . _pnames ) if type ( self . _pguess ) is not list : self . _pguess = list ( self . _pguess ) if type ( self . _cnames ) is not list : self . _cnames = list ( self . _cnames ) if type ( self . _constants ) is not list : self . _constants = list ( self . _constants ) self . _pnames . append ( self . _cnames . pop ( n ) ) self . _pguess . append ( self . _constants . pop ( n ) ) self . _update_functions ( ) return self
Turns a constant into a parameter . As arguments parameters must be strings . As keyword arguments they can be set at the same time .
39,641
def _evaluate_f ( self , n , xdata , p = None ) : if p is None and self . results is not None : p = self . results [ 0 ] elif p is None and self . results is None : p = self . _pguess args = ( xdata , ) + tuple ( p ) return self . f [ n ] ( * args )
Evaluates a single function n for arbitrary xdata and p tuple .
39,642
def _evaluate_bg ( self , n , xdata , p = None ) : if p is None and self . results is not None : p = self . results [ 0 ] elif p is None and self . results is None : p = self . _pguess if self . bg [ n ] is None : return None args = ( xdata , ) + tuple ( p ) return self . bg [ n ] ( * args )
Evaluates a single background function n for arbitrary xdata and p tuple .
39,643
def chi_squareds ( self , p = None ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : return None if p is None : p = self . results [ 0 ] rs = self . studentized_residuals ( p ) if rs == None : return None cs = [ ] for r in rs : cs . append ( sum ( r ** 2 ) ) return cs
Returns a list of chi squared for each data set . Also uses ydata_massaged .
39,644
def degrees_of_freedom ( self ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : return None r = self . studentized_residuals ( ) if r == None : return N = 0.0 for i in range ( len ( r ) ) : N += len ( r [ i ] ) return N - len ( self . _pnames )
Returns the number of degrees of freedom .
39,645
def reduced_chi_squareds ( self , p = None ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : return None if p is None : p = self . results [ 0 ] r = self . studentized_residuals ( p ) if r is None : return N = 0 for i in range ( len ( r ) ) : N += len ( r [ i ] ) dof_per_point = self . degrees_of_freedom ( ) / N for n in range ( len ( r ) ) : r [ n ] = sum ( r [ n ] ** 2 ) / ( len ( r [ n ] ) * dof_per_point ) return r
Returns the reduced chi squared for each massaged data set .
39,646
def reduced_chi_squared ( self , p = None ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : return None if p is None : p = self . results [ 0 ] chi2 = self . chi_squared ( p ) dof = self . degrees_of_freedom ( ) if not _s . fun . is_a_number ( chi2 ) or not _s . fun . is_a_number ( dof ) : return None return _n . divide ( self . chi_squared ( p ) , self . degrees_of_freedom ( ) )
Returns the reduced chi squared for all massaged data sets .
39,647
def autoscale_eydata ( self ) : if not self . results : self . _error ( "You must complete a fit first." ) return r = self . reduced_chi_squareds ( ) for n in range ( len ( r ) ) : self [ "scale_eydata" ] [ n ] *= _n . sqrt ( r [ n ] ) self . clear_results ( ) if self [ 'autoplot' ] : self . plot ( ) return self
Rescales the error so the next fit will give reduced chi squareds of 1 . Each data set will be scaled independently and you may wish to run this a few times until it converges .
39,648
def trim ( self , n = 'all' , x = True , y = True ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : self . _error ( "No data. Please use set_data() and plot() prior to trimming." ) return if _s . fun . is_a_number ( n ) : n = [ n ] elif isinstance ( n , str ) : n = list ( range ( len ( self . _set_xdata ) ) ) for i in n : try : if x : xmin , xmax = _p . figure ( self [ 'first_figure' ] + i ) . axes [ 1 ] . get_xlim ( ) self [ 'xmin' ] [ i ] = xmin self [ 'xmax' ] [ i ] = xmax if y : ymin , ymax = _p . figure ( self [ 'first_figure' ] + i ) . axes [ 1 ] . get_ylim ( ) self [ 'ymin' ] [ i ] = ymin self [ 'ymax' ] [ i ] = ymax except : self . _error ( "Data " + str ( i ) + " is not currently plotted." ) self . clear_results ( ) if self [ 'autoplot' ] : self . plot ( ) return self
This will set xmin and xmax based on the current zoom - level of the figures .
39,649
def zoom ( self , n = 'all' , xfactor = 2.0 , yfactor = 2.0 ) : if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : self . _error ( "No data. Please use set_data() and plot() prior to zooming." ) return xdata , ydata , eydata = self . get_data ( ) if _s . fun . is_a_number ( n ) : n = [ n ] elif isinstance ( n , str ) : n = list ( range ( len ( xdata ) ) ) for i in n : fig = self [ 'first_figure' ] + i try : xmin , xmax = _p . figure ( fig ) . axes [ 1 ] . get_xlim ( ) xc = 0.5 * ( xmin + xmax ) xs = 0.5 * abs ( xmax - xmin ) self [ 'xmin' ] [ i ] = xc - xfactor * xs self [ 'xmax' ] [ i ] = xc + xfactor * xs ymin , ymax = _p . figure ( fig ) . axes [ 1 ] . get_ylim ( ) yc = 0.5 * ( ymin + ymax ) ys = 0.5 * abs ( ymax - ymin ) self [ 'ymin' ] [ i ] = yc - yfactor * ys self [ 'ymax' ] [ i ] = yc + yfactor * ys except : self . _error ( "Data " + str ( fig ) + " is not currently plotted." ) self . clear_results ( ) if self [ 'autoplot' ] : self . plot ( ) return self
This will scale the chosen data set s plot range by the specified xfactor and yfactor respectively and set the trim limits xmin xmax ymin ymax accordingly
39,650
def ginput ( self , data_set = 0 , ** kwargs ) : import warnings import matplotlib . cbook warnings . filterwarnings ( "ignore" , category = matplotlib . cbook . mplDeprecation ) _s . tweaks . raise_figure_window ( data_set + self [ 'first_figure' ] ) return _p . ginput ( ** kwargs )
Pops up the figure for the specified data set .
39,651
def _match_data_sets ( x , y ) : if x is None : if _fun . is_iterable ( y [ 0 ] ) : x = [ ] for n in range ( len ( y ) ) : x . append ( list ( range ( len ( y [ n ] ) ) ) ) else : x = list ( range ( len ( y ) ) ) if y is None : if _fun . is_iterable ( x [ 0 ] ) : y = [ ] for n in range ( len ( x ) ) : y . append ( list ( range ( len ( x [ n ] ) ) ) ) else : y = list ( range ( len ( x ) ) ) if _fun . elements_are_numbers ( x ) and _fun . elements_are_numbers ( y ) : x = [ x ] y = [ y ] if _fun . elements_are_numbers ( x ) and not _fun . elements_are_numbers ( y ) : x = [ x ] * len ( y ) if _fun . elements_are_numbers ( y ) and not _fun . elements_are_numbers ( x ) : y = [ y ] * len ( x ) for n in range ( len ( x ) ) : if x [ n ] is None : x [ n ] = list ( range ( len ( y [ n ] ) ) ) if y [ n ] is None : y [ n ] = list ( range ( len ( x [ n ] ) ) ) return x , y
Makes sure everything is the same shape . Intelligently .
39,652
def _match_error_to_data_set ( x , ex ) : if not _fun . is_iterable ( ex ) : if ex is None : ex = [ ex ] * len ( x ) if _fun . is_a_number ( ex ) : value = ex ex = [ ] for n in range ( len ( x ) ) : ex . append ( [ value ] * len ( x [ n ] ) ) if _fun . elements_are_numbers ( ex ) and len ( ex ) == len ( x [ 0 ] ) : ex = [ ex ] * len ( x ) for n in range ( len ( x ) ) : if _fun . is_a_number ( ex [ n ] ) : ex [ n ] = [ ex [ n ] ] * len ( x [ n ] ) return ex
Inflates ex to match the dimensionality of x intelligently . x is assumed to be a 2D array .
39,653
def complex_data ( data , edata = None , draw = True , ** kwargs ) : _pylab . ioff ( ) try : rdata = _n . real ( data ) idata = _n . imag ( data ) if edata is None : erdata = None eidata = None else : erdata = _n . real ( edata ) eidata = _n . imag ( edata ) except : rdata = [ ] idata = [ ] if edata is None : erdata = None eidata = None else : erdata = [ ] eidata = [ ] for n in range ( len ( data ) ) : rdata . append ( _n . real ( data [ n ] ) ) idata . append ( _n . imag ( data [ n ] ) ) if not edata is None : erdata . append ( _n . real ( edata [ n ] ) ) eidata . append ( _n . imag ( edata [ n ] ) ) if 'xlabel' not in kwargs : kwargs [ 'xlabel' ] = 'Real' if 'ylabel' not in kwargs : kwargs [ 'ylabel' ] = 'Imaginary' xy_data ( rdata , idata , eidata , erdata , draw = False , ** kwargs ) if draw : _pylab . ion ( ) _pylab . draw ( ) _pylab . show ( )
Plots the imaginary vs real for complex data .
39,654
def complex_files ( script = 'd[1]+1j*d[2]' , escript = None , paths = None , ** kwargs ) : ds = _data . load_multiple ( paths = paths ) if len ( ds ) == 0 : return if 'title' not in kwargs : kwargs [ 'title' ] = _os . path . split ( ds [ 0 ] . path ) [ 0 ] return complex_databoxes ( ds , script = script , ** kwargs )
Loads files and plots complex data in the real - imaginary plane .
39,655
def magphase_databoxes ( ds , xscript = 0 , yscript = 'd[1]+1j*d[2]' , eyscript = None , exscript = None , g = None , ** kwargs ) : databoxes ( ds , xscript , yscript , eyscript , exscript , plotter = magphase_data , g = g , ** kwargs )
Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata .
39,656
def magphase_files ( xscript = 0 , yscript = 'd[1]+1j*d[2]' , eyscript = None , exscript = None , paths = None , g = None , ** kwargs ) : return files ( xscript , yscript , eyscript , exscript , plotter = magphase_databoxes , paths = paths , g = g , ** kwargs )
This will load a bunch of data files generate data based on the supplied scripts and then plot the ydata s magnitude and phase versus xdata .
39,657
def realimag_data ( xdata , ydata , eydata = None , exdata = None , xscale = 'linear' , rscale = 'linear' , iscale = 'linear' , rlabel = 'Real' , ilabel = 'Imaginary' , figure = 'gcf' , clear = 1 , draw = True , ** kwargs ) : _pylab . ioff ( ) xdata , ydata = _match_data_sets ( xdata , ydata ) exdata = _match_error_to_data_set ( xdata , exdata ) eydata = _match_error_to_data_set ( ydata , eydata ) rdata = [ ] idata = [ ] erdata = [ ] eidata = [ ] for l in range ( len ( ydata ) ) : rdata . append ( _n . real ( ydata [ l ] ) ) idata . append ( _n . imag ( ydata [ l ] ) ) if eydata [ l ] is None : erdata . append ( None ) eidata . append ( None ) else : erdata . append ( _n . real ( eydata [ l ] ) ) eidata . append ( _n . imag ( eydata [ l ] ) ) if figure == 'gcf' : f = _pylab . gcf ( ) if clear : f . clear ( ) axes1 = _pylab . subplot ( 211 ) axes2 = _pylab . subplot ( 212 , sharex = axes1 ) if 'xlabel' in kwargs : xlabel = kwargs . pop ( 'xlabel' ) else : xlabel = '' if 'ylabel' in kwargs : kwargs . pop ( 'ylabel' ) if 'tall' not in kwargs : kwargs [ 'tall' ] = False if 'autoformat' not in kwargs : kwargs [ 'autoformat' ] = True autoformat = kwargs [ 'autoformat' ] kwargs [ 'autoformat' ] = False kwargs [ 'xlabel' ] = '' xy_data ( xdata , rdata , eydata = erdata , exdata = exdata , ylabel = rlabel , axes = axes1 , clear = 0 , xscale = xscale , yscale = rscale , draw = False , ** kwargs ) kwargs [ 'autoformat' ] = autoformat kwargs [ 'xlabel' ] = xlabel xy_data ( xdata , idata , eydata = eidata , exdata = exdata , ylabel = ilabel , axes = axes2 , clear = 0 , xscale = xscale , yscale = iscale , draw = False , ** kwargs ) axes2 . set_title ( '' ) if draw : _pylab . ion ( ) _pylab . draw ( ) _pylab . show ( )
Plots the real and imaginary parts of complex ydata vs xdata .
39,658
def realimag_databoxes ( ds , xscript = 0 , yscript = "d[1]+1j*d[2]" , eyscript = None , exscript = None , g = None , ** kwargs ) : databoxes ( ds , xscript , yscript , eyscript , exscript , plotter = realimag_data , g = g , ** kwargs )
Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata .
39,659
def realimag_files ( xscript = 0 , yscript = "d[1]+1j*d[2]" , eyscript = None , exscript = None , paths = None , g = None , ** kwargs ) : return files ( xscript , yscript , eyscript , exscript , plotter = realimag_databoxes , paths = paths , g = g , ** kwargs )
This will load a bunch of data files generate data based on the supplied scripts and then plot the ydata s real and imaginary parts versus xdata .
39,660
def xy_databoxes ( ds , xscript = 0 , yscript = 'd[1]' , eyscript = None , exscript = None , g = None , ** kwargs ) : databoxes ( ds , xscript , yscript , eyscript , exscript , plotter = xy_data , g = g , ** kwargs )
Use databoxes and scripts to generate and plot ydata versus xdata .
39,661
def xy_files ( xscript = 0 , yscript = 'd[1]' , eyscript = None , exscript = None , paths = None , g = None , ** kwargs ) : return files ( xscript , yscript , eyscript , exscript , plotter = xy_databoxes , paths = paths , g = g , ** kwargs )
This will load a bunch of data files generate data based on the supplied scripts and then plot the ydata versus xdata .
39,662
def files ( xscript = 0 , yscript = 1 , eyscript = None , exscript = None , g = None , plotter = xy_databoxes , paths = None , ** kwargs ) : if 'delimiter' in kwargs : delimiter = kwargs . pop ( 'delimiter' ) else : delimiter = None if 'filters' in kwargs : filters = kwargs . pop ( 'filters' ) else : filters = '*.*' ds = _data . load_multiple ( paths = paths , delimiter = delimiter , filters = filters ) if ds is None or len ( ds ) == 0 : return if 'title' not in kwargs : kwargs [ 'title' ] = _os . path . split ( ds [ 0 ] . path ) [ 0 ] plotter ( ds , xscript = xscript , yscript = yscript , eyscript = eyscript , exscript = exscript , g = g , ** kwargs ) return ds
This will load a bunch of data files generate data based on the supplied scripts and then plot this data using the specified databox plotter .
39,663
def image_function ( f = 'sin(5*x)*cos(5*y)' , xmin = - 1 , xmax = 1 , ymin = - 1 , ymax = 1 , xsteps = 100 , ysteps = 100 , p = 'x,y' , g = None , ** kwargs ) : default_kwargs = dict ( clabel = str ( f ) , xlabel = 'x' , ylabel = 'y' ) default_kwargs . update ( kwargs ) if not g : g = { } for k in list ( globals ( ) . keys ( ) ) : if k not in g : g [ k ] = globals ( ) [ k ] if type ( f ) == str : f = eval ( 'lambda ' + p + ': ' + f , g ) xones = _n . linspace ( 1 , 1 , ysteps ) x = _n . linspace ( xmin , xmax , xsteps ) xgrid = _n . outer ( xones , x ) yones = _n . linspace ( 1 , 1 , xsteps ) y = _n . linspace ( ymin , ymax , ysteps ) ygrid = _n . outer ( y , yones ) try : zgrid = f ( xgrid , ygrid ) + xgrid * 0.0 except : print ( "Notice: function is not rocking hardcore. Generating grid the slow way..." ) zgrid = [ ] for ny in range ( 0 , len ( y ) ) : zgrid . append ( [ ] ) for nx in range ( 0 , len ( x ) ) : zgrid [ ny ] . append ( f ( x [ nx ] , y [ ny ] ) ) zgrid = _n . array ( zgrid ) image_data ( zgrid . transpose ( ) , x , y , ** default_kwargs )
Plots a 2 - d function over the specified range
39,664
def image_file ( path = None , zscript = 'self[1:]' , xscript = '[0,1]' , yscript = 'd[0]' , g = None , ** kwargs ) : if 'delimiter' in kwargs : delimiter = kwargs . pop ( 'delimiter' ) else : delimiter = None d = _data . load ( paths = path , delimiter = delimiter ) if d is None or len ( d ) == 0 : return default_kwargs = dict ( xlabel = str ( xscript ) , ylabel = str ( yscript ) , title = d . path , clabel = str ( zscript ) ) default_kwargs . update ( kwargs ) X = d ( xscript , g ) Y = d ( yscript , g ) Z = _n . array ( d ( zscript , g ) ) image_data ( Z , X , Y , ** default_kwargs )
Loads an data file and plots it with color . Data file must have columns of the same length!
39,665
def parametric_function ( fx = 'sin(t)' , fy = 'cos(t)' , tmin = - 1 , tmax = 1 , steps = 200 , p = 't' , g = None , erange = False , ** kwargs ) : if not g : g = { } for k in list ( globals ( ) . keys ( ) ) : if k not in g : g [ k ] = globals ( ) [ k ] if erange : r = _fun . erange ( tmin , tmax , steps ) else : r = _n . linspace ( tmin , tmax , steps ) if not type ( fy ) in [ type ( [ ] ) , type ( ( ) ) ] : fy = [ fy ] if not type ( fx ) in [ type ( [ ] ) , type ( ( ) ) ] : fx = [ fx ] xdatas = [ ] ydatas = [ ] labels = [ ] for fs in fx : if type ( fs ) == str : a = eval ( 'lambda ' + p + ': ' + fs , g ) a . __name__ = fs else : a = fs x = [ ] for z in r : x . append ( a ( z ) ) xdatas . append ( x ) labels . append ( a . __name__ ) for n in range ( len ( fy ) ) : fs = fy [ n ] if type ( fs ) == str : a = eval ( 'lambda ' + p + ': ' + fs , g ) a . __name__ = fs else : a = fs y = [ ] for z in r : y . append ( a ( z ) ) ydatas . append ( y ) labels [ n ] = labels [ n ] + ', ' + a . __name__ xy_data ( xdatas , ydatas , label = labels , ** kwargs )
Plots the parametric function over the specified range
39,666
def reset ( self ) : for key in list ( self . keys ( ) ) : self . iterators [ key ] = _itertools . cycle ( self [ key ] ) return self
Resets the style cycle .
39,667
def add_text ( text , x = 0.01 , y = 0.01 , axes = "gca" , draw = True , ** kwargs ) : if axes == "gca" : axes = _pylab . gca ( ) axes . text ( x , y , text , transform = axes . transAxes , ** kwargs ) if draw : _pylab . draw ( )
Adds text to the axes at the specified position .
39,668
def auto_zoom ( zoomx = True , zoomy = True , axes = "gca" , x_space = 0.04 , y_space = 0.04 , draw = True ) : _pylab . ioff ( ) if axes == "gca" : axes = _pylab . gca ( ) x10 , x20 = axes . get_xlim ( ) y10 , y20 = axes . get_ylim ( ) axes . autoscale ( enable = True , tight = True ) if axes . get_xscale ( ) == 'linear' : x1 , x2 = axes . get_xlim ( ) xc = 0.5 * ( x1 + x2 ) xs = 0.5 * ( 1 + x_space ) * ( x2 - x1 ) axes . set_xlim ( xc - xs , xc + xs ) if axes . get_yscale ( ) == 'linear' : y1 , y2 = axes . get_ylim ( ) yc = 0.5 * ( y1 + y2 ) ys = 0.5 * ( 1 + y_space ) * ( y2 - y1 ) axes . set_ylim ( yc - ys , yc + ys ) if not zoomx : axes . set_xlim ( x10 , x20 ) if not zoomy : axes . set_ylim ( y10 , y20 ) if draw : _pylab . ion ( ) _pylab . draw ( )
Looks at the bounds of the plotted data and zooms accordingly leaving some space around the data .
39,669
def click_estimate_slope ( ) : c1 = _pylab . ginput ( ) if len ( c1 ) == 0 : return None c2 = _pylab . ginput ( ) if len ( c2 ) == 0 : return None return ( c1 [ 0 ] [ 1 ] - c2 [ 0 ] [ 1 ] ) / ( c1 [ 0 ] [ 0 ] - c2 [ 0 ] [ 0 ] )
Takes two clicks and returns the slope .
39,670
def click_estimate_curvature ( ) : c1 = _pylab . ginput ( ) if len ( c1 ) == 0 : return None c2 = _pylab . ginput ( ) if len ( c2 ) == 0 : return None return 2 * ( c2 [ 0 ] [ 1 ] - c1 [ 0 ] [ 1 ] ) / ( c2 [ 0 ] [ 0 ] - c1 [ 0 ] [ 0 ] ) ** 2
Takes two clicks and returns the curvature assuming the first click was the minimum of a parabola and the second was some other point .
39,671
def copy_figure_to_clipboard ( figure = 'gcf' ) : try : import pyqtgraph as _p if figure is 'gcf' : figure = _s . pylab . gcf ( ) path = _os . path . join ( _s . settings . path_home , "clipboard.png" ) figure . savefig ( path ) _p . QtGui . QApplication . instance ( ) . clipboard ( ) . setImage ( _p . QtGui . QImage ( path ) ) except : print ( "This function currently requires pyqtgraph to be installed." )
Copies the specified figure to the system clipboard . Specifying gcf will use the current figure .
39,672
def get_figure_window_geometry ( fig = 'gcf' ) : if type ( fig ) == str : fig = _pylab . gcf ( ) elif _fun . is_a_number ( fig ) : fig = _pylab . figure ( fig ) if _pylab . get_backend ( ) . find ( 'Qt' ) >= 0 : size = fig . canvas . window ( ) . size ( ) pos = fig . canvas . window ( ) . pos ( ) return [ [ pos . x ( ) , pos . y ( ) ] , [ size . width ( ) , size . height ( ) ] ] else : print ( "get_figure_window_geometry() only implemented for QtAgg backend." ) return None
This will currently only work for Qt4Agg and WXAgg backends . Returns position size
39,673
def impose_legend_limit ( limit = 30 , axes = "gca" , ** kwargs ) : if axes == "gca" : axes = _pylab . gca ( ) _pylab . axes ( axes ) for n in range ( 0 , len ( axes . lines ) ) : if n > limit - 1 and not n == len ( axes . lines ) - 1 : axes . lines [ n ] . set_label ( "_nolegend_" ) if n == limit - 1 and not n == len ( axes . lines ) - 1 : axes . lines [ n ] . set_label ( "..." ) _pylab . legend ( ** kwargs )
This will erase all but say 30 of the legend entries and remake the legend . You ll probably have to move it back into your favorite position at this point .
39,674
def image_coarsen ( xlevel = 0 , ylevel = 0 , image = "auto" , method = 'average' ) : if image == "auto" : image = _pylab . gca ( ) . images [ 0 ] Z = _n . array ( image . get_array ( ) ) global image_undo_list image_undo_list . append ( [ image , Z ] ) if len ( image_undo_list ) > 10 : image_undo_list . pop ( 0 ) image . set_array ( _fun . coarsen_matrix ( Z , ylevel , xlevel , method ) ) _pylab . draw ( )
This will coarsen the image data by binning each xlevel + 1 along the x - axis and each ylevel + 1 points along the y - axis
39,675
def image_neighbor_smooth ( xlevel = 0.2 , ylevel = 0.2 , image = "auto" ) : if image == "auto" : image = _pylab . gca ( ) . images [ 0 ] Z = _n . array ( image . get_array ( ) ) global image_undo_list image_undo_list . append ( [ image , Z ] ) if len ( image_undo_list ) > 10 : image_undo_list . pop ( 0 ) dlevel = ( ( xlevel ** 2 + ylevel ** 2 ) / 2.0 ) ** ( 0.5 ) new_Z = [ Z [ 0 ] * 1.0 ] for m in range ( 1 , len ( Z ) - 1 ) : new_Z . append ( Z [ m ] * 1.0 ) for n in range ( 1 , len ( Z [ 0 ] ) - 1 ) : new_Z [ - 1 ] [ n ] = ( Z [ m , n ] + xlevel * ( Z [ m + 1 , n ] + Z [ m - 1 , n ] ) + ylevel * ( Z [ m , n + 1 ] + Z [ m , n - 1 ] ) + dlevel * ( Z [ m + 1 , n + 1 ] + Z [ m - 1 , n + 1 ] + Z [ m + 1 , n - 1 ] + Z [ m - 1 , n - 1 ] ) ) / ( 1.0 + xlevel * 2 + ylevel * 2 + dlevel * 4 ) new_Z . append ( Z [ - 1 ] * 1.0 ) image . set_array ( _n . array ( new_Z ) ) _pylab . draw ( )
This will bleed nearest neighbor pixels into each other with the specified weight factors .
39,676
def image_undo ( ) : if len ( image_undo_list ) <= 0 : print ( "no undos in memory" ) return [ image , Z ] = image_undo_list . pop ( - 1 ) image . set_array ( Z ) _pylab . draw ( )
Undoes the last coarsen or smooth command .
39,677
def image_set_aspect ( aspect = 1.0 , axes = "gca" ) : if axes is "gca" : axes = _pylab . gca ( ) e = axes . get_images ( ) [ 0 ] . get_extent ( ) axes . set_aspect ( abs ( ( e [ 1 ] - e [ 0 ] ) / ( e [ 3 ] - e [ 2 ] ) ) / aspect )
sets the aspect ratio of the current zoom level of the imshow image
39,678
def image_set_extent ( x = None , y = None , axes = "gca" ) : if axes == "gca" : axes = _pylab . gca ( ) xlim = axes . get_xlim ( ) ylim = axes . get_ylim ( ) extent = axes . images [ 0 ] . get_extent ( ) x0 = extent [ 0 ] y0 = extent [ 2 ] xwidth = extent [ 1 ] - x0 ywidth = extent [ 3 ] - y0 frac_x1 = ( xlim [ 0 ] - x0 ) / xwidth frac_x2 = ( xlim [ 1 ] - x0 ) / xwidth frac_y1 = ( ylim [ 0 ] - y0 ) / ywidth frac_y2 = ( ylim [ 1 ] - y0 ) / ywidth if not x == None : extent [ 0 ] = x [ 0 ] extent [ 1 ] = x [ 1 ] if not y == None : extent [ 2 ] = y [ 0 ] extent [ 3 ] = y [ 1 ] x0 = extent [ 0 ] y0 = extent [ 2 ] xwidth = extent [ 1 ] - x0 ywidth = extent [ 3 ] - y0 x1 = x0 + xwidth * frac_x1 x2 = x0 + xwidth * frac_x2 y1 = y0 + ywidth * frac_y1 y2 = y0 + ywidth * frac_y2 axes . images [ 0 ] . set_extent ( extent ) axes . set_xlim ( x1 , x2 ) axes . set_ylim ( y1 , y2 ) image_set_aspect ( 1.0 )
Set s the first image s extent then redraws .
39,679
def image_scale ( xscale = 1.0 , yscale = 1.0 , axes = "gca" ) : if axes == "gca" : axes = _pylab . gca ( ) e = axes . images [ 0 ] . get_extent ( ) x1 = e [ 0 ] * xscale x2 = e [ 1 ] * xscale y1 = e [ 2 ] * yscale y2 = e [ 3 ] * yscale image_set_extent ( [ x1 , x2 ] , [ y1 , y2 ] , axes )
Scales the image extent .
39,680
def image_shift ( xshift = 0 , yshift = 0 , axes = "gca" ) : if axes == "gca" : axes = _pylab . gca ( ) e = axes . images [ 0 ] . get_extent ( ) e [ 0 ] = e [ 0 ] + xshift e [ 1 ] = e [ 1 ] + xshift e [ 2 ] = e [ 2 ] + yshift e [ 3 ] = e [ 3 ] + yshift axes . images [ 0 ] . set_extent ( e ) _pylab . draw ( )
This will shift an image to a new location on x and y .
39,681
def _print_figures ( figures , arguments = '' , file_format = 'pdf' , target_width = 8.5 , target_height = 11.0 , target_pad = 0.5 ) : for fig in figures : temp_path = _os . path . join ( _settings . path_home , "temp" ) _settings . MakeDir ( temp_path ) path = _os . path . join ( temp_path , "graph." + file_format ) w = fig . get_figwidth ( ) h = fig . get_figheight ( ) target_height = target_height - 2 * target_pad target_width = target_width - 2 * target_pad if 1.0 * h / w > target_height / target_width : new_h = target_height new_w = w * target_height / h else : new_w = target_width new_h = h * target_width / w fig . set_figwidth ( new_w ) fig . set_figheight ( new_h ) fig . savefig ( path , bbox_inches = _pylab . matplotlib . transforms . Bbox ( [ [ - target_pad , new_h - target_height - target_pad ] , [ target_width - target_pad , target_height - target_pad ] ] ) ) fig . set_figheight ( h ) fig . set_figwidth ( w ) if not arguments == '' : c = _settings [ 'instaprint' ] + ' ' + arguments + ' "' + path + '"' else : c = _settings [ 'instaprint' ] + ' "' + path + '"' print ( c ) _os . system ( c )
figure printing loop designed to be launched in a separate thread .
39,682
def raise_figure_window ( f = 0 ) : if _fun . is_a_number ( f ) : f = _pylab . figure ( f ) f . canvas . manager . window . raise_ ( )
Raises the supplied figure number or figure window .
39,683
def set_figure_window_geometry ( fig = 'gcf' , position = None , size = None ) : if type ( fig ) == str : fig = _pylab . gcf ( ) elif _fun . is_a_number ( fig ) : fig = _pylab . figure ( fig ) if _pylab . get_backend ( ) . find ( 'Qt' ) >= 0 : w = fig . canvas . window ( ) if not size == None : w . resize ( size [ 0 ] , size [ 1 ] ) if not position == None : w . move ( position [ 0 ] , position [ 1 ] ) elif _pylab . get_backend ( ) . find ( 'WX' ) >= 0 : w = fig . canvas . Parent if not size == None : w . SetSize ( size ) if not position == None : w . SetPosition ( position )
This will currently only work for Qt4Agg and WXAgg backends .
39,684
def line_math ( fx = None , fy = None , axes = 'gca' ) : if axes == 'gca' : axes = _pylab . gca ( ) lines = axes . get_lines ( ) for line in lines : if isinstance ( line , _mpl . lines . Line2D ) : xdata , ydata = line . get_data ( ) if not fx == None : xdata = fx ( xdata ) if not fy == None : ydata = fy ( ydata ) line . set_data ( xdata , ydata ) _pylab . draw ( )
applies function fx to all xdata and fy to all ydata .
39,685
def export_figure ( dpi = 200 , figure = "gcf" , path = None ) : if figure == "gcf" : figure = _pylab . gcf ( ) if path == None : path = _s . dialogs . Save ( "*.*" , default_directory = "save_plot_default_directory" ) if path == "" : print ( "aborted." ) return figure . savefig ( path , dpi = dpi )
Saves the actual postscript data for the figure .
39,686
def save_plot ( axes = "gca" , path = None ) : global line_attributes if path == None : path = _s . dialogs . Save ( "*.plot" , default_directory = "save_plot_default_directory" ) if path == "" : print ( "aborted." ) return if not path . split ( "." ) [ - 1 ] == "plot" : path = path + ".plot" f = file ( path , "w" ) if axes == "gca" : axes = _pylab . gca ( ) f . write ( "title=" + axes . title . get_text ( ) . replace ( '\n' , '\\n' ) + '\n' ) f . write ( "xlabel=" + axes . xaxis . label . get_text ( ) . replace ( '\n' , '\\n' ) + '\n' ) f . write ( "ylabel=" + axes . yaxis . label . get_text ( ) . replace ( '\n' , '\\n' ) + '\n' ) for l in axes . lines : f . write ( "trace=new\n" ) f . write ( "legend=" + l . get_label ( ) . replace ( '\n' , '\\n' ) + "\n" ) for a in line_attributes : f . write ( a + "=" + str ( _pylab . getp ( l , a ) ) . replace ( '\n' , '' ) + "\n" ) x = l . get_xdata ( ) y = l . get_ydata ( ) for n in range ( 0 , len ( x ) ) : f . write ( str ( float ( x [ n ] ) ) + " " + str ( float ( y [ n ] ) ) + "\n" ) f . close ( )
Saves the figure in my own ascii format
39,687
def save_figure_raw_data ( figure = "gcf" , ** kwargs ) : path = _s . dialogs . Save ( ** kwargs ) if path == "" : return "aborted." if figure == "gcf" : figure = _pylab . gcf ( ) for n in range ( len ( figure . axes ) ) : a = figure . axes [ n ] for m in range ( len ( a . lines ) ) : l = a . lines [ m ] x = l . get_xdata ( ) y = l . get_ydata ( ) p = _os . path . split ( path ) p = _os . path . join ( p [ 0 ] , "axes" + str ( n ) + " line" + str ( m ) + " " + p [ 1 ] ) print ( p ) f = open ( p , 'w' ) for j in range ( 0 , len ( x ) ) : f . write ( str ( x [ j ] ) + "\t" + str ( y [ j ] ) + "\n" ) f . close ( )
This will just output an ascii file for each of the traces in the shown figure .
39,688
def get_line_color ( self , increment = 1 ) : i = self . line_colors_index self . line_colors_index += increment if self . line_colors_index >= len ( self . line_colors ) : self . line_colors_index = self . line_colors_index - len ( self . line_colors ) if self . line_colors_index >= len ( self . line_colors ) : self . line_colors_index = 0 return self . line_colors [ i ]
Returns the current color then increments the color by what s specified
39,689
def apply ( self , axes = "gca" ) : if axes == "gca" : axes = _pylab . gca ( ) self . reset ( ) lines = axes . get_lines ( ) for l in lines : l . set_color ( self . get_line_color ( 1 ) ) l . set_mfc ( self . get_face_color ( 1 ) ) l . set_marker ( self . get_marker ( 1 ) ) l . set_mec ( self . get_edge_color ( 1 ) ) l . set_linestyle ( self . get_linestyle ( 1 ) ) _pylab . draw ( )
Applies the style cycle to the lines in the axes specified
39,690
def copy_spline_array ( a ) : b = spline_array ( ) b . x_splines = a . x_splines b . y_splines = a . y_splines b . max_y_splines = a . max_y_splines b . xmin = a . xmin b . xmax = a . xmax b . ymin = a . ymin b . ymax = a . ymax b . xlabel = a . xlabel b . ylabel = a . ylabel b . zlabel = a . zlabel b . simple = a . simple b . generate_y_values ( ) return b
This returns an instance of a new spline_array with all the fixins and the data from a .
39,691
def splot ( axes = "gca" , smoothing = 5000 , degree = 5 , presmoothing = 0 , plot = True , spline_class = spline_single , interactive = True , show_derivative = 1 ) : if axes == "gca" : axes = _pylab . gca ( ) xlabel = axes . xaxis . label . get_text ( ) ylabel = axes . yaxis . label . get_text ( ) xdata = axes . get_lines ( ) [ 0 ] . get_xdata ( ) ydata = axes . get_lines ( ) [ 0 ] . get_ydata ( ) if interactive : return splinteractive ( xdata , ydata , smoothing , degree , presmoothing , spline_class , xlabel , ylabel ) else : return spline_class ( xdata , ydata , smoothing , degree , presmoothing , plot , xlabel , ylabel )
gets the data from the plot and feeds it into splint returns an instance of spline_single
39,692
def evaluate ( self , x , derivative = 0 , smooth = 0 , simple = 'auto' ) : if simple == 'auto' : simple = self . simple is_array = True if not type ( x ) == type ( _pylab . array ( [ ] ) ) : x = _pylab . array ( [ x ] ) is_array = False if simple : y = [ ] for n in range ( 0 , len ( x ) ) : if smooth : [ xtemp , ytemp , etemp ] = _fun . trim_data ( self . xdata , self . ydata , None , [ x [ n ] - smooth , x [ n ] + smooth ] ) else : i1 = _fun . index_nearest ( x [ n ] , self . xdata ) if self . xdata [ i1 ] <= x [ n ] or i1 <= 0 : i2 = i1 + 1 else : i2 = i1 - 1 if i2 >= len ( self . xdata ) : print ( x [ n ] , "is out of range. extrapolating" ) i2 = i1 - 1 x1 = self . xdata [ i1 ] y1 = self . ydata [ i1 ] x2 = self . xdata [ i2 ] y2 = self . ydata [ i2 ] slope = ( y2 - y1 ) / ( x2 - x1 ) xtemp = _numpy . array ( [ x [ n ] ] ) ytemp = _numpy . array ( [ y1 + ( x [ n ] - x1 ) * slope ] ) if derivative == 1 : if smooth : y . append ( ( _numpy . average ( xtemp * ytemp ) - _numpy . average ( xtemp ) * _numpy . average ( ytemp ) ) / ( _numpy . average ( xtemp * xtemp ) - _numpy . average ( xtemp ) ** 2 ) ) else : y . append ( slope ) elif derivative == 0 : y . append ( _numpy . average ( ytemp ) ) if is_array : return _numpy . array ( y ) else : return y [ 0 ] if smooth : y = [ ] for n in range ( 0 , len ( x ) ) : xlow = max ( self . xmin , x [ n ] - smooth ) xhi = min ( self . xmax , x [ n ] + smooth ) xdata = _pylab . linspace ( xlow , xhi , 20 ) ydata = _interpolate . splev ( xdata , self . pfit , derivative ) y . append ( _numpy . average ( ydata ) ) if is_array : return _numpy . array ( y ) else : return y [ 0 ] else : return _interpolate . splev ( x , self . pfit , derivative )
smooth = 0 is how much to smooth the spline data simple = auto is whether we should just use straight interpolation you may want smooth > 0 for this when derivative = 1
39,693
def evaluate ( self , x , y , x_derivative = 0 , smooth = 0 , simple = 'auto' ) : if simple == 'auto' : simple = self . simple for n in range ( 0 , len ( self . y_values ) - 1 ) : if self . y_values [ n ] <= y and self . y_values [ n + 1 ] >= y : y1 = self . y_values [ n ] y2 = self . y_values [ n + 1 ] z1 = self . x_splines [ y1 ] . evaluate ( x , x_derivative , smooth , simple ) z2 = self . x_splines [ y2 ] . evaluate ( x , x_derivative , smooth , simple ) return z1 + ( y - y1 ) * ( z2 - z1 ) / ( y2 - y1 ) print ( "YARG! The y value " + str ( y ) + " is out of interpolation range!" ) if y >= self . y_values [ - 1 ] : return self . x_splines [ self . y_values [ - 1 ] ] . evaluate ( x , x_derivative , smooth , simple ) else : return self . x_splines [ self . y_values [ 0 ] ] . evaluate ( x , x_derivative , smooth , simple )
this evaluates the 2 - d spline by doing linear interpolation of the curves
39,694
def plot_fixed_x ( self , x_values , x_derivative = 0 , steps = 1000 , smooth = 0 , simple = 'auto' , ymin = "auto" , ymax = "auto" , format = True , clear = 1 ) : if simple == 'auto' : simple = self . simple if ymin == "auto" : ymin = self . ymin if ymax == "auto" : ymax = self . ymax if clear : _pylab . gca ( ) . clear ( ) if not type ( x_values ) in [ type ( [ ] ) , type ( _pylab . array ( [ ] ) ) ] : x_values = [ x_values ] for x in x_values : def f ( y ) : return self . evaluate ( x , y , x_derivative , smooth , simple ) _pylab_help . plot_function ( f , ymin , ymax , steps , 0 , False ) a = _pylab . gca ( ) a . set_xlabel ( self . ylabel ) if x_derivative : a . set_ylabel ( str ( x_derivative ) + " " + str ( self . xlabel ) + " derivative of " + self . zlabel ) else : a . set_ylabel ( self . zlabel ) a . set_title ( self . _path + "\nSpline array plot at fixed x = " + self . xlabel ) a . get_lines ( ) [ - 1 ] . set_label ( "x (" + self . xlabel + ") = " + str ( x ) ) if format : _s . format_figure ( ) return a
plots the data at fixed x - value so z vs x
39,695
def plot_fixed_y ( self , y_values , x_derivative = 0 , steps = 1000 , smooth = 0 , simple = 'auto' , xmin = "auto" , xmax = "auto" , format = True , clear = 1 ) : if simple == 'auto' : simple = self . simple if xmin == "auto" : xmin = self . xmin if xmax == "auto" : xmax = self . xmax if clear : _pylab . gca ( ) . clear ( ) if not type ( y_values ) in [ type ( [ ] ) , type ( _pylab . array ( [ ] ) ) ] : y_values = [ y_values ] for y in y_values : def f ( x ) : return self . evaluate ( x , y , x_derivative , smooth , simple ) _pylab_help . plot_function ( f , xmin , xmax , steps , 0 , True ) a = _pylab . gca ( ) th = "th" if x_derivative == 1 : th = "st" if x_derivative == 2 : th = "nd" if x_derivative == 3 : th = "rd" if x_derivative : a . set_ylabel ( str ( x_derivative ) + th + " " + self . xlabel + " derivative of " + self . zlabel + " spline" ) else : a . set_ylabel ( self . zlabel ) a . set_xlabel ( self . xlabel ) a . set_title ( self . _path + "\nSpline array plot at fixed y " + self . ylabel ) a . get_lines ( ) [ - 1 ] . set_label ( "y (" + self . ylabel + ") = " + str ( y ) ) if format : _s . format_figure ( ) return a
plots the data at a fixed y - value so z vs y
39,696
def get_window ( self ) : x = self while not x . _parent == None and not isinstance ( x . _parent , Window ) : x = x . _parent return x . _parent
Returns the object s parent window . Returns None if no window found .
39,697
def block_events ( self ) : self . _widget . blockSignals ( True ) self . _widget . setUpdatesEnabled ( False )
Prevents the widget from sending signals .
39,698
def unblock_events ( self ) : self . _widget . blockSignals ( False ) self . _widget . setUpdatesEnabled ( True )
Allows the widget to send signals .
39,699
def print_message ( self , message = "heya!" ) : if self . log == None : print ( message ) else : self . log . append_text ( message )
If self . log is defined to be an instance of TextLog it print the message there . Otherwise use the usual print to command line .