[PYTHON MATRIX-SIG] Plotting with Mathematica

Konrad HINSEN hinsenk@ERE.UMontreal.CA
Tue, 23 Apr 1996 17:37:55 -0400


While we are all waiting for a good plotting package for Python, I
offer a simplistic, but very convenient temporary solution to those
who have Mathematica and run Unix.  The following module is hardly
documented, not carefully designed, and completely unsupported, but it
works for me.


# Interface to Mathematica for plotting
#
# Written by Konrad Hinsen <hinsenk@ere.umontreal.ca>
# last revision: 1996-4-23

import os, regsub, tempfile

# Class representing a Mathematica process

class Mathematica:

    def __init__(self, progname = 'math'):
	self.progname = progname
	self.script = ''
	self.font = "Courier"
	self.textsize = 10

    def clear(self):
	self.script = ''

    def execute(self):
	scriptfile = tempfile.mktemp()
	file = open(scriptfile, 'w')
	file.write(self.script)
	file.close()
	os.system(self.progname + ' -record "" <' + scriptfile + ' >/dev/null')
	os.unlink(scriptfile)

    def command(self, command):
	self.script = self.script + command

    def backup(self, n):
	self.script = self.script[:-n]

    def defineVariable(self, name, array):
	self.command(name + ' = ')
	self.command(formatValue(array))
	self.command('\n')

    def setFont(self, font, size):
	self.font = font
	self.textsize = size

    def displayOptions(self):
	s = 'DefaultFont->{"' + self.font + '",' + \
	    formatValue(self.textsize) + '}'
	return s

    def plot(self, data):
	s = 'Show['
	for dataset in data:
	    s = s + 'ListPlot[' + formatValue(dataset) + \
		', PlotJoined->True, DisplayFunction->Identity, ' + \
		self.displayOptions() + '], '
	s = s + 'DisplayFunction->$DisplayFunction]\n'
	self.command(s)

    def contourPlot(self, xaxis, yaxis, data, contours=None):
	s = 'Show[ContourGraphics[' + formatValue(data.transpose()) \
	    +  ', MeshRange->' \
	    + formatValue([[xaxis[0], xaxis[-1]], [yaxis[0], yaxis[-1]]]) \
	    + ', ContourShading->False'
	if contours:
	    s = s + ', Contours->' + formatValue(contours)
	s = s + ', ' + self.displayOptions() + ']]\n'
	self.command(s)

# Format scalars, arrays, and nested lists for Mathematica

def formatValue(x):
    is_sequence = 1
    try:
	x[0]
    except:
	is_sequence = 0
    if is_sequence:
	s = '{'
	for e in x:
	    s = s + formatValue(e) + ', '
	s = s[:-2] + '}'
    else:
	if type(x) == type(''):
	    s = '"' + x + '"'
	elif type(x) == type(0):
	    s = `x`
	elif type(x) == type(0.):
	    s = regsub.sub('e','*10^', `x`)
	elif type(x) == type(0.j):
	    s = '(' + regsub.sub('e','*10^', `x.real`) + \
		'+' + regsub.sub('e','*10^', `x.imag`) + 'I)'
	else:
	    raise TypeError, 'Unknown type ' + `type(x)`
    return s


# Simple plot functions

def plot(*data):
    m = Mathematica()
    m.plot(data)
    m.execute()

def contourPlot(xaxis, yaxis, data, contours=None):
    m = Mathematica()
    m.contourPlot(xaxis, yaxis, data, contours)
    m.execute()


# These examples are all the documentation you will get!
    
if __name__ == '__main__':

    from Numeric import *
    from umath import *
    plot([4,6,5,3])
    plot([(3,6.8),(4,4.2),(5,0.5)])
    x = arange(10)
    y = arange(15)
    data = x[:, NewAxis]*sin(y/2.)
    contourPlot(x, y, data, arange(0.,10.,0.1))

-------------------------------------------------------------------------------
Konrad Hinsen                     | E-Mail: hinsenk@ere.umontreal.ca
Departement de chimie             | Tel.: +1-514-343-6111 ext. 3953
Universite de Montreal            | Fax:  +1-514-343-7586
C.P. 6128, succ. Centre-Ville     | Deutsch/Esperanto/English/Nederlands/
Montreal (QC) H3C 3J7             | Francais (phase experimentale)
-------------------------------------------------------------------------------

=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================