Last active
April 2, 2020 00:27
-
-
Save fanannan/4c62ffd86b537d5bd40d881bcdfdbf9a to your computer and use it in GitHub Desktop.
Clojupyter Snippet for libpython-clj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Clojupyter Snippet | |
(require '[clojupyter.misc.helper :as helper]) | |
(helper/add-dependencies '[cnuernber/libpython-clj "1.36"]) | |
(require '[libpython-clj.require :refer [require-python]] | |
'[libpython-clj.python :refer [py. py.. py.- | |
as-python as-jvm | |
->python ->jvm | |
get-attr call-attr call-attr-kw | |
get-item att-type-map | |
call call-kw initialize! | |
as-numpy as-tensor ->numpy | |
run-simple-string | |
add-module module-dict | |
import-module | |
python-type] :as py]) | |
; Python 3.7 | |
(py/initialize! :python-executable "/..../anaconda3/envs/py37/bin/python" | |
:library-path "/..../anaconda3/envs/py37/lib/libpython3.7m.so") | |
; some utilities | |
(defn get-attr-list [obj] | |
(-> obj (py/get-attr "__class__") | |
(py/get-attr "__dict__") | |
(py/call-attr "keys") | |
vec)) | |
(defn has-attr? [obj attr] | |
(some #(= attr %) (get-attr-list obj))) | |
; for pandas dataframe | |
(require '[clojupyter.display :as display]) | |
(defn show [obj] | |
(if (has-attr? obj "to_html") | |
(display/html (py/call-attr obj "to_html")) | |
(print obj))) | |
; workaround for matplotlib, based on gigasquid's sample codes | |
(require '[clojupyter.display :as display]) | |
;;;; have to set the headless mode before requiring pyplot | |
(def mplt (py/import-module "matplotlib")) | |
(py. mplt "use" "Agg") | |
(require-python 'matplotlib.pyplot) | |
(require-python 'matplotlib.backends.backend_agg) | |
(defmacro with-show | |
"Takes forms with mathplotlib.pyplot to then show locally" | |
[& body] | |
`(let [_# (matplotlib.pyplot/clf) | |
fig# (matplotlib.pyplot/figure) | |
agg-canvas# (matplotlib.backends.backend_agg/FigureCanvasAgg fig#)] | |
~(cons 'do body) | |
(py. agg-canvas# "draw") | |
(matplotlib.pyplot/savefig "temp.png") | |
(display/html "<img src='temp.png'></img>"))) | |
; sample charts | |
(require-python '[numpy :as np]) | |
(let [x (np/arange 0 (* 3 numpy/pi) 0.1) | |
y (np/sin x)] | |
(with-show | |
(matplotlib.pyplot/plot x y))) | |
(require-python '[seaborn :as sns]) | |
(sns/set) | |
(def dots (sns/load_dataset "dots")) | |
(with-show | |
(sns/relplot :x "time" :y "firing_rate" :col "align" | |
:hue "choice" :size "coherence" :style "choice" | |
:facet_kws {:sharex false} :kind "line" | |
:legend "full" :data dots)) | |
(def fmri (sns/load_dataset "fmri")) | |
(with-show | |
(sns/relplot :x "timepoint" :y "signal" :col "region" | |
:hue "event" :style "event" :kind "line" | |
:data fmri)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment