Module: GRCommons::JupyterSupport

Included in:
GR
Defined in:
lib/gr_commons/jupyter_support.rb

Overview

Jupyter Notebook and Jpyter Lab.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(_obj) ⇒ Object

Sets the environment variable when the module is extended.



9
10
11
12
13
# File 'lib/gr_commons/jupyter_support.rb', line 9

def self.extended(_obj)
  require 'tmpdir'
  ENV['GKS_WSTYPE'] = 'svg'
  ENV['GKS_FILEPATH'] = Dir::Tmpname.create('plot-') {}
end

Instance Method Details

#show(display = true) ⇒ Object

Display your plot in Jupyter Notebook / Lab



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gr_commons/jupyter_support.rb', line 16

def show(display = true)
  emergencyclosegks
  sleep 0.5
  type = ENV['GKS_WSTYPE']
  case type
  when 'svg'
    data = File.read("#{ENV['GKS_FILEPATH']}.svg")
    IRuby.display(data, mime: 'image/svg+xml') if display
  when 'png', '322', '140'
    data = File.read("#{ENV['GKS_FILEPATH']}.png")
    IRuby.display(data, mime: 'image/png') if display
  when 'jpg', '321', '144'
    data = File.read("#{ENV['GKS_FILEPATH']}.jpg")
    IRuby.display(data, mime: 'image/jpeg') if display
  when 'gif', '130'
    data = File.read("#{ENV['GKS_FILEPATH']}.gif")
    IRuby.display(data, mime: 'image/gif') if display
  when 'webm', 'ogg', 'mp4', 'mov'
    require 'base64'
    mimespec = if type == 'mov'
                 'movie/quicktime'
               else
                 "video/#{type}"
               end
    data = File.binread("#{ENV['GKS_FILEPATH']}.#{type}")
    if display
      IRuby.display(
        "<video autoplay controls><source type=\"#{mimespec}\" " \
        "src=\"data:#{mimespec};base64,#{Base64.encode64(data)}\">" \
        '</video>',
        mime: 'text/html'
      )
    end
  end
  data unless display
end