Interface between Sage and the QuantityParser


This module defines the class DimPy and creates one instance of it.

The main purpose of this is the creation of Sage notebook cells that are evaluated using the QuantityParser. To use this interface, simply put ‘%dimpy’ in the first line of a cell in the Sage notebook. All subsequent lines of that cell will be passed to the QuantityParser one by one and evaluated there, the output will be printed. Variable and Flydim definitions and the ParseHistory persist from one cell to the next.


  • Miriam Backens (2009): initial version


(Mostly taken from the sage.server.notebook.worksheet documentation.)

sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('sage','sage','',force=True)
sage: W = nb.create_new_worksheet('Test', 'sage')
sage: W.edit_save('Sage\nsystem:sage\n{{{\n2+3\n}}}\n\n{{{\nfrom sage.dimpy import *\n}}}\n\n{{{\n%dimpy\n3 meters in miles\n}}}')
sage: c0, c1, c2 = W.cell_list()
sage: W.check_for_system_switching(c0.cleaned_input_text(), c0)
(False, '2+3')
sage: W.check_for_system_switching(c2.cleaned_input_text(), c2)
(True, "print _support_.syseval(dimpy, ur'''3 meters in miles''', '...')")
sage: c0.evaluate()
sage: W.check_comp() #random output -- depends on the computer's speed
('w', Cell 0; in=2+3, out=)
sage: c1.evaluate()
sage: c2.evaluate()
sage: W.check_comp()  #random output -- depends on the computer's speed
 Cell 2; in=%dimpy
3 meters in miles, out=
3*meter = 0.00186411357671 * mile
class sage.dimpy.interface.DimPy(maxread=200, logfile=None, server=None, server_tmpdir=None)

An interface from Sage to the DimPy QuantityParser.

Special commands inside the QuantityParser:
  • history() - prints the ParseHistory
  • delete(n) - n an integer, deletes the n-th entry from the history
  • illegal_requests() - toggle whether or not dimensionally invalid requests are allowed, i.e. whether inputs like “3 m/s in miles” cause an error or return a value (default: cause error)

See also the documentation for module quantity_parser.


Get the value of the variable var.


  • var - a string, the name of the variable to get

OUTPUT: a Quantity or number, the value of var


sage: from sage.dimpy import *
sage: dimpy.eval('energy_use = 125 kWh per person')
'energy_use = 125*kWh/person'
sage: dimpy.get('energy_use')
450000000.0 J person^-1
set(var, value)

Set the variable var to the given value.


  • var - a string, the name of the variable to set
  • value - a number, quantity or a parseable string


sage: from sage.dimpy import *
sage: dimpy.set('g', 9.81 * meter / second**2)
sage: dimpy.eval('g')
'g = 9.81 m s^-2'
sage: dimpy.set('test', 7 * meter**-2 * second)
sage: dimpy.eval('test')
'test = 7 m^-2 s'