repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ejeschke/ginga
ginga/mockw/ImageViewMock.py
ImageViewEvent.key_press_event
def key_press_event(self, widget, event): """ Called when a key is pressed and the window has the focus. Adjust method signature as appropriate for callback. """ # 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)
python
def key_press_event(self, widget, event): """ Called when a key is pressed and the window has the focus. Adjust method signature as appropriate for callback. """ # 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)
[ "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", "(", "...
Called when a key is pressed and the window has the focus. Adjust method signature as appropriate for callback.
[ "Called", "when", "a", "key", "is", "pressed", "and", "the", "window", "has", "the", "focus", ".", "Adjust", "method", "signature", "as", "appropriate", "for", "callback", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mockw/ImageViewMock.py#L309-L319
train
24,900
ejeschke/ginga
ginga/mockw/ImageViewMock.py
ImageViewEvent.key_release_event
def key_release_event(self, widget, event): """ Called when a key is released after being pressed. Adjust method signature as appropriate for callback. """ # 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)
python
def key_release_event(self, widget, event): """ Called when a key is released after being pressed. Adjust method signature as appropriate for callback. """ # 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)
[ "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", "(", ...
Called when a key is released after being pressed. Adjust method signature as appropriate for callback.
[ "Called", "when", "a", "key", "is", "released", "after", "being", "pressed", ".", "Adjust", "method", "signature", "as", "appropriate", "for", "callback", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mockw/ImageViewMock.py#L321-L331
train
24,901
ejeschke/ginga
ginga/qtw/ImageViewQt.py
ScrolledView.resizeEvent
def resizeEvent(self, event): """Override from QAbstractScrollArea. Resize the viewer widget when the viewport is resized.""" 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)
python
def resizeEvent(self, event): """Override from QAbstractScrollArea. Resize the viewer widget when the viewport is resized.""" 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)
[ "def", "resizeEvent", "(", "self", ",", "event", ")", ":", "vp", "=", "self", ".", "viewport", "(", ")", "rect", "=", "vp", ".", "geometry", "(", ")", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "rect", ".", "getCoords", "(", ")", "width", "=",...
Override from QAbstractScrollArea. Resize the viewer widget when the viewport is resized.
[ "Override", "from", "QAbstractScrollArea", ".", "Resize", "the", "viewer", "widget", "when", "the", "viewport", "is", "resized", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/ImageViewQt.py#L879-L888
train
24,902
ejeschke/ginga
ginga/qtw/ImageViewQt.py
ScrolledView.scrollContentsBy
def scrollContentsBy(self, dx, dy): """Override from QAbstractScrollArea. Called when the scroll bars are adjusted by the user. """ 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
python
def scrollContentsBy(self, dx, dy): """Override from QAbstractScrollArea. Called when the scroll bars are adjusted by the user. """ 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
[ "def", "scrollContentsBy", "(", "self", ",", "dx", ",", "dy", ")", ":", "if", "self", ".", "_adjusting", ":", "return", "self", ".", "_scrolling", "=", "True", "try", ":", "bd", "=", "self", ".", "viewer", ".", "get_bindings", "(", ")", "res", "=", ...
Override from QAbstractScrollArea. Called when the scroll bars are adjusted by the user.
[ "Override", "from", "QAbstractScrollArea", ".", "Called", "when", "the", "scroll", "bars", "are", "adjusted", "by", "the", "user", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/ImageViewQt.py#L927-L960
train
24,903
ejeschke/ginga
ginga/canvas/transform.py
get_catalog
def get_catalog(): """Returns a catalog of available transforms. These are used to build chains for rendering with different back ends. """ tforms = {} for name, value in list(globals().items()): if name.endswith('Transform'): tforms[name] = value return Bunch.Bunch(tforms, caseless=True)
python
def get_catalog(): """Returns a catalog of available transforms. These are used to build chains for rendering with different back ends. """ tforms = {} for name, value in list(globals().items()): if name.endswith('Transform'): tforms[name] = value return Bunch.Bunch(tforms, caseless=True)
[ "def", "get_catalog", "(", ")", ":", "tforms", "=", "{", "}", "for", "name", ",", "value", "in", "list", "(", "globals", "(", ")", ".", "items", "(", ")", ")", ":", "if", "name", ".", "endswith", "(", "'Transform'", ")", ":", "tforms", "[", "name...
Returns a catalog of available transforms. These are used to build chains for rendering with different back ends.
[ "Returns", "a", "catalog", "of", "available", "transforms", ".", "These", "are", "used", "to", "build", "chains", "for", "rendering", "with", "different", "back", "ends", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/transform.py#L553-L562
train
24,904
ejeschke/ginga
ginga/util/dp.py
masktorgb
def masktorgb(mask, color='lightgreen', alpha=1.0): """Convert boolean mask to RGB image object for canvas overlay. Parameters ---------- mask : ndarray Boolean mask to overlay. 2D image only. color : str Color name accepted by Ginga. alpha : float Opacity. Unmasked data are always transparent. Returns ------- rgbobj : RGBImage RGB image for canvas Image object. Raises ------ ValueError Invalid mask dimension. """ 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
python
def masktorgb(mask, color='lightgreen', alpha=1.0): """Convert boolean mask to RGB image object for canvas overlay. Parameters ---------- mask : ndarray Boolean mask to overlay. 2D image only. color : str Color name accepted by Ginga. alpha : float Opacity. Unmasked data are always transparent. Returns ------- rgbobj : RGBImage RGB image for canvas Image object. Raises ------ ValueError Invalid mask dimension. """ 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
[ "def", "masktorgb", "(", "mask", ",", "color", "=", "'lightgreen'", ",", "alpha", "=", "1.0", ")", ":", "mask", "=", "np", ".", "asarray", "(", "mask", ")", "if", "mask", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'ndim={0} is not suppor...
Convert boolean mask to RGB image object for canvas overlay. Parameters ---------- mask : ndarray Boolean mask to overlay. 2D image only. color : str Color name accepted by Ginga. alpha : float Opacity. Unmasked data are always transparent. Returns ------- rgbobj : RGBImage RGB image for canvas Image object. Raises ------ ValueError Invalid mask dimension.
[ "Convert", "boolean", "mask", "to", "RGB", "image", "object", "for", "canvas", "overlay", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/dp.py#L206-L254
train
24,905
ejeschke/ginga
ginga/doc/download_doc.py
_find_rtd_version
def _find_rtd_version(): """Find closest RTD doc 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
python
def _find_rtd_version(): """Find closest RTD doc 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
[ "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", "mi...
Find closest RTD doc version.
[ "Find", "closest", "RTD", "doc", "version", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L15-L52
train
24,906
ejeschke/ginga
ginga/doc/download_doc.py
_download_rtd_zip
def _download_rtd_zip(rtd_version=None, **kwargs): """ Download and extract HTML ZIP from RTD to installed doc data path. Download is skipped if content already exists. Parameters ---------- rtd_version : str or `None` RTD version to download; e.g., "latest", "stable", or "v2.6.0". If not given, download closest match to software version. kwargs : dict Keywords for ``urlretrieve()``. Returns ------- index_html : str Path to local "index.html". """ # 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
python
def _download_rtd_zip(rtd_version=None, **kwargs): """ Download and extract HTML ZIP from RTD to installed doc data path. Download is skipped if content already exists. Parameters ---------- rtd_version : str or `None` RTD version to download; e.g., "latest", "stable", or "v2.6.0". If not given, download closest match to software version. kwargs : dict Keywords for ``urlretrieve()``. Returns ------- index_html : str Path to local "index.html". """ # 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
[ "def", "_download_rtd_zip", "(", "rtd_version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134", "if", "not", "toolkit", ".", "family", ".", "startswith", "(", "'qt'", ")", ":", "raise", "ValueErr...
Download and extract HTML ZIP from RTD to installed doc data path. Download is skipped if content already exists. Parameters ---------- rtd_version : str or `None` RTD version to download; e.g., "latest", "stable", or "v2.6.0". If not given, download closest match to software version. kwargs : dict Keywords for ``urlretrieve()``. Returns ------- index_html : str Path to local "index.html".
[ "Download", "and", "extract", "HTML", "ZIP", "from", "RTD", "to", "installed", "doc", "data", "path", ".", "Download", "is", "skipped", "if", "content", "already", "exists", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L55-L115
train
24,907
ejeschke/ginga
ginga/doc/download_doc.py
get_doc
def get_doc(logger=None, plugin=None, reporthook=None): """ Return URL to documentation. Attempt download if does not exist. Parameters ---------- logger : obj or `None` Ginga logger. plugin : obj or `None` Plugin object. If given, URL points to plugin doc directly. If this function is called from within plugin class, pass ``self`` here. reporthook : callable or `None` Report hook for ``urlretrieve()``. Returns ------- url : str or `None` URL to local documentation, if available. """ 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
python
def get_doc(logger=None, plugin=None, reporthook=None): """ Return URL to documentation. Attempt download if does not exist. Parameters ---------- logger : obj or `None` Ginga logger. plugin : obj or `None` Plugin object. If given, URL points to plugin doc directly. If this function is called from within plugin class, pass ``self`` here. reporthook : callable or `None` Report hook for ``urlretrieve()``. Returns ------- url : str or `None` URL to local documentation, if available. """ 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
[ "def", "get_doc", "(", "logger", "=", "None", ",", "plugin", "=", "None", ",", "reporthook", "=", "None", ")", ":", "from", "ginga", ".", "GingaPlugin", "import", "GlobalPlugin", ",", "LocalPlugin", "if", "isinstance", "(", "plugin", ",", "GlobalPlugin", "...
Return URL to documentation. Attempt download if does not exist. Parameters ---------- logger : obj or `None` Ginga logger. plugin : obj or `None` Plugin object. If given, URL points to plugin doc directly. If this function is called from within plugin class, pass ``self`` here. reporthook : callable or `None` Report hook for ``urlretrieve()``. Returns ------- url : str or `None` URL to local documentation, if available.
[ "Return", "URL", "to", "documentation", ".", "Attempt", "download", "if", "does", "not", "exist", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L118-L180
train
24,908
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.redo
def redo(self, *args): """Generate listing of images that user can save.""" 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))
python
def redo(self, *args): """Generate listing of images that user can save.""" 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))
[ "def", "redo", "(", "self", ",", "*", "args", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "mod_only", "=", "self", ".", "w", ".", "modified_only", ".", "get_state", "(", ")", "treedict", "=", "Bunch", ".", "caselessDict", "(", ")", ...
Generate listing of images that user can save.
[ "Generate", "listing", "of", "images", "that", "user", "can", "save", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L181-L257
train
24,909
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.update_channels
def update_channels(self): """Update the GUI to reflect channels and image listing. """ 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()
python
def update_channels(self): """Update the GUI to reflect channels and image listing. """ 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()
[ "def", "update_channels", "(", "self", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "self", ".", "logger", ".", "debug", "(", "\"channel configuration has changed--updating gui\"", ")", "try", ":", "channel", "=", "self", ".", "fv", ".", "get...
Update the GUI to reflect channels and image listing.
[ "Update", "the", "GUI", "to", "reflect", "channels", "and", "image", "listing", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L259-L293
train
24,910
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage._format_extname
def _format_extname(self, ext): """Pretty print given extension name and number tuple.""" if ext is None: outs = ext else: outs = '{0},{1}'.format(ext[0], ext[1]) return outs
python
def _format_extname(self, ext): """Pretty print given extension name and number tuple.""" if ext is None: outs = ext else: outs = '{0},{1}'.format(ext[0], ext[1]) return outs
[ "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.
[ "Pretty", "print", "given", "extension", "name", "and", "number", "tuple", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L300-L306
train
24,911
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.browse_outdir
def browse_outdir(self): """Browse for output directory.""" self.dirsel.popup( 'Select directory', self.w.outdir.set_text, initialdir=self.outdir) self.set_outdir()
python
def browse_outdir(self): """Browse for output directory.""" self.dirsel.popup( 'Select directory', self.w.outdir.set_text, initialdir=self.outdir) self.set_outdir()
[ "def", "browse_outdir", "(", "self", ")", ":", "self", ".", "dirsel", ".", "popup", "(", "'Select directory'", ",", "self", ".", "w", ".", "outdir", ".", "set_text", ",", "initialdir", "=", "self", ".", "outdir", ")", "self", ".", "set_outdir", "(", ")...
Browse for output directory.
[ "Browse", "for", "output", "directory", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L308-L312
train
24,912
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.set_outdir
def set_outdir(self): """Set output directory.""" 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))
python
def set_outdir(self): """Set output directory.""" 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))
[ "def", "set_outdir", "(", "self", ")", ":", "dirname", "=", "self", ".", "w", ".", "outdir", ".", "get_text", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "self", ".", "outdir", "=", "dirname", "self", ".", "logger", ...
Set output directory.
[ "Set", "output", "directory", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L314-L322
train
24,913
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.set_suffix
def set_suffix(self): """Set output suffix.""" self.suffix = self.w.suffix.get_text() self.logger.debug('Output suffix set to {0}'.format(self.suffix))
python
def set_suffix(self): """Set output suffix.""" self.suffix = self.w.suffix.get_text() self.logger.debug('Output suffix set to {0}'.format(self.suffix))
[ "def", "set_suffix", "(", "self", ")", ":", "self", ".", "suffix", "=", "self", ".", "w", ".", "suffix", ".", "get_text", "(", ")", "self", ".", "logger", ".", "debug", "(", "'Output suffix set to {0}'", ".", "format", "(", "self", ".", "suffix", ")", ...
Set output suffix.
[ "Set", "output", "suffix", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L324-L327
train
24,914
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage._write_history
def _write_history(self, pfx, hdu, linechar=60, indentchar=2): """Write change history to given HDU header. Limit each HISTORY line to given number of characters. Subsequent lines of the same history will be indented. """ channel = self.fv.get_channel(self.chname) if channel is None: return history_plgname = 'ChangeHistory' try: history_obj = self.fv.gpmon.getPlugin(history_plgname) except Exception: self.logger.error( '{0} plugin is not loaded. No HISTORY will be written to ' '{1}.'.format(history_plgname, pfx)) return if channel.name not in history_obj.name_dict: self.logger.error( '{0} channel not found in {1}. No HISTORY will be written to ' '{2}.'.format(channel.name, history_plgname, pfx)) return file_dict = history_obj.name_dict[channel.name] chistory = [] ind = ' ' * indentchar # NOTE: List comprehension too slow! for key in file_dict: if not key.startswith(pfx): continue for bnch in file_dict[key].values(): chistory.append('{0} {1}'.format(bnch.MODIFIED, bnch.DESCRIP)) # Add each HISTORY prettily into header, sorted by timestamp for s in sorted(chistory): for i in range(0, len(s), linechar): subs = s[i:i + linechar] if i > 0: subs = ind + subs.lstrip() hdu.header.add_history(subs)
python
def _write_history(self, pfx, hdu, linechar=60, indentchar=2): """Write change history to given HDU header. Limit each HISTORY line to given number of characters. Subsequent lines of the same history will be indented. """ channel = self.fv.get_channel(self.chname) if channel is None: return history_plgname = 'ChangeHistory' try: history_obj = self.fv.gpmon.getPlugin(history_plgname) except Exception: self.logger.error( '{0} plugin is not loaded. No HISTORY will be written to ' '{1}.'.format(history_plgname, pfx)) return if channel.name not in history_obj.name_dict: self.logger.error( '{0} channel not found in {1}. No HISTORY will be written to ' '{2}.'.format(channel.name, history_plgname, pfx)) return file_dict = history_obj.name_dict[channel.name] chistory = [] ind = ' ' * indentchar # NOTE: List comprehension too slow! for key in file_dict: if not key.startswith(pfx): continue for bnch in file_dict[key].values(): chistory.append('{0} {1}'.format(bnch.MODIFIED, bnch.DESCRIP)) # Add each HISTORY prettily into header, sorted by timestamp for s in sorted(chistory): for i in range(0, len(s), linechar): subs = s[i:i + linechar] if i > 0: subs = ind + subs.lstrip() hdu.header.add_history(subs)
[ "def", "_write_history", "(", "self", ",", "pfx", ",", "hdu", ",", "linechar", "=", "60", ",", "indentchar", "=", "2", ")", ":", "channel", "=", "self", ".", "fv", ".", "get_channel", "(", "self", ".", "chname", ")", "if", "channel", "is", "None", ...
Write change history to given HDU header. Limit each HISTORY line to given number of characters. Subsequent lines of the same history will be indented.
[ "Write", "change", "history", "to", "given", "HDU", "header", ".", "Limit", "each", "HISTORY", "line", "to", "given", "number", "of", "characters", ".", "Subsequent", "lines", "of", "the", "same", "history", "will", "be", "indented", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L329-L370
train
24,915
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage._write_header
def _write_header(self, image, hdu): """Write header from image object to given HDU.""" hduhdr = hdu.header # Ginga image header object for the given extension only. # Cannot use get_header() because that might also return PRI hdr. ghdr = image.metadata['header'] for key in ghdr: # Need this to avoid duplication because COMMENT is a weird field if key.upper() == 'COMMENT': continue bnch = ghdr.get_card(key) # Insert new keyword if key not in hduhdr: hduhdr[key] = (bnch.value, bnch.comment) # Update existing keyword elif hduhdr[key] != bnch.value: hduhdr[key] = bnch.value
python
def _write_header(self, image, hdu): """Write header from image object to given HDU.""" hduhdr = hdu.header # Ginga image header object for the given extension only. # Cannot use get_header() because that might also return PRI hdr. ghdr = image.metadata['header'] for key in ghdr: # Need this to avoid duplication because COMMENT is a weird field if key.upper() == 'COMMENT': continue bnch = ghdr.get_card(key) # Insert new keyword if key not in hduhdr: hduhdr[key] = (bnch.value, bnch.comment) # Update existing keyword elif hduhdr[key] != bnch.value: hduhdr[key] = bnch.value
[ "def", "_write_header", "(", "self", ",", "image", ",", "hdu", ")", ":", "hduhdr", "=", "hdu", ".", "header", "# Ginga image header object for the given extension only.", "# Cannot use get_header() because that might also return PRI hdr.", "ghdr", "=", "image", ".", "metada...
Write header from image object to given HDU.
[ "Write", "header", "from", "image", "object", "to", "given", "HDU", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L372-L393
train
24,916
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage._write_mef
def _write_mef(self, key, extlist, outfile): """Write out regular multi-extension FITS data.""" channel = self.fv.get_channel(self.chname) with fits.open(outfile, mode='update') as pf: # Process each modified data extension for idx in extlist: k = '{0}[{1}]'.format(key, self._format_extname(idx)) image = channel.datasrc[k] # Insert data and header into output HDU pf[idx].data = image.get_data() self._write_header(image, pf[idx]) # Write history to PRIMARY self._write_history(key, pf['PRIMARY'])
python
def _write_mef(self, key, extlist, outfile): """Write out regular multi-extension FITS data.""" channel = self.fv.get_channel(self.chname) with fits.open(outfile, mode='update') as pf: # Process each modified data extension for idx in extlist: k = '{0}[{1}]'.format(key, self._format_extname(idx)) image = channel.datasrc[k] # Insert data and header into output HDU pf[idx].data = image.get_data() self._write_header(image, pf[idx]) # Write history to PRIMARY self._write_history(key, pf['PRIMARY'])
[ "def", "_write_mef", "(", "self", ",", "key", ",", "extlist", ",", "outfile", ")", ":", "channel", "=", "self", ".", "fv", ".", "get_channel", "(", "self", ".", "chname", ")", "with", "fits", ".", "open", "(", "outfile", ",", "mode", "=", "'update'",...
Write out regular multi-extension FITS data.
[ "Write", "out", "regular", "multi", "-", "extension", "FITS", "data", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L424-L438
train
24,917
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.toggle_save_cb
def toggle_save_cb(self, w, res_dict): """Only enable saving if something is selected.""" if len(res_dict) > 0: self.w.save.set_enabled(True) else: self.w.save.set_enabled(False)
python
def toggle_save_cb(self, w, res_dict): """Only enable saving if something is selected.""" if len(res_dict) > 0: self.w.save.set_enabled(True) else: self.w.save.set_enabled(False)
[ "def", "toggle_save_cb", "(", "self", ",", "w", ",", "res_dict", ")", ":", "if", "len", "(", "res_dict", ")", ">", "0", ":", "self", ".", "w", ".", "save", ".", "set_enabled", "(", "True", ")", "else", ":", "self", ".", "w", ".", "save", ".", "...
Only enable saving if something is selected.
[ "Only", "enable", "saving", "if", "something", "is", "selected", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L440-L445
train
24,918
ejeschke/ginga
ginga/rv/plugins/SaveImage.py
SaveImage.save_images
def save_images(self): """Save selected images. This uses Astropy FITS package to save the outputs no matter what user chose to load the images. """ res_dict = self.treeview.get_selected() clobber = self.settings.get('clobber', False) self.treeview.clear_selection() # Automatically disables Save button # If user gives empty string, no suffix. if self.suffix: sfx = '_' + self.suffix else: sfx = '' # Also include channel name in suffix. This is useful if user likes to # open the same image in multiple channels. if self.settings.get('include_chname', True): sfx += '_' + self.chname # Process each selected file. Each can have multiple edited extensions. for infile in res_dict: f_pfx = os.path.splitext(infile)[0] # prefix f_ext = '.fits' # Only FITS supported oname = f_pfx + sfx + f_ext outfile = os.path.join(self.outdir, oname) self.w.status.set_text( 'Writing out {0} to {1} ...'.format(shorten_name(infile, 10), shorten_name(oname, 10))) self.logger.debug( 'Writing out {0} to {1} ...'.format(infile, oname)) if os.path.exists(outfile) and not clobber: self.logger.error('{0} already exists'.format(outfile)) continue bnch = res_dict[infile] if bnch.path is None or not os.path.isfile(bnch.path): self._write_mosaic(f_pfx, outfile) else: shutil.copyfile(bnch.path, outfile) self._write_mef(f_pfx, bnch.extlist, outfile) self.logger.info('{0} written'.format(outfile)) self.w.status.set_text('Saving done, see log')
python
def save_images(self): """Save selected images. This uses Astropy FITS package to save the outputs no matter what user chose to load the images. """ res_dict = self.treeview.get_selected() clobber = self.settings.get('clobber', False) self.treeview.clear_selection() # Automatically disables Save button # If user gives empty string, no suffix. if self.suffix: sfx = '_' + self.suffix else: sfx = '' # Also include channel name in suffix. This is useful if user likes to # open the same image in multiple channels. if self.settings.get('include_chname', True): sfx += '_' + self.chname # Process each selected file. Each can have multiple edited extensions. for infile in res_dict: f_pfx = os.path.splitext(infile)[0] # prefix f_ext = '.fits' # Only FITS supported oname = f_pfx + sfx + f_ext outfile = os.path.join(self.outdir, oname) self.w.status.set_text( 'Writing out {0} to {1} ...'.format(shorten_name(infile, 10), shorten_name(oname, 10))) self.logger.debug( 'Writing out {0} to {1} ...'.format(infile, oname)) if os.path.exists(outfile) and not clobber: self.logger.error('{0} already exists'.format(outfile)) continue bnch = res_dict[infile] if bnch.path is None or not os.path.isfile(bnch.path): self._write_mosaic(f_pfx, outfile) else: shutil.copyfile(bnch.path, outfile) self._write_mef(f_pfx, bnch.extlist, outfile) self.logger.info('{0} written'.format(outfile)) self.w.status.set_text('Saving done, see log')
[ "def", "save_images", "(", "self", ")", ":", "res_dict", "=", "self", ".", "treeview", ".", "get_selected", "(", ")", "clobber", "=", "self", ".", "settings", ".", "get", "(", "'clobber'", ",", "False", ")", "self", ".", "treeview", ".", "clear_selection...
Save selected images. This uses Astropy FITS package to save the outputs no matter what user chose to load the images.
[ "Save", "selected", "images", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L447-L496
train
24,919
ejeschke/ginga
ginga/web/pgw/PgHelp.py
font_info
def font_info(font_str): """Extract font information from a font string, such as supplied to the 'font' argument to a widget. """ vals = font_str.split(';') point_size, style, weight = 8, 'normal', 'normal' family = vals[0] if len(vals) > 1: style = vals[1] if len(vals) > 2: weight = vals[2] match = font_regex.match(family) if match: family, point_size = match.groups() point_size = int(point_size) return Bunch.Bunch(family=family, point_size=point_size, style=style, weight=weight)
python
def font_info(font_str): """Extract font information from a font string, such as supplied to the 'font' argument to a widget. """ vals = font_str.split(';') point_size, style, weight = 8, 'normal', 'normal' family = vals[0] if len(vals) > 1: style = vals[1] if len(vals) > 2: weight = vals[2] match = font_regex.match(family) if match: family, point_size = match.groups() point_size = int(point_size) return Bunch.Bunch(family=family, point_size=point_size, style=style, weight=weight)
[ "def", "font_info", "(", "font_str", ")", ":", "vals", "=", "font_str", ".", "split", "(", "';'", ")", "point_size", ",", "style", ",", "weight", "=", "8", ",", "'normal'", ",", "'normal'", "family", "=", "vals", "[", "0", "]", "if", "len", "(", "v...
Extract font information from a font string, such as supplied to the 'font' argument to a widget.
[ "Extract", "font", "information", "from", "a", "font", "string", "such", "as", "supplied", "to", "the", "font", "argument", "to", "a", "widget", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/PgHelp.py#L259-L277
train
24,920
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.get_points
def get_points(self): """Get the set of points that is used to draw the object. Points are returned in *data* coordinates. """ if hasattr(self, 'points'): points = self.crdmap.to_data(self.points) else: points = [] return points
python
def get_points(self): """Get the set of points that is used to draw the object. Points are returned in *data* coordinates. """ if hasattr(self, 'points'): points = self.crdmap.to_data(self.points) else: points = [] return points
[ "def", "get_points", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'points'", ")", ":", "points", "=", "self", ".", "crdmap", ".", "to_data", "(", "self", ".", "points", ")", "else", ":", "points", "=", "[", "]", "return", "points" ]
Get the set of points that is used to draw the object. Points are returned in *data* coordinates.
[ "Get", "the", "set", "of", "points", "that", "is", "used", "to", "draw", "the", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L226-L235
train
24,921
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.get_data_points
def get_data_points(self, points=None): """Points returned are in data coordinates.""" if points is None: points = self.points points = self.crdmap.to_data(points) return points
python
def get_data_points(self, points=None): """Points returned are in data coordinates.""" if points is None: points = self.points points = self.crdmap.to_data(points) return points
[ "def", "get_data_points", "(", "self", ",", "points", "=", "None", ")", ":", "if", "points", "is", "None", ":", "points", "=", "self", ".", "points", "points", "=", "self", ".", "crdmap", ".", "to_data", "(", "points", ")", "return", "points" ]
Points returned are in data coordinates.
[ "Points", "returned", "are", "in", "data", "coordinates", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L237-L242
train
24,922
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.set_data_points
def set_data_points(self, points): """ Input `points` must be in data coordinates, will be converted to the coordinate space of the object and stored. """ self.points = np.asarray(self.crdmap.data_to(points))
python
def set_data_points(self, points): """ Input `points` must be in data coordinates, will be converted to the coordinate space of the object and stored. """ self.points = np.asarray(self.crdmap.data_to(points))
[ "def", "set_data_points", "(", "self", ",", "points", ")", ":", "self", ".", "points", "=", "np", ".", "asarray", "(", "self", ".", "crdmap", ".", "data_to", "(", "points", ")", ")" ]
Input `points` must be in data coordinates, will be converted to the coordinate space of the object and stored.
[ "Input", "points", "must", "be", "in", "data", "coordinates", "will", "be", "converted", "to", "the", "coordinate", "space", "of", "the", "object", "and", "stored", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L244-L249
train
24,923
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.convert_mapper
def convert_mapper(self, tomap): """ Converts our object from using one coordinate map to another. NOTE: In some cases this only approximately preserves the equivalent point values when transforming between coordinate spaces. """ frommap = self.crdmap if frommap == tomap: return # mild hack to convert radii on objects that have them if hasattr(self, 'radius'): # get coordinates of a point radius away from center # under current coordmap x0, y0 = frommap.offset_pt((self.x, self.y), (self.radius, 0)) pts = frommap.to_data(((self.x, self.y), (x0, y0))) pts = tomap.data_to(pts) self.radius = np.fabs(pts[1][0] - pts[0][0]) elif hasattr(self, 'xradius'): # similar to above case, but there are 2 radii x0, y0 = frommap.offset_pt((self.x, self.y), (self.xradius, self.yradius)) pts = frommap.to_data(((self.x, self.y), (x0, y0))) pts = tomap.data_to(pts) self.xradius = np.fabs(pts[1][0] - pts[0][0]) self.yradius = np.fabs(pts[1][1] - pts[0][1]) data_pts = self.get_data_points() # set our map to the new map self.crdmap = tomap self.set_data_points(data_pts)
python
def convert_mapper(self, tomap): """ Converts our object from using one coordinate map to another. NOTE: In some cases this only approximately preserves the equivalent point values when transforming between coordinate spaces. """ frommap = self.crdmap if frommap == tomap: return # mild hack to convert radii on objects that have them if hasattr(self, 'radius'): # get coordinates of a point radius away from center # under current coordmap x0, y0 = frommap.offset_pt((self.x, self.y), (self.radius, 0)) pts = frommap.to_data(((self.x, self.y), (x0, y0))) pts = tomap.data_to(pts) self.radius = np.fabs(pts[1][0] - pts[0][0]) elif hasattr(self, 'xradius'): # similar to above case, but there are 2 radii x0, y0 = frommap.offset_pt((self.x, self.y), (self.xradius, self.yradius)) pts = frommap.to_data(((self.x, self.y), (x0, y0))) pts = tomap.data_to(pts) self.xradius = np.fabs(pts[1][0] - pts[0][0]) self.yradius = np.fabs(pts[1][1] - pts[0][1]) data_pts = self.get_data_points() # set our map to the new map self.crdmap = tomap self.set_data_points(data_pts)
[ "def", "convert_mapper", "(", "self", ",", "tomap", ")", ":", "frommap", "=", "self", ".", "crdmap", "if", "frommap", "==", "tomap", ":", "return", "# mild hack to convert radii on objects that have them", "if", "hasattr", "(", "self", ",", "'radius'", ")", ":",...
Converts our object from using one coordinate map to another. NOTE: In some cases this only approximately preserves the equivalent point values when transforming between coordinate spaces.
[ "Converts", "our", "object", "from", "using", "one", "coordinate", "map", "to", "another", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L341-L376
train
24,924
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.point_within_radius
def point_within_radius(self, points, pt, canvas_radius, scales=(1.0, 1.0)): """Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius. """ scale_x, scale_y = scales x, y = pt a_arr, b_arr = np.asarray(points).T dx = np.fabs(x - a_arr) * scale_x dy = np.fabs(y - b_arr) * scale_y new_radius = np.sqrt(dx**2 + dy**2) res = (new_radius <= canvas_radius) return res
python
def point_within_radius(self, points, pt, canvas_radius, scales=(1.0, 1.0)): """Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius. """ scale_x, scale_y = scales x, y = pt a_arr, b_arr = np.asarray(points).T dx = np.fabs(x - a_arr) * scale_x dy = np.fabs(y - b_arr) * scale_y new_radius = np.sqrt(dx**2 + dy**2) res = (new_radius <= canvas_radius) return res
[ "def", "point_within_radius", "(", "self", ",", "points", ",", "pt", ",", "canvas_radius", ",", "scales", "=", "(", "1.0", ",", "1.0", ")", ")", ":", "scale_x", ",", "scale_y", "=", "scales", "x", ",", "y", "=", "pt", "a_arr", ",", "b_arr", "=", "n...
Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius.
[ "Points", "points", "and", "point", "pt", "are", "in", "data", "coordinates", ".", "Return", "True", "for", "points", "within", "the", "circle", "defined", "by", "a", "center", "at", "point", "pt", "and", "within", "canvas_radius", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L378-L391
train
24,925
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.within_radius
def within_radius(self, viewer, points, pt, canvas_radius): """Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius. The distance between points is scaled by the canvas scale. """ scales = viewer.get_scale_xy() return self.point_within_radius(points, pt, canvas_radius, scales)
python
def within_radius(self, viewer, points, pt, canvas_radius): """Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius. The distance between points is scaled by the canvas scale. """ scales = viewer.get_scale_xy() return self.point_within_radius(points, pt, canvas_radius, scales)
[ "def", "within_radius", "(", "self", ",", "viewer", ",", "points", ",", "pt", ",", "canvas_radius", ")", ":", "scales", "=", "viewer", ".", "get_scale_xy", "(", ")", "return", "self", ".", "point_within_radius", "(", "points", ",", "pt", ",", "canvas_radiu...
Points `points` and point `pt` are in data coordinates. Return True for points within the circle defined by a center at point `pt` and within canvas_radius. The distance between points is scaled by the canvas scale.
[ "Points", "points", "and", "point", "pt", "are", "in", "data", "coordinates", ".", "Return", "True", "for", "points", "within", "the", "circle", "defined", "by", "a", "center", "at", "point", "pt", "and", "within", "canvas_radius", ".", "The", "distance", ...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L393-L401
train
24,926
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.get_pt
def get_pt(self, viewer, points, pt, canvas_radius=None): """Takes an array of points `points` and a target point `pt`. Returns the first index of the point that is within the radius of the target point. If none of the points are within the radius, returns None. """ if canvas_radius is None: canvas_radius = self.cap_radius if hasattr(self, 'rot_deg'): # rotate point back to cartesian alignment for test ctr_pt = self.get_center_pt() pt = trcalc.rotate_coord(pt, [-self.rot_deg], ctr_pt) res = self.within_radius(viewer, points, pt, canvas_radius) return np.flatnonzero(res)
python
def get_pt(self, viewer, points, pt, canvas_radius=None): """Takes an array of points `points` and a target point `pt`. Returns the first index of the point that is within the radius of the target point. If none of the points are within the radius, returns None. """ if canvas_radius is None: canvas_radius = self.cap_radius if hasattr(self, 'rot_deg'): # rotate point back to cartesian alignment for test ctr_pt = self.get_center_pt() pt = trcalc.rotate_coord(pt, [-self.rot_deg], ctr_pt) res = self.within_radius(viewer, points, pt, canvas_radius) return np.flatnonzero(res)
[ "def", "get_pt", "(", "self", ",", "viewer", ",", "points", ",", "pt", ",", "canvas_radius", "=", "None", ")", ":", "if", "canvas_radius", "is", "None", ":", "canvas_radius", "=", "self", ".", "cap_radius", "if", "hasattr", "(", "self", ",", "'rot_deg'",...
Takes an array of points `points` and a target point `pt`. Returns the first index of the point that is within the radius of the target point. If none of the points are within the radius, returns None.
[ "Takes", "an", "array", "of", "points", "points", "and", "a", "target", "point", "pt", ".", "Returns", "the", "first", "index", "of", "the", "point", "that", "is", "within", "the", "radius", "of", "the", "target", "point", ".", "If", "none", "of", "the...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L403-L418
train
24,927
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.within_line
def within_line(self, viewer, points, p_start, p_stop, canvas_radius): """Points `points` and line endpoints `p_start`, `p_stop` are in data coordinates. Return True for points within the line defined by a line from p_start to p_end and within `canvas_radius`. The distance between points is scaled by the viewer's canvas scale. """ scale_x, scale_y = viewer.get_scale_xy() new_radius = canvas_radius * 1.0 / min(scale_x, scale_y) return self.point_within_line(points, p_start, p_stop, new_radius)
python
def within_line(self, viewer, points, p_start, p_stop, canvas_radius): """Points `points` and line endpoints `p_start`, `p_stop` are in data coordinates. Return True for points within the line defined by a line from p_start to p_end and within `canvas_radius`. The distance between points is scaled by the viewer's canvas scale. """ scale_x, scale_y = viewer.get_scale_xy() new_radius = canvas_radius * 1.0 / min(scale_x, scale_y) return self.point_within_line(points, p_start, p_stop, new_radius)
[ "def", "within_line", "(", "self", ",", "viewer", ",", "points", ",", "p_start", ",", "p_stop", ",", "canvas_radius", ")", ":", "scale_x", ",", "scale_y", "=", "viewer", ".", "get_scale_xy", "(", ")", "new_radius", "=", "canvas_radius", "*", "1.0", "/", ...
Points `points` and line endpoints `p_start`, `p_stop` are in data coordinates. Return True for points within the line defined by a line from p_start to p_end and within `canvas_radius`. The distance between points is scaled by the viewer's canvas scale.
[ "Points", "points", "and", "line", "endpoints", "p_start", "p_stop", "are", "in", "data", "coordinates", ".", "Return", "True", "for", "points", "within", "the", "line", "defined", "by", "a", "line", "from", "p_start", "to", "p_end", "and", "within", "canvas...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L439-L449
train
24,928
ejeschke/ginga
ginga/canvas/CanvasObject.py
CanvasObjectBase.get_bbox
def get_bbox(self, points=None): """ Get bounding box of this object. Returns ------- (p1, p2, p3, p4): a 4-tuple of the points in data coordinates, beginning with the lower-left and proceeding counter-clockwise. """ if points is None: x1, y1, x2, y2 = self.get_llur() return ((x1, y1), (x1, y2), (x2, y2), (x2, y1)) else: return trcalc.strip_z(trcalc.get_bounds(points))
python
def get_bbox(self, points=None): """ Get bounding box of this object. Returns ------- (p1, p2, p3, p4): a 4-tuple of the points in data coordinates, beginning with the lower-left and proceeding counter-clockwise. """ if points is None: x1, y1, x2, y2 = self.get_llur() return ((x1, y1), (x1, y2), (x2, y2), (x2, y1)) else: return trcalc.strip_z(trcalc.get_bounds(points))
[ "def", "get_bbox", "(", "self", ",", "points", "=", "None", ")", ":", "if", "points", "is", "None", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "self", ".", "get_llur", "(", ")", "return", "(", "(", "x1", ",", "y1", ")", ",", "(", "x1", ...
Get bounding box of this object. Returns ------- (p1, p2, p3, p4): a 4-tuple of the points in data coordinates, beginning with the lower-left and proceeding counter-clockwise.
[ "Get", "bounding", "box", "of", "this", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L503-L516
train
24,929
ejeschke/ginga
ginga/misc/Timer.py
TimerFactory.set
def set(self, time_sec, callback_fn, *args, **kwdargs): """Convenience function to create and set a timer. Equivalent to: timer = timer_factory.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec) """ timer = self.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec) return timer
python
def set(self, time_sec, callback_fn, *args, **kwdargs): """Convenience function to create and set a timer. Equivalent to: timer = timer_factory.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec) """ timer = self.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec) return timer
[ "def", "set", "(", "self", ",", "time_sec", ",", "callback_fn", ",", "*", "args", ",", "*", "*", "kwdargs", ")", ":", "timer", "=", "self", ".", "timer", "(", ")", "timer", ".", "set_callback", "(", "'expired'", ",", "callback_fn", ",", "*", "args", ...
Convenience function to create and set a timer. Equivalent to: timer = timer_factory.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec)
[ "Convenience", "function", "to", "create", "and", "set", "a", "timer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Timer.py#L29-L40
train
24,930
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_window_size
def set_window_size(self, width, height): """Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: This is called by the subclass with ``width`` and ``height`` as soon as the actual dimensions of the allocated window are known. Parameters ---------- width : int The width of the window in pixels. height : int The height of the window in pixels. """ self._imgwin_wd = int(width) self._imgwin_ht = int(height) self._ctr_x = width // 2 self._ctr_y = height // 2 self.logger.debug("widget resized to %dx%d" % (width, height)) self.make_callback('configure', width, height) self.redraw(whence=0)
python
def set_window_size(self, width, height): """Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: This is called by the subclass with ``width`` and ``height`` as soon as the actual dimensions of the allocated window are known. Parameters ---------- width : int The width of the window in pixels. height : int The height of the window in pixels. """ self._imgwin_wd = int(width) self._imgwin_ht = int(height) self._ctr_x = width // 2 self._ctr_y = height // 2 self.logger.debug("widget resized to %dx%d" % (width, height)) self.make_callback('configure', width, height) self.redraw(whence=0)
[ "def", "set_window_size", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "_imgwin_wd", "=", "int", "(", "width", ")", "self", ".", "_imgwin_ht", "=", "int", "(", "height", ")", "self", ".", "_ctr_x", "=", "width", "//", "2", "self",...
Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: This is called by the subclass with ``width`` and ``height`` as soon as the actual dimensions of the allocated window are known. Parameters ---------- width : int The width of the window in pixels. height : int The height of the window in pixels.
[ "Report", "the", "size", "of", "the", "window", "to", "display", "the", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L353-L384
train
24,931
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_renderer
def set_renderer(self, renderer): """Set and initialize the renderer used by this instance. """ self.renderer = renderer width, height = self.get_window_size() if width > 0 and height > 0: renderer.resize((width, height))
python
def set_renderer(self, renderer): """Set and initialize the renderer used by this instance. """ self.renderer = renderer width, height = self.get_window_size() if width > 0 and height > 0: renderer.resize((width, height))
[ "def", "set_renderer", "(", "self", ",", "renderer", ")", ":", "self", ".", "renderer", "=", "renderer", "width", ",", "height", "=", "self", ".", "get_window_size", "(", ")", "if", "width", ">", "0", "and", "height", ">", "0", ":", "renderer", ".", ...
Set and initialize the renderer used by this instance.
[ "Set", "and", "initialize", "the", "renderer", "used", "by", "this", "instance", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L470-L476
train
24,932
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_canvas
def set_canvas(self, canvas, private_canvas=None): """Set the canvas object. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas object. private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None` Private canvas object. If not given, this is the same as ``canvas``. """ self.canvas = canvas canvas.initialize(None, self, self.logger) canvas.add_callback('modified', self.canvas_changed_cb) canvas.set_surface(self) canvas.ui_set_active(True) self._imgobj = None # private canvas set? if private_canvas is not None: self.private_canvas = private_canvas if private_canvas != canvas: private_canvas.set_surface(self) private_canvas.ui_set_active(True) private_canvas.add_callback('modified', self.canvas_changed_cb) # sanity check that we have a private canvas, and if not, # set it to the "advertised" canvas if self.private_canvas is None: self.private_canvas = canvas # make sure private canvas has our non-private one added if (self.private_canvas != self.canvas) and ( not self.private_canvas.has_object(canvas)): self.private_canvas.add(canvas) self.initialize_private_canvas(self.private_canvas)
python
def set_canvas(self, canvas, private_canvas=None): """Set the canvas object. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas object. private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None` Private canvas object. If not given, this is the same as ``canvas``. """ self.canvas = canvas canvas.initialize(None, self, self.logger) canvas.add_callback('modified', self.canvas_changed_cb) canvas.set_surface(self) canvas.ui_set_active(True) self._imgobj = None # private canvas set? if private_canvas is not None: self.private_canvas = private_canvas if private_canvas != canvas: private_canvas.set_surface(self) private_canvas.ui_set_active(True) private_canvas.add_callback('modified', self.canvas_changed_cb) # sanity check that we have a private canvas, and if not, # set it to the "advertised" canvas if self.private_canvas is None: self.private_canvas = canvas # make sure private canvas has our non-private one added if (self.private_canvas != self.canvas) and ( not self.private_canvas.has_object(canvas)): self.private_canvas.add(canvas) self.initialize_private_canvas(self.private_canvas)
[ "def", "set_canvas", "(", "self", ",", "canvas", ",", "private_canvas", "=", "None", ")", ":", "self", ".", "canvas", "=", "canvas", "canvas", ".", "initialize", "(", "None", ",", "self", ",", "self", ".", "logger", ")", "canvas", ".", "add_callback", ...
Set the canvas object. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas object. private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None` Private canvas object. If not given, this is the same as ``canvas``.
[ "Set", "the", "canvas", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L489-L528
train
24,933
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.initialize_private_canvas
def initialize_private_canvas(self, private_canvas): """Initialize the private canvas used by this instance. """ if self.t_.get('show_pan_position', False): self.show_pan_mark(True) if self.t_.get('show_focus_indicator', False): self.show_focus_indicator(True)
python
def initialize_private_canvas(self, private_canvas): """Initialize the private canvas used by this instance. """ if self.t_.get('show_pan_position', False): self.show_pan_mark(True) if self.t_.get('show_focus_indicator', False): self.show_focus_indicator(True)
[ "def", "initialize_private_canvas", "(", "self", ",", "private_canvas", ")", ":", "if", "self", ".", "t_", ".", "get", "(", "'show_pan_position'", ",", "False", ")", ":", "self", ".", "show_pan_mark", "(", "True", ")", "if", "self", ".", "t_", ".", "get"...
Initialize the private canvas used by this instance.
[ "Initialize", "the", "private", "canvas", "used", "by", "this", "instance", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L541-L548
train
24,934
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_rgbmap
def set_rgbmap(self, rgbmap): """Set RGB map object used by this instance. It controls how the values in the image are mapped to color. Parameters ---------- rgbmap : `~ginga.RGBMap.RGBMapper` RGB map. """ self.rgbmap = rgbmap t_ = rgbmap.get_settings() t_.share_settings(self.t_, keylist=rgbmap.settings_keys) rgbmap.add_callback('changed', self.rgbmap_cb) self.redraw(whence=2)
python
def set_rgbmap(self, rgbmap): """Set RGB map object used by this instance. It controls how the values in the image are mapped to color. Parameters ---------- rgbmap : `~ginga.RGBMap.RGBMapper` RGB map. """ self.rgbmap = rgbmap t_ = rgbmap.get_settings() t_.share_settings(self.t_, keylist=rgbmap.settings_keys) rgbmap.add_callback('changed', self.rgbmap_cb) self.redraw(whence=2)
[ "def", "set_rgbmap", "(", "self", ",", "rgbmap", ")", ":", "self", ".", "rgbmap", "=", "rgbmap", "t_", "=", "rgbmap", ".", "get_settings", "(", ")", "t_", ".", "share_settings", "(", "self", ".", "t_", ",", "keylist", "=", "rgbmap", ".", "settings_keys...
Set RGB map object used by this instance. It controls how the values in the image are mapped to color. Parameters ---------- rgbmap : `~ginga.RGBMap.RGBMapper` RGB map.
[ "Set", "RGB", "map", "object", "used", "by", "this", "instance", ".", "It", "controls", "how", "the", "values", "in", "the", "image", "are", "mapped", "to", "color", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L684-L698
train
24,935
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_image
def get_image(self): """Get the image currently being displayed. Returns ------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. """ if self._imgobj is not None: # quick optomization return self._imgobj.get_image() canvas_img = self.get_canvas_image() return canvas_img.get_image()
python
def get_image(self): """Get the image currently being displayed. Returns ------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. """ if self._imgobj is not None: # quick optomization return self._imgobj.get_image() canvas_img = self.get_canvas_image() return canvas_img.get_image()
[ "def", "get_image", "(", "self", ")", ":", "if", "self", ".", "_imgobj", "is", "not", "None", ":", "# quick optomization", "return", "self", ".", "_imgobj", ".", "get_image", "(", ")", "canvas_img", "=", "self", ".", "get_canvas_image", "(", ")", "return",...
Get the image currently being displayed. Returns ------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object.
[ "Get", "the", "image", "currently", "being", "displayed", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L700-L714
train
24,936
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_canvas_image
def get_canvas_image(self): """Get canvas image object. Returns ------- imgobj : `~ginga.canvas.types.image.NormImage` Normalized image sitting on the canvas. """ if self._imgobj is not None: return self._imgobj try: # See if there is an image on the canvas self._imgobj = self.canvas.get_object_by_tag(self._canvas_img_tag) self._imgobj.add_callback('image-set', self._image_set_cb) except KeyError: # add a normalized image item to this canvas if we don't # have one already--then just keep reusing it NormImage = self.canvas.getDrawClass('normimage') interp = self.t_.get('interpolation', 'basic') # previous choice might not be available if preferences # were saved when opencv was being used (and not used now) # --if so, default to "basic" if interp not in trcalc.interpolation_methods: interp = 'basic' self._imgobj = NormImage(0, 0, None, alpha=1.0, interpolation=interp) self._imgobj.add_callback('image-set', self._image_set_cb) return self._imgobj
python
def get_canvas_image(self): """Get canvas image object. Returns ------- imgobj : `~ginga.canvas.types.image.NormImage` Normalized image sitting on the canvas. """ if self._imgobj is not None: return self._imgobj try: # See if there is an image on the canvas self._imgobj = self.canvas.get_object_by_tag(self._canvas_img_tag) self._imgobj.add_callback('image-set', self._image_set_cb) except KeyError: # add a normalized image item to this canvas if we don't # have one already--then just keep reusing it NormImage = self.canvas.getDrawClass('normimage') interp = self.t_.get('interpolation', 'basic') # previous choice might not be available if preferences # were saved when opencv was being used (and not used now) # --if so, default to "basic" if interp not in trcalc.interpolation_methods: interp = 'basic' self._imgobj = NormImage(0, 0, None, alpha=1.0, interpolation=interp) self._imgobj.add_callback('image-set', self._image_set_cb) return self._imgobj
[ "def", "get_canvas_image", "(", "self", ")", ":", "if", "self", ".", "_imgobj", "is", "not", "None", ":", "return", "self", ".", "_imgobj", "try", ":", "# See if there is an image on the canvas", "self", ".", "_imgobj", "=", "self", ".", "canvas", ".", "get_...
Get canvas image object. Returns ------- imgobj : `~ginga.canvas.types.image.NormImage` Normalized image sitting on the canvas.
[ "Get", "canvas", "image", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L716-L749
train
24,937
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_image
def set_image(self, image, add_to_canvas=True): """Set an image to be displayed. If there is no error, the ``'image-unset'`` and ``'image-set'`` callbacks will be invoked. Parameters ---------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. add_to_canvas : bool Add image to canvas. """ if not isinstance(image, BaseImage.BaseImage): raise ValueError("Wrong type of object to load: %s" % ( str(type(image)))) canvas_img = self.get_canvas_image() old_image = canvas_img.get_image() self.make_callback('image-unset', old_image) with self.suppress_redraw: # this line should force the callback of _image_set_cb() canvas_img.set_image(image) if add_to_canvas: try: self.canvas.get_object_by_tag(self._canvas_img_tag) except KeyError: self.canvas.add(canvas_img, tag=self._canvas_img_tag) #self.logger.debug("adding image to canvas %s" % self.canvas) # move image to bottom of layers self.canvas.lower_object(canvas_img)
python
def set_image(self, image, add_to_canvas=True): """Set an image to be displayed. If there is no error, the ``'image-unset'`` and ``'image-set'`` callbacks will be invoked. Parameters ---------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. add_to_canvas : bool Add image to canvas. """ if not isinstance(image, BaseImage.BaseImage): raise ValueError("Wrong type of object to load: %s" % ( str(type(image)))) canvas_img = self.get_canvas_image() old_image = canvas_img.get_image() self.make_callback('image-unset', old_image) with self.suppress_redraw: # this line should force the callback of _image_set_cb() canvas_img.set_image(image) if add_to_canvas: try: self.canvas.get_object_by_tag(self._canvas_img_tag) except KeyError: self.canvas.add(canvas_img, tag=self._canvas_img_tag) #self.logger.debug("adding image to canvas %s" % self.canvas) # move image to bottom of layers self.canvas.lower_object(canvas_img)
[ "def", "set_image", "(", "self", ",", "image", ",", "add_to_canvas", "=", "True", ")", ":", "if", "not", "isinstance", "(", "image", ",", "BaseImage", ".", "BaseImage", ")", ":", "raise", "ValueError", "(", "\"Wrong type of object to load: %s\"", "%", "(", "...
Set an image to be displayed. If there is no error, the ``'image-unset'`` and ``'image-set'`` callbacks will be invoked. Parameters ---------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. add_to_canvas : bool Add image to canvas.
[ "Set", "an", "image", "to", "be", "displayed", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L751-L789
train
24,938
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.save_profile
def save_profile(self, **params): """Save the given parameters into profile settings. Parameters ---------- params : dict Keywords and values to be saved. """ image = self.get_image() if (image is None): return profile = image.get('profile', None) if profile is None: # If image has no profile then create one profile = Settings.SettingGroup() image.set(profile=profile) self.logger.debug("saving to image profile: params=%s" % ( str(params))) profile.set(**params) return profile
python
def save_profile(self, **params): """Save the given parameters into profile settings. Parameters ---------- params : dict Keywords and values to be saved. """ image = self.get_image() if (image is None): return profile = image.get('profile', None) if profile is None: # If image has no profile then create one profile = Settings.SettingGroup() image.set(profile=profile) self.logger.debug("saving to image profile: params=%s" % ( str(params))) profile.set(**params) return profile
[ "def", "save_profile", "(", "self", ",", "*", "*", "params", ")", ":", "image", "=", "self", ".", "get_image", "(", ")", "if", "(", "image", "is", "None", ")", ":", "return", "profile", "=", "image", ".", "get", "(", "'profile'", ",", "None", ")", ...
Save the given parameters into profile settings. Parameters ---------- params : dict Keywords and values to be saved.
[ "Save", "the", "given", "parameters", "into", "profile", "settings", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L909-L931
train
24,939
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_data
def set_data(self, data, metadata=None): """Set an image to be displayed by providing raw data. This is a convenience method for first constructing an image with `~ginga.AstroImage.AstroImage` and then calling :meth:`set_image`. Parameters ---------- data : ndarray This should be at least a 2D Numpy array. metadata : dict or `None` Image metadata mapping keywords to their respective values. """ image = AstroImage.AstroImage(data, metadata=metadata, logger=self.logger) self.set_image(image)
python
def set_data(self, data, metadata=None): """Set an image to be displayed by providing raw data. This is a convenience method for first constructing an image with `~ginga.AstroImage.AstroImage` and then calling :meth:`set_image`. Parameters ---------- data : ndarray This should be at least a 2D Numpy array. metadata : dict or `None` Image metadata mapping keywords to their respective values. """ image = AstroImage.AstroImage(data, metadata=metadata, logger=self.logger) self.set_image(image)
[ "def", "set_data", "(", "self", ",", "data", ",", "metadata", "=", "None", ")", ":", "image", "=", "AstroImage", ".", "AstroImage", "(", "data", ",", "metadata", "=", "metadata", ",", "logger", "=", "self", ".", "logger", ")", "self", ".", "set_image",...
Set an image to be displayed by providing raw data. This is a convenience method for first constructing an image with `~ginga.AstroImage.AstroImage` and then calling :meth:`set_image`. Parameters ---------- data : ndarray This should be at least a 2D Numpy array. metadata : dict or `None` Image metadata mapping keywords to their respective values.
[ "Set", "an", "image", "to", "be", "displayed", "by", "providing", "raw", "data", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L984-L1001
train
24,940
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.clear
def clear(self): """Clear the displayed image.""" self._imgobj = None try: # See if there is an image on the canvas self.canvas.delete_object_by_tag(self._canvas_img_tag) self.redraw() except KeyError: pass
python
def clear(self): """Clear the displayed image.""" self._imgobj = None try: # See if there is an image on the canvas self.canvas.delete_object_by_tag(self._canvas_img_tag) self.redraw() except KeyError: pass
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_imgobj", "=", "None", "try", ":", "# See if there is an image on the canvas", "self", ".", "canvas", ".", "delete_object_by_tag", "(", "self", ".", "_canvas_img_tag", ")", "self", ".", "redraw", "(", ")", ...
Clear the displayed image.
[ "Clear", "the", "displayed", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1003-L1011
train
24,941
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.redraw
def redraw(self, whence=0): """Redraw the canvas. Parameters ---------- whence See :meth:`get_rgb_object`. """ with self._defer_lock: whence = min(self._defer_whence, whence) if not self.defer_redraw: if self._hold_redraw_cnt == 0: self._defer_whence = self._defer_whence_reset self.redraw_now(whence=whence) else: self._defer_whence = whence return elapsed = time.time() - self.time_last_redraw # If there is no redraw scheduled, or we are overdue for one: if (not self._defer_flag) or (elapsed > self.defer_lagtime): # If more time than defer_lagtime has passed since the # last redraw then just do the redraw immediately if elapsed > self.defer_lagtime: if self._hold_redraw_cnt > 0: #self._defer_flag = True self._defer_whence = whence return self._defer_whence = self._defer_whence_reset self.logger.debug("lagtime expired--forced redraw") self.redraw_now(whence=whence) return # Indicate that a redraw is necessary and record whence self._defer_flag = True self._defer_whence = whence # schedule a redraw by the end of the defer_lagtime secs = self.defer_lagtime - elapsed self.logger.debug("defer redraw (whence=%.2f) in %.f sec" % ( whence, secs)) self.reschedule_redraw(secs) else: # A redraw is already scheduled. Just record whence. self._defer_whence = whence self.logger.debug("update whence=%.2f" % (whence))
python
def redraw(self, whence=0): """Redraw the canvas. Parameters ---------- whence See :meth:`get_rgb_object`. """ with self._defer_lock: whence = min(self._defer_whence, whence) if not self.defer_redraw: if self._hold_redraw_cnt == 0: self._defer_whence = self._defer_whence_reset self.redraw_now(whence=whence) else: self._defer_whence = whence return elapsed = time.time() - self.time_last_redraw # If there is no redraw scheduled, or we are overdue for one: if (not self._defer_flag) or (elapsed > self.defer_lagtime): # If more time than defer_lagtime has passed since the # last redraw then just do the redraw immediately if elapsed > self.defer_lagtime: if self._hold_redraw_cnt > 0: #self._defer_flag = True self._defer_whence = whence return self._defer_whence = self._defer_whence_reset self.logger.debug("lagtime expired--forced redraw") self.redraw_now(whence=whence) return # Indicate that a redraw is necessary and record whence self._defer_flag = True self._defer_whence = whence # schedule a redraw by the end of the defer_lagtime secs = self.defer_lagtime - elapsed self.logger.debug("defer redraw (whence=%.2f) in %.f sec" % ( whence, secs)) self.reschedule_redraw(secs) else: # A redraw is already scheduled. Just record whence. self._defer_whence = whence self.logger.debug("update whence=%.2f" % (whence))
[ "def", "redraw", "(", "self", ",", "whence", "=", "0", ")", ":", "with", "self", ".", "_defer_lock", ":", "whence", "=", "min", "(", "self", ".", "_defer_whence", ",", "whence", ")", "if", "not", "self", ".", "defer_redraw", ":", "if", "self", ".", ...
Redraw the canvas. Parameters ---------- whence See :meth:`get_rgb_object`.
[ "Redraw", "the", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1025-L1075
train
24,942
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.canvas_changed_cb
def canvas_changed_cb(self, canvas, whence): """Handle callback for when canvas has changed.""" self.logger.debug("root canvas changed, whence=%d" % (whence)) # special check for whether image changed out from under us in # a shared canvas scenario try: # See if there is an image on the canvas canvas_img = self.canvas.get_object_by_tag(self._canvas_img_tag) if self._imgobj is not canvas_img: self._imgobj = canvas_img self._imgobj.add_callback('image-set', self._image_set_cb) self._image_set_cb(canvas_img, canvas_img.get_image()) except KeyError: self._imgobj = None self.redraw(whence=whence)
python
def canvas_changed_cb(self, canvas, whence): """Handle callback for when canvas has changed.""" self.logger.debug("root canvas changed, whence=%d" % (whence)) # special check for whether image changed out from under us in # a shared canvas scenario try: # See if there is an image on the canvas canvas_img = self.canvas.get_object_by_tag(self._canvas_img_tag) if self._imgobj is not canvas_img: self._imgobj = canvas_img self._imgobj.add_callback('image-set', self._image_set_cb) self._image_set_cb(canvas_img, canvas_img.get_image()) except KeyError: self._imgobj = None self.redraw(whence=whence)
[ "def", "canvas_changed_cb", "(", "self", ",", "canvas", ",", "whence", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"root canvas changed, whence=%d\"", "%", "(", "whence", ")", ")", "# special check for whether image changed out from under us in", "# a shared c...
Handle callback for when canvas has changed.
[ "Handle", "callback", "for", "when", "canvas", "has", "changed", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1088-L1106
train
24,943
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.delayed_redraw
def delayed_redraw(self): """Handle delayed redrawing of the canvas.""" # This is the optimized redraw method with self._defer_lock: # pick up the lowest necessary level of redrawing whence = self._defer_whence self._defer_whence = self._defer_whence_reset flag = self._defer_flag self._defer_flag = False if flag: # If a redraw was scheduled, do it now self.redraw_now(whence=whence)
python
def delayed_redraw(self): """Handle delayed redrawing of the canvas.""" # This is the optimized redraw method with self._defer_lock: # pick up the lowest necessary level of redrawing whence = self._defer_whence self._defer_whence = self._defer_whence_reset flag = self._defer_flag self._defer_flag = False if flag: # If a redraw was scheduled, do it now self.redraw_now(whence=whence)
[ "def", "delayed_redraw", "(", "self", ")", ":", "# This is the optimized redraw method", "with", "self", ".", "_defer_lock", ":", "# pick up the lowest necessary level of redrawing", "whence", "=", "self", ".", "_defer_whence", "self", ".", "_defer_whence", "=", "self", ...
Handle delayed redrawing of the canvas.
[ "Handle", "delayed", "redrawing", "of", "the", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1108-L1121
train
24,944
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_redraw_lag
def set_redraw_lag(self, lag_sec): """Set lag time for redrawing the canvas. Parameters ---------- lag_sec : float Number of seconds to wait. """ self.defer_redraw = (lag_sec > 0.0) if self.defer_redraw: self.defer_lagtime = lag_sec
python
def set_redraw_lag(self, lag_sec): """Set lag time for redrawing the canvas. Parameters ---------- lag_sec : float Number of seconds to wait. """ self.defer_redraw = (lag_sec > 0.0) if self.defer_redraw: self.defer_lagtime = lag_sec
[ "def", "set_redraw_lag", "(", "self", ",", "lag_sec", ")", ":", "self", ".", "defer_redraw", "=", "(", "lag_sec", ">", "0.0", ")", "if", "self", ".", "defer_redraw", ":", "self", ".", "defer_lagtime", "=", "lag_sec" ]
Set lag time for redrawing the canvas. Parameters ---------- lag_sec : float Number of seconds to wait.
[ "Set", "lag", "time", "for", "redrawing", "the", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1123-L1134
train
24,945
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_refresh_rate
def set_refresh_rate(self, fps): """Set the refresh rate for redrawing the canvas at a timed interval. Parameters ---------- fps : float Desired rate in frames per second. """ self.rf_fps = fps self.rf_rate = 1.0 / self.rf_fps #self.set_redraw_lag(self.rf_rate) self.logger.info("set a refresh rate of %.2f fps" % (self.rf_fps))
python
def set_refresh_rate(self, fps): """Set the refresh rate for redrawing the canvas at a timed interval. Parameters ---------- fps : float Desired rate in frames per second. """ self.rf_fps = fps self.rf_rate = 1.0 / self.rf_fps #self.set_redraw_lag(self.rf_rate) self.logger.info("set a refresh rate of %.2f fps" % (self.rf_fps))
[ "def", "set_refresh_rate", "(", "self", ",", "fps", ")", ":", "self", ".", "rf_fps", "=", "fps", "self", ".", "rf_rate", "=", "1.0", "/", "self", ".", "rf_fps", "#self.set_redraw_lag(self.rf_rate)", "self", ".", "logger", ".", "info", "(", "\"set a refresh r...
Set the refresh rate for redrawing the canvas at a timed interval. Parameters ---------- fps : float Desired rate in frames per second.
[ "Set", "the", "refresh", "rate", "for", "redrawing", "the", "canvas", "at", "a", "timed", "interval", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1136-L1148
train
24,946
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.start_refresh
def start_refresh(self): """Start redrawing the canvas at the previously set timed interval. """ self.logger.debug("starting timed refresh interval") self.rf_flags['done'] = False self.rf_draw_count = 0 self.rf_timer_count = 0 self.rf_late_count = 0 self.rf_late_total = 0.0 self.rf_early_count = 0 self.rf_early_total = 0.0 self.rf_delta_total = 0.0 self.rf_skip_total = 0.0 self.rf_start_time = time.time() self.rf_deadline = self.rf_start_time self.refresh_timer_cb(self.rf_timer, self.rf_flags)
python
def start_refresh(self): """Start redrawing the canvas at the previously set timed interval. """ self.logger.debug("starting timed refresh interval") self.rf_flags['done'] = False self.rf_draw_count = 0 self.rf_timer_count = 0 self.rf_late_count = 0 self.rf_late_total = 0.0 self.rf_early_count = 0 self.rf_early_total = 0.0 self.rf_delta_total = 0.0 self.rf_skip_total = 0.0 self.rf_start_time = time.time() self.rf_deadline = self.rf_start_time self.refresh_timer_cb(self.rf_timer, self.rf_flags)
[ "def", "start_refresh", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"starting timed refresh interval\"", ")", "self", ".", "rf_flags", "[", "'done'", "]", "=", "False", "self", ".", "rf_draw_count", "=", "0", "self", ".", "rf_timer_cou...
Start redrawing the canvas at the previously set timed interval.
[ "Start", "redrawing", "the", "canvas", "at", "the", "previously", "set", "timed", "interval", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1150-L1165
train
24,947
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.stop_refresh
def stop_refresh(self): """Stop redrawing the canvas at the previously set timed interval. """ self.logger.debug("stopping timed refresh") self.rf_flags['done'] = True self.rf_timer.clear()
python
def stop_refresh(self): """Stop redrawing the canvas at the previously set timed interval. """ self.logger.debug("stopping timed refresh") self.rf_flags['done'] = True self.rf_timer.clear()
[ "def", "stop_refresh", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"stopping timed refresh\"", ")", "self", ".", "rf_flags", "[", "'done'", "]", "=", "True", "self", ".", "rf_timer", ".", "clear", "(", ")" ]
Stop redrawing the canvas at the previously set timed interval.
[ "Stop", "redrawing", "the", "canvas", "at", "the", "previously", "set", "timed", "interval", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1167-L1172
train
24,948
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_refresh_stats
def get_refresh_stats(self): """Return the measured statistics for timed refresh intervals. Returns ------- stats : float The measured rate of actual back end updates in frames per second. """ if self.rf_draw_count == 0: fps = 0.0 else: interval = time.time() - self.rf_start_time fps = self.rf_draw_count / interval jitter = self.rf_delta_total / max(1, self.rf_timer_count) late_avg = self.rf_late_total / max(1, self.rf_late_count) late_pct = self.rf_late_count / max(1.0, float(self.rf_timer_count)) * 100 early_avg = self.rf_early_total / max(1, self.rf_early_count) early_pct = self.rf_early_count / max(1.0, float(self.rf_timer_count)) * 100 balance = self.rf_late_total - self.rf_early_total stats = dict(fps=fps, jitter=jitter, early_avg=early_avg, early_pct=early_pct, late_avg=late_avg, late_pct=late_pct, balance=balance) return stats
python
def get_refresh_stats(self): """Return the measured statistics for timed refresh intervals. Returns ------- stats : float The measured rate of actual back end updates in frames per second. """ if self.rf_draw_count == 0: fps = 0.0 else: interval = time.time() - self.rf_start_time fps = self.rf_draw_count / interval jitter = self.rf_delta_total / max(1, self.rf_timer_count) late_avg = self.rf_late_total / max(1, self.rf_late_count) late_pct = self.rf_late_count / max(1.0, float(self.rf_timer_count)) * 100 early_avg = self.rf_early_total / max(1, self.rf_early_count) early_pct = self.rf_early_count / max(1.0, float(self.rf_timer_count)) * 100 balance = self.rf_late_total - self.rf_early_total stats = dict(fps=fps, jitter=jitter, early_avg=early_avg, early_pct=early_pct, late_avg=late_avg, late_pct=late_pct, balance=balance) return stats
[ "def", "get_refresh_stats", "(", "self", ")", ":", "if", "self", ".", "rf_draw_count", "==", "0", ":", "fps", "=", "0.0", "else", ":", "interval", "=", "time", ".", "time", "(", ")", "-", "self", ".", "rf_start_time", "fps", "=", "self", ".", "rf_dra...
Return the measured statistics for timed refresh intervals. Returns ------- stats : float The measured rate of actual back end updates in frames per second.
[ "Return", "the", "measured", "statistics", "for", "timed", "refresh", "intervals", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1174-L1203
train
24,949
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.refresh_timer_cb
def refresh_timer_cb(self, timer, flags): """Refresh timer callback. This callback will normally only be called internally. Parameters ---------- timer : a Ginga GUI timer A GUI-based Ginga timer flags : dict-like A set of flags controlling the timer """ # this is the timer call back, from the GUI thread start_time = time.time() if flags.get('done', False): return # calculate next deadline deadline = self.rf_deadline self.rf_deadline += self.rf_rate self.rf_timer_count += 1 delta = abs(start_time - deadline) self.rf_delta_total += delta adjust = 0.0 if start_time > deadline: # we are late self.rf_late_total += delta self.rf_late_count += 1 late_avg = self.rf_late_total / self.rf_late_count adjust = - (late_avg / 2.0) self.rf_skip_total += delta if self.rf_skip_total < self.rf_rate: self.rf_draw_count += 1 # TODO: can we optimize whence? self.redraw_now(whence=0) else: # <-- we are behind by amount of time equal to one frame. # skip a redraw and attempt to catch up some time self.rf_skip_total = 0 else: if start_time < deadline: # we are early self.rf_early_total += delta self.rf_early_count += 1 self.rf_skip_total = max(0.0, self.rf_skip_total - delta) early_avg = self.rf_early_total / self.rf_early_count adjust = early_avg / 4.0 self.rf_draw_count += 1 # TODO: can we optimize whence? self.redraw_now(whence=0) delay = max(0.0, self.rf_deadline - time.time() + adjust) timer.start(delay)
python
def refresh_timer_cb(self, timer, flags): """Refresh timer callback. This callback will normally only be called internally. Parameters ---------- timer : a Ginga GUI timer A GUI-based Ginga timer flags : dict-like A set of flags controlling the timer """ # this is the timer call back, from the GUI thread start_time = time.time() if flags.get('done', False): return # calculate next deadline deadline = self.rf_deadline self.rf_deadline += self.rf_rate self.rf_timer_count += 1 delta = abs(start_time - deadline) self.rf_delta_total += delta adjust = 0.0 if start_time > deadline: # we are late self.rf_late_total += delta self.rf_late_count += 1 late_avg = self.rf_late_total / self.rf_late_count adjust = - (late_avg / 2.0) self.rf_skip_total += delta if self.rf_skip_total < self.rf_rate: self.rf_draw_count += 1 # TODO: can we optimize whence? self.redraw_now(whence=0) else: # <-- we are behind by amount of time equal to one frame. # skip a redraw and attempt to catch up some time self.rf_skip_total = 0 else: if start_time < deadline: # we are early self.rf_early_total += delta self.rf_early_count += 1 self.rf_skip_total = max(0.0, self.rf_skip_total - delta) early_avg = self.rf_early_total / self.rf_early_count adjust = early_avg / 4.0 self.rf_draw_count += 1 # TODO: can we optimize whence? self.redraw_now(whence=0) delay = max(0.0, self.rf_deadline - time.time() + adjust) timer.start(delay)
[ "def", "refresh_timer_cb", "(", "self", ",", "timer", ",", "flags", ")", ":", "# this is the timer call back, from the GUI thread", "start_time", "=", "time", ".", "time", "(", ")", "if", "flags", ".", "get", "(", "'done'", ",", "False", ")", ":", "return", ...
Refresh timer callback. This callback will normally only be called internally. Parameters ---------- timer : a Ginga GUI timer A GUI-based Ginga timer flags : dict-like A set of flags controlling the timer
[ "Refresh", "timer", "callback", ".", "This", "callback", "will", "normally", "only", "be", "called", "internally", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1205-L1261
train
24,950
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.redraw_now
def redraw_now(self, whence=0): """Redraw the displayed image. Parameters ---------- whence See :meth:`get_rgb_object`. """ try: time_start = time.time() self.redraw_data(whence=whence) # finally update the window drawable from the offscreen surface self.update_image() time_done = time.time() time_delta = time_start - self.time_last_redraw time_elapsed = time_done - time_start self.time_last_redraw = time_done self.logger.debug( "widget '%s' redraw (whence=%d) delta=%.4f elapsed=%.4f sec" % ( self.name, whence, time_delta, time_elapsed)) except Exception as e: self.logger.error("Error redrawing image: %s" % (str(e))) try: # log traceback, if possible (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception: tb_str = "Traceback information unavailable." self.logger.error(tb_str)
python
def redraw_now(self, whence=0): """Redraw the displayed image. Parameters ---------- whence See :meth:`get_rgb_object`. """ try: time_start = time.time() self.redraw_data(whence=whence) # finally update the window drawable from the offscreen surface self.update_image() time_done = time.time() time_delta = time_start - self.time_last_redraw time_elapsed = time_done - time_start self.time_last_redraw = time_done self.logger.debug( "widget '%s' redraw (whence=%d) delta=%.4f elapsed=%.4f sec" % ( self.name, whence, time_delta, time_elapsed)) except Exception as e: self.logger.error("Error redrawing image: %s" % (str(e))) try: # log traceback, if possible (type, value, tb) = sys.exc_info() tb_str = "".join(traceback.format_tb(tb)) self.logger.error("Traceback:\n%s" % (tb_str)) except Exception: tb_str = "Traceback information unavailable." self.logger.error(tb_str)
[ "def", "redraw_now", "(", "self", ",", "whence", "=", "0", ")", ":", "try", ":", "time_start", "=", "time", ".", "time", "(", ")", "self", ".", "redraw_data", "(", "whence", "=", "whence", ")", "# finally update the window drawable from the offscreen surface", ...
Redraw the displayed image. Parameters ---------- whence See :meth:`get_rgb_object`.
[ "Redraw", "the", "displayed", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1263-L1296
train
24,951
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.redraw_data
def redraw_data(self, whence=0): """Render image from RGB map and redraw private canvas. .. note:: Do not call this method unless you are implementing a subclass. Parameters ---------- whence See :meth:`get_rgb_object`. """ if not self._imgwin_set: # window has not been realized yet return if not self._self_scaling: rgbobj = self.get_rgb_object(whence=whence) self.renderer.render_image(rgbobj, self._dst_x, self._dst_y) self.private_canvas.draw(self) self.make_callback('redraw', whence) if whence < 2: self.check_cursor_location()
python
def redraw_data(self, whence=0): """Render image from RGB map and redraw private canvas. .. note:: Do not call this method unless you are implementing a subclass. Parameters ---------- whence See :meth:`get_rgb_object`. """ if not self._imgwin_set: # window has not been realized yet return if not self._self_scaling: rgbobj = self.get_rgb_object(whence=whence) self.renderer.render_image(rgbobj, self._dst_x, self._dst_y) self.private_canvas.draw(self) self.make_callback('redraw', whence) if whence < 2: self.check_cursor_location()
[ "def", "redraw_data", "(", "self", ",", "whence", "=", "0", ")", ":", "if", "not", "self", ".", "_imgwin_set", ":", "# window has not been realized yet", "return", "if", "not", "self", ".", "_self_scaling", ":", "rgbobj", "=", "self", ".", "get_rgb_object", ...
Render image from RGB map and redraw private canvas. .. note:: Do not call this method unless you are implementing a subclass. Parameters ---------- whence See :meth:`get_rgb_object`.
[ "Render", "image", "from", "RGB", "map", "and", "redraw", "private", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1298-L1324
train
24,952
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.check_cursor_location
def check_cursor_location(self): """Check whether the data location of the last known position of the cursor has changed. If so, issue a callback. """ # Check whether cursor data position has changed relative # to previous value data_x, data_y = self.get_data_xy(self.last_win_x, self.last_win_y) if (data_x != self.last_data_x or data_y != self.last_data_y): self.last_data_x, self.last_data_y = data_x, data_y self.logger.debug("cursor location changed %.4f,%.4f => %.4f,%.4f" % ( self.last_data_x, self.last_data_y, data_x, data_y)) # we make this call compatible with the motion callback # for now, but there is no concept of a button here button = 0 self.make_ui_callback('cursor-changed', button, data_x, data_y) return data_x, data_y
python
def check_cursor_location(self): """Check whether the data location of the last known position of the cursor has changed. If so, issue a callback. """ # Check whether cursor data position has changed relative # to previous value data_x, data_y = self.get_data_xy(self.last_win_x, self.last_win_y) if (data_x != self.last_data_x or data_y != self.last_data_y): self.last_data_x, self.last_data_y = data_x, data_y self.logger.debug("cursor location changed %.4f,%.4f => %.4f,%.4f" % ( self.last_data_x, self.last_data_y, data_x, data_y)) # we make this call compatible with the motion callback # for now, but there is no concept of a button here button = 0 self.make_ui_callback('cursor-changed', button, data_x, data_y) return data_x, data_y
[ "def", "check_cursor_location", "(", "self", ")", ":", "# Check whether cursor data position has changed relative", "# to previous value", "data_x", ",", "data_y", "=", "self", ".", "get_data_xy", "(", "self", ".", "last_win_x", ",", "self", ".", "last_win_y", ")", "i...
Check whether the data location of the last known position of the cursor has changed. If so, issue a callback.
[ "Check", "whether", "the", "data", "location", "of", "the", "last", "known", "position", "of", "the", "cursor", "has", "changed", ".", "If", "so", "issue", "a", "callback", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1326-L1346
train
24,953
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.getwin_array
def getwin_array(self, order='RGB', alpha=1.0, dtype=None): """Get Numpy data array for display window. Parameters ---------- order : str The desired order of RGB color layers. alpha : float Opacity. dtype : numpy dtype Numpy data type desired; defaults to rgb mapper setting. Returns ------- outarr : ndarray Numpy data array for display window. """ order = order.upper() depth = len(order) if dtype is None: rgbmap = self.get_rgbmap() dtype = rgbmap.dtype # Prepare data array for rendering data = self._rgbobj.get_array(order, dtype=dtype) # NOTE [A] height, width, depth = data.shape imgwin_wd, imgwin_ht = self.get_window_size() # create RGBA image array with the background color for output r, g, b = self.img_bg outarr = trcalc.make_filled_array((imgwin_ht, imgwin_wd, len(order)), dtype, order, r, g, b, alpha) # overlay our data trcalc.overlay_image(outarr, (self._dst_x, self._dst_y), data, dst_order=order, src_order=order, flipy=False, fill=False, copy=False) return outarr
python
def getwin_array(self, order='RGB', alpha=1.0, dtype=None): """Get Numpy data array for display window. Parameters ---------- order : str The desired order of RGB color layers. alpha : float Opacity. dtype : numpy dtype Numpy data type desired; defaults to rgb mapper setting. Returns ------- outarr : ndarray Numpy data array for display window. """ order = order.upper() depth = len(order) if dtype is None: rgbmap = self.get_rgbmap() dtype = rgbmap.dtype # Prepare data array for rendering data = self._rgbobj.get_array(order, dtype=dtype) # NOTE [A] height, width, depth = data.shape imgwin_wd, imgwin_ht = self.get_window_size() # create RGBA image array with the background color for output r, g, b = self.img_bg outarr = trcalc.make_filled_array((imgwin_ht, imgwin_wd, len(order)), dtype, order, r, g, b, alpha) # overlay our data trcalc.overlay_image(outarr, (self._dst_x, self._dst_y), data, dst_order=order, src_order=order, flipy=False, fill=False, copy=False) return outarr
[ "def", "getwin_array", "(", "self", ",", "order", "=", "'RGB'", ",", "alpha", "=", "1.0", ",", "dtype", "=", "None", ")", ":", "order", "=", "order", ".", "upper", "(", ")", "depth", "=", "len", "(", "order", ")", "if", "dtype", "is", "None", ":"...
Get Numpy data array for display window. Parameters ---------- order : str The desired order of RGB color layers. alpha : float Opacity. dtype : numpy dtype Numpy data type desired; defaults to rgb mapper setting. Returns ------- outarr : ndarray Numpy data array for display window.
[ "Get", "Numpy", "data", "array", "for", "display", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1348-L1393
train
24,954
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_datarect
def get_datarect(self): """Get the approximate bounding box of the displayed image. Returns ------- rect : tuple Bounding box in data coordinates in the form of ``(x1, y1, x2, y2)``. """ x1, y1, x2, y2 = self._org_x1, self._org_y1, self._org_x2, self._org_y2 return (x1, y1, x2, y2)
python
def get_datarect(self): """Get the approximate bounding box of the displayed image. Returns ------- rect : tuple Bounding box in data coordinates in the form of ``(x1, y1, x2, y2)``. """ x1, y1, x2, y2 = self._org_x1, self._org_y1, self._org_x2, self._org_y2 return (x1, y1, x2, y2)
[ "def", "get_datarect", "(", "self", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "self", ".", "_org_x1", ",", "self", ".", "_org_y1", ",", "self", ".", "_org_x2", ",", "self", ".", "_org_y2", "return", "(", "x1", ",", "y1", ",", "x2", ...
Get the approximate bounding box of the displayed image. Returns ------- rect : tuple Bounding box in data coordinates in the form of ``(x1, y1, x2, y2)``.
[ "Get", "the", "approximate", "bounding", "box", "of", "the", "displayed", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1407-L1418
train
24,955
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_limits
def get_limits(self, coord='data'): """Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``. """ limits = self.t_['limits'] if limits is None: # No user defined limits. If there is an image loaded # use its dimensions as the limits image = self.get_image() if image is not None: wd, ht = image.get_size() limits = ((self.data_off, self.data_off), (float(wd - 1 + self.data_off), float(ht - 1 + self.data_off))) else: # Calculate limits based on plotted points, if any canvas = self.get_canvas() pts = canvas.get_points() if len(pts) > 0: limits = trcalc.get_bounds(pts) else: # No limits found, go to default limits = ((0.0, 0.0), (0.0, 0.0)) # convert to desired coordinates crdmap = self.get_coordmap(coord) limits = crdmap.data_to(limits) return limits
python
def get_limits(self, coord='data'): """Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``. """ limits = self.t_['limits'] if limits is None: # No user defined limits. If there is an image loaded # use its dimensions as the limits image = self.get_image() if image is not None: wd, ht = image.get_size() limits = ((self.data_off, self.data_off), (float(wd - 1 + self.data_off), float(ht - 1 + self.data_off))) else: # Calculate limits based on plotted points, if any canvas = self.get_canvas() pts = canvas.get_points() if len(pts) > 0: limits = trcalc.get_bounds(pts) else: # No limits found, go to default limits = ((0.0, 0.0), (0.0, 0.0)) # convert to desired coordinates crdmap = self.get_coordmap(coord) limits = crdmap.data_to(limits) return limits
[ "def", "get_limits", "(", "self", ",", "coord", "=", "'data'", ")", ":", "limits", "=", "self", ".", "t_", "[", "'limits'", "]", "if", "limits", "is", "None", ":", "# No user defined limits. If there is an image loaded", "# use its dimensions as the limits", "image...
Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``.
[ "Get", "the", "bounding", "box", "of", "the", "viewer", "extents", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1420-L1456
train
24,956
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_limits
def set_limits(self, limits, coord='data'): """Set the bounding box of the viewer extents. Parameters ---------- limits : tuple or None A tuple setting the extents of the viewer in the form of ``(ll_pt, ur_pt)``. """ if limits is not None: if len(limits) != 2: raise ValueError("limits takes a 2 tuple, or None") # convert to data coordinates crdmap = self.get_coordmap(coord) limits = crdmap.to_data(limits) self.t_.set(limits=limits)
python
def set_limits(self, limits, coord='data'): """Set the bounding box of the viewer extents. Parameters ---------- limits : tuple or None A tuple setting the extents of the viewer in the form of ``(ll_pt, ur_pt)``. """ if limits is not None: if len(limits) != 2: raise ValueError("limits takes a 2 tuple, or None") # convert to data coordinates crdmap = self.get_coordmap(coord) limits = crdmap.to_data(limits) self.t_.set(limits=limits)
[ "def", "set_limits", "(", "self", ",", "limits", ",", "coord", "=", "'data'", ")", ":", "if", "limits", "is", "not", "None", ":", "if", "len", "(", "limits", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"limits takes a 2 tuple, or None\"", ")", "# ...
Set the bounding box of the viewer extents. Parameters ---------- limits : tuple or None A tuple setting the extents of the viewer in the form of ``(ll_pt, ur_pt)``.
[ "Set", "the", "bounding", "box", "of", "the", "viewer", "extents", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1458-L1475
train
24,957
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_rgb_object
def get_rgb_object(self, whence=0): """Create and return RGB slices representing the data that should be rendered at the current zoom level and pan settings. Parameters ---------- whence : {0, 1, 2, 3} Optimization flag that reduces the time to create the RGB object by only recalculating what is necessary: 0. New image, pan/scale has changed, or rotation/transform has changed; Recalculate everything 1. Cut levels or similar has changed 2. Color mapping has changed 3. Graphical overlays have changed Returns ------- rgbobj : `~ginga.RGBMap.RGBPlanes` RGB object. """ time_start = t2 = t3 = time.time() win_wd, win_ht = self.get_window_size() order = self.get_rgb_order() if (whence <= 0.0) or (self._rgbarr is None): # calculate dimensions of window RGB backing image pan_x, pan_y = self.get_pan(coord='data')[:2] scale_x, scale_y = self.get_scale_xy() wd, ht = self._calc_bg_dimensions(scale_x, scale_y, pan_x, pan_y, win_wd, win_ht) # create backing image depth = len(order) rgbmap = self.get_rgbmap() # make backing image with the background color r, g, b = self.img_bg rgba = trcalc.make_filled_array((ht, wd, depth), rgbmap.dtype, order, r, g, b, 1.0) self._rgbarr = rgba t2 = time.time() if (whence <= 2.0) or (self._rgbarr2 is None): # Apply any RGB image overlays self._rgbarr2 = np.copy(self._rgbarr) self.overlay_images(self.private_canvas, self._rgbarr2, whence=whence) # convert to output ICC profile, if one is specified output_profile = self.t_.get('icc_output_profile', None) working_profile = rgb_cms.working_profile if (working_profile is not None) and (output_profile is not None): self.convert_via_profile(self._rgbarr2, order, working_profile, output_profile) t3 = time.time() if (whence <= 2.5) or (self._rgbobj is None): rotimg = self._rgbarr2 # Apply any viewing transformations or rotations # if not applied earlier rotimg = self.apply_transforms(rotimg, self.t_['rot_deg']) rotimg = np.ascontiguousarray(rotimg) self._rgbobj = RGBMap.RGBPlanes(rotimg, order) time_end = time.time() ## self.logger.debug("times: total=%.4f" % ( ## (time_end - time_start))) self.logger.debug("times: t1=%.4f t2=%.4f t3=%.4f total=%.4f" % ( t2 - time_start, t3 - t2, time_end - t3, (time_end - time_start))) return self._rgbobj
python
def get_rgb_object(self, whence=0): """Create and return RGB slices representing the data that should be rendered at the current zoom level and pan settings. Parameters ---------- whence : {0, 1, 2, 3} Optimization flag that reduces the time to create the RGB object by only recalculating what is necessary: 0. New image, pan/scale has changed, or rotation/transform has changed; Recalculate everything 1. Cut levels or similar has changed 2. Color mapping has changed 3. Graphical overlays have changed Returns ------- rgbobj : `~ginga.RGBMap.RGBPlanes` RGB object. """ time_start = t2 = t3 = time.time() win_wd, win_ht = self.get_window_size() order = self.get_rgb_order() if (whence <= 0.0) or (self._rgbarr is None): # calculate dimensions of window RGB backing image pan_x, pan_y = self.get_pan(coord='data')[:2] scale_x, scale_y = self.get_scale_xy() wd, ht = self._calc_bg_dimensions(scale_x, scale_y, pan_x, pan_y, win_wd, win_ht) # create backing image depth = len(order) rgbmap = self.get_rgbmap() # make backing image with the background color r, g, b = self.img_bg rgba = trcalc.make_filled_array((ht, wd, depth), rgbmap.dtype, order, r, g, b, 1.0) self._rgbarr = rgba t2 = time.time() if (whence <= 2.0) or (self._rgbarr2 is None): # Apply any RGB image overlays self._rgbarr2 = np.copy(self._rgbarr) self.overlay_images(self.private_canvas, self._rgbarr2, whence=whence) # convert to output ICC profile, if one is specified output_profile = self.t_.get('icc_output_profile', None) working_profile = rgb_cms.working_profile if (working_profile is not None) and (output_profile is not None): self.convert_via_profile(self._rgbarr2, order, working_profile, output_profile) t3 = time.time() if (whence <= 2.5) or (self._rgbobj is None): rotimg = self._rgbarr2 # Apply any viewing transformations or rotations # if not applied earlier rotimg = self.apply_transforms(rotimg, self.t_['rot_deg']) rotimg = np.ascontiguousarray(rotimg) self._rgbobj = RGBMap.RGBPlanes(rotimg, order) time_end = time.time() ## self.logger.debug("times: total=%.4f" % ( ## (time_end - time_start))) self.logger.debug("times: t1=%.4f t2=%.4f t3=%.4f total=%.4f" % ( t2 - time_start, t3 - t2, time_end - t3, (time_end - time_start))) return self._rgbobj
[ "def", "get_rgb_object", "(", "self", ",", "whence", "=", "0", ")", ":", "time_start", "=", "t2", "=", "t3", "=", "time", ".", "time", "(", ")", "win_wd", ",", "win_ht", "=", "self", ".", "get_window_size", "(", ")", "order", "=", "self", ".", "get...
Create and return RGB slices representing the data that should be rendered at the current zoom level and pan settings. Parameters ---------- whence : {0, 1, 2, 3} Optimization flag that reduces the time to create the RGB object by only recalculating what is necessary: 0. New image, pan/scale has changed, or rotation/transform has changed; Recalculate everything 1. Cut levels or similar has changed 2. Color mapping has changed 3. Graphical overlays have changed Returns ------- rgbobj : `~ginga.RGBMap.RGBPlanes` RGB object.
[ "Create", "and", "return", "RGB", "slices", "representing", "the", "data", "that", "should", "be", "rendered", "at", "the", "current", "zoom", "level", "and", "pan", "settings", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1482-L1559
train
24,958
ejeschke/ginga
ginga/ImageView.py
ImageViewBase._reset_bbox
def _reset_bbox(self): """This function should only be called internally. It resets the viewers bounding box based on changes to pan or scale. """ scale_x, scale_y = self.get_scale_xy() pan_x, pan_y = self.get_pan(coord='data')[:2] win_wd, win_ht = self.get_window_size() # NOTE: need to set at least a minimum 1-pixel dimension on # the window or we get a scale calculation exception. See github # issue 431 win_wd, win_ht = max(1, win_wd), max(1, win_ht) self._calc_bg_dimensions(scale_x, scale_y, pan_x, pan_y, win_wd, win_ht)
python
def _reset_bbox(self): """This function should only be called internally. It resets the viewers bounding box based on changes to pan or scale. """ scale_x, scale_y = self.get_scale_xy() pan_x, pan_y = self.get_pan(coord='data')[:2] win_wd, win_ht = self.get_window_size() # NOTE: need to set at least a minimum 1-pixel dimension on # the window or we get a scale calculation exception. See github # issue 431 win_wd, win_ht = max(1, win_wd), max(1, win_ht) self._calc_bg_dimensions(scale_x, scale_y, pan_x, pan_y, win_wd, win_ht)
[ "def", "_reset_bbox", "(", "self", ")", ":", "scale_x", ",", "scale_y", "=", "self", ".", "get_scale_xy", "(", ")", "pan_x", ",", "pan_y", "=", "self", ".", "get_pan", "(", "coord", "=", "'data'", ")", "[", ":", "2", "]", "win_wd", ",", "win_ht", "...
This function should only be called internally. It resets the viewers bounding box based on changes to pan or scale.
[ "This", "function", "should", "only", "be", "called", "internally", ".", "It", "resets", "the", "viewers", "bounding", "box", "based", "on", "changes", "to", "pan", "or", "scale", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1623-L1636
train
24,959
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.overlay_images
def overlay_images(self, canvas, data, whence=0.0): """Overlay data from any canvas image objects. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas containing possible images to overlay. data : ndarray Output array on which to overlay image data. whence See :meth:`get_rgb_object`. """ #if not canvas.is_compound(): if not hasattr(canvas, 'objects'): return for obj in canvas.get_objects(): if hasattr(obj, 'draw_image'): obj.draw_image(self, data, whence=whence) elif obj.is_compound() and (obj != canvas): self.overlay_images(obj, data, whence=whence)
python
def overlay_images(self, canvas, data, whence=0.0): """Overlay data from any canvas image objects. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas containing possible images to overlay. data : ndarray Output array on which to overlay image data. whence See :meth:`get_rgb_object`. """ #if not canvas.is_compound(): if not hasattr(canvas, 'objects'): return for obj in canvas.get_objects(): if hasattr(obj, 'draw_image'): obj.draw_image(self, data, whence=whence) elif obj.is_compound() and (obj != canvas): self.overlay_images(obj, data, whence=whence)
[ "def", "overlay_images", "(", "self", ",", "canvas", ",", "data", ",", "whence", "=", "0.0", ")", ":", "#if not canvas.is_compound():", "if", "not", "hasattr", "(", "canvas", ",", "'objects'", ")", ":", "return", "for", "obj", "in", "canvas", ".", "get_obj...
Overlay data from any canvas image objects. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas containing possible images to overlay. data : ndarray Output array on which to overlay image data. whence See :meth:`get_rgb_object`.
[ "Overlay", "data", "from", "any", "canvas", "image", "objects", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1712-L1735
train
24,960
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.convert_via_profile
def convert_via_profile(self, data_np, order, inprof_name, outprof_name): """Convert the given RGB data from the working ICC profile to the output profile in-place. Parameters ---------- data_np : ndarray RGB image data to be displayed. order : str Order of channels in the data (e.g. "BGRA"). inprof_name, outprof_name : str ICC profile names (see :func:`ginga.util.rgb_cms.get_profiles`). """ # get rest of necessary conversion parameters to_intent = self.t_.get('icc_output_intent', 'perceptual') proofprof_name = self.t_.get('icc_proof_profile', None) proof_intent = self.t_.get('icc_proof_intent', 'perceptual') use_black_pt = self.t_.get('icc_black_point_compensation', False) try: rgbobj = RGBMap.RGBPlanes(data_np, order) arr_np = rgbobj.get_array('RGB') arr = rgb_cms.convert_profile_fromto(arr_np, inprof_name, outprof_name, to_intent=to_intent, proof_name=proofprof_name, proof_intent=proof_intent, use_black_pt=use_black_pt, logger=self.logger) ri, gi, bi = rgbobj.get_order_indexes('RGB') out = data_np out[..., ri] = arr[..., 0] out[..., gi] = arr[..., 1] out[..., bi] = arr[..., 2] self.logger.debug("Converted from '%s' to '%s' profile" % ( inprof_name, outprof_name)) except Exception as e: self.logger.warning("Error converting output from working profile: %s" % (str(e))) # TODO: maybe should have a traceback here self.logger.info("Output left unprofiled")
python
def convert_via_profile(self, data_np, order, inprof_name, outprof_name): """Convert the given RGB data from the working ICC profile to the output profile in-place. Parameters ---------- data_np : ndarray RGB image data to be displayed. order : str Order of channels in the data (e.g. "BGRA"). inprof_name, outprof_name : str ICC profile names (see :func:`ginga.util.rgb_cms.get_profiles`). """ # get rest of necessary conversion parameters to_intent = self.t_.get('icc_output_intent', 'perceptual') proofprof_name = self.t_.get('icc_proof_profile', None) proof_intent = self.t_.get('icc_proof_intent', 'perceptual') use_black_pt = self.t_.get('icc_black_point_compensation', False) try: rgbobj = RGBMap.RGBPlanes(data_np, order) arr_np = rgbobj.get_array('RGB') arr = rgb_cms.convert_profile_fromto(arr_np, inprof_name, outprof_name, to_intent=to_intent, proof_name=proofprof_name, proof_intent=proof_intent, use_black_pt=use_black_pt, logger=self.logger) ri, gi, bi = rgbobj.get_order_indexes('RGB') out = data_np out[..., ri] = arr[..., 0] out[..., gi] = arr[..., 1] out[..., bi] = arr[..., 2] self.logger.debug("Converted from '%s' to '%s' profile" % ( inprof_name, outprof_name)) except Exception as e: self.logger.warning("Error converting output from working profile: %s" % (str(e))) # TODO: maybe should have a traceback here self.logger.info("Output left unprofiled")
[ "def", "convert_via_profile", "(", "self", ",", "data_np", ",", "order", ",", "inprof_name", ",", "outprof_name", ")", ":", "# get rest of necessary conversion parameters", "to_intent", "=", "self", ".", "t_", ".", "get", "(", "'icc_output_intent'", ",", "'perceptua...
Convert the given RGB data from the working ICC profile to the output profile in-place. Parameters ---------- data_np : ndarray RGB image data to be displayed. order : str Order of channels in the data (e.g. "BGRA"). inprof_name, outprof_name : str ICC profile names (see :func:`ginga.util.rgb_cms.get_profiles`).
[ "Convert", "the", "given", "RGB", "data", "from", "the", "working", "ICC", "profile", "to", "the", "output", "profile", "in", "-", "place", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1737-L1782
train
24,961
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_data_xy
def get_data_xy(self, win_x, win_y, center=None): """Get the closest coordinates in the data array to those reported on the window. Parameters ---------- win_x, win_y : float or ndarray Window coordinates. center : bool If `True`, then the coordinates are mapped such that the pixel is centered on the square when the image is zoomed in past 1X. This is the specification of the FITS image standard, that the pixel is centered on the integer row/column. Returns ------- coord : tuple Data coordinates in the form of ``(x, y)``. """ if center is not None: self.logger.warning("`center` keyword is ignored and will be deprecated") arr_pts = np.asarray((win_x, win_y)).T return self.tform['data_to_native'].from_(arr_pts).T[:2]
python
def get_data_xy(self, win_x, win_y, center=None): """Get the closest coordinates in the data array to those reported on the window. Parameters ---------- win_x, win_y : float or ndarray Window coordinates. center : bool If `True`, then the coordinates are mapped such that the pixel is centered on the square when the image is zoomed in past 1X. This is the specification of the FITS image standard, that the pixel is centered on the integer row/column. Returns ------- coord : tuple Data coordinates in the form of ``(x, y)``. """ if center is not None: self.logger.warning("`center` keyword is ignored and will be deprecated") arr_pts = np.asarray((win_x, win_y)).T return self.tform['data_to_native'].from_(arr_pts).T[:2]
[ "def", "get_data_xy", "(", "self", ",", "win_x", ",", "win_y", ",", "center", "=", "None", ")", ":", "if", "center", "is", "not", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"`center` keyword is ignored and will be deprecated\"", ")", "arr_pts",...
Get the closest coordinates in the data array to those reported on the window. Parameters ---------- win_x, win_y : float or ndarray Window coordinates. center : bool If `True`, then the coordinates are mapped such that the pixel is centered on the square when the image is zoomed in past 1X. This is the specification of the FITS image standard, that the pixel is centered on the integer row/column. Returns ------- coord : tuple Data coordinates in the form of ``(x, y)``.
[ "Get", "the", "closest", "coordinates", "in", "the", "data", "array", "to", "those", "reported", "on", "the", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1791-L1816
train
24,962
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.offset_to_window
def offset_to_window(self, off_x, off_y): """Convert data offset to window coordinates. Parameters ---------- off_x, off_y : float or ndarray Data offsets. Returns ------- coord : tuple Offset in window coordinates in the form of ``(x, y)``. """ arr_pts = np.asarray((off_x, off_y)).T return self.tform['cartesian_to_native'].to_(arr_pts).T[:2]
python
def offset_to_window(self, off_x, off_y): """Convert data offset to window coordinates. Parameters ---------- off_x, off_y : float or ndarray Data offsets. Returns ------- coord : tuple Offset in window coordinates in the form of ``(x, y)``. """ arr_pts = np.asarray((off_x, off_y)).T return self.tform['cartesian_to_native'].to_(arr_pts).T[:2]
[ "def", "offset_to_window", "(", "self", ",", "off_x", ",", "off_y", ")", ":", "arr_pts", "=", "np", ".", "asarray", "(", "(", "off_x", ",", "off_y", ")", ")", ".", "T", "return", "self", ".", "tform", "[", "'cartesian_to_native'", "]", ".", "to_", "(...
Convert data offset to window coordinates. Parameters ---------- off_x, off_y : float or ndarray Data offsets. Returns ------- coord : tuple Offset in window coordinates in the form of ``(x, y)``.
[ "Convert", "data", "offset", "to", "window", "coordinates", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1866-L1881
train
24,963
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_pan_rect
def get_pan_rect(self): """Get the coordinates in the actual data corresponding to the area shown in the display for the current zoom level and pan. Returns ------- points : list Coordinates in the form of ``[(x0, y0), (x1, y1), (x2, y2), (x3, y3)]`` from lower-left to lower-right. """ wd, ht = self.get_window_size() #win_pts = np.asarray([(0, 0), (wd-1, 0), (wd-1, ht-1), (0, ht-1)]) win_pts = np.asarray([(0, 0), (wd, 0), (wd, ht), (0, ht)]) arr_pts = self.tform['data_to_window'].from_(win_pts) return arr_pts
python
def get_pan_rect(self): """Get the coordinates in the actual data corresponding to the area shown in the display for the current zoom level and pan. Returns ------- points : list Coordinates in the form of ``[(x0, y0), (x1, y1), (x2, y2), (x3, y3)]`` from lower-left to lower-right. """ wd, ht = self.get_window_size() #win_pts = np.asarray([(0, 0), (wd-1, 0), (wd-1, ht-1), (0, ht-1)]) win_pts = np.asarray([(0, 0), (wd, 0), (wd, ht), (0, ht)]) arr_pts = self.tform['data_to_window'].from_(win_pts) return arr_pts
[ "def", "get_pan_rect", "(", "self", ")", ":", "wd", ",", "ht", "=", "self", ".", "get_window_size", "(", ")", "#win_pts = np.asarray([(0, 0), (wd-1, 0), (wd-1, ht-1), (0, ht-1)])", "win_pts", "=", "np", ".", "asarray", "(", "[", "(", "0", ",", "0", ")", ",", ...
Get the coordinates in the actual data corresponding to the area shown in the display for the current zoom level and pan. Returns ------- points : list Coordinates in the form of ``[(x0, y0), (x1, y1), (x2, y2), (x3, y3)]`` from lower-left to lower-right.
[ "Get", "the", "coordinates", "in", "the", "actual", "data", "corresponding", "to", "the", "area", "shown", "in", "the", "display", "for", "the", "current", "zoom", "level", "and", "pan", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1921-L1937
train
24,964
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_data
def get_data(self, data_x, data_y): """Get the data value at the given position. Indices are zero-based, as in Numpy. Parameters ---------- data_x, data_y : int Data indices for X and Y, respectively. Returns ------- value Data slice. Raises ------ ginga.ImageView.ImageViewNoDataError Image not found. """ image = self.get_image() if image is not None: return image.get_data_xy(data_x, data_y) raise ImageViewNoDataError("No image found")
python
def get_data(self, data_x, data_y): """Get the data value at the given position. Indices are zero-based, as in Numpy. Parameters ---------- data_x, data_y : int Data indices for X and Y, respectively. Returns ------- value Data slice. Raises ------ ginga.ImageView.ImageViewNoDataError Image not found. """ image = self.get_image() if image is not None: return image.get_data_xy(data_x, data_y) raise ImageViewNoDataError("No image found")
[ "def", "get_data", "(", "self", ",", "data_x", ",", "data_y", ")", ":", "image", "=", "self", ".", "get_image", "(", ")", "if", "image", "is", "not", "None", ":", "return", "image", ".", "get_data_xy", "(", "data_x", ",", "data_y", ")", "raise", "Ima...
Get the data value at the given position. Indices are zero-based, as in Numpy. Parameters ---------- data_x, data_y : int Data indices for X and Y, respectively. Returns ------- value Data slice. Raises ------ ginga.ImageView.ImageViewNoDataError Image not found.
[ "Get", "the", "data", "value", "at", "the", "given", "position", ".", "Indices", "are", "zero", "-", "based", "as", "in", "Numpy", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1939-L1963
train
24,965
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_pixel_distance
def get_pixel_distance(self, x1, y1, x2, y2): """Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance. """ dx = abs(x2 - x1) dy = abs(y2 - y1) dist = np.sqrt(dx * dx + dy * dy) dist = np.round(dist) return dist
python
def get_pixel_distance(self, x1, y1, x2, y2): """Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance. """ dx = abs(x2 - x1) dy = abs(y2 - y1) dist = np.sqrt(dx * dx + dy * dy) dist = np.round(dist) return dist
[ "def", "get_pixel_distance", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "dx", "=", "abs", "(", "x2", "-", "x1", ")", "dy", "=", "abs", "(", "y2", "-", "y1", ")", "dist", "=", "np", ".", "sqrt", "(", "dx", "*", "dx", ...
Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance.
[ "Calculate", "distance", "between", "the", "given", "pixel", "positions", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1965-L1983
train
24,966
ejeschke/ginga
ginga/ImageView.py
ImageViewBase._sanity_check_scale
def _sanity_check_scale(self, scale_x, scale_y): """Do a sanity check on the proposed scale vs. window size. Raises an exception if there will be a problem. """ win_wd, win_ht = self.get_window_size() if (win_wd <= 0) or (win_ht <= 0): raise ImageViewError("window size undefined") # final sanity check on resulting output image size if (win_wd * scale_x < 1) or (win_ht * scale_y < 1): raise ValueError( "resulting scale (%f, %f) would result in image size of " "<1 in width or height" % (scale_x, scale_y)) sx = float(win_wd) / scale_x sy = float(win_ht) / scale_y if (sx < 1.0) or (sy < 1.0): raise ValueError( "resulting scale (%f, %f) would result in pixel size " "approaching window size" % (scale_x, scale_y))
python
def _sanity_check_scale(self, scale_x, scale_y): """Do a sanity check on the proposed scale vs. window size. Raises an exception if there will be a problem. """ win_wd, win_ht = self.get_window_size() if (win_wd <= 0) or (win_ht <= 0): raise ImageViewError("window size undefined") # final sanity check on resulting output image size if (win_wd * scale_x < 1) or (win_ht * scale_y < 1): raise ValueError( "resulting scale (%f, %f) would result in image size of " "<1 in width or height" % (scale_x, scale_y)) sx = float(win_wd) / scale_x sy = float(win_ht) / scale_y if (sx < 1.0) or (sy < 1.0): raise ValueError( "resulting scale (%f, %f) would result in pixel size " "approaching window size" % (scale_x, scale_y))
[ "def", "_sanity_check_scale", "(", "self", ",", "scale_x", ",", "scale_y", ")", ":", "win_wd", ",", "win_ht", "=", "self", ".", "get_window_size", "(", ")", "if", "(", "win_wd", "<=", "0", ")", "or", "(", "win_ht", "<=", "0", ")", ":", "raise", "Imag...
Do a sanity check on the proposed scale vs. window size. Raises an exception if there will be a problem.
[ "Do", "a", "sanity", "check", "on", "the", "proposed", "scale", "vs", ".", "window", "size", ".", "Raises", "an", "exception", "if", "there", "will", "be", "a", "problem", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1985-L2004
train
24,967
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.scale_cb
def scale_cb(self, setting, value): """Handle callback related to image scaling.""" zoomlevel = self.zoom.calc_level(value) self.t_.set(zoomlevel=zoomlevel) self.redraw(whence=0)
python
def scale_cb(self, setting, value): """Handle callback related to image scaling.""" zoomlevel = self.zoom.calc_level(value) self.t_.set(zoomlevel=zoomlevel) self.redraw(whence=0)
[ "def", "scale_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "zoomlevel", "=", "self", ".", "zoom", ".", "calc_level", "(", "value", ")", "self", ".", "t_", ".", "set", "(", "zoomlevel", "=", "zoomlevel", ")", "self", ".", "redraw", "(", ...
Handle callback related to image scaling.
[ "Handle", "callback", "related", "to", "image", "scaling", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2088-L2093
train
24,968
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_scale_base_xy
def set_scale_base_xy(self, scale_x_base, scale_y_base): """Set stretch factors. Parameters ---------- scale_x_base, scale_y_base : float Stretch factors for X and Y, respectively. """ self.t_.set(scale_x_base=scale_x_base, scale_y_base=scale_y_base)
python
def set_scale_base_xy(self, scale_x_base, scale_y_base): """Set stretch factors. Parameters ---------- scale_x_base, scale_y_base : float Stretch factors for X and Y, respectively. """ self.t_.set(scale_x_base=scale_x_base, scale_y_base=scale_y_base)
[ "def", "set_scale_base_xy", "(", "self", ",", "scale_x_base", ",", "scale_y_base", ")", ":", "self", ".", "t_", ".", "set", "(", "scale_x_base", "=", "scale_x_base", ",", "scale_y_base", "=", "scale_y_base", ")" ]
Set stretch factors. Parameters ---------- scale_x_base, scale_y_base : float Stretch factors for X and Y, respectively.
[ "Set", "stretch", "factors", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2148-L2157
train
24,969
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_scale_text
def get_scale_text(self): """Report current scaling in human-readable format. Returns ------- text : str ``'<num> x'`` if enlarged, or ``'1/<num> x'`` if shrunken. """ scalefactor = self.get_scale_max() if scalefactor >= 1.0: text = '%.2fx' % (scalefactor) else: text = '1/%.2fx' % (1.0 / scalefactor) return text
python
def get_scale_text(self): """Report current scaling in human-readable format. Returns ------- text : str ``'<num> x'`` if enlarged, or ``'1/<num> x'`` if shrunken. """ scalefactor = self.get_scale_max() if scalefactor >= 1.0: text = '%.2fx' % (scalefactor) else: text = '1/%.2fx' % (1.0 / scalefactor) return text
[ "def", "get_scale_text", "(", "self", ")", ":", "scalefactor", "=", "self", ".", "get_scale_max", "(", ")", "if", "scalefactor", ">=", "1.0", ":", "text", "=", "'%.2fx'", "%", "(", "scalefactor", ")", "else", ":", "text", "=", "'1/%.2fx'", "%", "(", "1...
Report current scaling in human-readable format. Returns ------- text : str ``'<num> x'`` if enlarged, or ``'1/<num> x'`` if shrunken.
[ "Report", "current", "scaling", "in", "human", "-", "readable", "format", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2159-L2173
train
24,970
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_zoom_algorithm
def set_zoom_algorithm(self, name): """Set zoom algorithm. Parameters ---------- name : str Name of a zoom algorithm to use. """ name = name.lower() alg_names = list(zoom.get_zoom_alg_names()) if name not in alg_names: raise ImageViewError("Alg '%s' must be one of: %s" % ( name, ', '.join(alg_names))) self.t_.set(zoom_algorithm=name)
python
def set_zoom_algorithm(self, name): """Set zoom algorithm. Parameters ---------- name : str Name of a zoom algorithm to use. """ name = name.lower() alg_names = list(zoom.get_zoom_alg_names()) if name not in alg_names: raise ImageViewError("Alg '%s' must be one of: %s" % ( name, ', '.join(alg_names))) self.t_.set(zoom_algorithm=name)
[ "def", "set_zoom_algorithm", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "alg_names", "=", "list", "(", "zoom", ".", "get_zoom_alg_names", "(", ")", ")", "if", "name", "not", "in", "alg_names", ":", "raise", "ImageV...
Set zoom algorithm. Parameters ---------- name : str Name of a zoom algorithm to use.
[ "Set", "zoom", "algorithm", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2328-L2342
train
24,971
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.zoomsetting_change_cb
def zoomsetting_change_cb(self, setting, value): """Handle callback related to changes in zoom.""" alg_name = self.t_['zoom_algorithm'] self.zoom = zoom.get_zoom_alg(alg_name)(self) self.zoom_to(self.get_zoom())
python
def zoomsetting_change_cb(self, setting, value): """Handle callback related to changes in zoom.""" alg_name = self.t_['zoom_algorithm'] self.zoom = zoom.get_zoom_alg(alg_name)(self) self.zoom_to(self.get_zoom())
[ "def", "zoomsetting_change_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "alg_name", "=", "self", ".", "t_", "[", "'zoom_algorithm'", "]", "self", ".", "zoom", "=", "zoom", ".", "get_zoom_alg", "(", "alg_name", ")", "(", "self", ")", "self", ...
Handle callback related to changes in zoom.
[ "Handle", "callback", "related", "to", "changes", "in", "zoom", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2344-L2349
train
24,972
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.interpolation_change_cb
def interpolation_change_cb(self, setting, value): """Handle callback related to changes in interpolation.""" canvas_img = self.get_canvas_image() canvas_img.interpolation = value canvas_img.reset_optimize() self.redraw(whence=0)
python
def interpolation_change_cb(self, setting, value): """Handle callback related to changes in interpolation.""" canvas_img = self.get_canvas_image() canvas_img.interpolation = value canvas_img.reset_optimize() self.redraw(whence=0)
[ "def", "interpolation_change_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "canvas_img", "=", "self", ".", "get_canvas_image", "(", ")", "canvas_img", ".", "interpolation", "=", "value", "canvas_img", ".", "reset_optimize", "(", ")", "self", ".", ...
Handle callback related to changes in interpolation.
[ "Handle", "callback", "related", "to", "changes", "in", "interpolation", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2351-L2356
train
24,973
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_scale_limits
def set_scale_limits(self, scale_min, scale_max): """Set scale limits. Parameters ---------- scale_min, scale_max : float Minimum and maximum scale limits, respectively. """ # TODO: force scale to within limits if already outside? self.t_.set(scale_min=scale_min, scale_max=scale_max)
python
def set_scale_limits(self, scale_min, scale_max): """Set scale limits. Parameters ---------- scale_min, scale_max : float Minimum and maximum scale limits, respectively. """ # TODO: force scale to within limits if already outside? self.t_.set(scale_min=scale_min, scale_max=scale_max)
[ "def", "set_scale_limits", "(", "self", ",", "scale_min", ",", "scale_max", ")", ":", "# TODO: force scale to within limits if already outside?", "self", ".", "t_", ".", "set", "(", "scale_min", "=", "scale_min", ",", "scale_max", "=", "scale_max", ")" ]
Set scale limits. Parameters ---------- scale_min, scale_max : float Minimum and maximum scale limits, respectively.
[ "Set", "scale", "limits", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2373-L2383
train
24,974
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.enable_autozoom
def enable_autozoom(self, option): """Set ``autozoom`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for zoom behavior. A list of acceptable options can also be obtained by :meth:`get_autozoom_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autozoom_options), \ ImageViewError("Bad autozoom option '%s': must be one of %s" % ( str(self.autozoom_options))) self.t_.set(autozoom=option)
python
def enable_autozoom(self, option): """Set ``autozoom`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for zoom behavior. A list of acceptable options can also be obtained by :meth:`get_autozoom_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autozoom_options), \ ImageViewError("Bad autozoom option '%s': must be one of %s" % ( str(self.autozoom_options))) self.t_.set(autozoom=option)
[ "def", "enable_autozoom", "(", "self", ",", "option", ")", ":", "option", "=", "option", ".", "lower", "(", ")", "assert", "(", "option", "in", "self", ".", "autozoom_options", ")", ",", "ImageViewError", "(", "\"Bad autozoom option '%s': must be one of %s\"", "...
Set ``autozoom`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for zoom behavior. A list of acceptable options can also be obtained by :meth:`get_autozoom_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option.
[ "Set", "autozoom", "behavior", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2385-L2404
train
24,975
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_pan
def set_pan(self, pan_x, pan_y, coord='data', no_reset=False): """Set pan position. Parameters ---------- pan_x, pan_y : float Pan positions in X and Y. coord : {'data', 'wcs'} Indicates whether the given pan positions are in data or WCS space. no_reset : bool Do not reset ``autocenter`` setting. """ pan_pos = (pan_x, pan_y) with self.suppress_redraw: self.t_.set(pan=pan_pos, pan_coord=coord) self._reset_bbox() # If user specified "override" or "once" for auto center, then turn off # auto center now that they have set the pan manually if (not no_reset) and (self.t_['autocenter'] in ('override', 'once')): self.t_.set(autocenter='off')
python
def set_pan(self, pan_x, pan_y, coord='data', no_reset=False): """Set pan position. Parameters ---------- pan_x, pan_y : float Pan positions in X and Y. coord : {'data', 'wcs'} Indicates whether the given pan positions are in data or WCS space. no_reset : bool Do not reset ``autocenter`` setting. """ pan_pos = (pan_x, pan_y) with self.suppress_redraw: self.t_.set(pan=pan_pos, pan_coord=coord) self._reset_bbox() # If user specified "override" or "once" for auto center, then turn off # auto center now that they have set the pan manually if (not no_reset) and (self.t_['autocenter'] in ('override', 'once')): self.t_.set(autocenter='off')
[ "def", "set_pan", "(", "self", ",", "pan_x", ",", "pan_y", ",", "coord", "=", "'data'", ",", "no_reset", "=", "False", ")", ":", "pan_pos", "=", "(", "pan_x", ",", "pan_y", ")", "with", "self", ".", "suppress_redraw", ":", "self", ".", "t_", ".", "...
Set pan position. Parameters ---------- pan_x, pan_y : float Pan positions in X and Y. coord : {'data', 'wcs'} Indicates whether the given pan positions are in data or WCS space. no_reset : bool Do not reset ``autocenter`` setting.
[ "Set", "pan", "position", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2417-L2441
train
24,976
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.pan_cb
def pan_cb(self, setting, value): """Handle callback related to changes in pan.""" pan_x, pan_y = value[:2] self.logger.debug("pan set to %.2f,%.2f" % (pan_x, pan_y)) self.redraw(whence=0)
python
def pan_cb(self, setting, value): """Handle callback related to changes in pan.""" pan_x, pan_y = value[:2] self.logger.debug("pan set to %.2f,%.2f" % (pan_x, pan_y)) self.redraw(whence=0)
[ "def", "pan_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "pan_x", ",", "pan_y", "=", "value", "[", ":", "2", "]", "self", ".", "logger", ".", "debug", "(", "\"pan set to %.2f,%.2f\"", "%", "(", "pan_x", ",", "pan_y", ")", ")", "self", ...
Handle callback related to changes in pan.
[ "Handle", "callback", "related", "to", "changes", "in", "pan", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2443-L2448
train
24,977
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_pan
def get_pan(self, coord='data'): """Get pan positions. Parameters ---------- coord : {'data', 'wcs'} Indicates whether the pan positions are returned in data or WCS space. Returns ------- positions : tuple X and Y positions, in that order. """ pan_x, pan_y = self.t_['pan'][:2] if coord == 'wcs': if self.t_['pan_coord'] == 'data': image = self.get_image() if image is not None: try: return image.pixtoradec(pan_x, pan_y) except Exception as e: pass # <-- data already in coordinates form return (pan_x, pan_y) # <-- requesting data coords if self.t_['pan_coord'] == 'data': return (pan_x, pan_y) image = self.get_image() if image is not None: try: return image.radectopix(pan_x, pan_y) except Exception as e: pass return (pan_x, pan_y)
python
def get_pan(self, coord='data'): """Get pan positions. Parameters ---------- coord : {'data', 'wcs'} Indicates whether the pan positions are returned in data or WCS space. Returns ------- positions : tuple X and Y positions, in that order. """ pan_x, pan_y = self.t_['pan'][:2] if coord == 'wcs': if self.t_['pan_coord'] == 'data': image = self.get_image() if image is not None: try: return image.pixtoradec(pan_x, pan_y) except Exception as e: pass # <-- data already in coordinates form return (pan_x, pan_y) # <-- requesting data coords if self.t_['pan_coord'] == 'data': return (pan_x, pan_y) image = self.get_image() if image is not None: try: return image.radectopix(pan_x, pan_y) except Exception as e: pass return (pan_x, pan_y)
[ "def", "get_pan", "(", "self", ",", "coord", "=", "'data'", ")", ":", "pan_x", ",", "pan_y", "=", "self", ".", "t_", "[", "'pan'", "]", "[", ":", "2", "]", "if", "coord", "==", "'wcs'", ":", "if", "self", ".", "t_", "[", "'pan_coord'", "]", "==...
Get pan positions. Parameters ---------- coord : {'data', 'wcs'} Indicates whether the pan positions are returned in data or WCS space. Returns ------- positions : tuple X and Y positions, in that order.
[ "Get", "pan", "positions", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2450-L2486
train
24,978
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.center_image
def center_image(self, no_reset=True): """Pan to the center of the image. Parameters ---------- no_reset : bool See :meth:`set_pan`. """ try: xy_mn, xy_mx = self.get_limits() data_x = float(xy_mn[0] + xy_mx[0]) / 2.0 data_y = float(xy_mn[1] + xy_mx[1]) / 2.0 except ImageViewNoDataError: # No data, so try to get center of any plotted objects canvas = self.get_canvas() try: data_x, data_y = canvas.get_center_pt()[:2] except Exception as e: self.logger.error("Can't compute center point: %s" % (str(e))) return self.panset_xy(data_x, data_y, no_reset=no_reset) if self.t_['autocenter'] == 'once': self.t_.set(autocenter='off')
python
def center_image(self, no_reset=True): """Pan to the center of the image. Parameters ---------- no_reset : bool See :meth:`set_pan`. """ try: xy_mn, xy_mx = self.get_limits() data_x = float(xy_mn[0] + xy_mx[0]) / 2.0 data_y = float(xy_mn[1] + xy_mx[1]) / 2.0 except ImageViewNoDataError: # No data, so try to get center of any plotted objects canvas = self.get_canvas() try: data_x, data_y = canvas.get_center_pt()[:2] except Exception as e: self.logger.error("Can't compute center point: %s" % (str(e))) return self.panset_xy(data_x, data_y, no_reset=no_reset) if self.t_['autocenter'] == 'once': self.t_.set(autocenter='off')
[ "def", "center_image", "(", "self", ",", "no_reset", "=", "True", ")", ":", "try", ":", "xy_mn", ",", "xy_mx", "=", "self", ".", "get_limits", "(", ")", "data_x", "=", "float", "(", "xy_mn", "[", "0", "]", "+", "xy_mx", "[", "0", "]", ")", "/", ...
Pan to the center of the image. Parameters ---------- no_reset : bool See :meth:`set_pan`.
[ "Pan", "to", "the", "center", "of", "the", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2523-L2550
train
24,979
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.enable_autocenter
def enable_autocenter(self, option): """Set ``autocenter`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-center behavior. A list of acceptable options can also be obtained by :meth:`get_autocenter_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autocenter_options), \ ImageViewError("Bad autocenter option '%s': must be one of %s" % ( str(self.autocenter_options))) self.t_.set(autocenter=option)
python
def enable_autocenter(self, option): """Set ``autocenter`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-center behavior. A list of acceptable options can also be obtained by :meth:`get_autocenter_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autocenter_options), \ ImageViewError("Bad autocenter option '%s': must be one of %s" % ( str(self.autocenter_options))) self.t_.set(autocenter=option)
[ "def", "enable_autocenter", "(", "self", ",", "option", ")", ":", "option", "=", "option", ".", "lower", "(", ")", "assert", "(", "option", "in", "self", ".", "autocenter_options", ")", ",", "ImageViewError", "(", "\"Bad autocenter option '%s': must be one of %s\"...
Set ``autocenter`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-center behavior. A list of acceptable options can also be obtained by :meth:`get_autocenter_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option.
[ "Set", "autocenter", "behavior", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2552-L2571
train
24,980
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.cut_levels
def cut_levels(self, loval, hival, no_reset=False): """Apply cut levels on the image view. Parameters ---------- loval, hival : float Low and high values of the cut levels, respectively. no_reset : bool Do not reset ``autocuts`` setting. """ self.t_.set(cuts=(loval, hival)) # If user specified "override" or "once" for auto levels, # then turn off auto levels now that they have set the levels # manually if (not no_reset) and (self.t_['autocuts'] in ('once', 'override')): self.t_.set(autocuts='off')
python
def cut_levels(self, loval, hival, no_reset=False): """Apply cut levels on the image view. Parameters ---------- loval, hival : float Low and high values of the cut levels, respectively. no_reset : bool Do not reset ``autocuts`` setting. """ self.t_.set(cuts=(loval, hival)) # If user specified "override" or "once" for auto levels, # then turn off auto levels now that they have set the levels # manually if (not no_reset) and (self.t_['autocuts'] in ('once', 'override')): self.t_.set(autocuts='off')
[ "def", "cut_levels", "(", "self", ",", "loval", ",", "hival", ",", "no_reset", "=", "False", ")", ":", "self", ".", "t_", ".", "set", "(", "cuts", "=", "(", "loval", ",", "hival", ")", ")", "# If user specified \"override\" or \"once\" for auto levels,", "# ...
Apply cut levels on the image view. Parameters ---------- loval, hival : float Low and high values of the cut levels, respectively. no_reset : bool Do not reset ``autocuts`` setting.
[ "Apply", "cut", "levels", "on", "the", "image", "view", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2608-L2626
train
24,981
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.auto_levels
def auto_levels(self, autocuts=None): """Apply auto-cut levels on the image view. Parameters ---------- autocuts : subclass of `~ginga.AutoCuts.AutoCutsBase` or `None` An object that implements the desired auto-cut algorithm. If not given, use algorithm from preferences. """ if autocuts is None: autocuts = self.autocuts image = self.get_image() if image is None: return loval, hival = autocuts.calc_cut_levels(image) # this will invoke cut_levels_cb() self.t_.set(cuts=(loval, hival)) # If user specified "once" for auto levels, then turn off # auto levels now that we have cut levels established if self.t_['autocuts'] == 'once': self.t_.set(autocuts='off')
python
def auto_levels(self, autocuts=None): """Apply auto-cut levels on the image view. Parameters ---------- autocuts : subclass of `~ginga.AutoCuts.AutoCutsBase` or `None` An object that implements the desired auto-cut algorithm. If not given, use algorithm from preferences. """ if autocuts is None: autocuts = self.autocuts image = self.get_image() if image is None: return loval, hival = autocuts.calc_cut_levels(image) # this will invoke cut_levels_cb() self.t_.set(cuts=(loval, hival)) # If user specified "once" for auto levels, then turn off # auto levels now that we have cut levels established if self.t_['autocuts'] == 'once': self.t_.set(autocuts='off')
[ "def", "auto_levels", "(", "self", ",", "autocuts", "=", "None", ")", ":", "if", "autocuts", "is", "None", ":", "autocuts", "=", "self", ".", "autocuts", "image", "=", "self", ".", "get_image", "(", ")", "if", "image", "is", "None", ":", "return", "l...
Apply auto-cut levels on the image view. Parameters ---------- autocuts : subclass of `~ginga.AutoCuts.AutoCutsBase` or `None` An object that implements the desired auto-cut algorithm. If not given, use algorithm from preferences.
[ "Apply", "auto", "-", "cut", "levels", "on", "the", "image", "view", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2628-L2653
train
24,982
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.auto_levels_cb
def auto_levels_cb(self, setting, value): """Handle callback related to changes in auto-cut levels.""" # Did we change the method? method = self.t_['autocut_method'] params = self.t_.get('autocut_params', []) params = dict(params) if method != str(self.autocuts): ac_class = AutoCuts.get_autocuts(method) self.autocuts = ac_class(self.logger, **params) else: self.autocuts.update_params(**params) # Redo the auto levels #if self.t_['autocuts'] != 'off': # NOTE: users seems to expect that when the auto cuts parameters # are changed that the cuts should be immediately recalculated self.auto_levels()
python
def auto_levels_cb(self, setting, value): """Handle callback related to changes in auto-cut levels.""" # Did we change the method? method = self.t_['autocut_method'] params = self.t_.get('autocut_params', []) params = dict(params) if method != str(self.autocuts): ac_class = AutoCuts.get_autocuts(method) self.autocuts = ac_class(self.logger, **params) else: self.autocuts.update_params(**params) # Redo the auto levels #if self.t_['autocuts'] != 'off': # NOTE: users seems to expect that when the auto cuts parameters # are changed that the cuts should be immediately recalculated self.auto_levels()
[ "def", "auto_levels_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "# Did we change the method?", "method", "=", "self", ".", "t_", "[", "'autocut_method'", "]", "params", "=", "self", ".", "t_", ".", "get", "(", "'autocut_params'", ",", "[", "]...
Handle callback related to changes in auto-cut levels.
[ "Handle", "callback", "related", "to", "changes", "in", "auto", "-", "cut", "levels", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2655-L2672
train
24,983
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.enable_autocuts
def enable_autocuts(self, option): """Set ``autocuts`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-cut behavior. A list of acceptable options can also be obtained by :meth:`get_autocuts_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autocuts_options), \ ImageViewError("Bad autocuts option '%s': must be one of %s" % ( str(self.autocuts_options))) self.t_.set(autocuts=option)
python
def enable_autocuts(self, option): """Set ``autocuts`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-cut behavior. A list of acceptable options can also be obtained by :meth:`get_autocuts_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option. """ option = option.lower() assert(option in self.autocuts_options), \ ImageViewError("Bad autocuts option '%s': must be one of %s" % ( str(self.autocuts_options))) self.t_.set(autocuts=option)
[ "def", "enable_autocuts", "(", "self", ",", "option", ")", ":", "option", "=", "option", ".", "lower", "(", ")", "assert", "(", "option", "in", "self", ".", "autocuts_options", ")", ",", "ImageViewError", "(", "\"Bad autocuts option '%s': must be one of %s\"", "...
Set ``autocuts`` behavior. Parameters ---------- option : {'on', 'override', 'once', 'off'} Option for auto-cut behavior. A list of acceptable options can also be obtained by :meth:`get_autocuts_options`. Raises ------ ginga.ImageView.ImageViewError Invalid option.
[ "Set", "autocuts", "behavior", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2678-L2697
train
24,984
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_autocut_params
def set_autocut_params(self, method, **params): """Set auto-cut parameters. Parameters ---------- method : str Auto-cut algorithm. A list of acceptable options can be obtained by :meth:`get_autocut_methods`. params : dict Algorithm-specific keywords and values. """ self.logger.debug("Setting autocut params method=%s params=%s" % ( method, str(params))) params = list(params.items()) self.t_.set(autocut_method=method, autocut_params=params)
python
def set_autocut_params(self, method, **params): """Set auto-cut parameters. Parameters ---------- method : str Auto-cut algorithm. A list of acceptable options can be obtained by :meth:`get_autocut_methods`. params : dict Algorithm-specific keywords and values. """ self.logger.debug("Setting autocut params method=%s params=%s" % ( method, str(params))) params = list(params.items()) self.t_.set(autocut_method=method, autocut_params=params)
[ "def", "set_autocut_params", "(", "self", ",", "method", ",", "*", "*", "params", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Setting autocut params method=%s params=%s\"", "%", "(", "method", ",", "str", "(", "params", ")", ")", ")", "params", ...
Set auto-cut parameters. Parameters ---------- method : str Auto-cut algorithm. A list of acceptable options can be obtained by :meth:`get_autocut_methods`. params : dict Algorithm-specific keywords and values.
[ "Set", "auto", "-", "cut", "parameters", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2710-L2726
train
24,985
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.transform
def transform(self, flip_x, flip_y, swap_xy): """Transform view of the image. .. note:: Transforming the image is generally faster than rotating, if rotating in 90 degree increments. Also see :meth:`rotate`. Parameters ---------- flipx, flipy : bool If `True`, flip the image in the X and Y axes, respectively swapxy : bool If `True`, swap the X and Y axes. """ self.logger.debug("flip_x=%s flip_y=%s swap_xy=%s" % ( flip_x, flip_y, swap_xy)) with self.suppress_redraw: self.t_.set(flip_x=flip_x, flip_y=flip_y, swap_xy=swap_xy)
python
def transform(self, flip_x, flip_y, swap_xy): """Transform view of the image. .. note:: Transforming the image is generally faster than rotating, if rotating in 90 degree increments. Also see :meth:`rotate`. Parameters ---------- flipx, flipy : bool If `True`, flip the image in the X and Y axes, respectively swapxy : bool If `True`, swap the X and Y axes. """ self.logger.debug("flip_x=%s flip_y=%s swap_xy=%s" % ( flip_x, flip_y, swap_xy)) with self.suppress_redraw: self.t_.set(flip_x=flip_x, flip_y=flip_y, swap_xy=swap_xy)
[ "def", "transform", "(", "self", ",", "flip_x", ",", "flip_y", ",", "swap_xy", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"flip_x=%s flip_y=%s swap_xy=%s\"", "%", "(", "flip_x", ",", "flip_y", ",", "swap_xy", ")", ")", "with", "self", ".", "su...
Transform view of the image. .. note:: Transforming the image is generally faster than rotating, if rotating in 90 degree increments. Also see :meth:`rotate`. Parameters ---------- flipx, flipy : bool If `True`, flip the image in the X and Y axes, respectively swapxy : bool If `True`, swap the X and Y axes.
[ "Transform", "view", "of", "the", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2743-L2764
train
24,986
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.transform_cb
def transform_cb(self, setting, value): """Handle callback related to changes in transformations.""" self.make_callback('transform') # whence=0 because need to calculate new extents for proper # cutout for rotation (TODO: always make extents consider # room for rotation) whence = 0 self.redraw(whence=whence)
python
def transform_cb(self, setting, value): """Handle callback related to changes in transformations.""" self.make_callback('transform') # whence=0 because need to calculate new extents for proper # cutout for rotation (TODO: always make extents consider # room for rotation) whence = 0 self.redraw(whence=whence)
[ "def", "transform_cb", "(", "self", ",", "setting", ",", "value", ")", ":", "self", ".", "make_callback", "(", "'transform'", ")", "# whence=0 because need to calculate new extents for proper", "# cutout for rotation (TODO: always make extents consider", "# room for rotation)", ...
Handle callback related to changes in transformations.
[ "Handle", "callback", "related", "to", "changes", "in", "transformations", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2766-L2774
train
24,987
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.copy_attributes
def copy_attributes(self, dst_fi, attrlist, share=False): """Copy interesting attributes of our configuration to another image view. Parameters ---------- dst_fi : subclass of `ImageViewBase` Another instance of image view. attrlist : list A list of attribute names to copy. They can be ``'transforms'``, ``'rotation'``, ``'cutlevels'``, ``'rgbmap'``, ``'zoom'``, ``'pan'``, ``'autocuts'``. share : bool If True, the designated settings will be shared, otherwise the values are simply copied. """ # TODO: change API to just go with settings names? keylist = [] if 'transforms' in attrlist: keylist.extend(['flip_x', 'flip_y', 'swap_xy']) if 'rotation' in attrlist: keylist.extend(['rot_deg']) if 'autocuts' in attrlist: keylist.extend(['autocut_method', 'autocut_params']) if 'cutlevels' in attrlist: keylist.extend(['cuts']) if 'rgbmap' in attrlist: keylist.extend(['color_algorithm', 'color_hashsize', 'color_map', 'intensity_map', 'color_array', 'shift_array']) if 'zoom' in attrlist: keylist.extend(['scale']) if 'pan' in attrlist: keylist.extend(['pan']) with dst_fi.suppress_redraw: if share: self.t_.share_settings(dst_fi.get_settings(), keylist=keylist) else: self.t_.copy_settings(dst_fi.get_settings(), keylist=keylist) dst_fi.redraw(whence=0)
python
def copy_attributes(self, dst_fi, attrlist, share=False): """Copy interesting attributes of our configuration to another image view. Parameters ---------- dst_fi : subclass of `ImageViewBase` Another instance of image view. attrlist : list A list of attribute names to copy. They can be ``'transforms'``, ``'rotation'``, ``'cutlevels'``, ``'rgbmap'``, ``'zoom'``, ``'pan'``, ``'autocuts'``. share : bool If True, the designated settings will be shared, otherwise the values are simply copied. """ # TODO: change API to just go with settings names? keylist = [] if 'transforms' in attrlist: keylist.extend(['flip_x', 'flip_y', 'swap_xy']) if 'rotation' in attrlist: keylist.extend(['rot_deg']) if 'autocuts' in attrlist: keylist.extend(['autocut_method', 'autocut_params']) if 'cutlevels' in attrlist: keylist.extend(['cuts']) if 'rgbmap' in attrlist: keylist.extend(['color_algorithm', 'color_hashsize', 'color_map', 'intensity_map', 'color_array', 'shift_array']) if 'zoom' in attrlist: keylist.extend(['scale']) if 'pan' in attrlist: keylist.extend(['pan']) with dst_fi.suppress_redraw: if share: self.t_.share_settings(dst_fi.get_settings(), keylist=keylist) else: self.t_.copy_settings(dst_fi.get_settings(), keylist=keylist) dst_fi.redraw(whence=0)
[ "def", "copy_attributes", "(", "self", ",", "dst_fi", ",", "attrlist", ",", "share", "=", "False", ")", ":", "# TODO: change API to just go with settings names?", "keylist", "=", "[", "]", "if", "'transforms'", "in", "attrlist", ":", "keylist", ".", "extend", "(...
Copy interesting attributes of our configuration to another image view. Parameters ---------- dst_fi : subclass of `ImageViewBase` Another instance of image view. attrlist : list A list of attribute names to copy. They can be ``'transforms'``, ``'rotation'``, ``'cutlevels'``, ``'rgbmap'``, ``'zoom'``, ``'pan'``, ``'autocuts'``. share : bool If True, the designated settings will be shared, otherwise the values are simply copied.
[ "Copy", "interesting", "attributes", "of", "our", "configuration", "to", "another", "image", "view", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2776-L2826
train
24,988
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.auto_orient
def auto_orient(self): """Set the orientation for the image to a reasonable default.""" image = self.get_image() if image is None: return invert_y = not isinstance(image, AstroImage.AstroImage) # Check for various things to set based on metadata header = image.get_header() if header: # Auto-orientation orient = header.get('Orientation', None) if orient is None: orient = header.get('Image Orientation', None) if orient is not None: self.logger.debug("orientation [%s]" % orient) try: orient = int(str(orient)) self.logger.info( "setting orientation from metadata [%d]" % (orient)) flip_x, flip_y, swap_xy = self.orient_map[orient] self.transform(flip_x, flip_y, swap_xy) invert_y = False except Exception as e: # problems figuring out orientation--let it be self.logger.error("orientation error: %s" % str(e)) if invert_y: flip_x, flip_y, swap_xy = self.get_transforms() #flip_y = not flip_y flip_y = True self.transform(flip_x, flip_y, swap_xy)
python
def auto_orient(self): """Set the orientation for the image to a reasonable default.""" image = self.get_image() if image is None: return invert_y = not isinstance(image, AstroImage.AstroImage) # Check for various things to set based on metadata header = image.get_header() if header: # Auto-orientation orient = header.get('Orientation', None) if orient is None: orient = header.get('Image Orientation', None) if orient is not None: self.logger.debug("orientation [%s]" % orient) try: orient = int(str(orient)) self.logger.info( "setting orientation from metadata [%d]" % (orient)) flip_x, flip_y, swap_xy = self.orient_map[orient] self.transform(flip_x, flip_y, swap_xy) invert_y = False except Exception as e: # problems figuring out orientation--let it be self.logger.error("orientation error: %s" % str(e)) if invert_y: flip_x, flip_y, swap_xy = self.get_transforms() #flip_y = not flip_y flip_y = True self.transform(flip_x, flip_y, swap_xy)
[ "def", "auto_orient", "(", "self", ")", ":", "image", "=", "self", ".", "get_image", "(", ")", "if", "image", "is", "None", ":", "return", "invert_y", "=", "not", "isinstance", "(", "image", ",", "AstroImage", ".", "AstroImage", ")", "# Check for various t...
Set the orientation for the image to a reasonable default.
[ "Set", "the", "orientation", "for", "the", "image", "to", "a", "reasonable", "default", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2908-L2941
train
24,989
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_image_as_buffer
def get_image_as_buffer(self, output=None): """Get the current image shown in the viewer, with any overlaid graphics, in a IO buffer with channels as needed and ordered by the back end widget. This can be overridden by subclasses. Parameters ---------- output : a file IO-like object or None open python IO descriptor or None to have one created Returns ------- buffer : file IO-like object This will be the one passed in, unless `output` is None in which case a BytesIO obejct is returned """ obuf = output if obuf is None: obuf = BytesIO() arr8 = self.get_image_as_array() if not hasattr(arr8, 'tobytes'): # older versions of numpy obuf.write(arr8.tostring(order='C')) else: obuf.write(arr8.tobytes(order='C')) ## if output is not None: ## return None return obuf
python
def get_image_as_buffer(self, output=None): """Get the current image shown in the viewer, with any overlaid graphics, in a IO buffer with channels as needed and ordered by the back end widget. This can be overridden by subclasses. Parameters ---------- output : a file IO-like object or None open python IO descriptor or None to have one created Returns ------- buffer : file IO-like object This will be the one passed in, unless `output` is None in which case a BytesIO obejct is returned """ obuf = output if obuf is None: obuf = BytesIO() arr8 = self.get_image_as_array() if not hasattr(arr8, 'tobytes'): # older versions of numpy obuf.write(arr8.tostring(order='C')) else: obuf.write(arr8.tobytes(order='C')) ## if output is not None: ## return None return obuf
[ "def", "get_image_as_buffer", "(", "self", ",", "output", "=", "None", ")", ":", "obuf", "=", "output", "if", "obuf", "is", "None", ":", "obuf", "=", "BytesIO", "(", ")", "arr8", "=", "self", ".", "get_image_as_array", "(", ")", "if", "not", "hasattr",...
Get the current image shown in the viewer, with any overlaid graphics, in a IO buffer with channels as needed and ordered by the back end widget. This can be overridden by subclasses. Parameters ---------- output : a file IO-like object or None open python IO descriptor or None to have one created Returns ------- buffer : file IO-like object This will be the one passed in, unless `output` is None in which case a BytesIO obejct is returned
[ "Get", "the", "current", "image", "shown", "in", "the", "viewer", "with", "any", "overlaid", "graphics", "in", "a", "IO", "buffer", "with", "channels", "as", "needed", "and", "ordered", "by", "the", "back", "end", "widget", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3282-L3314
train
24,990
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.get_rgb_image_as_bytes
def get_rgb_image_as_bytes(self, format='png', quality=90): """Get the current image shown in the viewer, with any overlaid graphics, in the form of a buffer in the form of bytes. Parameters ---------- format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`. Returns ------- buffer : bytes The window contents as a buffer in the form of bytes. """ obuf = self.get_rgb_image_as_buffer(format=format, quality=quality) return bytes(obuf.getvalue())
python
def get_rgb_image_as_bytes(self, format='png', quality=90): """Get the current image shown in the viewer, with any overlaid graphics, in the form of a buffer in the form of bytes. Parameters ---------- format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`. Returns ------- buffer : bytes The window contents as a buffer in the form of bytes. """ obuf = self.get_rgb_image_as_buffer(format=format, quality=quality) return bytes(obuf.getvalue())
[ "def", "get_rgb_image_as_bytes", "(", "self", ",", "format", "=", "'png'", ",", "quality", "=", "90", ")", ":", "obuf", "=", "self", ".", "get_rgb_image_as_buffer", "(", "format", "=", "format", ",", "quality", "=", "quality", ")", "return", "bytes", "(", ...
Get the current image shown in the viewer, with any overlaid graphics, in the form of a buffer in the form of bytes. Parameters ---------- format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`. Returns ------- buffer : bytes The window contents as a buffer in the form of bytes.
[ "Get", "the", "current", "image", "shown", "in", "the", "viewer", "with", "any", "overlaid", "graphics", "in", "the", "form", "of", "a", "buffer", "in", "the", "form", "of", "bytes", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3344-L3363
train
24,991
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.save_rgb_image_as_file
def save_rgb_image_as_file(self, filepath, format='png', quality=90): """Save the current image shown in the viewer, with any overlaid graphics, in a file with the specified format and quality. This can be overridden by subclasses. Parameters ---------- filepath : str path of the file to write format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`. """ with open(filepath, 'wb') as out_f: self.get_rgb_image_as_buffer(output=out_f, format=format, quality=quality) self.logger.debug("wrote %s file '%s'" % (format, filepath))
python
def save_rgb_image_as_file(self, filepath, format='png', quality=90): """Save the current image shown in the viewer, with any overlaid graphics, in a file with the specified format and quality. This can be overridden by subclasses. Parameters ---------- filepath : str path of the file to write format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`. """ with open(filepath, 'wb') as out_f: self.get_rgb_image_as_buffer(output=out_f, format=format, quality=quality) self.logger.debug("wrote %s file '%s'" % (format, filepath))
[ "def", "save_rgb_image_as_file", "(", "self", ",", "filepath", ",", "format", "=", "'png'", ",", "quality", "=", "90", ")", ":", "with", "open", "(", "filepath", ",", "'wb'", ")", "as", "out_f", ":", "self", ".", "get_rgb_image_as_buffer", "(", "output", ...
Save the current image shown in the viewer, with any overlaid graphics, in a file with the specified format and quality. This can be overridden by subclasses. Parameters ---------- filepath : str path of the file to write format : str See :meth:`get_rgb_image_as_buffer`. quality: int See :meth:`get_rgb_image_as_buffer`.
[ "Save", "the", "current", "image", "shown", "in", "the", "viewer", "with", "any", "overlaid", "graphics", "in", "a", "file", "with", "the", "specified", "format", "and", "quality", ".", "This", "can", "be", "overridden", "by", "subclasses", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3383-L3403
train
24,992
ejeschke/ginga
ginga/ImageView.py
ImageViewBase.set_onscreen_message
def set_onscreen_message(self, text, redraw=True): """Called by a subclass to update the onscreen message. Parameters ---------- text : str The text to show in the display. """ width, height = self.get_window_size() font = self.t_.get('onscreen_font', 'sans serif') font_size = self.t_.get('onscreen_font_size', None) if font_size is None: font_size = self._calc_font_size(width) # TODO: need some way to accurately estimate text extents # without actually putting text on the canvas ht, wd = font_size, font_size if text is not None: wd = len(text) * font_size * 1.1 x = (width // 2) - (wd // 2) y = ((height // 3) * 2) - (ht // 2) tag = '_$onscreen_msg' canvas = self.get_private_canvas() try: message = canvas.get_object_by_tag(tag) if text is None: message.text = '' else: message.x = x message.y = y message.text = text message.fontsize = font_size except KeyError: if text is None: text = '' Text = canvas.get_draw_class('text') canvas.add(Text(x, y, text=text, font=font, fontsize=font_size, color=self.img_fg, coord='window'), tag=tag, redraw=False) if redraw: canvas.update_canvas(whence=3)
python
def set_onscreen_message(self, text, redraw=True): """Called by a subclass to update the onscreen message. Parameters ---------- text : str The text to show in the display. """ width, height = self.get_window_size() font = self.t_.get('onscreen_font', 'sans serif') font_size = self.t_.get('onscreen_font_size', None) if font_size is None: font_size = self._calc_font_size(width) # TODO: need some way to accurately estimate text extents # without actually putting text on the canvas ht, wd = font_size, font_size if text is not None: wd = len(text) * font_size * 1.1 x = (width // 2) - (wd // 2) y = ((height // 3) * 2) - (ht // 2) tag = '_$onscreen_msg' canvas = self.get_private_canvas() try: message = canvas.get_object_by_tag(tag) if text is None: message.text = '' else: message.x = x message.y = y message.text = text message.fontsize = font_size except KeyError: if text is None: text = '' Text = canvas.get_draw_class('text') canvas.add(Text(x, y, text=text, font=font, fontsize=font_size, color=self.img_fg, coord='window'), tag=tag, redraw=False) if redraw: canvas.update_canvas(whence=3)
[ "def", "set_onscreen_message", "(", "self", ",", "text", ",", "redraw", "=", "True", ")", ":", "width", ",", "height", "=", "self", ".", "get_window_size", "(", ")", "font", "=", "self", ".", "t_", ".", "get", "(", "'onscreen_font'", ",", "'sans serif'",...
Called by a subclass to update the onscreen message. Parameters ---------- text : str The text to show in the display.
[ "Called", "by", "a", "subclass", "to", "update", "the", "onscreen", "message", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3447-L3495
train
24,993
ejeschke/ginga
ginga/ImageView.py
ImageViewBase._calc_font_size
def _calc_font_size(self, win_wd): """Heuristic to calculate an appropriate font size based on the width of the viewer window. Parameters ---------- win_wd : int The width of the viewer window. Returns ------- font_size : int Approximately appropriate font size in points """ font_size = 4 if win_wd >= 1600: font_size = 24 elif win_wd >= 1000: font_size = 18 elif win_wd >= 800: font_size = 16 elif win_wd >= 600: font_size = 14 elif win_wd >= 500: font_size = 12 elif win_wd >= 400: font_size = 11 elif win_wd >= 300: font_size = 10 elif win_wd >= 250: font_size = 8 elif win_wd >= 200: font_size = 6 return font_size
python
def _calc_font_size(self, win_wd): """Heuristic to calculate an appropriate font size based on the width of the viewer window. Parameters ---------- win_wd : int The width of the viewer window. Returns ------- font_size : int Approximately appropriate font size in points """ font_size = 4 if win_wd >= 1600: font_size = 24 elif win_wd >= 1000: font_size = 18 elif win_wd >= 800: font_size = 16 elif win_wd >= 600: font_size = 14 elif win_wd >= 500: font_size = 12 elif win_wd >= 400: font_size = 11 elif win_wd >= 300: font_size = 10 elif win_wd >= 250: font_size = 8 elif win_wd >= 200: font_size = 6 return font_size
[ "def", "_calc_font_size", "(", "self", ",", "win_wd", ")", ":", "font_size", "=", "4", "if", "win_wd", ">=", "1600", ":", "font_size", "=", "24", "elif", "win_wd", ">=", "1000", ":", "font_size", "=", "18", "elif", "win_wd", ">=", "800", ":", "font_siz...
Heuristic to calculate an appropriate font size based on the width of the viewer window. Parameters ---------- win_wd : int The width of the viewer window. Returns ------- font_size : int Approximately appropriate font size in points
[ "Heuristic", "to", "calculate", "an", "appropriate", "font", "size", "based", "on", "the", "width", "of", "the", "viewer", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3497-L3532
train
24,994
ejeschke/ginga
ginga/gtkw/GtkHelp.py
FileSelection.popup
def popup(self, title, callfn, initialdir=None, filename=None): """Let user select and load file.""" self.cb = callfn self.filew.set_title(title) if initialdir: self.filew.set_current_folder(initialdir) if filename: #self.filew.set_filename(filename) self.filew.set_current_name(filename) self.filew.show()
python
def popup(self, title, callfn, initialdir=None, filename=None): """Let user select and load file.""" self.cb = callfn self.filew.set_title(title) if initialdir: self.filew.set_current_folder(initialdir) if filename: #self.filew.set_filename(filename) self.filew.set_current_name(filename) self.filew.show()
[ "def", "popup", "(", "self", ",", "title", ",", "callfn", ",", "initialdir", "=", "None", ",", "filename", "=", "None", ")", ":", "self", ".", "cb", "=", "callfn", "self", ".", "filew", ".", "set_title", "(", "title", ")", "if", "initialdir", ":", ...
Let user select and load file.
[ "Let", "user", "select", "and", "load", "file", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtkw/GtkHelp.py#L735-L746
train
24,995
ejeschke/ginga
ginga/util/loader.py
get_fileinfo
def get_fileinfo(self, filespec, dldir=None): """Break down a file specification into its components. Parameters ---------- filespec : str The path of the file to load (can be a URL). dldir Returns ------- res : `~ginga.misc.Bunch.Bunch` """ if dldir is None: dldir = self.tmpdir # Get information about this file/URL info = iohelper.get_fileinfo(filespec, cache_dir=dldir)
python
def get_fileinfo(self, filespec, dldir=None): """Break down a file specification into its components. Parameters ---------- filespec : str The path of the file to load (can be a URL). dldir Returns ------- res : `~ginga.misc.Bunch.Bunch` """ if dldir is None: dldir = self.tmpdir # Get information about this file/URL info = iohelper.get_fileinfo(filespec, cache_dir=dldir)
[ "def", "get_fileinfo", "(", "self", ",", "filespec", ",", "dldir", "=", "None", ")", ":", "if", "dldir", "is", "None", ":", "dldir", "=", "self", ".", "tmpdir", "# Get information about this file/URL", "info", "=", "iohelper", ".", "get_fileinfo", "(", "file...
Break down a file specification into its components. Parameters ---------- filespec : str The path of the file to load (can be a URL). dldir Returns ------- res : `~ginga.misc.Bunch.Bunch`
[ "Break", "down", "a", "file", "specification", "into", "its", "components", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/loader.py#L70-L89
train
24,996
ejeschke/ginga
ginga/rv/plugins/Zoom.py
Zoom.zoomset_cb
def zoomset_cb(self, setting, zoomlevel, fitsimage): """This method is called when a main FITS widget changes zoom level. """ if not self.gui_up: return fac_x, fac_y = fitsimage.get_scale_base_xy() fac_x_me, fac_y_me = self.zoomimage.get_scale_base_xy() if (fac_x != fac_x_me) or (fac_y != fac_y_me): alg = fitsimage.get_zoom_algorithm() self.zoomimage.set_zoom_algorithm(alg) self.zoomimage.set_scale_base_xy(fac_x, fac_y) return self._zoomset(self.fitsimage_focus, zoomlevel)
python
def zoomset_cb(self, setting, zoomlevel, fitsimage): """This method is called when a main FITS widget changes zoom level. """ if not self.gui_up: return fac_x, fac_y = fitsimage.get_scale_base_xy() fac_x_me, fac_y_me = self.zoomimage.get_scale_base_xy() if (fac_x != fac_x_me) or (fac_y != fac_y_me): alg = fitsimage.get_zoom_algorithm() self.zoomimage.set_zoom_algorithm(alg) self.zoomimage.set_scale_base_xy(fac_x, fac_y) return self._zoomset(self.fitsimage_focus, zoomlevel)
[ "def", "zoomset_cb", "(", "self", ",", "setting", ",", "zoomlevel", ",", "fitsimage", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "fac_x", ",", "fac_y", "=", "fitsimage", ".", "get_scale_base_xy", "(", ")", "fac_x_me", ",", "fac_y_me", "...
This method is called when a main FITS widget changes zoom level.
[ "This", "method", "is", "called", "when", "a", "main", "FITS", "widget", "changes", "zoom", "level", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Zoom.py#L279-L290
train
24,997
ejeschke/ginga
ginga/rv/plugins/Zoom.py
Zoom.set_amount_cb
def set_amount_cb(self, widget, val): """This method is called when 'Zoom Amount' control is adjusted. """ self.zoom_amount = val zoomlevel = self.fitsimage_focus.get_zoom() self._zoomset(self.fitsimage_focus, zoomlevel)
python
def set_amount_cb(self, widget, val): """This method is called when 'Zoom Amount' control is adjusted. """ self.zoom_amount = val zoomlevel = self.fitsimage_focus.get_zoom() self._zoomset(self.fitsimage_focus, zoomlevel)
[ "def", "set_amount_cb", "(", "self", ",", "widget", ",", "val", ")", ":", "self", ".", "zoom_amount", "=", "val", "zoomlevel", "=", "self", ".", "fitsimage_focus", ".", "get_zoom", "(", ")", "self", ".", "_zoomset", "(", "self", ".", "fitsimage_focus", "...
This method is called when 'Zoom Amount' control is adjusted.
[ "This", "method", "is", "called", "when", "Zoom", "Amount", "control", "is", "adjusted", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Zoom.py#L377-L382
train
24,998
ejeschke/ginga
experimental/remote_image/plugin/RemoteImage.py
RemoteImage._slice
def _slice(self, view): """ Send view to remote server and do slicing there. """ if self._data is not None: return self._data[view] return self._proxy.get_view(self.id, view)
python
def _slice(self, view): """ Send view to remote server and do slicing there. """ if self._data is not None: return self._data[view] return self._proxy.get_view(self.id, view)
[ "def", "_slice", "(", "self", ",", "view", ")", ":", "if", "self", ".", "_data", "is", "not", "None", ":", "return", "self", ".", "_data", "[", "view", "]", "return", "self", ".", "_proxy", ".", "get_view", "(", "self", ".", "id", ",", "view", ")...
Send view to remote server and do slicing there.
[ "Send", "view", "to", "remote", "server", "and", "do", "slicing", "there", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/remote_image/plugin/RemoteImage.py#L49-L55
train
24,999