idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
24,700
def get_RaDecOffsets ( ra1_deg , dec1_deg , ra2_deg , dec2_deg ) : delta_ra_deg = ra1_deg - ra2_deg adj = math . cos ( math . radians ( dec2_deg ) ) if delta_ra_deg > 180.0 : delta_ra_deg = ( delta_ra_deg - 360.0 ) * adj elif delta_ra_deg < - 180.0 : delta_ra_deg = ( delta_ra_deg + 360.0 ) * adj else : delta_ra_deg *= adj delta_dec_deg = dec1_deg - dec2_deg return ( delta_ra_deg , delta_dec_deg )
Calculate offset .
162
5
24,701
def lon_to_deg ( lon ) : if isinstance ( lon , str ) and ( ':' in lon ) : # TODO: handle other coordinate systems lon_deg = hmsStrToDeg ( lon ) else : lon_deg = float ( lon ) return lon_deg
Convert longitude to degrees .
70
7
24,702
def lat_to_deg ( lat ) : if isinstance ( lat , str ) and ( ':' in lat ) : # TODO: handle other coordinate systems lat_deg = dmsStrToDeg ( lat ) else : lat_deg = float ( lat ) return lat_deg
Convert latitude to degrees .
61
6
24,703
def get_ruler_distances ( image , p1 , p2 ) : x1 , y1 = p1 [ : 2 ] x2 , y2 = p2 [ : 2 ] dx , dy = x2 - x1 , y2 - y1 res = Bunch . Bunch ( x1 = x1 , y1 = y1 , x2 = x2 , y2 = y2 , theta = np . arctan2 ( y2 - y1 , x2 - x1 ) , dx_pix = dx , dy_pix = dy , dh_pix = np . sqrt ( dx ** 2 + dy ** 2 ) , ra_org = None , dec_org = None , ra_dst = None , dec_dst = None , ra_heel = None , dec_heel = None , dx_deg = None , dy_deg = None , dh_deg = None ) if image is not None and hasattr ( image , 'wcs' ) and image . wcs is not None : # Calculate RA and DEC for the three points try : # origination point ra_org , dec_org = image . pixtoradec ( x1 , y1 ) res . ra_org , res . dec_org = ra_org , dec_org # destination point ra_dst , dec_dst = image . pixtoradec ( x2 , y2 ) res . ra_dst , res . dec_dst = ra_dst , dec_dst # "heel" point making a right triangle ra_heel , dec_heel = image . pixtoradec ( x2 , y1 ) res . ra_heel , res . dec_heel = ra_heel , dec_heel res . dh_deg = deltaStarsRaDecDeg ( ra_org , dec_org , ra_dst , dec_dst ) res . dx_deg = deltaStarsRaDecDeg ( ra_org , dec_org , ra_heel , dec_heel ) res . dy_deg = deltaStarsRaDecDeg ( ra_heel , dec_heel , ra_dst , dec_dst ) except Exception as e : pass return res
Get the distance calculated between two points . A Bunch of results is returned containing pixel values and distance values if the image contains a valid WCS .
494
29
24,704
def add_font ( font_file , font_name = None ) : global font_dir if font_name is None : # determine family name from filename of font dirname , filename = os . path . split ( font_file ) font_name , ext = os . path . splitext ( filename ) font_dir [ font_name ] = Bunch . Bunch ( name = font_name , font_path = font_file ) return font_name
Add a font description to our directory of externally loadable fonts . font_file is the path to the font and optional font_name is the name to register it under .
99
35
24,705
def have_font ( font_name ) : if font_name in font_dir : return True # try it as an alias font_name = resolve_alias ( font_name , font_name ) return font_name in font_dir
Return True if the given font name is registered as one of our externally loadable fonts . If font_name is not found it will try to look it up as an alias and report if that is found .
51
42
24,706
def toggle_create_button ( self ) : if len ( self . _drawn_tags ) > 0 : self . w . create_mask . set_enabled ( True ) else : self . w . create_mask . set_enabled ( False )
Enable or disable Create Mask button based on drawn objects .
53
11
24,707
def create_mask ( self ) : ntags = len ( self . _drawn_tags ) if ntags == 0 : return old_image = self . fitsimage . get_image ( ) if old_image is None : return mask = None obj_kinds = set ( ) # Create mask for tag in self . _drawn_tags : obj = self . canvas . get_object_by_tag ( tag ) try : cur_mask = old_image . get_shape_mask ( obj ) except Exception as e : self . logger . error ( 'Cannot create mask: {0}' . format ( str ( e ) ) ) continue if mask is not None : mask |= cur_mask else : mask = cur_mask obj_kinds . add ( obj . kind ) # Might be useful to inherit header from displayed image (e.g., WCS) # but the displayed image should not be modified. # Bool needs to be converted to int so FITS writer would not crash. image = dp . make_image ( mask . astype ( 'int16' ) , old_image , { } , pfx = self . _mask_prefix ) imname = image . get ( 'name' ) # Insert new image self . fv . gui_call ( self . fv . add_image , imname , image , chname = self . chname ) # Add description to ChangeHistory s = 'Mask created from {0} drawings ({1})' . format ( ntags , ',' . join ( sorted ( obj_kinds ) ) ) info = dict ( time_modified = datetime . utcnow ( ) , reason_modified = s ) self . fv . update_image_info ( image , info ) self . logger . info ( s )
Create boolean mask from drawing .
381
6
24,708
def cmd_load ( self , * args , * * kwargs ) : ch = kwargs . get ( 'ch' , None ) for item in args : # TODO: check for URI syntax files = glob . glob ( item ) self . fv . gui_do ( self . fv . open_uris , files , chname = ch )
load file ... ch = chname
78
7
24,709
def cmd_cuts ( self , lo = None , hi = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return loval , hival = viewer . get_cut_levels ( ) if ( lo is None ) and ( hi is None ) : self . log ( "lo=%f hi=%f" % ( loval , hival ) ) else : if lo is not None : loval = lo if hi is not None : hival = hi viewer . cut_levels ( loval , hival ) self . log ( "lo=%f hi=%f" % ( loval , hival ) )
cuts lo = val hi = val ch = chname
157
11
24,710
def cmd_ac ( self , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return viewer . auto_levels ( ) self . cmd_cuts ( ch = ch )
ac ch = chname
58
5
24,711
def cmd_cm ( self , nm = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return if nm is None : rgbmap = viewer . get_rgbmap ( ) cmap = rgbmap . get_cmap ( ) self . log ( cmap . name ) else : viewer . set_color_map ( nm )
cm nm = color_map_name ch = chname
95
12
24,712
def cmd_cminv ( self , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return viewer . invert_cmap ( )
cminv ch = chname
52
7
24,713
def cmd_dist ( self , nm = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return if nm is None : rgbmap = viewer . get_rgbmap ( ) dist = rgbmap . get_dist ( ) self . log ( str ( dist ) ) else : viewer . set_color_algorithm ( nm )
dist nm = dist_name ch = chname
94
10
24,714
def cmd_imap ( self , nm = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return if nm is None : rgbmap = viewer . get_rgbmap ( ) imap = rgbmap . get_imap ( ) self . log ( imap . name ) else : viewer . set_intensity_map ( nm )
imap nm = intensity_map_name ch = chname
96
13
24,715
def cmd_rot ( self , deg = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return if deg is None : self . log ( "%f deg" % ( viewer . get_rotation ( ) ) ) else : viewer . rotate ( deg )
rot deg = num_deg ch = chname
78
10
24,716
def cmd_tr ( self , x = None , y = None , xy = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return fx , fy , sxy = viewer . get_transforms ( ) if x is None and y is None and xy is None : self . log ( "x=%s y=%s xy=%s" % ( fx , fy , sxy ) ) else : # turn these into True or False if x is None : x = fx else : x = ( x != 0 ) if y is None : y = fy else : y = ( y != 0 ) if xy is None : xy = sxy else : xy = ( xy != 0 ) viewer . transform ( x , y , xy )
tr x = 0|1 y = 0|1 xy = 0|1 ch = chname
194
21
24,717
def cmd_scale ( self , x = None , y = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return scale_x , scale_y = viewer . get_scale_xy ( ) if x is None and y is None : self . log ( "x=%f y=%f" % ( scale_x , scale_y ) ) else : if x is not None : if y is None : y = x if y is not None : if x is None : x = y viewer . scale_to ( x , y )
scale x = scale_x y = scale_y ch = chname
140
15
24,718
def cmd_z ( self , lvl = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return cur_lvl = viewer . get_zoom ( ) if lvl is None : self . log ( "zoom=%f" % ( cur_lvl ) ) else : viewer . zoom_to ( lvl )
z lvl = level ch = chname
90
8
24,719
def cmd_zf ( self , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return viewer . zoom_fit ( ) cur_lvl = viewer . get_zoom ( ) self . log ( "zoom=%f" % ( cur_lvl ) )
zf ch = chname
79
6
24,720
def cmd_c ( self , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return viewer . center_image ( )
c ch = chname
48
5
24,721
def cmd_pan ( self , x = None , y = None , ch = None ) : viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return pan_x , pan_y = viewer . get_pan ( ) if x is None and y is None : self . log ( "x=%f y=%f" % ( pan_x , pan_y ) ) else : if x is not None : if y is None : y = pan_y if y is not None : if x is None : x = pan_x viewer . set_pan ( x , y )
scale ch = chname x = pan_x y = pan_y
142
15
24,722
def timer ( self , jitter , action , * args , * * kwargs ) : return Timer ( self , jitter , action , * args , * * kwargs )
Convenience method to create a Timer from the heap
40
12
24,723
def add ( self , timer ) : with self . lock : if self . heap : top = self . heap [ 0 ] else : top = None assert timer not in self . timers self . timers [ timer ] = timer heapq . heappush ( self . heap , timer ) # Check to see if we need to reschedule our main timer. # Only do this if we aren't expiring in the other thread. if self . heap [ 0 ] != top and not self . expiring : if self . rtimer is not None : self . rtimer . cancel ( ) # self.rtimer.join() self . rtimer = None # If we are expiring timers right now then that will reschedule # as appropriate otherwise let's start a timer if we don't have # one if self . rtimer is None and not self . expiring : top = self . heap [ 0 ] ival = top . expire - time . time ( ) if ival < 0 : ival = 0 self . rtimer = threading . Timer ( ival , self . expire ) self . rtimer . start ( )
Add a timer to the heap
237
6
24,724
def _remove ( self , timer ) : assert timer . timer_heap == self del self . timers [ timer ] assert timer in self . heap self . heap . remove ( timer ) heapq . heapify ( self . heap )
Remove timer from heap lock and presence are assumed
49
9
24,725
def remove ( self , timer ) : with self . lock : # This is somewhat expensive as we have to heapify. if timer in self . timers : self . _remove ( timer ) return False else : return True
Remove a timer from the heap return True if already run
45
11
24,726
def remove_all_timers ( self ) : with self . lock : if self . rtimer is not None : self . rtimer . cancel ( ) self . timers = { } self . heap = [ ] self . rtimer = None self . expiring = False
Remove all waiting timers and terminate any blocking threads .
57
10
24,727
def get_llur ( self ) : points = np . array ( [ obj . get_llur ( ) for obj in self . objects ] ) t_ = points . T x1 , y1 = t_ [ 0 ] . min ( ) , t_ [ 1 ] . min ( ) x2 , y2 = t_ [ 2 ] . max ( ) , t_ [ 3 ] . max ( ) return ( x1 , y1 , x2 , y2 )
Get lower - left and upper - right coordinates of the bounding box of this compound object .
102
19
24,728
def build_gui ( self , container ) : vbox = Widgets . VBox ( ) vbox . set_border_width ( 0 ) w = Viewers . GingaViewerWidget ( viewer = self ) vbox . add_widget ( w , stretch = 1 ) # need to put this in an hbox with an expanding label or the # browser wants to resize the canvas, distorting it hbox = Widgets . HBox ( ) hbox . add_widget ( vbox , stretch = 0 ) hbox . add_widget ( Widgets . Label ( '' ) , stretch = 1 ) container . set_widget ( hbox )
This is responsible for building the viewer s UI . It should place the UI in container . Override this to make a custom UI .
137
27
24,729
def embed ( self , width = 600 , height = 650 ) : from IPython . display import IFrame return IFrame ( self . url , width , height )
Embed a viewer into a Jupyter notebook .
34
12
24,730
def load_fits ( self , filepath ) : image = AstroImage . AstroImage ( logger = self . logger ) image . load_file ( filepath ) self . set_image ( image )
Load a FITS file into the viewer .
42
9
24,731
def load_hdu ( self , hdu ) : image = AstroImage . AstroImage ( logger = self . logger ) image . load_hdu ( hdu ) self . set_image ( image )
Load an HDU into the viewer .
44
8
24,732
def load_data ( self , data_np ) : image = AstroImage . AstroImage ( logger = self . logger ) image . set_data ( data_np ) self . set_image ( image )
Load raw numpy data into the viewer .
44
9
24,733
def set_html5_canvas_format ( self , fmt ) : fmt = fmt . lower ( ) if fmt not in ( 'jpeg' , 'png' ) : raise ValueError ( "Format must be one of {jpeg|png} not '%s'" % ( fmt ) ) settings = self . get_settings ( ) settings . set ( html5_canvas_format = fmt )
Sets the format used for rendering to the HTML5 canvas . png offers greater clarity especially for small text but does not have as good of performance as jpeg .
87
34
24,734
def build_gui ( self , container ) : vbox = Widgets . VBox ( ) vbox . set_border_width ( 2 ) vbox . set_spacing ( 1 ) w = Viewers . GingaViewerWidget ( viewer = self ) vbox . add_widget ( w , stretch = 1 ) # set up to capture cursor movement for reading out coordinates # coordinates reported in base 1 or 0? self . pixel_base = 1.0 self . readout = Widgets . Label ( "" ) vbox . add_widget ( self . readout , stretch = 0 ) #self.set_callback('none-move', self.motion_cb) self . set_callback ( 'cursor-changed' , self . motion_cb ) # need to put this in an hbox with an expanding label or the # browser wants to resize the canvas, distorting it hbox = Widgets . HBox ( ) hbox . add_widget ( vbox , stretch = 0 ) hbox . add_widget ( Widgets . Label ( '' ) , stretch = 1 ) container . set_widget ( hbox )
This is responsible for building the viewer s UI . It should place the UI in container .
240
18
24,735
def get_viewer ( self , v_id , viewer_class = None , width = 512 , height = 512 , force_new = False ) : if not force_new : try : return self . viewers [ v_id ] except KeyError : pass # create top level window window = self . app . make_window ( "Viewer %s" % v_id , wid = v_id ) # We get back a record with information about the viewer v_info = self . make_viewer ( window , viewer_class = viewer_class , width = width , height = height ) # Save it under this viewer id self . viewers [ v_id ] = v_info return v_info
Get an existing viewer by viewer id . If the viewer does not yet exist make a new one .
150
20
24,736
def detailxy ( self , canvas , button , data_x , data_y ) : if button == 0 : # TODO: we could track the focus changes to make this check # more efficient chviewer = self . fv . getfocus_viewer ( ) # Don't update global information if our chviewer isn't focused if chviewer != self . fitsimage : return True # Add offsets from cutout data_x = data_x + self . pick_x1 data_y = data_y + self . pick_y1 return self . fv . showxy ( chviewer , data_x , data_y )
Motion event in the pick fits window . Show the pointing information under the cursor .
138
16
24,737
def reference_viewer ( sys_argv ) : viewer = ReferenceViewer ( layout = default_layout ) viewer . add_default_plugins ( ) viewer . add_separately_distributed_plugins ( ) # Parse command line options with optparse module from optparse import OptionParser usage = "usage: %prog [options] cmd [args]" optprs = OptionParser ( usage = usage , version = ( '%%prog %s' % version . version ) ) viewer . add_default_options ( optprs ) ( options , args ) = optprs . parse_args ( sys_argv [ 1 : ] ) if options . display : os . environ [ 'DISPLAY' ] = options . display # Are we debugging this? if options . debug : import pdb pdb . run ( 'viewer.main(options, args)' ) # Are we profiling this? elif options . profile : import profile print ( ( "%s profile:" % sys_argv [ 0 ] ) ) profile . run ( 'viewer.main(options, args)' ) else : viewer . main ( options , args )
Create reference viewer from command line .
244
7
24,738
def add_default_plugins ( self , except_global = [ ] , except_local = [ ] ) : # add default global plugins for spec in plugins : ptype = spec . get ( 'ptype' , 'local' ) if ptype == 'global' and spec . module not in except_global : self . add_plugin_spec ( spec ) if ptype == 'local' and spec . module not in except_local : self . add_plugin_spec ( spec )
Add the ginga - distributed default set of plugins to the reference viewer .
104
16
24,739
def add_default_options ( self , optprs ) : optprs . add_option ( "--bufsize" , dest = "bufsize" , metavar = "NUM" , type = "int" , default = 10 , help = "Buffer length to NUM" ) optprs . add_option ( '-c' , "--channels" , dest = "channels" , help = "Specify list of channels to create" ) optprs . add_option ( "--debug" , dest = "debug" , default = False , action = "store_true" , help = "Enter the pdb debugger on main()" ) optprs . add_option ( "--disable-plugins" , dest = "disable_plugins" , metavar = "NAMES" , help = "Specify plugins that should be disabled" ) optprs . add_option ( "--display" , dest = "display" , metavar = "HOST:N" , help = "Use X display on HOST:N" ) optprs . add_option ( "--fitspkg" , dest = "fitspkg" , metavar = "NAME" , default = None , help = "Prefer FITS I/O module NAME" ) optprs . add_option ( "-g" , "--geometry" , dest = "geometry" , default = None , metavar = "GEOM" , help = "X geometry for initial size and placement" ) optprs . add_option ( "--modules" , dest = "modules" , metavar = "NAMES" , help = "Specify additional modules to load" ) optprs . add_option ( "--norestore" , dest = "norestore" , default = False , action = "store_true" , help = "Don't restore the GUI from a saved layout" ) optprs . add_option ( "--nosplash" , dest = "nosplash" , default = False , action = "store_true" , help = "Don't display the splash screen" ) optprs . add_option ( "--numthreads" , dest = "numthreads" , type = "int" , default = 30 , metavar = "NUM" , help = "Start NUM threads in thread pool" ) optprs . add_option ( "--opencv" , dest = "opencv" , default = False , action = "store_true" , help = "Use OpenCv acceleration" ) optprs . add_option ( "--opencl" , dest = "opencl" , default = False , action = "store_true" , help = "Use OpenCL acceleration" ) optprs . add_option ( "--plugins" , dest = "plugins" , metavar = "NAMES" , help = "Specify additional plugins to load" ) optprs . add_option ( "--profile" , dest = "profile" , action = "store_true" , default = False , help = "Run the profiler on main()" ) optprs . add_option ( "--sep" , dest = "separate_channels" , default = False , action = "store_true" , help = "Load files in separate channels" ) optprs . add_option ( "-t" , "--toolkit" , dest = "toolkit" , metavar = "NAME" , default = None , help = "Prefer GUI toolkit (gtk|qt)" ) optprs . add_option ( "--wcspkg" , dest = "wcspkg" , metavar = "NAME" , default = None , help = "Prefer WCS module NAME" ) log . addlogopts ( optprs )
Adds the default reference viewer startup options to an OptionParser instance optprs .
837
16
24,740
def gui_call ( self , method , * args , * * kwdargs ) : my_id = thread . get_ident ( ) if my_id == self . gui_thread_id : return method ( * args , * * kwdargs ) else : future = self . gui_do ( method , * args , * * kwdargs ) return future . wait ( )
General method for synchronously calling into the GUI . This waits until the method has completed before returning .
82
20
24,741
def show_help ( self , plugin = None , no_url_callback = None ) : if not Widgets . has_webkit : return self . fv . nongui_do ( self . _download_doc , plugin = plugin , no_url_callback = no_url_callback )
See ~ginga . GingaPlugin for usage of optional keywords .
64
14
24,742
def get_mean ( data_np ) : i = np . isfinite ( data_np ) if not np . any ( i ) : return np . nan return np . mean ( data_np [ i ] )
Calculate mean for valid values .
47
8
24,743
def calc_fwhm_gaussian ( self , arr1d , medv = None , gauss_fn = None ) : if gauss_fn is None : gauss_fn = self . gaussian N = len ( arr1d ) X = np . array ( list ( range ( N ) ) ) Y = arr1d # Fitting works more reliably if we do the following # a. subtract sky background if medv is None : medv = get_median ( Y ) Y = Y - medv maxv = Y . max ( ) # b. clamp to 0..max (of the sky subtracted field) Y = Y . clip ( 0 , maxv ) # Fit a gaussian p0 = [ 0 , N - 1 , maxv ] # Inital guess # Distance to the target function errfunc = lambda p , x , y : gauss_fn ( x , p ) - y # noqa # Least square fit to the gaussian with self . lock : # NOTE: without this mutex, optimize.leastsq causes a fatal error # sometimes--it appears not to be thread safe. # The error is: # "SystemError: null argument to internal routine" # "Fatal Python error: GC object already tracked" p1 , success = optimize . leastsq ( errfunc , p0 [ : ] , args = ( X , Y ) ) if not success : raise IQCalcError ( "FWHM gaussian fitting failed" ) mu , sdev , maxv = p1 self . logger . debug ( "mu=%f sdev=%f maxv=%f" % ( mu , sdev , maxv ) ) # Now that we have the sdev from fitting, we can calculate FWHM fwhm = 2.0 * np . sqrt ( 2.0 * np . log ( 2.0 ) ) * sdev # some routines choke on numpy values and need "pure" Python floats # e.g. when marshalling through a remote procedure interface fwhm = float ( fwhm ) mu = float ( mu ) sdev = float ( sdev ) maxv = float ( maxv ) res = Bunch . Bunch ( fwhm = fwhm , mu = mu , sdev = sdev , maxv = maxv , fit_fn = gauss_fn , fit_args = [ mu , sdev , maxv ] ) return res
FWHM calculation on a 1D array by using least square fitting of a gaussian function on the data . arr1d is a 1D array cut in either X or Y direction on the object .
522
42
24,744
def calc_fwhm_moffat ( self , arr1d , medv = None , moffat_fn = None ) : if moffat_fn is None : moffat_fn = self . moffat N = len ( arr1d ) X = np . array ( list ( range ( N ) ) ) Y = arr1d # Fitting works more reliably if we do the following # a. subtract sky background if medv is None : medv = get_median ( Y ) Y = Y - medv maxv = Y . max ( ) # b. clamp to 0..max (of the sky subtracted field) Y = Y . clip ( 0 , maxv ) # Fit a moffat p0 = [ 0 , N - 1 , 2 , maxv ] # Inital guess # Distance to the target function errfunc = lambda p , x , y : moffat_fn ( x , p ) - y # noqa # Least square fit to the gaussian with self . lock : # NOTE: without this mutex, optimize.leastsq causes a fatal error # sometimes--it appears not to be thread safe. # The error is: # "SystemError: null argument to internal routine" # "Fatal Python error: GC object already tracked" p1 , success = optimize . leastsq ( errfunc , p0 [ : ] , args = ( X , Y ) ) if not success : raise IQCalcError ( "FWHM moffat fitting failed" ) mu , width , power , maxv = p1 width = np . abs ( width ) self . logger . debug ( "mu=%f width=%f power=%f maxv=%f" % ( mu , width , power , maxv ) ) fwhm = 2.0 * width * np . sqrt ( 2.0 ** ( 1.0 / power ) - 1.0 ) # some routines choke on numpy values and need "pure" Python floats # e.g. when marshalling through a remote procedure interface fwhm = float ( fwhm ) mu = float ( mu ) width = float ( width ) power = float ( power ) maxv = float ( maxv ) res = Bunch . Bunch ( fwhm = fwhm , mu = mu , width = width , power = power , maxv = maxv , fit_fn = moffat_fn , fit_args = [ mu , width , power , maxv ] ) return res
FWHM calculation on a 1D array by using least square fitting of a Moffat function on the data . arr1d is a 1D array cut in either X or Y direction on the object .
538
42
24,745
def my_import ( name , path = None ) : # Documentation for importlib says this may be needed to pick up # modules created after the program has started if hasattr ( importlib , 'invalidate_caches' ) : # python 3.3+ importlib . invalidate_caches ( ) if path is not None : directory , src_file = os . path . split ( path ) # TODO: use the importlib.util machinery sys . path . insert ( 0 , directory ) try : mod = importlib . import_module ( name ) finally : sys . path . pop ( 0 ) else : mod = importlib . import_module ( name ) return mod
Return imported module for the given name .
145
8
24,746
def get_module ( self , module_name ) : try : return self . module [ module_name ] except KeyError : return sys . modules [ module_name ]
Return loaded module from the given name .
36
8
24,747
def parse_combo ( self , combo , modes_set , modifiers_set , pfx ) : mode , mods , trigger = None , set ( [ ] ) , combo if '+' in combo : if combo . endswith ( '+' ) : # special case: probably contains the keystroke '+' trigger , combo = '+' , combo [ : - 1 ] if '+' in combo : items = set ( combo . split ( '+' ) ) else : items = set ( combo ) else : # trigger is always specified last items = combo . split ( '+' ) trigger , items = items [ - 1 ] , set ( items [ : - 1 ] ) if '*' in items : items . remove ( '*' ) # modifier wildcard mods = '*' else : mods = items . intersection ( modifiers_set ) mode = items . intersection ( modes_set ) if len ( mode ) == 0 : mode = None else : mode = mode . pop ( ) if pfx is not None : trigger = pfx + trigger return ( mode , mods , trigger )
Parse a string into a mode a set of modifiers and a trigger .
234
15
24,748
def get_direction ( self , direction , rev = False ) : if ( direction < 90.0 ) or ( direction >= 270.0 ) : if not rev : return 'up' else : return 'down' elif ( 90.0 <= direction < 270.0 ) : if not rev : return 'down' else : return 'up' else : return 'none'
Translate a direction in compass degrees into up or down .
79
12
24,749
def kp_pan_px_center ( self , viewer , event , data_x , data_y , msg = True ) : if not self . canpan : return False self . pan_center_px ( viewer ) return True
This pans so that the cursor is over the center of the current pixel .
50
15
24,750
def ms_zoom ( self , viewer , event , data_x , data_y , msg = True ) : if not self . canzoom : return True msg = self . settings . get ( 'msg_zoom' , msg ) x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _zoom_xy ( viewer , x , y ) elif event . state == 'down' : if msg : viewer . onscreen_message ( "Zoom (drag mouse L-R)" , delay = 1.0 ) self . _start_x , self . _start_y = x , y else : viewer . onscreen_message ( None ) return True
Zoom the image by dragging the cursor left or right .
157
12
24,751
def ms_zoom_in ( self , viewer , event , data_x , data_y , msg = False ) : if not self . canzoom : return True if not ( event . state == 'down' ) : return True with viewer . suppress_redraw : viewer . panset_xy ( data_x , data_y ) if self . settings . get ( 'scroll_zoom_direct_scale' , True ) : zoom_accel = self . settings . get ( 'scroll_zoom_acceleration' , 1.0 ) # change scale by 100% amount = self . _scale_adjust ( 2.0 , 15.0 , zoom_accel , max_limit = 4.0 ) self . _scale_image ( viewer , 0.0 , amount , msg = msg ) else : viewer . zoom_in ( ) if hasattr ( viewer , 'center_cursor' ) : viewer . center_cursor ( ) if msg : viewer . onscreen_message ( viewer . get_scale_text ( ) , delay = 1.0 ) return True
Zoom in one level by a mouse click .
235
10
24,752
def ms_rotate ( self , viewer , event , data_x , data_y , msg = True ) : if not self . canrotate : return True msg = self . settings . get ( 'msg_rotate' , msg ) x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _rotate_xy ( viewer , x , y ) elif event . state == 'down' : if msg : viewer . onscreen_message ( "Rotate (drag around center)" , delay = 1.0 ) self . _start_x , self . _start_y = x , y self . _start_rot = viewer . get_rotation ( ) else : viewer . onscreen_message ( None ) return True
Rotate the image by dragging the cursor left or right .
170
12
24,753
def ms_contrast ( self , viewer , event , data_x , data_y , msg = True ) : if not self . cancmap : return True msg = self . settings . get ( 'msg_contrast' , msg ) x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _tweak_colormap ( viewer , x , y , 'preview' ) elif event . state == 'down' : self . _start_x , self . _start_y = x , y if msg : viewer . onscreen_message ( "Shift and stretch colormap (drag mouse)" , delay = 1.0 ) else : viewer . onscreen_message ( None ) return True
Shift the colormap by dragging the cursor left or right . Stretch the colormap by dragging the cursor up or down .
165
26
24,754
def ms_contrast_restore ( self , viewer , event , data_x , data_y , msg = True ) : if self . cancmap and ( event . state == 'down' ) : self . restore_contrast ( viewer , msg = msg ) return True
An interactive way to restore the colormap contrast settings after a warp operation .
60
16
24,755
def ms_cmap_restore ( self , viewer , event , data_x , data_y , msg = True ) : if self . cancmap and ( event . state == 'down' ) : self . restore_colormap ( viewer , msg ) return True
An interactive way to restore the colormap settings after a rotate or invert operation .
59
18
24,756
def ms_pan ( self , viewer , event , data_x , data_y ) : if not self . canpan : return True x , y = viewer . get_last_win_xy ( ) if event . state == 'move' : data_x , data_y = self . get_new_pan ( viewer , x , y , ptype = self . _pantype ) viewer . panset_xy ( data_x , data_y ) elif event . state == 'down' : self . pan_set_origin ( viewer , x , y , data_x , data_y ) self . pan_start ( viewer , ptype = 2 ) else : self . pan_stop ( viewer ) return True
A drag or proportional pan where the image is panned by dragging the canvas up or down . The amount of the pan is proportionate to the length of the drag .
157
34
24,757
def ms_cutlo ( self , viewer , event , data_x , data_y ) : if not self . cancut : return True x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _cutlow_xy ( viewer , x , y ) elif event . state == 'down' : self . _start_x , self . _start_y = x , y self . _loval , self . _hival = viewer . get_cut_levels ( ) else : viewer . onscreen_message ( None ) return True
An interactive way to set the low cut level .
128
10
24,758
def ms_cutall ( self , viewer , event , data_x , data_y ) : if not self . cancut : return True x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _cutboth_xy ( viewer , x , y ) elif event . state == 'down' : self . _start_x , self . _start_y = x , y image = viewer . get_image ( ) #self._loval, self._hival = viewer.get_cut_levels() self . _loval , self . _hival = viewer . autocuts . calc_cut_levels ( image ) else : viewer . onscreen_message ( None ) return True
An interactive way to set the low AND high cut levels .
161
12
24,759
def sc_cuts_coarse ( self , viewer , event , msg = True ) : if self . cancut : # adjust the cut by 10% on each end self . _adjust_cuts ( viewer , event . direction , 0.1 , msg = msg ) return True
Adjust cuts interactively by setting the low AND high cut levels . This function adjusts it coarsely .
58
20
24,760
def sc_cuts_alg ( self , viewer , event , msg = True ) : if self . cancut : direction = self . get_direction ( event . direction ) self . _cycle_cuts_alg ( viewer , msg , direction = direction ) return True
Adjust cuts algorithm interactively .
55
6
24,761
def sc_zoom ( self , viewer , event , msg = True ) : self . _sc_zoom ( viewer , event , msg = msg , origin = None ) return True
Interactively zoom the image by scrolling motion . This zooms by the zoom steps configured under Preferences .
39
20
24,762
def sc_zoom_coarse ( self , viewer , event , msg = True ) : if not self . canzoom : return True zoom_accel = self . settings . get ( 'scroll_zoom_acceleration' , 1.0 ) # change scale by 20% amount = self . _scale_adjust ( 1.2 , event . amount , zoom_accel , max_limit = 4.0 ) self . _scale_image ( viewer , event . direction , amount , msg = msg ) return True
Interactively zoom the image by scrolling motion . This zooms by adjusting the scale in x and y coarsely .
113
23
24,763
def sc_pan ( self , viewer , event , msg = True ) : if not self . canpan : return True # User has "Pan Reverse" preference set? rev = self . settings . get ( 'pan_reverse' , False ) direction = event . direction if rev : direction = math . fmod ( direction + 180.0 , 360.0 ) pan_accel = self . settings . get ( 'scroll_pan_acceleration' , 1.0 ) # Internal factor to adjust the panning speed so that user-adjustable # scroll_pan_acceleration is normalized to 1.0 for "normal" speed scr_pan_adj_factor = 1.4142135623730951 amount = ( event . amount * scr_pan_adj_factor * pan_accel ) / 360.0 self . pan_omni ( viewer , direction , amount ) return True
Interactively pan the image by scrolling motion .
191
9
24,764
def sc_dist ( self , viewer , event , msg = True ) : direction = self . get_direction ( event . direction ) self . _cycle_dist ( viewer , msg , direction = direction ) return True
Interactively change the color distribution algorithm by scrolling .
45
10
24,765
def sc_cmap ( self , viewer , event , msg = True ) : direction = self . get_direction ( event . direction ) self . _cycle_cmap ( viewer , msg , direction = direction ) return True
Interactively change the color map by scrolling .
47
9
24,766
def sc_imap ( self , viewer , event , msg = True ) : direction = self . get_direction ( event . direction ) self . _cycle_imap ( viewer , msg , direction = direction ) return True
Interactively change the intensity map by scrolling .
47
9
24,767
def pa_naxis ( self , viewer , event , msg = True ) : event = self . _pa_synth_scroll_event ( event ) if event . state != 'move' : return False # TODO: be able to pick axis axis = 2 direction = self . get_direction ( event . direction ) return self . _nav_naxis ( viewer , axis , direction , msg = msg )
Interactively change the slice of the image in a data cube by pan gesture .
87
16
24,768
def mode_key_down ( self , viewer , keyname ) : # Is this a mode key? if keyname not in self . mode_map : if ( keyname not in self . mode_tbl ) or ( self . _kbdmode != 'meta' ) : # No return False bnch = self . mode_tbl [ keyname ] else : bnch = self . mode_map [ keyname ] mode_name = bnch . name self . logger . debug ( "cur mode='%s' mode pressed='%s'" % ( self . _kbdmode , mode_name ) ) if mode_name == self . _kbdmode : # <== same key was pressed that started the mode we're in # standard handling is to close the mode when we press the # key again that started that mode self . reset_mode ( viewer ) return True if self . _delayed_reset : # <== this shouldn't happen, but put here to reset handling # of delayed_reset just in case (see cursor up handling) self . _delayed_reset = False return True if ( ( self . _kbdmode in ( None , 'meta' ) ) or ( self . _kbdmode_type != 'locked' ) or ( mode_name == 'meta' ) ) : if self . _kbdmode is not None : self . reset_mode ( viewer ) # activate this mode if self . _kbdmode in ( None , 'meta' ) : mode_type = bnch . type if mode_type is None : mode_type = self . _kbdmode_type_default self . set_mode ( mode_name , mode_type ) if bnch . msg is not None : viewer . onscreen_message ( bnch . msg ) return True return False
This method is called when a key is pressed and was not handled by some other handler with precedence such as a subcanvas .
393
26
24,769
def mode_key_up ( self , viewer , keyname ) : # Is this a mode key? if keyname not in self . mode_map : # <== no return False bnch = self . mode_map [ keyname ] if self . _kbdmode == bnch . name : # <-- the current mode key is being released if bnch . type == 'held' : if self . _button == 0 : # if no button is being held, then reset mode self . reset_mode ( viewer ) else : self . _delayed_reset = True return True return False
This method is called when a key is pressed in a mode and was not handled by some other handler with precedence such as a subcanvas .
129
29
24,770
def get_4pt_bezier ( steps , points ) : for i in range ( steps ) : t = i / float ( steps ) xloc = ( math . pow ( 1 - t , 3 ) * points [ 0 ] [ 0 ] + 3 * t * math . pow ( 1 - t , 2 ) * points [ 1 ] [ 0 ] + 3 * ( 1 - t ) * math . pow ( t , 2 ) * points [ 2 ] [ 0 ] + math . pow ( t , 3 ) * points [ 3 ] [ 0 ] ) yloc = ( math . pow ( 1 - t , 3 ) * points [ 0 ] [ 1 ] + 3 * t * math . pow ( 1 - t , 2 ) * points [ 1 ] [ 1 ] + 3 * ( 1 - t ) * math . pow ( t , 2 ) * points [ 2 ] [ 1 ] + math . pow ( t , 3 ) * points [ 3 ] [ 1 ] ) yield ( xloc , yloc )
Gets a series of bezier curve points with 1 set of 4 control points .
215
18
24,771
def get_bezier ( steps , points ) : res = [ ] num_pts = len ( points ) for i in range ( 0 , num_pts + 1 , 3 ) : if i + 4 < num_pts + 1 : res . extend ( list ( get_4pt_bezier ( steps , points [ i : i + 4 ] ) ) ) return res
Gets a series of bezier curve points with any number of sets of 4 control points .
84
20
24,772
def get_bezier_ellipse ( x , y , xradius , yradius , kappa = 0.5522848 ) : xs , ys = x - xradius , y - yradius ox , oy = xradius * kappa , yradius * kappa xe , ye = x + xradius , y + yradius pts = [ ( xs , y ) , ( xs , y - oy ) , ( x - ox , ys ) , ( x , ys ) , ( x + ox , ys ) , ( xe , y - oy ) , ( xe , y ) , ( xe , y + oy ) , ( x + ox , ye ) , ( x , ye ) , ( x - ox , ye ) , ( xs , y + oy ) , ( xs , y ) ] return pts
Get a set of 12 bezier control points necessary to form an ellipse .
184
18
24,773
def set_cmap_cb ( self , w , index ) : name = cmap . get_names ( ) [ index ] self . t_ . set ( color_map = name )
This callback is invoked when the user selects a new color map from the preferences pane .
41
17
24,774
def set_imap_cb ( self , w , index ) : name = imap . get_names ( ) [ index ] self . t_ . set ( intensity_map = name )
This callback is invoked when the user selects a new intensity map from the preferences pane .
41
17
24,775
def set_calg_cb ( self , w , index ) : #index = w.get_index() name = self . calg_names [ index ] self . t_ . set ( color_algorithm = name )
This callback is invoked when the user selects a new color hashing algorithm from the preferences pane .
49
18
24,776
def autocut_params_changed_cb ( self , paramObj , ac_obj ) : args , kwdargs = paramObj . get_params ( ) params = list ( kwdargs . items ( ) ) self . t_ . set ( autocut_params = params )
This callback is called when the user changes the attributes of an object via the paramSet .
62
18
24,777
def set_sort_cb ( self , w , index ) : name = self . sort_options [ index ] self . t_ . set ( sort_order = name )
This callback is invoked when the user selects a new sort order from the preferences pane .
37
17
24,778
def set_scrollbars_cb ( self , w , tf ) : scrollbars = 'on' if tf else 'off' self . t_ . set ( scrollbars = scrollbars )
This callback is invoked when the user checks the Use Scrollbars box in the preferences pane .
40
18
24,779
def zoomset_cb ( self , setting , value , channel ) : if not self . gui_up : return info = channel . extdata . _info_info if info is None : return #scale_x, scale_y = fitsimage.get_scale_xy() scale_x , scale_y = value # Set text showing zoom factor (1X, 2X, etc.) if scale_x == scale_y : text = self . fv . scale2text ( scale_x ) else : textx = self . fv . scale2text ( scale_x ) texty = self . fv . scale2text ( scale_y ) text = "X: %s Y: %s" % ( textx , texty ) info . winfo . zoom . set_text ( text )
This callback is called when the main window is zoomed .
174
12
24,780
def redo ( self ) : image = self . channel . get_current_image ( ) if image is None : return True path = image . get ( 'path' , None ) if path is None : self . fv . show_error ( "Cannot open image: no value for metadata key 'path'" ) return # TODO: How to properly reset GUI components? # They are still showing info from prev FITS. # No-op for ASDF if path . endswith ( 'asdf' ) : return True if path != self . img_path : # <-- New file is being looked at self . img_path = path # close previous file opener, if any if self . file_obj is not None : try : self . file_obj . close ( ) except Exception : pass self . file_obj = io_fits . get_fitsloader ( logger = self . logger ) # TODO: specify 'readonly' somehow? self . file_obj . open_file ( path ) upper = len ( self . file_obj ) - 1 self . prep_hdu_menu ( self . w . hdu , self . file_obj . hdu_info ) self . num_hdu = upper self . logger . debug ( "there are %d hdus" % ( upper + 1 ) ) self . w . numhdu . set_text ( "%d" % ( upper + 1 ) ) self . w . hdu . set_enabled ( len ( self . file_obj ) > 0 ) name = image . get ( 'name' , iohelper . name_image_from_path ( path ) ) idx = image . get ( 'idx' , None ) # remove index designation from root of name, if any match = re . match ( r'^(.+)\[(.+)\]$' , name ) if match : name = match . group ( 1 ) self . name_pfx = name htype = None if idx is not None : # set the HDU in the drop down if known info = self . file_obj . hdu_db . get ( idx , None ) if info is not None : htype = info . htype . lower ( ) toc_ent = self . _toc_fmt % info self . w . hdu . show_text ( toc_ent ) # rebuild the NAXIS controls, if necessary # No two images in the same channel can have the same name. # Here we keep track of the name to decide if we need to rebuild if self . img_name != name : self . img_name = name dims = [ 0 , 0 ] data = image . get_data ( ) if data is None : # <- empty data part to this HDU self . logger . warning ( "Empty data part in HDU %s" % ( str ( idx ) ) ) elif htype in ( 'bintablehdu' , 'tablehdu' , ) : pass elif htype not in ( 'imagehdu' , 'primaryhdu' , 'compimagehdu' ) : self . logger . warning ( "HDU %s is not an image (%s)" % ( str ( idx ) , htype ) ) else : mddata = image . get_mddata ( ) if mddata is not None : dims = list ( mddata . shape ) dims . reverse ( ) self . build_naxis ( dims , image )
Called when an image is set in the channel .
753
11
24,781
def reorder_image ( dst_order , src_arr , src_order ) : depth = src_arr . shape [ 2 ] if depth != len ( src_order ) : raise ValueError ( "src_order (%s) does not match array depth (%d)" % ( src_order , depth ) ) bands = [ ] if dst_order == src_order : return np . ascontiguousarray ( src_arr ) elif 'A' not in dst_order or 'A' in src_order : # <-- we don't have to add an alpha plane, just create a new view idx = np . array ( [ src_order . index ( c ) for c in dst_order ] ) return np . ascontiguousarray ( src_arr [ ... , idx ] ) else : # <-- dst order requires missing alpha channel indexes = [ src_order . index ( c ) for c in dst_order . replace ( 'A' , '' ) ] bands = [ src_arr [ ... , idx , np . newaxis ] for idx in indexes ] ht , wd = src_arr . shape [ : 2 ] dst_type = src_arr . dtype dst_max_val = np . iinfo ( dst_type ) . max alpha = np . full ( ( ht , wd , 1 ) , dst_max_val , dtype = dst_type ) bands . insert ( dst_order . index ( 'A' ) , alpha ) return np . concatenate ( bands , axis = - 1 )
Reorder src_arr with order of color planes in src_order as dst_order .
334
19
24,782
def strip_z ( pts ) : pts = np . asarray ( pts ) if pts . shape [ - 1 ] > 2 : pts = np . asarray ( ( pts . T [ 0 ] , pts . T [ 1 ] ) ) . T return pts
Strips a Z component from pts if it is present .
55
13
24,783
def get_bounds ( pts ) : pts_t = np . asarray ( pts ) . T return np . asarray ( ( [ np . min ( _pts ) for _pts in pts_t ] , [ np . max ( _pts ) for _pts in pts_t ] ) )
Return the minimum point and maximum point bounding a set of points .
68
14
24,784
def trim_prefix ( text , nchr ) : res = [ ] for line in text . split ( '\n' ) : if line . startswith ( ' ' * nchr ) : line = line [ nchr : ] res . append ( line ) return '\n' . join ( res )
Trim characters off of the beginnings of text lines .
69
11
24,785
def _get_color ( self , r , g , b ) : clr = ( r , g , b ) return clr
Convert red green and blue values specified in floats with range 0 - 1 to whatever the native widget color object is .
28
24
24,786
def key_press_event ( self , widget , event ) : # get keyname or keycode and translate to ginga standard # keyname = # keycode = keyname = '' # self.transkey(keyname, keycode) self . logger . debug ( "key press event, key=%s" % ( keyname ) ) return self . make_ui_callback ( 'key-press' , keyname )
Called when a key is pressed and the window has the focus . Adjust method signature as appropriate for callback .
93
22
24,787
def key_release_event ( self , widget , event ) : # get keyname or keycode and translate to ginga standard # keyname = # keycode = keyname = '' # self.transkey(keyname, keycode) self . logger . debug ( "key release event, key=%s" % ( keyname ) ) return self . make_ui_callback ( 'key-release' , keyname )
Called when a key is released after being pressed . Adjust method signature as appropriate for callback .
93
19
24,788
def resizeEvent ( self , event ) : vp = self . viewport ( ) rect = vp . geometry ( ) x1 , y1 , x2 , y2 = rect . getCoords ( ) width = x2 - x1 + 1 height = y2 - y1 + 1 self . v_w . resize ( width , height )
Override from QAbstractScrollArea . Resize the viewer widget when the viewport is resized .
75
20
24,789
def scrollContentsBy ( self , dx , dy ) : if self . _adjusting : return self . _scrolling = True try : bd = self . viewer . get_bindings ( ) res = bd . calc_pan_pct ( self . viewer , pad = self . pad ) if res is None : return pct_x , pct_y = res . pan_pct_x , res . pan_pct_y # Only adjust pan setting for axes that have changed if dx != 0 : hsb = self . horizontalScrollBar ( ) pos_x = float ( hsb . value ( ) ) pct_x = pos_x / float ( self . upper_h ) if dy != 0 : vsb = self . verticalScrollBar ( ) pos_y = float ( vsb . value ( ) ) # invert Y pct because of orientation of scrollbar pct_y = 1.0 - ( pos_y / float ( self . upper_v ) ) bd = self . viewer . get_bindings ( ) bd . pan_by_pct ( self . viewer , pct_x , pct_y , pad = self . pad ) # This shouldn't be necessary, but seems to be self . viewer . redraw ( whence = 0 ) finally : self . _scrolling = False
Override from QAbstractScrollArea . Called when the scroll bars are adjusted by the user .
289
18
24,790
def get_catalog ( ) : tforms = { } for name , value in list ( globals ( ) . items ( ) ) : if name . endswith ( 'Transform' ) : tforms [ name ] = value return Bunch . Bunch ( tforms , caseless = True )
Returns a catalog of available transforms . These are used to build chains for rendering with different back ends .
64
20
24,791
def masktorgb ( mask , color = 'lightgreen' , alpha = 1.0 ) : mask = np . asarray ( mask ) if mask . ndim != 2 : raise ValueError ( 'ndim={0} is not supported' . format ( mask . ndim ) ) ht , wd = mask . shape r , g , b = colors . lookup_color ( color ) rgbobj = RGBImage ( data_np = np . zeros ( ( ht , wd , 4 ) , dtype = np . uint8 ) ) rc = rgbobj . get_slice ( 'R' ) gc = rgbobj . get_slice ( 'G' ) bc = rgbobj . get_slice ( 'B' ) ac = rgbobj . get_slice ( 'A' ) ac [ : ] = 0 # Transparent background rc [ mask ] = int ( r * 255 ) gc [ mask ] = int ( g * 255 ) bc [ mask ] = int ( b * 255 ) ac [ mask ] = int ( alpha * 255 ) # For debugging #rgbobj.save_as_file('ztmp_rgbobj.png') return rgbobj
Convert boolean mask to RGB image object for canvas overlay .
254
12
24,792
def _find_rtd_version ( ) : vstr = 'latest' try : import ginga from bs4 import BeautifulSoup except ImportError : return vstr # No active doc build before this release, just use latest. if not minversion ( ginga , '2.6.0' ) : return vstr # Get RTD download listing. url = 'https://readthedocs.org/projects/ginga/downloads/' with urllib . request . urlopen ( url ) as r : soup = BeautifulSoup ( r , 'html.parser' ) # Compile a list of available HTML doc versions for download. all_rtd_vernums = [ ] for link in soup . find_all ( 'a' ) : href = link . get ( 'href' ) if 'htmlzip' not in href : continue s = href . split ( '/' ) [ - 2 ] if s . startswith ( 'v' ) : # Ignore latest and stable all_rtd_vernums . append ( s ) all_rtd_vernums . sort ( reverse = True ) # Find closest match. ginga_ver = ginga . __version__ for rtd_ver in all_rtd_vernums : if ginga_ver > rtd_ver [ 1 : ] : # Ignore "v" in comparison break else : vstr = rtd_ver return vstr
Find closest RTD doc version .
311
7
24,793
def _download_rtd_zip ( rtd_version = None , * * kwargs ) : # https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134 if not toolkit . family . startswith ( 'qt' ) : raise ValueError ( 'Downloaded documentation not compatible with {} ' 'UI toolkit browser' . format ( toolkit . family ) ) if rtd_version is None : rtd_version = _find_rtd_version ( ) data_path = os . path . dirname ( _find_pkg_data_path ( 'help.html' , package = 'ginga.doc' ) ) index_html = os . path . join ( data_path , 'index.html' ) # There is a previous download of documentation; Do nothing. # There is no check if downloaded version is outdated; The idea is that # this folder would be empty again when installing new version. if os . path . isfile ( index_html ) : return index_html url = ( 'https://readthedocs.org/projects/ginga/downloads/htmlzip/' '{}/' . format ( rtd_version ) ) local_path = urllib . request . urlretrieve ( url , * * kwargs ) [ 0 ] with zipfile . ZipFile ( local_path , 'r' ) as zf : zf . extractall ( data_path ) # RTD makes an undesirable sub-directory, so move everything there # up one level and delete it. subdir = os . path . join ( data_path , 'ginga-{}' . format ( rtd_version ) ) for s in os . listdir ( subdir ) : src = os . path . join ( subdir , s ) if os . path . isfile ( src ) : shutil . copy ( src , data_path ) else : # directory shutil . copytree ( src , os . path . join ( data_path , s ) ) shutil . rmtree ( subdir ) if not os . path . isfile ( index_html ) : raise OSError ( '{} is missing; Ginga doc download failed' . format ( index_html ) ) return index_html
Download and extract HTML ZIP from RTD to installed doc data path . Download is skipped if content already exists .
498
22
24,794
def get_doc ( logger = None , plugin = None , reporthook = None ) : from ginga . GingaPlugin import GlobalPlugin , LocalPlugin if isinstance ( plugin , GlobalPlugin ) : plugin_page = 'plugins_global' plugin_name = str ( plugin ) elif isinstance ( plugin , LocalPlugin ) : plugin_page = 'plugins_local' plugin_name = str ( plugin ) else : plugin_page = None plugin_name = None try : index_html = _download_rtd_zip ( reporthook = reporthook ) # Download failed, use online resource except Exception as e : url = 'https://ginga.readthedocs.io/en/latest/' if plugin_name is not None : if toolkit . family . startswith ( 'qt' ) : # This displays plugin docstring. url = None else : # This redirects to online doc. url += 'manual/{}/{}.html' . format ( plugin_page , plugin_name ) if logger is not None : logger . error ( str ( e ) ) # Use local resource else : pfx = 'file:' url = '{}{}' . format ( pfx , index_html ) # https://github.com/rtfd/readthedocs.org/issues/2803 if plugin_name is not None : url += '#{}' . format ( plugin_name ) return url
Return URL to documentation . Attempt download if does not exist .
313
12
24,795
def redo ( self , * args ) : if not self . gui_up : return mod_only = self . w . modified_only . get_state ( ) treedict = Bunch . caselessDict ( ) self . treeview . clear ( ) self . w . status . set_text ( '' ) channel = self . fv . get_channel ( self . chname ) if channel is None : return # Only list modified images for saving. Scanning Datasrc is enough. if mod_only : all_keys = channel . datasrc . keys ( sort = 'alpha' ) # List all images in the channel. else : all_keys = channel . get_image_names ( ) # Extract info for listing and saving for key in all_keys : iminfo = channel . get_image_info ( key ) path = iminfo . get ( 'path' ) idx = iminfo . get ( 'idx' ) t = iminfo . get ( 'time_modified' ) if path is None : # Special handling for generated buffer, eg mosaic infile = key is_fits = True else : infile = os . path . basename ( path ) infile_ext = os . path . splitext ( path ) [ 1 ] infile_ext = infile_ext . lower ( ) is_fits = False if 'fit' in infile_ext : is_fits = True # Only list FITS files unless it is Ginga generated buffer if not is_fits : continue # Only list modified buffers if mod_only and t is None : continue # More than one ext modified, append to existing entry if infile in treedict : if t is not None : treedict [ infile ] . extlist . add ( idx ) elist = sorted ( treedict [ infile ] . extlist ) treedict [ infile ] . MODEXT = ';' . join ( map ( self . _format_extname , elist ) ) # Add new entry else : if t is None : s = '' extlist = set ( ) else : s = self . _format_extname ( idx ) extlist = set ( [ idx ] ) treedict [ infile ] = Bunch . Bunch ( IMAGE = infile , MODEXT = s , extlist = extlist , path = path ) self . treeview . set_tree ( treedict ) # Resize column widths n_rows = len ( treedict ) if n_rows == 0 : self . w . status . set_text ( 'Nothing available for saving' ) elif n_rows < self . settings . get ( 'max_rows_for_col_resize' , 5000 ) : self . treeview . set_optimal_column_widths ( ) self . logger . debug ( 'Resized columns for {0} row(s)' . format ( n_rows ) )
Generate listing of images that user can save .
630
10
24,796
def update_channels ( self ) : if not self . gui_up : return self . logger . debug ( "channel configuration has changed--updating gui" ) try : channel = self . fv . get_channel ( self . chname ) except KeyError : channel = self . fv . get_channel_info ( ) if channel is None : raise ValueError ( 'No channel available' ) self . chname = channel . name w = self . w . channel_name w . clear ( ) self . chnames = list ( self . fv . get_channel_names ( ) ) #self.chnames.sort() for chname in self . chnames : w . append_text ( chname ) # select the channel that is the current one try : i = self . chnames . index ( channel . name ) except IndexError : i = 0 self . w . channel_name . set_index ( i ) # update the image listing self . redo ( )
Update the GUI to reflect channels and image listing .
210
10
24,797
def _format_extname ( self , ext ) : if ext is None : outs = ext else : outs = '{0},{1}' . format ( ext [ 0 ] , ext [ 1 ] ) return outs
Pretty print given extension name and number tuple .
47
9
24,798
def browse_outdir ( self ) : self . dirsel . popup ( 'Select directory' , self . w . outdir . set_text , initialdir = self . outdir ) self . set_outdir ( )
Browse for output directory .
48
6
24,799
def set_outdir ( self ) : dirname = self . w . outdir . get_text ( ) if os . path . isdir ( dirname ) : self . outdir = dirname self . logger . debug ( 'Output directory set to {0}' . format ( self . outdir ) ) else : self . w . outdir . set_text ( self . outdir ) self . logger . error ( '{0} is not a directory' . format ( dirname ) )
Set output directory .
107
4