Giter Club home page Giter Club logo

ob-sagemath's Introduction

ob-sagemath

http://melpa.org/packages/ob-sagemath-badge.svg http://stable.melpa.org/packages/ob-sagemath-badge.svg https://travis-ci.org/stakemori/ob-sagemath.svg

ob-sagemath provides an org-babel integration with SageMath by sage-shell-mode. This package is inspired by ob-ipython, though the implementation is completely different.

Requirements

  1. SageMath 6.6 or newer.
  2. GNU Emacs 24.3 or newer.
  3. sage-shell-mode

Installation and sample configuration

You can install ob-sagemath from MELPA. ob-sagemath requires sage-shell-mode. See Installation and Setup to setup sage-shell-mode. The following is a sample configuration for ob-sagemath. Put these lines in your “~/.emacs.d/init.el”.

;; Ob-sagemath supports only evaluating with a session.
(setq org-babel-default-header-args:sage '((:session . t)
                                           (:results . "output")))

;; C-c c for asynchronous evaluating (only for SageMath code blocks).
(with-eval-after-load "org"
  (define-key org-mode-map (kbd "C-c c") 'ob-sagemath-execute-async))

;; Do not confirm before evaluation
(setq org-confirm-babel-evaluate nil)

;; Do not evaluate code blocks when exporting.
(setq org-export-babel-evaluate nil)

;; Show images when opening a file.
(setq org-startup-with-inline-images t)

;; Show images after evaluating code blocks.
(add-hook 'org-babel-after-execute-hook 'org-display-inline-images)

Example file

Here is an example org file.

example.org

Session

ob-sagemath currently supports only evaluating with a session by using sage-shell-mode. So like in the sample configuration, you have to provide the :session header argument. Usually, code blocks are evaluated in the *Sage* process buffer. If the :session argument is provided and it is a string, then the code block is evaluated in another process buffer. For example, by evaluating the following code block, a process buffer *Sage<foo>* is created and the code block is evaluated in the process buffer.

#+BEGIN_SRC  sage :session foo
  print 'This code will be evaluated in the process buffer *Sage<foo>*.'
#+END_SRC

Asynchronous evaluation

You can evaluate SageMath code blocks by C-c C-c (bound to org-ctrl-c-ctrl-c) like in other org-babel packages. But usually it blocks user inputs. In the sample configuration, C-c c is bound to ob-sagemath-execute-async. And it enables the asynchronous evaluation. So you can interact with Emacs during the evaluation. With a prefix argument, it evaluates all code blocks in a buffer. If the org-mode buffer is killed during the evaluation, the output will be lost. Please do not kill the org-mode buffer until the evaluation completes.

Because org-mode doesn’t provide a standard way for asynchronous evaluation, this feature is unstable.

Images

Image files of graphs can be embedded by providing the :file header argument. By evaluating the code block, the image file is stored in the file. Here is an example.

#+BEGIN_SRC sage :file sin.png
  # You can change the size of the image by providing the figsize argument.
  plot(sin, [0, 2*pi], figsize=4)
#+END_SRC

#+RESULTS:
[[file:sin.png]]

If the :file header argument is not provided and the :results header argument contains file, then the code block returns a temporally file name. SageMath deletes these temporally files when the process exits.

#+BEGIN_SRC sage :results file
  plot(sin, [0, 2*pi])
#+END_SRC

Tables

If the :results header argument contains table and the output looks like a table (a list/tuple of lists/tuples), then the result is converted to a table.

#+BEGIN_SRC sage :results table :colnames '(Fruit Price)
  [("Apple", 300), ("Banana", 200), ("Orange", 300)]
#+END_SRC

#+RESULTS:
| Fruit  | Price |
|--------+-------|
| Apple  |   300 |
| Banana |   200 |
| Orange |   300 |

Kill evaluation

To kill the evaluation, switch to the process buffer (usually its buffer name is *Sage*), and hit C-c C-c (bound to sage-shell:interrupt-subjob).

Issues or pull requests

I am new to org-babel. There may be missing features. Feel free to post issues or send pull requests.

ob-sagemath's People

Contributors

emmanuelcharpentier avatar stakemori avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ob-sagemath's Issues

Slight encoding problem with `org-mode`

I noticed that, when I use non-ASCII characters in my code or comments, the execution of sage blocks from org-babel was interrupted, emacs complaining of a mispatch in encoding and asking for an encoding. Answering utf-8 solves the problem.

Since this happens every time a non-ASCII-containing block is executed, this becomes a chore (to remain polite...). Could we have this configurable by a custom variable or, failing that, by having utf-8 encoding ?

error when generating sage pdf files

Thanks for the sage integration with org-babel. It works well for text, code, and tables output, but not for some graphics output types. More specifically I am not able to specify pdf or eps as file output types. I need at least one vector format, even svg would be fine. Alas but to no avail.

Your png example works well. But change that same src block png to pdf or eps, the output generated is not valid postscript file. (see attached pdf for an sample file generated by sage). Is this something that can be fixed with ob-sagemath or a problem with org-babel?

A related question: how can I use the src_block vars inside sage code in that block? For example, :file below?

Try this src_block in any org file to recreate the problem PDF file:

#+begin_src sage  :file image.pdf
g=Graph({1:[2,3], 2:[1,3], 3:[1,2]});g
#+end_src

ai-graph-theory-1.pdf

When plotting ":exports both" fails but ":results file" works

This issue was observed on Sage 9.0 (packaged for Ubuntu 20.04), using the latest git master branch of ob-sagemath. If a sage
plot command block is written as in

#+begin_src sage :file images/sin.png :exports both
  P = plot(sin(x), (0, 2*pi), figsize=[5, 4]); P
#+end_src

then after C-c C-c event though images/sin.png is generated it is not loaded into the org-file but instead the result shown are blank as in

#+RESULTS

Also the mini buffer shows a message stating no output was produced. However if the same plot block is written as

#+begin_src sage :results file
  P = plot(sin(x), (0, 2*pi), figsize=[5, 4]); P
#+end_src

Then the plot is indeed shown in the org file.

This problem does not occur using an older version of Sage 8.6.6 on Debian/Buster using the same git version of ob-sagemath

Runs very slow and cannot reuse session in my setting

Hello, thank you for this package! I installed ob-sagemath and sage-shell-mode, and thankfully it works.

However, the performance is a bit slow on my setting, and also the session cannot be re-used. I wonder if I have missed something.

1

#+BEGIN_SRC sage :session foo
1+1
#+END_SRC

This code block takes 6 seconds to evaluate. Is this normal?

2

#+BEGIN_SRC sage :session foo
1+1+1
#+END_SRC

In the same session, lets say I change my code to 1+1+1. This time it tries to evaluate, but doesn't give an output for 60 seconds. Changing foo to fooo does solve this question. I suspect that in my setting, a session can only be used properly one time.

Opening sage session

I would like to be able to open a sage session using C-c C-v C-z in a sage source block.
When I use this shortcut, it currently shows "Error: no org-babel-initiate-session function for sage".

:results latex

Hi,

it'd be great if ob-sage could support something like :results latex which would insert LaTeX into the org document, something like this:

#+BEGIN_SRC sage :results latex
sage: K.<zeta> = CyclotomicField(8)
sage: OK = K.ring_of_integers()
sage: h = -36*zeta^3 + 44*zeta^2 + 14*zeta + 28
sage: h
#+END_SRC

#+RESULTS:
\(-36 \zeta_{8}^{3} + 44 \zeta_{8}^{2} + 14 \zeta_{8} + 28\)

I know that :results raw almost accomplishes this, but it leaves out the enclosing \(…\)

python3.* does `print('...')` but not `print '...'`

I believe sagemath has completely moved to python3.*, which support print("...") but not print "..." by default. This raises a conflict in the example usage

#+BEGIN_SRC  sage :session foo
  print 'This code will be evaluated in the process buffer *Sage<foo>*.'
#+END_SRC

I think it's better to change it to

#+BEGIN_SRC sage foo.sage
  1+1
#+END_SRC

for the favor of those who are new.

writing output to file

I'm having trouble writing the output of execution to a local file. For example

#+header: :results output file silent
#+header: :session nil
#+header: :file analog-type-I-phase-detector.dat :output-dir data/
#+begin_src sage
import numpy as np
from sage.symbolic.integration.integral import definite_integral

x = var("x")
phi = var("phi")
fref = sin(x)
fsig = sin(x + phi)
for phase in np.linspace(0, 2 * np.pi, num=10):
    avg = definite_integral(fref * fsig(phi=phase), x, 0, 2 * pi)
    print("{:.3f}\t{:.3f}".format(phase, float(avg)))
#+end_src

Does not write the data/analog-type-I-phase-detector.dat file. It simply echos the file link in the minibuffer. A similar python example works fine:

#+begin_src python :results output silent file :file test.txt
print("hello")
#+end_src

Is there a way to write stdout to a local file with sage? thanks.

EDIT:
Something like this works, but it would be nice to be able to use the file header directly instead of delegating to python logic.

#+begin_src sage :results output silent :var cwd=(file-name-directory buffer-file-name)
import numpy as np
from os.path import abspath
from sage.symbolic.integration.integral import definite_integral

fname = cwd + "data/analog-type-I-phase-detector.dat"

x = var("x")
phi = var("phi")
fref = sin(x)
fsig = sin(x - phi)
with open(fname, "w") as f:
    f.write("phi vout\n")
    for phase in np.linspace(0, 2 * np.pi, num=1000):
        avg = definite_integral(fref * fsig(phi=phase), x, 0, 2 * pi)
        f.write("{:.3f}\t{:.3f}\n".format(phase, float(avg)))
#+end_src

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.