id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
26,400 | 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):
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 |
26,401 | 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):
# 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 |
26,402 | 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):
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 |
26,403 | 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):
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 |
26,404 | 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):
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 |
26,405 | 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):
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 |
26,406 | 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):
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 |
26,407 | 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):
# 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 |
26,408 | 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):
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 |
26,409 | 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):
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 |
26,410 | 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 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 |
26,411 | 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):
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 |
26,412 | 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):
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 |
26,413 | 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'):
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 |
26,414 | 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'):
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 |
26,415 | 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):
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 |
26,416 | 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):
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 |
26,417 | 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):
#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 |
26,418 | 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):
# 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 |
26,419 | 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):
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 |
26,420 | 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):
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 |
26,421 | 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):
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 |
26,422 | 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):
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 |
26,423 | 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):
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 |
26,424 | 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):
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 |
26,425 | 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):
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 |
26,426 | 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):
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 |
26,427 | 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):
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 |
26,428 | 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):
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 |
26,429 | 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):
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 |
26,430 | 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):
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 |
26,431 | 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):
# 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 |
26,432 | 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):
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 |
26,433 | 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):
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 |
26,434 | 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):
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 |
26,435 | 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'):
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 |
26,436 | 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):
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 |
26,437 | 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):
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 |
26,438 | 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):
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 |
26,439 | 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):
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 |
26,440 | 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):
# 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 |
26,441 | 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):
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 |
26,442 | 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):
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 |
26,443 | 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):
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 |
26,444 | 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):
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 |
26,445 | 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):
# 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 |
26,446 | 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):
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 |
26,447 | 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):
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 |
26,448 | 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):
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 |
26,449 | 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):
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 |
26,450 | 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):
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 |
26,451 | 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):
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 |
26,452 | 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):
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 |
26,453 | 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):
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 |
26,454 | 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):
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 |
26,455 | 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):
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 |
26,456 | 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):
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 |
26,457 | ejeschke/ginga | ginga/examples/reference-viewer/MyGlobalPlugin.py | MyGlobalPlugin.build_gui | def build_gui(self, container):
"""
This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method could be called several times if the plugin is opened
and closed. The method may be omitted if there is no GUI for the
plugin.
This specific example uses the GUI widget set agnostic wrappers
to build the GUI, but you can also just as easily use explicit
toolkit calls here if you only want to support one widget set.
"""
top = Widgets.VBox()
top.set_border_width(4)
# this is a little trick for making plugins that work either in
# a vertical or horizontal orientation. It returns a box container,
# a scroll widget and an orientation ('vertical', 'horizontal')
vbox, sw, orientation = Widgets.get_oriented_box(container)
vbox.set_border_width(4)
vbox.set_spacing(2)
# Take a text widget to show some instructions
self.msg_font = self.fv.get_font("sans", 12)
tw = Widgets.TextArea(wrap=True, editable=False)
tw.set_font(self.msg_font)
self.tw = tw
# Frame for instructions and add the text widget with another
# blank widget to stretch as needed to fill emp
fr = Widgets.Frame("Status")
fr.set_widget(tw)
vbox.add_widget(fr, stretch=0)
# Add a spacer to stretch the rest of the way to the end of the
# plugin space
spacer = Widgets.Label('')
vbox.add_widget(spacer, stretch=1)
# scroll bars will allow lots of content to be accessed
top.add_widget(sw, stretch=1)
# A button box that is always visible at the bottom
btns = Widgets.HBox()
btns.set_spacing(3)
# Add a close button for the convenience of the user
btn = Widgets.Button("Close")
btn.add_callback('activated', lambda w: self.close())
btns.add_widget(btn, stretch=0)
btns.add_widget(Widgets.Label(''), stretch=1)
top.add_widget(btns, stretch=0)
# Add our GUI to the container
container.add_widget(top, stretch=1)
# NOTE: if you are building a GUI using a specific widget toolkit
# (e.g. Qt) GUI calls, you need to extract the widget or layout
# from the non-toolkit specific container wrapper and call on that
# to pack your widget, e.g.:
#cw = container.get_widget()
#cw.addWidget(widget, stretch=1)
self.gui_up = True | python | def build_gui(self, container):
top = Widgets.VBox()
top.set_border_width(4)
# this is a little trick for making plugins that work either in
# a vertical or horizontal orientation. It returns a box container,
# a scroll widget and an orientation ('vertical', 'horizontal')
vbox, sw, orientation = Widgets.get_oriented_box(container)
vbox.set_border_width(4)
vbox.set_spacing(2)
# Take a text widget to show some instructions
self.msg_font = self.fv.get_font("sans", 12)
tw = Widgets.TextArea(wrap=True, editable=False)
tw.set_font(self.msg_font)
self.tw = tw
# Frame for instructions and add the text widget with another
# blank widget to stretch as needed to fill emp
fr = Widgets.Frame("Status")
fr.set_widget(tw)
vbox.add_widget(fr, stretch=0)
# Add a spacer to stretch the rest of the way to the end of the
# plugin space
spacer = Widgets.Label('')
vbox.add_widget(spacer, stretch=1)
# scroll bars will allow lots of content to be accessed
top.add_widget(sw, stretch=1)
# A button box that is always visible at the bottom
btns = Widgets.HBox()
btns.set_spacing(3)
# Add a close button for the convenience of the user
btn = Widgets.Button("Close")
btn.add_callback('activated', lambda w: self.close())
btns.add_widget(btn, stretch=0)
btns.add_widget(Widgets.Label(''), stretch=1)
top.add_widget(btns, stretch=0)
# Add our GUI to the container
container.add_widget(top, stretch=1)
# NOTE: if you are building a GUI using a specific widget toolkit
# (e.g. Qt) GUI calls, you need to extract the widget or layout
# from the non-toolkit specific container wrapper and call on that
# to pack your widget, e.g.:
#cw = container.get_widget()
#cw.addWidget(widget, stretch=1)
self.gui_up = True | [
"def",
"build_gui",
"(",
"self",
",",
"container",
")",
":",
"top",
"=",
"Widgets",
".",
"VBox",
"(",
")",
"top",
".",
"set_border_width",
"(",
"4",
")",
"# this is a little trick for making plugins that work either in",
"# a vertical or horizontal orientation. It return... | This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method could be called several times if the plugin is opened
and closed. The method may be omitted if there is no GUI for the
plugin.
This specific example uses the GUI widget set agnostic wrappers
to build the GUI, but you can also just as easily use explicit
toolkit calls here if you only want to support one widget set. | [
"This",
"method",
"is",
"called",
"when",
"the",
"plugin",
"is",
"invoked",
".",
"It",
"builds",
"the",
"GUI",
"used",
"by",
"the",
"plugin",
"into",
"the",
"widget",
"layout",
"passed",
"as",
"container",
".",
"This",
"method",
"could",
"be",
"called",
... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L43-L106 |
26,458 | ejeschke/ginga | ginga/examples/reference-viewer/MyGlobalPlugin.py | MyGlobalPlugin.focus_cb | def focus_cb(self, viewer, channel):
"""
Callback from the reference viewer shell when the focus changes
between channels.
"""
chname = channel.name
if self.active != chname:
# focus has shifted to a different channel than our idea
# of the active one
self.active = chname
self.set_info("Focus is now in channel '%s'" % (
self.active))
return True | python | def focus_cb(self, viewer, channel):
chname = channel.name
if self.active != chname:
# focus has shifted to a different channel than our idea
# of the active one
self.active = chname
self.set_info("Focus is now in channel '%s'" % (
self.active))
return True | [
"def",
"focus_cb",
"(",
"self",
",",
"viewer",
",",
"channel",
")",
":",
"chname",
"=",
"channel",
".",
"name",
"if",
"self",
".",
"active",
"!=",
"chname",
":",
"# focus has shifted to a different channel than our idea",
"# of the active one",
"self",
".",
"activ... | Callback from the reference viewer shell when the focus changes
between channels. | [
"Callback",
"from",
"the",
"reference",
"viewer",
"shell",
"when",
"the",
"focus",
"changes",
"between",
"channels",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L136-L149 |
26,459 | ejeschke/ginga | ginga/examples/reference-viewer/MyGlobalPlugin.py | MyGlobalPlugin.redo | def redo(self, channel, image):
"""
Called from the reference viewer shell when a new image has
been added to a channel.
"""
chname = channel.name
# Only update our GUI if the activity is in the focused
# channel
if self.active == chname:
imname = image.get('name', 'NONAME')
self.set_info("A new image '%s' has been added to channel %s" % (
imname, chname))
return True | python | def redo(self, channel, image):
chname = channel.name
# Only update our GUI if the activity is in the focused
# channel
if self.active == chname:
imname = image.get('name', 'NONAME')
self.set_info("A new image '%s' has been added to channel %s" % (
imname, chname))
return True | [
"def",
"redo",
"(",
"self",
",",
"channel",
",",
"image",
")",
":",
"chname",
"=",
"channel",
".",
"name",
"# Only update our GUI if the activity is in the focused",
"# channel",
"if",
"self",
".",
"active",
"==",
"chname",
":",
"imname",
"=",
"image",
".",
"g... | Called from the reference viewer shell when a new image has
been added to a channel. | [
"Called",
"from",
"the",
"reference",
"viewer",
"shell",
"when",
"a",
"new",
"image",
"has",
"been",
"added",
"to",
"a",
"channel",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L151-L164 |
26,460 | ejeschke/ginga | ginga/misc/grc.py | _main | def _main():
"""Run from command line."""
usage = "usage: %prog [options] cmd [arg] ..."
optprs = OptionParser(usage=usage, version=version)
optprs.add_option("--debug", dest="debug", default=False,
action="store_true",
help="Enter the pdb debugger on main()")
optprs.add_option("--host", dest="host", metavar="HOST",
default="localhost", help="Connect to server at HOST")
optprs.add_option("--port", dest="port", type="int",
default=9000, metavar="PORT",
help="Connect to server at PORT")
optprs.add_option("--profile", dest="profile", action="store_true",
default=False,
help="Run the profiler on main()")
(options, args) = optprs.parse_args(sys.argv[1:])
# Are we debugging this?
if options.debug:
import pdb
pdb.run('main(options, args)')
# Are we profiling this?
elif options.profile:
import profile
print("%s profile:" % sys.argv[0])
profile.run('main(options, args)')
else:
main(options, args) | python | def _main():
usage = "usage: %prog [options] cmd [arg] ..."
optprs = OptionParser(usage=usage, version=version)
optprs.add_option("--debug", dest="debug", default=False,
action="store_true",
help="Enter the pdb debugger on main()")
optprs.add_option("--host", dest="host", metavar="HOST",
default="localhost", help="Connect to server at HOST")
optprs.add_option("--port", dest="port", type="int",
default=9000, metavar="PORT",
help="Connect to server at PORT")
optprs.add_option("--profile", dest="profile", action="store_true",
default=False,
help="Run the profiler on main()")
(options, args) = optprs.parse_args(sys.argv[1:])
# Are we debugging this?
if options.debug:
import pdb
pdb.run('main(options, args)')
# Are we profiling this?
elif options.profile:
import profile
print("%s profile:" % sys.argv[0])
profile.run('main(options, args)')
else:
main(options, args) | [
"def",
"_main",
"(",
")",
":",
"usage",
"=",
"\"usage: %prog [options] cmd [arg] ...\"",
"optprs",
"=",
"OptionParser",
"(",
"usage",
"=",
"usage",
",",
"version",
"=",
"version",
")",
"optprs",
".",
"add_option",
"(",
"\"--debug\"",
",",
"dest",
"=",
"\"debug... | Run from command line. | [
"Run",
"from",
"command",
"line",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/grc.py#L49-L82 |
26,461 | ejeschke/ginga | ginga/util/io_rgb.py | RGBFileHandler._imload | def _imload(self, filepath, kwds):
"""Load an image file, guessing the format, and return a numpy
array containing an RGB image. If EXIF keywords can be read
they are returned in the dict _kwds_.
"""
start_time = time.time()
typ, enc = mimetypes.guess_type(filepath)
if not typ:
typ = 'image/jpeg'
typ, subtyp = typ.split('/')
self.logger.debug("MIME type is %s/%s" % (typ, subtyp))
data_loaded = False
if have_opencv and subtyp not in ['gif']:
# First choice is OpenCv, because it supports high-bit depth
# multiband images
means = 'opencv'
data_np = cv2.imread(filepath,
cv2.IMREAD_ANYDEPTH + cv2.IMREAD_ANYCOLOR)
if data_np is not None:
data_loaded = True
# funky indexing because opencv returns BGR images,
# whereas PIL and others return RGB
if len(data_np.shape) >= 3 and data_np.shape[2] >= 3:
data_np = data_np[..., :: -1]
# OpenCv doesn't "do" image metadata, so we punt to piexif
# library (if installed)
self.piexif_getexif(filepath, kwds)
# OpenCv added a feature to do auto-orientation when loading
# (see https://github.com/opencv/opencv/issues/4344)
# So reset these values to prevent auto-orientation from
# happening later
kwds['Orientation'] = 1
kwds['Image Orientation'] = 1
# convert to working color profile, if can
if self.clr_mgr.can_profile():
data_np = self.clr_mgr.profile_to_working_numpy(data_np, kwds)
if not data_loaded and have_pil:
means = 'PIL'
image = PILimage.open(filepath)
try:
if hasattr(image, '_getexif'):
info = image._getexif()
if info is not None:
for tag, value in info.items():
kwd = TAGS.get(tag, tag)
kwds[kwd] = value
elif have_exif:
self.piexif_getexif(image.info["exif"], kwds)
else:
self.logger.warning("Please install 'piexif' module to get image metadata")
except Exception as e:
self.logger.warning("Failed to get image metadata: %s" % (str(e)))
# convert to working color profile, if can
if self.clr_mgr.can_profile():
image = self.clr_mgr.profile_to_working_pil(image, kwds)
# convert from PIL to numpy
data_np = np.array(image)
if data_np is not None:
data_loaded = True
if (not data_loaded and (typ == 'image') and
(subtyp in ('x-portable-pixmap', 'x-portable-greymap'))):
# Special opener for PPM files, preserves high bit depth
means = 'built-in'
data_np = open_ppm(filepath)
if data_np is not None:
data_loaded = True
if not data_loaded:
raise ImageError("No way to load image format '%s/%s'" % (
typ, subtyp))
end_time = time.time()
self.logger.debug("loading (%s) time %.4f sec" % (
means, end_time - start_time))
return data_np | python | def _imload(self, filepath, kwds):
start_time = time.time()
typ, enc = mimetypes.guess_type(filepath)
if not typ:
typ = 'image/jpeg'
typ, subtyp = typ.split('/')
self.logger.debug("MIME type is %s/%s" % (typ, subtyp))
data_loaded = False
if have_opencv and subtyp not in ['gif']:
# First choice is OpenCv, because it supports high-bit depth
# multiband images
means = 'opencv'
data_np = cv2.imread(filepath,
cv2.IMREAD_ANYDEPTH + cv2.IMREAD_ANYCOLOR)
if data_np is not None:
data_loaded = True
# funky indexing because opencv returns BGR images,
# whereas PIL and others return RGB
if len(data_np.shape) >= 3 and data_np.shape[2] >= 3:
data_np = data_np[..., :: -1]
# OpenCv doesn't "do" image metadata, so we punt to piexif
# library (if installed)
self.piexif_getexif(filepath, kwds)
# OpenCv added a feature to do auto-orientation when loading
# (see https://github.com/opencv/opencv/issues/4344)
# So reset these values to prevent auto-orientation from
# happening later
kwds['Orientation'] = 1
kwds['Image Orientation'] = 1
# convert to working color profile, if can
if self.clr_mgr.can_profile():
data_np = self.clr_mgr.profile_to_working_numpy(data_np, kwds)
if not data_loaded and have_pil:
means = 'PIL'
image = PILimage.open(filepath)
try:
if hasattr(image, '_getexif'):
info = image._getexif()
if info is not None:
for tag, value in info.items():
kwd = TAGS.get(tag, tag)
kwds[kwd] = value
elif have_exif:
self.piexif_getexif(image.info["exif"], kwds)
else:
self.logger.warning("Please install 'piexif' module to get image metadata")
except Exception as e:
self.logger.warning("Failed to get image metadata: %s" % (str(e)))
# convert to working color profile, if can
if self.clr_mgr.can_profile():
image = self.clr_mgr.profile_to_working_pil(image, kwds)
# convert from PIL to numpy
data_np = np.array(image)
if data_np is not None:
data_loaded = True
if (not data_loaded and (typ == 'image') and
(subtyp in ('x-portable-pixmap', 'x-portable-greymap'))):
# Special opener for PPM files, preserves high bit depth
means = 'built-in'
data_np = open_ppm(filepath)
if data_np is not None:
data_loaded = True
if not data_loaded:
raise ImageError("No way to load image format '%s/%s'" % (
typ, subtyp))
end_time = time.time()
self.logger.debug("loading (%s) time %.4f sec" % (
means, end_time - start_time))
return data_np | [
"def",
"_imload",
"(",
"self",
",",
"filepath",
",",
"kwds",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"typ",
",",
"enc",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filepath",
")",
"if",
"not",
"typ",
":",
"typ",
"=",
"'image/jpeg'"... | Load an image file, guessing the format, and return a numpy
array containing an RGB image. If EXIF keywords can be read
they are returned in the dict _kwds_. | [
"Load",
"an",
"image",
"file",
"guessing",
"the",
"format",
"and",
"return",
"a",
"numpy",
"array",
"containing",
"an",
"RGB",
"image",
".",
"If",
"EXIF",
"keywords",
"can",
"be",
"read",
"they",
"are",
"returned",
"in",
"the",
"dict",
"_kwds_",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/io_rgb.py#L125-L211 |
26,462 | ejeschke/ginga | ginga/util/io_rgb.py | RGBFileHandler.imresize | def imresize(self, data, new_wd, new_ht, method='bilinear'):
"""Scale an image in numpy array _data_ to the specified width and
height. A smooth scaling is preferred.
"""
old_ht, old_wd = data.shape[:2]
start_time = time.time()
if have_pilutil:
means = 'PIL'
zoom_x = float(new_wd) / float(old_wd)
zoom_y = float(new_ht) / float(old_ht)
if (old_wd >= new_wd) or (old_ht >= new_ht):
# data size is bigger, skip pixels
zoom = max(zoom_x, zoom_y)
else:
zoom = min(zoom_x, zoom_y)
newdata = imresize(data, zoom, interp=method)
else:
raise ImageError("No way to scale image smoothly")
end_time = time.time()
self.logger.debug("scaling (%s) time %.4f sec" % (
means, end_time - start_time))
return newdata | python | def imresize(self, data, new_wd, new_ht, method='bilinear'):
old_ht, old_wd = data.shape[:2]
start_time = time.time()
if have_pilutil:
means = 'PIL'
zoom_x = float(new_wd) / float(old_wd)
zoom_y = float(new_ht) / float(old_ht)
if (old_wd >= new_wd) or (old_ht >= new_ht):
# data size is bigger, skip pixels
zoom = max(zoom_x, zoom_y)
else:
zoom = min(zoom_x, zoom_y)
newdata = imresize(data, zoom, interp=method)
else:
raise ImageError("No way to scale image smoothly")
end_time = time.time()
self.logger.debug("scaling (%s) time %.4f sec" % (
means, end_time - start_time))
return newdata | [
"def",
"imresize",
"(",
"self",
",",
"data",
",",
"new_wd",
",",
"new_ht",
",",
"method",
"=",
"'bilinear'",
")",
":",
"old_ht",
",",
"old_wd",
"=",
"data",
".",
"shape",
"[",
":",
"2",
"]",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
... | Scale an image in numpy array _data_ to the specified width and
height. A smooth scaling is preferred. | [
"Scale",
"an",
"image",
"in",
"numpy",
"array",
"_data_",
"to",
"the",
"specified",
"width",
"and",
"height",
".",
"A",
"smooth",
"scaling",
"is",
"preferred",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/io_rgb.py#L265-L291 |
26,463 | ejeschke/ginga | ginga/RGBMap.py | RGBPlanes.get_array | def get_array(self, order, dtype=None):
"""Get Numpy array that represents the RGB layers.
Parameters
----------
order : str
The desired order of RGB color layers.
Returns
-------
arr : ndarray
Numpy array that represents the RGB layers.
dtype : numpy array dtype (optional)
Type of the numpy array desired.
"""
if dtype is None:
dtype = self.rgbarr.dtype
order = order.upper()
if order == self.order:
return self.rgbarr.astype(dtype, copy=False)
res = trcalc.reorder_image(order, self.rgbarr, self.order)
res = res.astype(dtype, copy=False, casting='unsafe')
return res | python | def get_array(self, order, dtype=None):
if dtype is None:
dtype = self.rgbarr.dtype
order = order.upper()
if order == self.order:
return self.rgbarr.astype(dtype, copy=False)
res = trcalc.reorder_image(order, self.rgbarr, self.order)
res = res.astype(dtype, copy=False, casting='unsafe')
return res | [
"def",
"get_array",
"(",
"self",
",",
"order",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"self",
".",
"rgbarr",
".",
"dtype",
"order",
"=",
"order",
".",
"upper",
"(",
")",
"if",
"order",
"==",
"self",
"... | Get Numpy array that represents the RGB layers.
Parameters
----------
order : str
The desired order of RGB color layers.
Returns
-------
arr : ndarray
Numpy array that represents the RGB layers.
dtype : numpy array dtype (optional)
Type of the numpy array desired. | [
"Get",
"Numpy",
"array",
"that",
"represents",
"the",
"RGB",
"layers",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L40-L65 |
26,464 | ejeschke/ginga | ginga/RGBMap.py | RGBMapper.set_cmap | def set_cmap(self, cmap, callback=True):
"""
Set the color map used by this RGBMapper.
`cmap` specifies a ColorMap object. If `callback` is True, then
any callbacks associated with this change will be invoked.
"""
self.cmap = cmap
with self.suppress_changed:
self.calc_cmap()
# TEMP: ignore passed callback parameter
# callback=False in the following because we don't want to
# recursively invoke set_cmap()
self.t_.set(color_map=cmap.name, callback=False) | python | def set_cmap(self, cmap, callback=True):
self.cmap = cmap
with self.suppress_changed:
self.calc_cmap()
# TEMP: ignore passed callback parameter
# callback=False in the following because we don't want to
# recursively invoke set_cmap()
self.t_.set(color_map=cmap.name, callback=False) | [
"def",
"set_cmap",
"(",
"self",
",",
"cmap",
",",
"callback",
"=",
"True",
")",
":",
"self",
".",
"cmap",
"=",
"cmap",
"with",
"self",
".",
"suppress_changed",
":",
"self",
".",
"calc_cmap",
"(",
")",
"# TEMP: ignore passed callback parameter",
"# callback=Fal... | Set the color map used by this RGBMapper.
`cmap` specifies a ColorMap object. If `callback` is True, then
any callbacks associated with this change will be invoked. | [
"Set",
"the",
"color",
"map",
"used",
"by",
"this",
"RGBMapper",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L199-L212 |
26,465 | ejeschke/ginga | ginga/RGBMap.py | RGBMapper.set_imap | def set_imap(self, imap, callback=True):
"""
Set the intensity map used by this RGBMapper.
`imap` specifies an IntensityMap object. If `callback` is True, then
any callbacks associated with this change will be invoked.
"""
self.imap = imap
self.calc_imap()
with self.suppress_changed:
# TEMP: ignore passed callback parameter
self.recalc()
# callback=False in the following because we don't want to
# recursively invoke set_imap()
self.t_.set(intensity_map=imap.name, callback=False) | python | def set_imap(self, imap, callback=True):
self.imap = imap
self.calc_imap()
with self.suppress_changed:
# TEMP: ignore passed callback parameter
self.recalc()
# callback=False in the following because we don't want to
# recursively invoke set_imap()
self.t_.set(intensity_map=imap.name, callback=False) | [
"def",
"set_imap",
"(",
"self",
",",
"imap",
",",
"callback",
"=",
"True",
")",
":",
"self",
".",
"imap",
"=",
"imap",
"self",
".",
"calc_imap",
"(",
")",
"with",
"self",
".",
"suppress_changed",
":",
"# TEMP: ignore passed callback parameter",
"self",
".",
... | Set the intensity map used by this RGBMapper.
`imap` specifies an IntensityMap object. If `callback` is True, then
any callbacks associated with this change will be invoked. | [
"Set",
"the",
"intensity",
"map",
"used",
"by",
"this",
"RGBMapper",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L273-L287 |
26,466 | ejeschke/ginga | ginga/RGBMap.py | RGBMapper.stretch | def stretch(self, scale_factor, callback=True):
"""Stretch the color map via altering the shift map.
"""
self.scale_pct *= scale_factor
self.scale_and_shift(self.scale_pct, 0.0, callback=callback) | python | def stretch(self, scale_factor, callback=True):
self.scale_pct *= scale_factor
self.scale_and_shift(self.scale_pct, 0.0, callback=callback) | [
"def",
"stretch",
"(",
"self",
",",
"scale_factor",
",",
"callback",
"=",
"True",
")",
":",
"self",
".",
"scale_pct",
"*=",
"scale_factor",
"self",
".",
"scale_and_shift",
"(",
"self",
".",
"scale_pct",
",",
"0.0",
",",
"callback",
"=",
"callback",
")"
] | Stretch the color map via altering the shift map. | [
"Stretch",
"the",
"color",
"map",
"via",
"altering",
"the",
"shift",
"map",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L557-L561 |
26,467 | ejeschke/ginga | ginga/rv/plugins/WCSMatch.py | WCSMatch._set_reference_channel_cb | def _set_reference_channel_cb(self, w, idx):
"""This is the GUI callback for the control that sets the reference
channel.
"""
chname = self.chnames[idx]
self._set_reference_channel(chname) | python | def _set_reference_channel_cb(self, w, idx):
chname = self.chnames[idx]
self._set_reference_channel(chname) | [
"def",
"_set_reference_channel_cb",
"(",
"self",
",",
"w",
",",
"idx",
")",
":",
"chname",
"=",
"self",
".",
"chnames",
"[",
"idx",
"]",
"self",
".",
"_set_reference_channel",
"(",
"chname",
")"
] | This is the GUI callback for the control that sets the reference
channel. | [
"This",
"is",
"the",
"GUI",
"callback",
"for",
"the",
"control",
"that",
"sets",
"the",
"reference",
"channel",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L192-L197 |
26,468 | ejeschke/ginga | ginga/rv/plugins/WCSMatch.py | WCSMatch.set_reference_channel | def set_reference_channel(self, chname):
"""This is the API call to set the reference channel.
"""
# change the GUI control to match
idx = self.chnames.index(str(chname))
self.w.ref_channel.set_index(idx)
return self._set_reference_channel(chname) | python | def set_reference_channel(self, chname):
# change the GUI control to match
idx = self.chnames.index(str(chname))
self.w.ref_channel.set_index(idx)
return self._set_reference_channel(chname) | [
"def",
"set_reference_channel",
"(",
"self",
",",
"chname",
")",
":",
"# change the GUI control to match",
"idx",
"=",
"self",
".",
"chnames",
".",
"index",
"(",
"str",
"(",
"chname",
")",
")",
"self",
".",
"w",
".",
"ref_channel",
".",
"set_index",
"(",
"... | This is the API call to set the reference channel. | [
"This",
"is",
"the",
"API",
"call",
"to",
"set",
"the",
"reference",
"channel",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L199-L205 |
26,469 | ejeschke/ginga | ginga/rv/plugins/WCSMatch.py | WCSMatch.zoomset_cb | def zoomset_cb(self, setting, value, chviewer, info):
"""This callback is called when a channel window is zoomed.
"""
return self.zoomset(chviewer, info.chinfo) | python | def zoomset_cb(self, setting, value, chviewer, info):
return self.zoomset(chviewer, info.chinfo) | [
"def",
"zoomset_cb",
"(",
"self",
",",
"setting",
",",
"value",
",",
"chviewer",
",",
"info",
")",
":",
"return",
"self",
".",
"zoomset",
"(",
"chviewer",
",",
"info",
".",
"chinfo",
")"
] | This callback is called when a channel window is zoomed. | [
"This",
"callback",
"is",
"called",
"when",
"a",
"channel",
"window",
"is",
"zoomed",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L234-L237 |
26,470 | ejeschke/ginga | ginga/rv/plugins/WCSMatch.py | WCSMatch.rotset_cb | def rotset_cb(self, setting, value, chviewer, info):
"""This callback is called when a channel window is rotated.
"""
return self.rotset(chviewer, info.chinfo) | python | def rotset_cb(self, setting, value, chviewer, info):
return self.rotset(chviewer, info.chinfo) | [
"def",
"rotset_cb",
"(",
"self",
",",
"setting",
",",
"value",
",",
"chviewer",
",",
"info",
")",
":",
"return",
"self",
".",
"rotset",
"(",
"chviewer",
",",
"info",
".",
"chinfo",
")"
] | This callback is called when a channel window is rotated. | [
"This",
"callback",
"is",
"called",
"when",
"a",
"channel",
"window",
"is",
"rotated",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L301-L304 |
26,471 | ejeschke/ginga | ginga/rv/plugins/WCSMatch.py | WCSMatch.panset_cb | def panset_cb(self, setting, value, chviewer, info):
"""This callback is called when a channel window is panned.
"""
return self.panset(chviewer, info.chinfo) | python | def panset_cb(self, setting, value, chviewer, info):
return self.panset(chviewer, info.chinfo) | [
"def",
"panset_cb",
"(",
"self",
",",
"setting",
",",
"value",
",",
"chviewer",
",",
"info",
")",
":",
"return",
"self",
".",
"panset",
"(",
"chviewer",
",",
"info",
".",
"chinfo",
")"
] | This callback is called when a channel window is panned. | [
"This",
"callback",
"is",
"called",
"when",
"a",
"channel",
"window",
"is",
"panned",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L358-L361 |
26,472 | ejeschke/ginga | ginga/web/jupyterw/JpHelp.py | TimerFactory.timer_tick | def timer_tick(self):
"""Callback executed every self.base_interval_msec to check timer
expirations.
"""
# TODO: should exceptions thrown from this be caught and ignored
self.process_timers()
delta = datetime.timedelta(milliseconds=self.base_interval_msec)
self._timeout = IOLoop.current().add_timeout(delta, self.timer_tick) | python | def timer_tick(self):
# TODO: should exceptions thrown from this be caught and ignored
self.process_timers()
delta = datetime.timedelta(milliseconds=self.base_interval_msec)
self._timeout = IOLoop.current().add_timeout(delta, self.timer_tick) | [
"def",
"timer_tick",
"(",
"self",
")",
":",
"# TODO: should exceptions thrown from this be caught and ignored",
"self",
".",
"process_timers",
"(",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"milliseconds",
"=",
"self",
".",
"base_interval_msec",
")",
"self... | Callback executed every self.base_interval_msec to check timer
expirations. | [
"Callback",
"executed",
"every",
"self",
".",
"base_interval_msec",
"to",
"check",
"timer",
"expirations",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/jupyterw/JpHelp.py#L45-L53 |
26,473 | ejeschke/ginga | ginga/rv/plugins/ColorMapPicker.py | ColorMapPicker.select_cb | def select_cb(self, viewer, event, data_x, data_y):
"""Called when the user clicks on the color bar viewer.
Calculate the index of the color bar they clicked on and
set that color map in the current channel viewer.
"""
if not (self._cmxoff <= data_x < self._cmwd):
# need to click within the width of the bar
return
i = int(data_y / (self._cmht + self._cmsep))
if 0 <= i < len(self.cm_names):
name = self.cm_names[i]
msg = "cmap => '%s'" % (name)
self.logger.info(msg)
channel = self.fv.get_channel_info()
if channel is not None:
viewer = channel.fitsimage
#viewer.onscreen_message(msg, delay=0.5)
viewer.set_color_map(name) | python | def select_cb(self, viewer, event, data_x, data_y):
if not (self._cmxoff <= data_x < self._cmwd):
# need to click within the width of the bar
return
i = int(data_y / (self._cmht + self._cmsep))
if 0 <= i < len(self.cm_names):
name = self.cm_names[i]
msg = "cmap => '%s'" % (name)
self.logger.info(msg)
channel = self.fv.get_channel_info()
if channel is not None:
viewer = channel.fitsimage
#viewer.onscreen_message(msg, delay=0.5)
viewer.set_color_map(name) | [
"def",
"select_cb",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"not",
"(",
"self",
".",
"_cmxoff",
"<=",
"data_x",
"<",
"self",
".",
"_cmwd",
")",
":",
"# need to click within the width of the bar",
"return",
"i... | Called when the user clicks on the color bar viewer.
Calculate the index of the color bar they clicked on and
set that color map in the current channel viewer. | [
"Called",
"when",
"the",
"user",
"clicks",
"on",
"the",
"color",
"bar",
"viewer",
".",
"Calculate",
"the",
"index",
"of",
"the",
"color",
"bar",
"they",
"clicked",
"on",
"and",
"set",
"that",
"color",
"map",
"in",
"the",
"current",
"channel",
"viewer",
"... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L130-L149 |
26,474 | ejeschke/ginga | ginga/rv/plugins/ColorMapPicker.py | ColorMapPicker.scroll_cb | def scroll_cb(self, viewer, direction, amt, data_x, data_y):
"""Called when the user scrolls in the color bar viewer.
Pan up or down to show additional bars.
"""
bd = viewer.get_bindings()
direction = bd.get_direction(direction)
pan_x, pan_y = viewer.get_pan()[:2]
qty = self._cmsep * amt * self.settings.get('cbar_pan_accel', 1.0)
if direction == 'up':
pan_y -= qty
else:
pan_y += qty
pan_y = min(max(pan_y, 0), self._max_y)
viewer.set_pan(pan_x, pan_y) | python | def scroll_cb(self, viewer, direction, amt, data_x, data_y):
bd = viewer.get_bindings()
direction = bd.get_direction(direction)
pan_x, pan_y = viewer.get_pan()[:2]
qty = self._cmsep * amt * self.settings.get('cbar_pan_accel', 1.0)
if direction == 'up':
pan_y -= qty
else:
pan_y += qty
pan_y = min(max(pan_y, 0), self._max_y)
viewer.set_pan(pan_x, pan_y) | [
"def",
"scroll_cb",
"(",
"self",
",",
"viewer",
",",
"direction",
",",
"amt",
",",
"data_x",
",",
"data_y",
")",
":",
"bd",
"=",
"viewer",
".",
"get_bindings",
"(",
")",
"direction",
"=",
"bd",
".",
"get_direction",
"(",
"direction",
")",
"pan_x",
",",... | Called when the user scrolls in the color bar viewer.
Pan up or down to show additional bars. | [
"Called",
"when",
"the",
"user",
"scrolls",
"in",
"the",
"color",
"bar",
"viewer",
".",
"Pan",
"up",
"or",
"down",
"to",
"show",
"additional",
"bars",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L151-L166 |
26,475 | ejeschke/ginga | ginga/rv/plugins/ColorMapPicker.py | ColorMapPicker.rebuild_cmaps | def rebuild_cmaps(self):
"""Builds a color RGB image containing color bars of all the
possible color maps and their labels.
"""
self.logger.info("building color maps image")
ht, wd, sep = self._cmht, self._cmwd, self._cmsep
viewer = self.p_view
# put the canvas into pick mode
canvas = viewer.get_canvas()
canvas.delete_all_objects()
# get the list of color maps
cm_names = self.cm_names
num_cmaps = len(cm_names)
viewer.configure_surface(500, (ht + sep) * num_cmaps)
# create a bunch of color bars and make one large compound object
# with callbacks for clicking on individual color bars
l2 = []
ColorBar = canvas.get_draw_class('drawablecolorbar')
Text = canvas.get_draw_class('text')
#ch_rgbmap = chviewer.get_rgbmap()
#dist = ch_rgbmap.get_dist()
dist = None
#imap = ch_rgbmap.get_imap()
logger = viewer.get_logger()
for i, name in enumerate(cm_names):
rgbmap = RGBMap.RGBMapper(logger, dist=dist)
rgbmap.set_cmap(cmap.get_cmap(name))
#rgbmap.set_imap(imap)
x1, y1 = self._cmxoff, i * (ht + sep)
x2, y2 = x1 + wd, y1 + ht
cbar = ColorBar(x1, y1, x2, y2, cm_name=name, showrange=False,
rgbmap=rgbmap, coord='window')
l2.append(cbar)
l2.append(Text(x2 + sep, y2, name, color='white', fontsize=16,
coord='window'))
Compound = canvas.get_draw_class('compoundobject')
obj = Compound(*l2)
canvas.add(obj)
self._max_y = y2
rgb_img = self.p_view.get_image_as_array()
self.r_image.set_data(rgb_img) | python | def rebuild_cmaps(self):
self.logger.info("building color maps image")
ht, wd, sep = self._cmht, self._cmwd, self._cmsep
viewer = self.p_view
# put the canvas into pick mode
canvas = viewer.get_canvas()
canvas.delete_all_objects()
# get the list of color maps
cm_names = self.cm_names
num_cmaps = len(cm_names)
viewer.configure_surface(500, (ht + sep) * num_cmaps)
# create a bunch of color bars and make one large compound object
# with callbacks for clicking on individual color bars
l2 = []
ColorBar = canvas.get_draw_class('drawablecolorbar')
Text = canvas.get_draw_class('text')
#ch_rgbmap = chviewer.get_rgbmap()
#dist = ch_rgbmap.get_dist()
dist = None
#imap = ch_rgbmap.get_imap()
logger = viewer.get_logger()
for i, name in enumerate(cm_names):
rgbmap = RGBMap.RGBMapper(logger, dist=dist)
rgbmap.set_cmap(cmap.get_cmap(name))
#rgbmap.set_imap(imap)
x1, y1 = self._cmxoff, i * (ht + sep)
x2, y2 = x1 + wd, y1 + ht
cbar = ColorBar(x1, y1, x2, y2, cm_name=name, showrange=False,
rgbmap=rgbmap, coord='window')
l2.append(cbar)
l2.append(Text(x2 + sep, y2, name, color='white', fontsize=16,
coord='window'))
Compound = canvas.get_draw_class('compoundobject')
obj = Compound(*l2)
canvas.add(obj)
self._max_y = y2
rgb_img = self.p_view.get_image_as_array()
self.r_image.set_data(rgb_img) | [
"def",
"rebuild_cmaps",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"building color maps image\"",
")",
"ht",
",",
"wd",
",",
"sep",
"=",
"self",
".",
"_cmht",
",",
"self",
".",
"_cmwd",
",",
"self",
".",
"_cmsep",
"viewer",
"=",
... | Builds a color RGB image containing color bars of all the
possible color maps and their labels. | [
"Builds",
"a",
"color",
"RGB",
"image",
"containing",
"color",
"bars",
"of",
"all",
"the",
"possible",
"color",
"maps",
"and",
"their",
"labels",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L168-L215 |
26,476 | ejeschke/ginga | ginga/gw/Desktop.py | Desktop.record_sizes | def record_sizes(self):
"""Record sizes of all container widgets in the layout.
The sizes are recorded in the `params` mappings in the layout.
"""
for rec in self.node.values():
w = rec.widget
wd, ht = w.get_size()
rec.params.update(dict(name=rec.name, width=wd, height=ht))
if rec.kind in ('hpanel', 'vpanel'):
sizes = w.get_sizes()
rec.params.update(dict(sizes=sizes))
if rec.kind in ('ws',):
# record ws type
# TODO: record positions of subwindows
rec.params.update(dict(wstype=rec.ws.wstype))
if rec.kind == 'top':
# record position for top-level widgets as well
x, y = w.get_pos()
if x is not None and y is not None:
# we don't always get reliable information about position
rec.params.update(dict(xpos=x, ypos=y)) | python | def record_sizes(self):
for rec in self.node.values():
w = rec.widget
wd, ht = w.get_size()
rec.params.update(dict(name=rec.name, width=wd, height=ht))
if rec.kind in ('hpanel', 'vpanel'):
sizes = w.get_sizes()
rec.params.update(dict(sizes=sizes))
if rec.kind in ('ws',):
# record ws type
# TODO: record positions of subwindows
rec.params.update(dict(wstype=rec.ws.wstype))
if rec.kind == 'top':
# record position for top-level widgets as well
x, y = w.get_pos()
if x is not None and y is not None:
# we don't always get reliable information about position
rec.params.update(dict(xpos=x, ypos=y)) | [
"def",
"record_sizes",
"(",
"self",
")",
":",
"for",
"rec",
"in",
"self",
".",
"node",
".",
"values",
"(",
")",
":",
"w",
"=",
"rec",
".",
"widget",
"wd",
",",
"ht",
"=",
"w",
".",
"get_size",
"(",
")",
"rec",
".",
"params",
".",
"update",
"(",... | Record sizes of all container widgets in the layout.
The sizes are recorded in the `params` mappings in the layout. | [
"Record",
"sizes",
"of",
"all",
"container",
"widgets",
"in",
"the",
"layout",
".",
"The",
"sizes",
"are",
"recorded",
"in",
"the",
"params",
"mappings",
"in",
"the",
"layout",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gw/Desktop.py#L615-L639 |
26,477 | ejeschke/ginga | ginga/rv/plugins/RC.py | GingaWrapper.help | def help(self, *args):
"""Get help for a remote interface method.
Examples
--------
help('ginga', `method`)
name of the method for which you want help
help('channel', `chname`, `method`)
name of the method in the channel for which you want help
Returns
-------
help : string
a help message
"""
if len(args) == 0:
return help_msg
which = args[0].lower()
if which == 'ginga':
method = args[1]
_method = getattr(self.fv, method)
return _method.__doc__
elif which == 'channel':
chname = args[1]
method = args[2]
chinfo = self.fv.get_channel(chname)
_method = getattr(chinfo.viewer, method)
return _method.__doc__
else:
return ("Please use 'help ginga <method>' or "
"'help channel <chname> <method>'") | python | def help(self, *args):
if len(args) == 0:
return help_msg
which = args[0].lower()
if which == 'ginga':
method = args[1]
_method = getattr(self.fv, method)
return _method.__doc__
elif which == 'channel':
chname = args[1]
method = args[2]
chinfo = self.fv.get_channel(chname)
_method = getattr(chinfo.viewer, method)
return _method.__doc__
else:
return ("Please use 'help ginga <method>' or "
"'help channel <chname> <method>'") | [
"def",
"help",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"help_msg",
"which",
"=",
"args",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"which",
"==",
"'ginga'",
":",
"method",
"=",
"args"... | Get help for a remote interface method.
Examples
--------
help('ginga', `method`)
name of the method for which you want help
help('channel', `chname`, `method`)
name of the method in the channel for which you want help
Returns
-------
help : string
a help message | [
"Get",
"help",
"for",
"a",
"remote",
"interface",
"method",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/RC.py#L300-L335 |
26,478 | ejeschke/ginga | ginga/rv/plugins/RC.py | GingaWrapper.load_buffer | def load_buffer(self, imname, chname, img_buf, dims, dtype,
header, metadata, compressed):
"""Display a FITS image buffer.
Parameters
----------
imname : string
a name to use for the image in Ginga
chname : string
channel in which to load the image
img_buf : string
the image data, as a bytes object
dims : tuple
image dimensions in pixels (usually (height, width))
dtype : string
numpy data type of encoding (e.g. 'float32')
header : dict
fits file header as a dictionary
metadata : dict
other metadata about image to attach to image
compressed : bool
decompress buffer using "bz2"
Returns
-------
0
Notes
-----
* Get array dims: data.shape
* Get array dtype: str(data.dtype)
* Make a string from a numpy array: buf = data.tostring()
* Compress the buffer: buf = bz2.compress(buf)
"""
self.logger.info("received image data len=%d" % (len(img_buf)))
# Unpack the data
try:
# Uncompress data if necessary
decompress = metadata.get('decompress', None)
if compressed or (decompress == 'bz2'):
img_buf = bz2.decompress(img_buf)
# dtype string works for most instances
if dtype == '':
dtype = numpy.float32
byteswap = metadata.get('byteswap', False)
# Create image container
image = AstroImage.AstroImage(logger=self.logger)
image.load_buffer(img_buf, dims, dtype, byteswap=byteswap,
metadata=metadata)
image.update_keywords(header)
image.set(name=imname, path=None)
except Exception as e:
# Some kind of error unpacking the data
errmsg = "Error creating image data for '%s': %s" % (
imname, str(e))
self.logger.error(errmsg)
raise GingaPlugin.PluginError(errmsg)
# Display the image
channel = self.fv.gui_call(self.fv.get_channel_on_demand, chname)
# Note: this little hack needed to let window resize in time for
# file to auto-size properly
self.fv.gui_do(self.fv.change_channel, channel.name)
self.fv.gui_do(self.fv.add_image, imname, image,
chname=channel.name)
return 0 | python | def load_buffer(self, imname, chname, img_buf, dims, dtype,
header, metadata, compressed):
self.logger.info("received image data len=%d" % (len(img_buf)))
# Unpack the data
try:
# Uncompress data if necessary
decompress = metadata.get('decompress', None)
if compressed or (decompress == 'bz2'):
img_buf = bz2.decompress(img_buf)
# dtype string works for most instances
if dtype == '':
dtype = numpy.float32
byteswap = metadata.get('byteswap', False)
# Create image container
image = AstroImage.AstroImage(logger=self.logger)
image.load_buffer(img_buf, dims, dtype, byteswap=byteswap,
metadata=metadata)
image.update_keywords(header)
image.set(name=imname, path=None)
except Exception as e:
# Some kind of error unpacking the data
errmsg = "Error creating image data for '%s': %s" % (
imname, str(e))
self.logger.error(errmsg)
raise GingaPlugin.PluginError(errmsg)
# Display the image
channel = self.fv.gui_call(self.fv.get_channel_on_demand, chname)
# Note: this little hack needed to let window resize in time for
# file to auto-size properly
self.fv.gui_do(self.fv.change_channel, channel.name)
self.fv.gui_do(self.fv.add_image, imname, image,
chname=channel.name)
return 0 | [
"def",
"load_buffer",
"(",
"self",
",",
"imname",
",",
"chname",
",",
"img_buf",
",",
"dims",
",",
"dtype",
",",
"header",
",",
"metadata",
",",
"compressed",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"received image data len=%d\"",
"%",
"(",
... | Display a FITS image buffer.
Parameters
----------
imname : string
a name to use for the image in Ginga
chname : string
channel in which to load the image
img_buf : string
the image data, as a bytes object
dims : tuple
image dimensions in pixels (usually (height, width))
dtype : string
numpy data type of encoding (e.g. 'float32')
header : dict
fits file header as a dictionary
metadata : dict
other metadata about image to attach to image
compressed : bool
decompress buffer using "bz2"
Returns
-------
0
Notes
-----
* Get array dims: data.shape
* Get array dtype: str(data.dtype)
* Make a string from a numpy array: buf = data.tostring()
* Compress the buffer: buf = bz2.compress(buf) | [
"Display",
"a",
"FITS",
"image",
"buffer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/RC.py#L337-L411 |
26,479 | ejeschke/ginga | ginga/toolkit.py | use | def use(name):
"""
Set the name of the GUI toolkit we should use.
"""
global toolkit, family
name = name.lower()
if name.startswith('choose'):
pass
elif name.startswith('qt') or name.startswith('pyside'):
family = 'qt'
if name == 'qt':
name = 'qt4'
assert name in ('qt4', 'pyside', 'qt5'), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('gtk'):
# default for "gtk" is gtk3
if name in ('gtk', 'gtk3'):
name = 'gtk3'
family = 'gtk3'
elif name in ('gtk2',):
family = 'gtk'
assert name in ('gtk2', 'gtk3'), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('tk'):
family = 'tk'
assert name in ('tk', ), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('pg'):
family = 'pg'
assert name in ('pg', ), \
ToolKitError("ToolKit '%s' not supported!" % (name))
else:
ToolKitError("ToolKit '%s' not supported!" % (name))
toolkit = name | python | def use(name):
global toolkit, family
name = name.lower()
if name.startswith('choose'):
pass
elif name.startswith('qt') or name.startswith('pyside'):
family = 'qt'
if name == 'qt':
name = 'qt4'
assert name in ('qt4', 'pyside', 'qt5'), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('gtk'):
# default for "gtk" is gtk3
if name in ('gtk', 'gtk3'):
name = 'gtk3'
family = 'gtk3'
elif name in ('gtk2',):
family = 'gtk'
assert name in ('gtk2', 'gtk3'), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('tk'):
family = 'tk'
assert name in ('tk', ), \
ToolKitError("ToolKit '%s' not supported!" % (name))
elif name.startswith('pg'):
family = 'pg'
assert name in ('pg', ), \
ToolKitError("ToolKit '%s' not supported!" % (name))
else:
ToolKitError("ToolKit '%s' not supported!" % (name))
toolkit = name | [
"def",
"use",
"(",
"name",
")",
":",
"global",
"toolkit",
",",
"family",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
".",
"startswith",
"(",
"'choose'",
")",
":",
"pass",
"elif",
"name",
".",
"startswith",
"(",
"'qt'",
")",
"or",
"na... | Set the name of the GUI toolkit we should use. | [
"Set",
"the",
"name",
"of",
"the",
"GUI",
"toolkit",
"we",
"should",
"use",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/toolkit.py#L16-L57 |
26,480 | ejeschke/ginga | ginga/misc/Settings.py | SettingGroup.share_settings | def share_settings(self, other, keylist=None, include_callbacks=True,
callback=True):
"""Sharing settings with `other`
"""
if keylist is None:
keylist = self.group.keys()
if include_callbacks:
for key in keylist:
oset, mset = other.group[key], self.group[key]
other.group[key] = mset
oset.merge_callbacks_to(mset)
if callback:
# make callbacks only after all items are set in the group
# TODO: only make callbacks for values that changed?
for key in keylist:
other.group[key].make_callback('set', other.group[key].value) | python | def share_settings(self, other, keylist=None, include_callbacks=True,
callback=True):
if keylist is None:
keylist = self.group.keys()
if include_callbacks:
for key in keylist:
oset, mset = other.group[key], self.group[key]
other.group[key] = mset
oset.merge_callbacks_to(mset)
if callback:
# make callbacks only after all items are set in the group
# TODO: only make callbacks for values that changed?
for key in keylist:
other.group[key].make_callback('set', other.group[key].value) | [
"def",
"share_settings",
"(",
"self",
",",
"other",
",",
"keylist",
"=",
"None",
",",
"include_callbacks",
"=",
"True",
",",
"callback",
"=",
"True",
")",
":",
"if",
"keylist",
"is",
"None",
":",
"keylist",
"=",
"self",
".",
"group",
".",
"keys",
"(",
... | Sharing settings with `other` | [
"Sharing",
"settings",
"with",
"other"
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Settings.py#L107-L122 |
26,481 | ejeschke/ginga | ginga/util/wcsmod/__init__.py | use | def use(wcspkg, raise_err=True):
"""Choose WCS package."""
global coord_types, wcs_configured, WCS
if wcspkg not in common.custom_wcs:
# Try to dynamically load WCS
modname = 'wcs_%s' % (wcspkg)
path = os.path.join(wcs_home, '%s.py' % (modname))
try:
my_import(modname, path)
except ImportError:
return False
if wcspkg in common.custom_wcs:
bnch = common.custom_wcs[wcspkg]
WCS = bnch.wrapper_class
coord_types = bnch.coord_types
wcs_configured = True
return True
return False | python | def use(wcspkg, raise_err=True):
global coord_types, wcs_configured, WCS
if wcspkg not in common.custom_wcs:
# Try to dynamically load WCS
modname = 'wcs_%s' % (wcspkg)
path = os.path.join(wcs_home, '%s.py' % (modname))
try:
my_import(modname, path)
except ImportError:
return False
if wcspkg in common.custom_wcs:
bnch = common.custom_wcs[wcspkg]
WCS = bnch.wrapper_class
coord_types = bnch.coord_types
wcs_configured = True
return True
return False | [
"def",
"use",
"(",
"wcspkg",
",",
"raise_err",
"=",
"True",
")",
":",
"global",
"coord_types",
",",
"wcs_configured",
",",
"WCS",
"if",
"wcspkg",
"not",
"in",
"common",
".",
"custom_wcs",
":",
"# Try to dynamically load WCS",
"modname",
"=",
"'wcs_%s'",
"%",
... | Choose WCS package. | [
"Choose",
"WCS",
"package",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/__init__.py#L63-L83 |
26,482 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable._set_combobox | def _set_combobox(self, attrname, vals, default=0):
"""Populate combobox with given list."""
combobox = getattr(self.w, attrname)
for val in vals:
combobox.append_text(val)
if default > len(vals):
default = 0
val = vals[default]
combobox.show_text(val)
return val | python | def _set_combobox(self, attrname, vals, default=0):
combobox = getattr(self.w, attrname)
for val in vals:
combobox.append_text(val)
if default > len(vals):
default = 0
val = vals[default]
combobox.show_text(val)
return val | [
"def",
"_set_combobox",
"(",
"self",
",",
"attrname",
",",
"vals",
",",
"default",
"=",
"0",
")",
":",
"combobox",
"=",
"getattr",
"(",
"self",
".",
"w",
",",
"attrname",
")",
"for",
"val",
"in",
"vals",
":",
"combobox",
".",
"append_text",
"(",
"val... | Populate combobox with given list. | [
"Populate",
"combobox",
"with",
"given",
"list",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L177-L186 |
26,483 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.clear_data | def clear_data(self):
"""Clear comboboxes and columns."""
self.tab = None
self.cols = []
self._idx = []
self.x_col = ''
self.y_col = ''
self.w.xcombo.clear()
self.w.ycombo.clear()
self.w.x_lo.set_text('')
self.w.x_hi.set_text('')
self.w.y_lo.set_text('')
self.w.y_hi.set_text('') | python | def clear_data(self):
self.tab = None
self.cols = []
self._idx = []
self.x_col = ''
self.y_col = ''
self.w.xcombo.clear()
self.w.ycombo.clear()
self.w.x_lo.set_text('')
self.w.x_hi.set_text('')
self.w.y_lo.set_text('')
self.w.y_hi.set_text('') | [
"def",
"clear_data",
"(",
"self",
")",
":",
"self",
".",
"tab",
"=",
"None",
"self",
".",
"cols",
"=",
"[",
"]",
"self",
".",
"_idx",
"=",
"[",
"]",
"self",
".",
"x_col",
"=",
"''",
"self",
".",
"y_col",
"=",
"''",
"self",
".",
"w",
".",
"xco... | Clear comboboxes and columns. | [
"Clear",
"comboboxes",
"and",
"columns",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L217-L229 |
26,484 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.clear_plot | def clear_plot(self):
"""Clear plot display."""
self.tab_plot.clear()
self.tab_plot.draw()
self.save_plot.set_enabled(False) | python | def clear_plot(self):
self.tab_plot.clear()
self.tab_plot.draw()
self.save_plot.set_enabled(False) | [
"def",
"clear_plot",
"(",
"self",
")",
":",
"self",
".",
"tab_plot",
".",
"clear",
"(",
")",
"self",
".",
"tab_plot",
".",
"draw",
"(",
")",
"self",
".",
"save_plot",
".",
"set_enabled",
"(",
"False",
")"
] | Clear plot display. | [
"Clear",
"plot",
"display",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L231-L235 |
26,485 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.plot_two_columns | def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False):
"""Simple line plot for two selected columns."""
self.clear_plot()
if self.tab is None: # No table data to plot
return
plt_kw = {
'lw': self.settings.get('linewidth', 1),
'ls': self.settings.get('linestyle', '-'),
'color': self.settings.get('linecolor', 'blue'),
'ms': self.settings.get('markersize', 6),
'mew': self.settings.get('markerwidth', 0.5),
'mfc': self.settings.get('markercolor', 'red')}
plt_kw['mec'] = plt_kw['mfc']
try:
x_data, y_data, marker = self._get_plot_data()
self.tab_plot.plot(
x_data, y_data,
xtitle=self._get_label('x'), ytitle=self._get_label('y'),
marker=marker, **plt_kw)
if reset_xlimits:
self.set_ylim_cb()
self.set_xlimits_widgets()
if reset_ylimits:
self.set_xlim_cb()
self.set_ylimits_widgets()
if not (reset_xlimits or reset_ylimits):
self.set_xlim_cb(redraw=False)
self.set_ylim_cb()
except Exception as e:
self.logger.error(str(e))
else:
self.save_plot.set_enabled(True) | python | def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False):
self.clear_plot()
if self.tab is None: # No table data to plot
return
plt_kw = {
'lw': self.settings.get('linewidth', 1),
'ls': self.settings.get('linestyle', '-'),
'color': self.settings.get('linecolor', 'blue'),
'ms': self.settings.get('markersize', 6),
'mew': self.settings.get('markerwidth', 0.5),
'mfc': self.settings.get('markercolor', 'red')}
plt_kw['mec'] = plt_kw['mfc']
try:
x_data, y_data, marker = self._get_plot_data()
self.tab_plot.plot(
x_data, y_data,
xtitle=self._get_label('x'), ytitle=self._get_label('y'),
marker=marker, **plt_kw)
if reset_xlimits:
self.set_ylim_cb()
self.set_xlimits_widgets()
if reset_ylimits:
self.set_xlim_cb()
self.set_ylimits_widgets()
if not (reset_xlimits or reset_ylimits):
self.set_xlim_cb(redraw=False)
self.set_ylim_cb()
except Exception as e:
self.logger.error(str(e))
else:
self.save_plot.set_enabled(True) | [
"def",
"plot_two_columns",
"(",
"self",
",",
"reset_xlimits",
"=",
"False",
",",
"reset_ylimits",
"=",
"False",
")",
":",
"self",
".",
"clear_plot",
"(",
")",
"if",
"self",
".",
"tab",
"is",
"None",
":",
"# No table data to plot",
"return",
"plt_kw",
"=",
... | Simple line plot for two selected columns. | [
"Simple",
"line",
"plot",
"for",
"two",
"selected",
"columns",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L237-L274 |
26,486 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable._get_plot_data | def _get_plot_data(self):
"""Extract only good data point for plotting."""
_marker_type = self.settings.get('markerstyle', 'o')
if self.x_col == self._idxname:
x_data = self._idx
else:
x_data = self.tab[self.x_col].data
if self.y_col == self._idxname:
y_data = self._idx
else:
y_data = self.tab[self.y_col].data
if self.tab.masked:
if self.x_col == self._idxname:
x_mask = np.ones_like(self._idx, dtype=np.bool)
else:
x_mask = ~self.tab[self.x_col].mask
if self.y_col == self._idxname:
y_mask = np.ones_like(self._idx, dtype=np.bool)
else:
y_mask = ~self.tab[self.y_col].mask
mask = x_mask & y_mask
x_data = x_data[mask]
y_data = y_data[mask]
if len(x_data) > 1:
i = np.argsort(x_data) # Sort X-axis to avoid messy line plot
x_data = x_data[i]
y_data = y_data[i]
if not self.w.show_marker.get_state():
_marker_type = None
return x_data, y_data, _marker_type | python | def _get_plot_data(self):
_marker_type = self.settings.get('markerstyle', 'o')
if self.x_col == self._idxname:
x_data = self._idx
else:
x_data = self.tab[self.x_col].data
if self.y_col == self._idxname:
y_data = self._idx
else:
y_data = self.tab[self.y_col].data
if self.tab.masked:
if self.x_col == self._idxname:
x_mask = np.ones_like(self._idx, dtype=np.bool)
else:
x_mask = ~self.tab[self.x_col].mask
if self.y_col == self._idxname:
y_mask = np.ones_like(self._idx, dtype=np.bool)
else:
y_mask = ~self.tab[self.y_col].mask
mask = x_mask & y_mask
x_data = x_data[mask]
y_data = y_data[mask]
if len(x_data) > 1:
i = np.argsort(x_data) # Sort X-axis to avoid messy line plot
x_data = x_data[i]
y_data = y_data[i]
if not self.w.show_marker.get_state():
_marker_type = None
return x_data, y_data, _marker_type | [
"def",
"_get_plot_data",
"(",
"self",
")",
":",
"_marker_type",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'markerstyle'",
",",
"'o'",
")",
"if",
"self",
".",
"x_col",
"==",
"self",
".",
"_idxname",
":",
"x_data",
"=",
"self",
".",
"_idx",
"else",... | Extract only good data point for plotting. | [
"Extract",
"only",
"good",
"data",
"point",
"for",
"plotting",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L292-L329 |
26,487 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable._get_label | def _get_label(self, axis):
"""Return plot label for column for the given axis."""
if axis == 'x':
colname = self.x_col
else: # y
colname = self.y_col
if colname == self._idxname:
label = 'Index'
else:
col = self.tab[colname]
if col.unit:
label = '{0} ({1})'.format(col.name, col.unit)
else:
label = col.name
return label | python | def _get_label(self, axis):
if axis == 'x':
colname = self.x_col
else: # y
colname = self.y_col
if colname == self._idxname:
label = 'Index'
else:
col = self.tab[colname]
if col.unit:
label = '{0} ({1})'.format(col.name, col.unit)
else:
label = col.name
return label | [
"def",
"_get_label",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"==",
"'x'",
":",
"colname",
"=",
"self",
".",
"x_col",
"else",
":",
"# y",
"colname",
"=",
"self",
".",
"y_col",
"if",
"colname",
"==",
"self",
".",
"_idxname",
":",
"label",
"... | Return plot label for column for the given axis. | [
"Return",
"plot",
"label",
"for",
"column",
"for",
"the",
"given",
"axis",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L331-L348 |
26,488 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.x_select_cb | def x_select_cb(self, w, index):
"""Callback to set X-axis column."""
try:
self.x_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_xlimits=True) | python | def x_select_cb(self, w, index):
try:
self.x_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_xlimits=True) | [
"def",
"x_select_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"try",
":",
"self",
".",
"x_col",
"=",
"self",
".",
"cols",
"[",
"index",
"]",
"except",
"IndexError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"str",
"(",
"e",... | Callback to set X-axis column. | [
"Callback",
"to",
"set",
"X",
"-",
"axis",
"column",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L350-L357 |
26,489 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.y_select_cb | def y_select_cb(self, w, index):
"""Callback to set Y-axis column."""
try:
self.y_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_ylimits=True) | python | def y_select_cb(self, w, index):
try:
self.y_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_ylimits=True) | [
"def",
"y_select_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"try",
":",
"self",
".",
"y_col",
"=",
"self",
".",
"cols",
"[",
"index",
"]",
"except",
"IndexError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"str",
"(",
"e",... | Callback to set Y-axis column. | [
"Callback",
"to",
"set",
"Y",
"-",
"axis",
"column",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L359-L366 |
26,490 | ejeschke/ginga | ginga/rv/plugins/PlotTable.py | PlotTable.save_cb | def save_cb(self):
"""Save plot to file."""
# This just defines the basename.
# Extension has to be explicitly defined or things can get messy.
w = Widgets.SaveDialog(title='Save plot')
target = w.get_path()
if target is None:
# Save canceled
return
plot_ext = self.settings.get('file_suffix', '.png')
if not target.endswith(plot_ext):
target += plot_ext
# TODO: This can be a user preference?
fig_dpi = 100
try:
fig = self.tab_plot.get_figure()
fig.savefig(target, dpi=fig_dpi)
except Exception as e:
self.logger.error(str(e))
else:
self.logger.info('Table plot saved as {0}'.format(target)) | python | def save_cb(self):
# This just defines the basename.
# Extension has to be explicitly defined or things can get messy.
w = Widgets.SaveDialog(title='Save plot')
target = w.get_path()
if target is None:
# Save canceled
return
plot_ext = self.settings.get('file_suffix', '.png')
if not target.endswith(plot_ext):
target += plot_ext
# TODO: This can be a user preference?
fig_dpi = 100
try:
fig = self.tab_plot.get_figure()
fig.savefig(target, dpi=fig_dpi)
except Exception as e:
self.logger.error(str(e))
else:
self.logger.info('Table plot saved as {0}'.format(target)) | [
"def",
"save_cb",
"(",
"self",
")",
":",
"# This just defines the basename.",
"# Extension has to be explicitly defined or things can get messy.",
"w",
"=",
"Widgets",
".",
"SaveDialog",
"(",
"title",
"=",
"'Save plot'",
")",
"target",
"=",
"w",
".",
"get_path",
"(",
... | Save plot to file. | [
"Save",
"plot",
"to",
"file",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L432-L458 |
26,491 | ejeschke/ginga | ginga/examples/gtk/fits2pdf.py | convert | def convert(filepath, outfilepath):
"""Convert FITS image to PDF."""
logger = logging.getLogger("example1")
logger.setLevel(logging.INFO)
fmt = logging.Formatter(STD_FORMAT)
stderrHdlr = logging.StreamHandler()
stderrHdlr.setFormatter(fmt)
logger.addHandler(stderrHdlr)
fi = ImageViewCairo(logger)
fi.configure(500, 1000)
# Load fits file
image = load_data(filepath, logger=logger)
# Make any adjustments to the image that we want
fi.set_bg(1.0, 1.0, 1.0)
fi.set_image(image)
fi.auto_levels()
fi.zoom_fit()
fi.center_image()
ht_pts = 11.0 / point_in
wd_pts = 8.5 / point_in
off_x, off_y = 0, 0
out_f = open(outfilepath, 'w')
surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
# set pixels per inch
surface.set_fallback_resolution(300, 300)
surface.set_device_offset(off_x, off_y)
try:
fi.save_image_as_surface(surface)
surface.show_page()
surface.flush()
surface.finish()
finally:
out_f.close() | python | def convert(filepath, outfilepath):
logger = logging.getLogger("example1")
logger.setLevel(logging.INFO)
fmt = logging.Formatter(STD_FORMAT)
stderrHdlr = logging.StreamHandler()
stderrHdlr.setFormatter(fmt)
logger.addHandler(stderrHdlr)
fi = ImageViewCairo(logger)
fi.configure(500, 1000)
# Load fits file
image = load_data(filepath, logger=logger)
# Make any adjustments to the image that we want
fi.set_bg(1.0, 1.0, 1.0)
fi.set_image(image)
fi.auto_levels()
fi.zoom_fit()
fi.center_image()
ht_pts = 11.0 / point_in
wd_pts = 8.5 / point_in
off_x, off_y = 0, 0
out_f = open(outfilepath, 'w')
surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
# set pixels per inch
surface.set_fallback_resolution(300, 300)
surface.set_device_offset(off_x, off_y)
try:
fi.save_image_as_surface(surface)
surface.show_page()
surface.flush()
surface.finish()
finally:
out_f.close() | [
"def",
"convert",
"(",
"filepath",
",",
"outfilepath",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"example1\"",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"fmt",
"=",
"logging",
".",
"Formatter",
"(",
"STD_FORMAT",
... | Convert FITS image to PDF. | [
"Convert",
"FITS",
"image",
"to",
"PDF",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gtk/fits2pdf.py#L35-L73 |
26,492 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.redo | def redo(self):
"""Image or masks have changed. Clear and redraw."""
if not self.gui_up:
return
self.clear_mask()
image = self.fitsimage.get_image()
if image is None:
return
n_obj = len(self._maskobjs)
self.logger.debug('Displaying {0} masks'.format(n_obj))
if n_obj == 0:
return
# Display info table
self.recreate_toc()
# Draw on canvas
self.masktag = self.canvas.add(self.dc.CompoundObject(*self._maskobjs))
self.fitsimage.redraw() | python | def redo(self):
if not self.gui_up:
return
self.clear_mask()
image = self.fitsimage.get_image()
if image is None:
return
n_obj = len(self._maskobjs)
self.logger.debug('Displaying {0} masks'.format(n_obj))
if n_obj == 0:
return
# Display info table
self.recreate_toc()
# Draw on canvas
self.masktag = self.canvas.add(self.dc.CompoundObject(*self._maskobjs))
self.fitsimage.redraw() | [
"def",
"redo",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"gui_up",
":",
"return",
"self",
".",
"clear_mask",
"(",
")",
"image",
"=",
"self",
".",
"fitsimage",
".",
"get_image",
"(",
")",
"if",
"image",
"is",
"None",
":",
"return",
"n_obj",
"... | Image or masks have changed. Clear and redraw. | [
"Image",
"or",
"masks",
"have",
"changed",
".",
"Clear",
"and",
"redraw",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L207-L228 |
26,493 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.clear_mask | def clear_mask(self):
"""Clear mask from image.
This does not clear loaded masks from memory."""
if self.masktag:
try:
self.canvas.delete_object_by_tag(self.masktag, redraw=False)
except Exception:
pass
if self.maskhltag:
try:
self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
except Exception:
pass
self.treeview.clear() # Clear table too
self.fitsimage.redraw() | python | def clear_mask(self):
if self.masktag:
try:
self.canvas.delete_object_by_tag(self.masktag, redraw=False)
except Exception:
pass
if self.maskhltag:
try:
self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
except Exception:
pass
self.treeview.clear() # Clear table too
self.fitsimage.redraw() | [
"def",
"clear_mask",
"(",
"self",
")",
":",
"if",
"self",
".",
"masktag",
":",
"try",
":",
"self",
".",
"canvas",
".",
"delete_object_by_tag",
"(",
"self",
".",
"masktag",
",",
"redraw",
"=",
"False",
")",
"except",
"Exception",
":",
"pass",
"if",
"sel... | Clear mask from image.
This does not clear loaded masks from memory. | [
"Clear",
"mask",
"from",
"image",
".",
"This",
"does",
"not",
"clear",
"loaded",
"masks",
"from",
"memory",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L230-L246 |
26,494 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.load_file | def load_file(self, filename):
"""Load mask image.
Results are appended to previously loaded masks.
This can be used to load mask per color.
"""
if not os.path.isfile(filename):
return
self.logger.info('Loading mask image from {0}'.format(filename))
try:
# 0=False, everything else True
dat = fits.getdata(filename).astype(np.bool)
except Exception as e:
self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e)))
return
key = '{0},{1}'.format(self.maskcolor, self.maskalpha)
if key in self.tree_dict:
sub_dict = self.tree_dict[key]
else:
sub_dict = {}
self.tree_dict[key] = sub_dict
# Add to listing
seqstr = '{0:04d}'.format(self._seqno) # Prepend 0s for proper sort
sub_dict[seqstr] = Bunch.Bunch(ID=seqstr,
MASKFILE=os.path.basename(filename))
self._treepaths.append((key, seqstr))
self._seqno += 1
# Create mask layer
obj = self.dc.Image(0, 0, masktorgb(
dat, color=self.maskcolor, alpha=self.maskalpha))
self._maskobjs.append(obj)
self.redo() | python | def load_file(self, filename):
if not os.path.isfile(filename):
return
self.logger.info('Loading mask image from {0}'.format(filename))
try:
# 0=False, everything else True
dat = fits.getdata(filename).astype(np.bool)
except Exception as e:
self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e)))
return
key = '{0},{1}'.format(self.maskcolor, self.maskalpha)
if key in self.tree_dict:
sub_dict = self.tree_dict[key]
else:
sub_dict = {}
self.tree_dict[key] = sub_dict
# Add to listing
seqstr = '{0:04d}'.format(self._seqno) # Prepend 0s for proper sort
sub_dict[seqstr] = Bunch.Bunch(ID=seqstr,
MASKFILE=os.path.basename(filename))
self._treepaths.append((key, seqstr))
self._seqno += 1
# Create mask layer
obj = self.dc.Image(0, 0, masktorgb(
dat, color=self.maskcolor, alpha=self.maskalpha))
self._maskobjs.append(obj)
self.redo() | [
"def",
"load_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"self",
".",
"logger",
".",
"info",
"(",
"'Loading mask image from {0}'",
".",
"format",
"(",
"filename",
")",... | Load mask image.
Results are appended to previously loaded masks.
This can be used to load mask per color. | [
"Load",
"mask",
"image",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L257-L296 |
26,495 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask._rgbtomask | def _rgbtomask(self, obj):
"""Convert RGB arrays from mask canvas object back to boolean mask."""
dat = obj.get_image().get_data() # RGB arrays
return dat.sum(axis=2).astype(np.bool) | python | def _rgbtomask(self, obj):
dat = obj.get_image().get_data() # RGB arrays
return dat.sum(axis=2).astype(np.bool) | [
"def",
"_rgbtomask",
"(",
"self",
",",
"obj",
")",
":",
"dat",
"=",
"obj",
".",
"get_image",
"(",
")",
".",
"get_data",
"(",
")",
"# RGB arrays",
"return",
"dat",
".",
"sum",
"(",
"axis",
"=",
"2",
")",
".",
"astype",
"(",
"np",
".",
"bool",
")"
... | Convert RGB arrays from mask canvas object back to boolean mask. | [
"Convert",
"RGB",
"arrays",
"from",
"mask",
"canvas",
"object",
"back",
"to",
"boolean",
"mask",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L317-L320 |
26,496 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.hl_table2canvas | def hl_table2canvas(self, w, res_dict):
"""Highlight mask on canvas when user click on table."""
objlist = []
# Remove existing highlight
if self.maskhltag:
try:
self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
except Exception:
pass
for sub_dict in res_dict.values():
for seqno in sub_dict:
mobj = self._maskobjs[int(seqno) - 1]
dat = self._rgbtomask(mobj)
obj = self.dc.Image(0, 0, masktorgb(
dat, color=self.hlcolor, alpha=self.hlalpha))
objlist.append(obj)
# Draw on canvas
if len(objlist) > 0:
self.maskhltag = self.canvas.add(self.dc.CompoundObject(*objlist))
self.fitsimage.redraw() | python | def hl_table2canvas(self, w, res_dict):
objlist = []
# Remove existing highlight
if self.maskhltag:
try:
self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
except Exception:
pass
for sub_dict in res_dict.values():
for seqno in sub_dict:
mobj = self._maskobjs[int(seqno) - 1]
dat = self._rgbtomask(mobj)
obj = self.dc.Image(0, 0, masktorgb(
dat, color=self.hlcolor, alpha=self.hlalpha))
objlist.append(obj)
# Draw on canvas
if len(objlist) > 0:
self.maskhltag = self.canvas.add(self.dc.CompoundObject(*objlist))
self.fitsimage.redraw() | [
"def",
"hl_table2canvas",
"(",
"self",
",",
"w",
",",
"res_dict",
")",
":",
"objlist",
"=",
"[",
"]",
"# Remove existing highlight",
"if",
"self",
".",
"maskhltag",
":",
"try",
":",
"self",
".",
"canvas",
".",
"delete_object_by_tag",
"(",
"self",
".",
"mas... | Highlight mask on canvas when user click on table. | [
"Highlight",
"mask",
"on",
"canvas",
"when",
"user",
"click",
"on",
"table",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L322-L345 |
26,497 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.hl_canvas2table_box | def hl_canvas2table_box(self, canvas, tag):
"""Highlight all masks inside user drawn box on table."""
self.treeview.clear_selection()
# Remove existing box
cobj = canvas.get_object_by_tag(tag)
if cobj.kind != 'rectangle':
return
canvas.delete_object_by_tag(tag, redraw=False)
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
except Exception:
pass
# Nothing to do if no masks are displayed
try:
obj = canvas.get_object_by_tag(self.masktag)
except Exception:
return
if obj.kind != 'compound':
return
# Nothing to do if table has no data
if len(self._maskobjs) == 0:
return
# Find masks that intersect the rectangle
for i, mobj in enumerate(self._maskobjs):
# The actual mask
mask1 = self._rgbtomask(mobj)
# The selected area
rgbimage = mobj.get_image()
mask2 = rgbimage.get_shape_mask(cobj)
# Highlight mask with intersect
if np.any(mask1 & mask2):
self._highlight_path(self._treepaths[i]) | python | def hl_canvas2table_box(self, canvas, tag):
self.treeview.clear_selection()
# Remove existing box
cobj = canvas.get_object_by_tag(tag)
if cobj.kind != 'rectangle':
return
canvas.delete_object_by_tag(tag, redraw=False)
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
except Exception:
pass
# Nothing to do if no masks are displayed
try:
obj = canvas.get_object_by_tag(self.masktag)
except Exception:
return
if obj.kind != 'compound':
return
# Nothing to do if table has no data
if len(self._maskobjs) == 0:
return
# Find masks that intersect the rectangle
for i, mobj in enumerate(self._maskobjs):
# The actual mask
mask1 = self._rgbtomask(mobj)
# The selected area
rgbimage = mobj.get_image()
mask2 = rgbimage.get_shape_mask(cobj)
# Highlight mask with intersect
if np.any(mask1 & mask2):
self._highlight_path(self._treepaths[i]) | [
"def",
"hl_canvas2table_box",
"(",
"self",
",",
"canvas",
",",
"tag",
")",
":",
"self",
".",
"treeview",
".",
"clear_selection",
"(",
")",
"# Remove existing box",
"cobj",
"=",
"canvas",
".",
"get_object_by_tag",
"(",
"tag",
")",
"if",
"cobj",
".",
"kind",
... | Highlight all masks inside user drawn box on table. | [
"Highlight",
"all",
"masks",
"inside",
"user",
"drawn",
"box",
"on",
"table",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L347-L388 |
26,498 | ejeschke/ginga | ginga/rv/plugins/TVMask.py | TVMask.hl_canvas2table | def hl_canvas2table(self, canvas, button, data_x, data_y):
"""Highlight mask on table when user click on canvas."""
self.treeview.clear_selection()
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
except Exception:
pass
# Nothing to do if no masks are displayed
try:
obj = canvas.get_object_by_tag(self.masktag)
except Exception:
return
if obj.kind != 'compound':
return
# Nothing to do if table has no data
if len(self._maskobjs) == 0:
return
for i, mobj in enumerate(self._maskobjs):
mask1 = self._rgbtomask(mobj)
# Highlight mask covering selected cursor position
if mask1[int(data_y), int(data_x)]:
self._highlight_path(self._treepaths[i]) | python | def hl_canvas2table(self, canvas, button, data_x, data_y):
self.treeview.clear_selection()
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
except Exception:
pass
# Nothing to do if no masks are displayed
try:
obj = canvas.get_object_by_tag(self.masktag)
except Exception:
return
if obj.kind != 'compound':
return
# Nothing to do if table has no data
if len(self._maskobjs) == 0:
return
for i, mobj in enumerate(self._maskobjs):
mask1 = self._rgbtomask(mobj)
# Highlight mask covering selected cursor position
if mask1[int(data_y), int(data_x)]:
self._highlight_path(self._treepaths[i]) | [
"def",
"hl_canvas2table",
"(",
"self",
",",
"canvas",
",",
"button",
",",
"data_x",
",",
"data_y",
")",
":",
"self",
".",
"treeview",
".",
"clear_selection",
"(",
")",
"# Remove existing highlight",
"if",
"self",
".",
"maskhltag",
":",
"try",
":",
"canvas",
... | Highlight mask on table when user click on canvas. | [
"Highlight",
"mask",
"on",
"table",
"when",
"user",
"click",
"on",
"canvas",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L391-L420 |
26,499 | ejeschke/ginga | ginga/canvas/types/astro.py | AnnulusMixin.contains_pt | def contains_pt(self, pt):
"""Containment test."""
obj1, obj2 = self.objects
return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt)) | python | def contains_pt(self, pt):
obj1, obj2 = self.objects
return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt)) | [
"def",
"contains_pt",
"(",
"self",
",",
"pt",
")",
":",
"obj1",
",",
"obj2",
"=",
"self",
".",
"objects",
"return",
"obj2",
".",
"contains_pt",
"(",
"pt",
")",
"and",
"np",
".",
"logical_not",
"(",
"obj1",
".",
"contains_pt",
"(",
"pt",
")",
")"
] | Containment test. | [
"Containment",
"test",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/types/astro.py#L561-L564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.