diff --git a/.gitignore b/.gitignore index 583abf7..703b7bc 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ _build docs/man/*.gz docs/source/api/generated docs/gh-pages -IPython/frontend/html/notebook/static/mathjax +IPython/html/notebook/static/mathjax *.py[co] __pycache__ build diff --git a/.gitmodules b/.gitmodules index b32380c..1eaa243 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "components"] - path = IPython/frontend/html/notebook/static/components + path = IPython/html/static/components url = https://github.com/ipython/ipython-components.git diff --git a/IPython/__init__.py b/IPython/__init__.py index d553587..c804cd4 100644 --- a/IPython/__init__.py +++ b/IPython/__init__.py @@ -44,7 +44,7 @@ from .config.loader import Config from .core.getipython import get_ipython from .core import release from .core.application import Application -from .frontend.terminal.embed import embed +from .terminal.embed import embed from .core.error import TryNext from .core.interactiveshell import InteractiveShell diff --git a/IPython/__main__.py b/IPython/__main__.py index 66af32a..1e2ee07 100644 --- a/IPython/__main__.py +++ b/IPython/__main__.py @@ -9,6 +9,6 @@ # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- -from IPython.frontend.terminal.ipapp import launch_new_instance +from IPython.terminal.ipapp import launch_new_instance launch_new_instance() diff --git a/IPython/frontend/consoleapp.py b/IPython/consoleapp.py similarity index 99% rename from IPython/frontend/consoleapp.py rename to IPython/consoleapp.py index 67148f7..8813d83 100644 --- a/IPython/frontend/consoleapp.py +++ b/IPython/consoleapp.py @@ -2,7 +2,7 @@ This is not a complete console app, as subprocess will not be able to receive input, there is no real readline support, among other limitations. This is a -refactoring of what used to be the IPython/frontend/qt/console/qtconsoleapp.py +refactoring of what used to be the IPython/qt/console/qtconsoleapp.py Authors: diff --git a/IPython/core/profileapp.py b/IPython/core/profileapp.py index 39479cd..9c6a529 100644 --- a/IPython/core/profileapp.py +++ b/IPython/core/profileapp.py @@ -238,10 +238,10 @@ class ProfileCreate(BaseIPythonApplication): def init_config_files(self): super(ProfileCreate, self).init_config_files() # use local imports, since these classes may import from here - from IPython.frontend.terminal.ipapp import TerminalIPythonApp + from IPython.terminal.ipapp import TerminalIPythonApp apps = [TerminalIPythonApp] try: - from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp + from IPython.qt.console.qtconsoleapp import IPythonQtConsoleApp except Exception: # this should be ImportError, but under weird circumstances # this might be an AttributeError, or possibly others @@ -250,7 +250,7 @@ class ProfileCreate(BaseIPythonApplication): else: apps.append(IPythonQtConsoleApp) try: - from IPython.frontend.html.notebook.notebookapp import NotebookApp + from IPython.html.notebookapp import NotebookApp except ImportError: pass except Exception: diff --git a/IPython/core/tests/test_display.py b/IPython/core/tests/test_display.py index c34674d..785bdd8 100644 --- a/IPython/core/tests/test_display.py +++ b/IPython/core/tests/test_display.py @@ -29,7 +29,7 @@ def test_image_filename_defaults(): embed=True) nt.assert_raises(ValueError, display.Image) nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True) - imgfile = os.path.join(tpath, 'frontend/html/notebook/static/base/images/ipynblogo.png') + imgfile = os.path.join(tpath, 'html/static/base/images/ipynblogo.png') img = display.Image(filename=imgfile) nt.assert_equal('png', img.format) nt.assert_is_not_none(img._repr_png_()) diff --git a/IPython/deathrow/Gnuplot2.py b/IPython/deathrow/Gnuplot2.py deleted file mode 100644 index b75fe20..0000000 --- a/IPython/deathrow/Gnuplot2.py +++ /dev/null @@ -1,665 +0,0 @@ -# -*- coding: utf-8 -*- -"""Improved replacement for the Gnuplot.Gnuplot class. - -This module imports Gnuplot and replaces some of its functionality with -improved versions. They add better handling of arrays for plotting and more -convenient PostScript generation, plus some fixes for hardcopy(). - -It also adds a convenient plot2 method for plotting dictionaries and -lists/tuples of arrays. - -This module is meant to be used as a drop-in replacement to the original -Gnuplot, so it should be safe to do: - -import IPython.Gnuplot2 as Gnuplot -""" - -import cStringIO -import os -import string -import sys -import tempfile -import time -import types - -import Gnuplot as Gnuplot_ori -import Numeric - -from IPython.utils.genutils import popkey,xsys - -# needed by hardcopy(): -gp = Gnuplot_ori.gp - -# Patch for Gnuplot.py 1.6 compatibility. -# Thanks to Hayden Callow -try: - OptionException = Gnuplot_ori.PlotItems.OptionException -except AttributeError: - OptionException = Gnuplot_ori.Errors.OptionError - -# exhibit a similar interface to Gnuplot so it can be somewhat drop-in -Data = Gnuplot_ori.Data -Func = Gnuplot_ori.Func -GridData = Gnuplot_ori.GridData -PlotItem = Gnuplot_ori.PlotItem -PlotItems = Gnuplot_ori.PlotItems - -# Modify some of Gnuplot's functions with improved versions (or bugfixed, in -# hardcopy's case). In order to preserve the docstrings at runtime, I've -# copied them from the original code. - -# After some significant changes in v 1.7 of Gnuplot.py, we need to do a bit -# of version checking. - -if Gnuplot_ori.__version__ <= '1.6': - _BaseFileItem = PlotItems.File - _BaseTempFileItem = PlotItems.TempFile - - # Fix the File class to add the 'index' option for Gnuplot versions < 1.7 - class File(_BaseFileItem): - - _option_list = _BaseFileItem._option_list.copy() - _option_list.update({ - 'index' : lambda self, index: self.set_option_index(index), - }) - - # A new initializer is needed b/c we want to add a modified - # _option_sequence list which includes 'index' in the right place. - def __init__(self,*args,**kw): - self._option_sequence = ['binary', 'index', 'using', 'smooth', 'axes', - 'title', 'with'] - - _BaseFileItem.__init__(self,*args,**kw) - - # Let's fix the constructor docstring - __newdoc = \ - """Additional Keyword arguments added by IPython: - - 'index=' -- similar to the `index` keyword in Gnuplot. - This allows only some of the datasets in a file to be - plotted. Datasets within a file are assumed to be separated - by _pairs_ of blank lines, and the first one is numbered as - 0 (similar to C/Python usage).""" - __init__.__doc__ = PlotItems.File.__init__.__doc__ + __newdoc - - def set_option_index(self, index): - if index is None: - self.clear_option('index') - elif type(index) in [type(''), type(1)]: - self._options['index'] = (index, 'index %s' % index) - elif type(index) is type(()): - self._options['index'] = (index,'index %s' % - string.join(map(repr, index), ':')) - else: - raise OptionException('index=%s' % (index,)) - - # We need a FileClass with a different name from 'File', which is a - # factory function in 1.7, so that our String class can subclass FileClass - # in any version. - _FileClass = File - -elif Gnuplot_ori.__version__ =='1.7': - _FileClass = _BaseFileItem = PlotItems._FileItem - _BaseTempFileItem = PlotItems._TempFileItem - File = PlotItems.File - -else: # changes in the newer version (svn as of March'06) - _FileClass = _BaseFileItem = PlotItems._FileItem - _BaseTempFileItem = PlotItems._NewFileItem - File = PlotItems.File - - -# Now, we can add our generic code which is version independent - -# First some useful utilities -def eps_fix_bbox(fname): - """Fix the bounding box of an eps file by running ps2eps on it. - - If its name ends in .eps, the original file is removed. - - This is particularly useful for plots made by Gnuplot with square aspect - ratio: there is a bug in Gnuplot which makes it generate a bounding box - which is far wider than the actual plot. - - This function assumes that ps2eps is installed in your system.""" - - # note: ps2ps and eps2eps do NOT work, ONLY ps2eps works correctly. The - # others make output with bitmapped fonts, which looks horrible. - print 'Fixing eps file: <%s>' % fname - xsys('ps2eps -f -q -l %s' % fname) - if fname.endswith('.eps'): - os.rename(fname+'.eps',fname) - -def is_list1d(x,containers = [types.ListType,types.TupleType]): - """Returns true if x appears to be a 1d list/tuple/array. - - The heuristics are: identify Numeric arrays, or lists/tuples whose first - element is not itself a list/tuple. This way zipped lists should work like - the original Gnuplot. There's no inexpensive way to know if a list doesn't - have a composite object after its first element, so that kind of input - will produce an error. But it should work well in most cases. - """ - x_type = type(x) - - return x_type == Numeric.ArrayType and len(x.shape)==1 or \ - (x_type in containers and - type(x[0]) not in containers + [Numeric.ArrayType]) - -def zip_items(items,titles=None): - """zip together neighboring 1-d arrays, and zip standalone ones - with their index. Leave other plot items alone.""" - - class StandaloneItem(Exception): pass - - def get_titles(titles): - """Return the next title and the input titles array. - - The input array may be changed to None when no titles are left to - prevent extra unnecessary calls to this function.""" - - try: - title = titles[tit_ct[0]] # tit_ct[0] is in zip_items'scope - except IndexError: - titles = None # so we don't enter again - title = None - else: - tit_ct[0] += 1 - return title,titles - - new_items = [] - - if titles: - # Initialize counter. It was put in a list as a hack to allow the - # nested get_titles to modify it without raising a NameError. - tit_ct = [0] - - n = 0 # this loop needs to be done by hand - while n < len(items): - item = items[n] - try: - if is_list1d(item): - if n==len(items)-1: # last in list - raise StandaloneItem - else: # check the next item and zip together if needed - next_item = items[n+1] - if next_item is None: - n += 1 - raise StandaloneItem - elif is_list1d(next_item): - # this would be best done with an iterator - if titles: - title,titles = get_titles(titles) - else: - title = None - new_items.append(Data(zip(item,next_item), - title=title)) - n += 1 # avoid double-inclusion of next item - else: # can't zip with next, zip with own index list - raise StandaloneItem - else: # not 1-d array - new_items.append(item) - except StandaloneItem: - if titles: - title,titles = get_titles(titles) - else: - title = None - new_items.append(Data(zip(range(len(item)),item),title=title)) - except AttributeError: - new_items.append(item) - n+=1 - - return new_items - -# And some classes with enhanced functionality. -class String(_FileClass): - """Make a PlotItem from data in a string with the same format as a File. - - This allows writing data directly inside python scripts using the exact - same format and manipulation options which would be used for external - files.""" - - def __init__(self, data_str, **keyw): - """Construct a String object. - - is a string formatted exactly like a valid Gnuplot data - file would be. All options from the File constructor are valid here. - - Warning: when used for interactive plotting in scripts which exit - immediately, you may get an error because the temporary file used to - hold the string data was deleted before Gnuplot had a chance to see - it. You can work around this problem by putting a raw_input() call at - the end of the script. - - This problem does not appear when generating PostScript output, only - with Gnuplot windows.""" - - self.tmpfile = _BaseTempFileItem() - tmpfile = file(self.tmpfile.filename,'w') - tmpfile.write(data_str) - _BaseFileItem.__init__(self,self.tmpfile,**keyw) - - -class Gnuplot(Gnuplot_ori.Gnuplot): - """Improved Gnuplot class. - - Enhancements: better plot,replot and hardcopy methods. New methods for - quick range setting. - """ - - def xrange(self,min='*',max='*'): - """Set xrange. If min/max is omitted, it is set to '*' (auto). - - Note that this is different from the regular Gnuplot behavior, where - an unspecified limit means no change. Here any unspecified limit is - set to autoscaling, allowing these functions to be used for full - autoscaling when called with no arguments. - - To preserve one limit's current value while changing the other, an - explicit '' argument must be given as the limit to be kept. - - Similar functions exist for [y{2}z{2}rtuv]range.""" - - self('set xrange [%s:%s]' % (min,max)) - - def yrange(self,min='*',max='*'): - self('set yrange [%s:%s]' % (min,max)) - - def zrange(self,min='*',max='*'): - self('set zrange [%s:%s]' % (min,max)) - - def x2range(self,min='*',max='*'): - self('set xrange [%s:%s]' % (min,max)) - - def y2range(self,min='*',max='*'): - self('set yrange [%s:%s]' % (min,max)) - - def z2range(self,min='*',max='*'): - self('set zrange [%s:%s]' % (min,max)) - - def rrange(self,min='*',max='*'): - self('set rrange [%s:%s]' % (min,max)) - - def trange(self,min='*',max='*'): - self('set trange [%s:%s]' % (min,max)) - - def urange(self,min='*',max='*'): - self('set urange [%s:%s]' % (min,max)) - - def vrange(self,min='*',max='*'): - self('set vrange [%s:%s]' % (min,max)) - - def set_ps(self,option): - """Set an option for the PostScript terminal and reset default term.""" - - self('set terminal postscript %s ' % option) - self('set terminal %s' % gp.GnuplotOpts.default_term) - - def __plot_ps(self, plot_method,*items, **keyw): - """Wrapper for plot/splot/replot, with processing of hardcopy options. - - For internal use only.""" - - # Filter out PostScript options which will crash the normal plot/replot - psargs = {'filename':None, - 'mode':None, - 'eps':None, - 'enhanced':None, - 'color':None, - 'solid':None, - 'duplexing':None, - 'fontname':None, - 'fontsize':None, - 'debug':0 } - - for k in psargs.keys(): - if keyw.has_key(k): - psargs[k] = keyw[k] - del keyw[k] - - # Filter out other options the original plot doesn't know - hardcopy = popkey(keyw,'hardcopy',psargs['filename'] is not None) - titles = popkey(keyw,'titles',0) - - # the filename keyword should control hardcopy generation, this is an - # override switch only which needs to be explicitly set to zero - if hardcopy: - if psargs['filename'] is None: - raise ValueError, \ - 'If you request hardcopy, you must give a filename.' - - # set null output so nothing goes to screen. hardcopy() restores output - self('set term dumb') - # I don't know how to prevent screen output in Windows - if os.name == 'posix': - self('set output "/dev/null"') - - new_items = zip_items(items,titles) - # plot_method is either plot or replot from the original Gnuplot class: - plot_method(self,*new_items,**keyw) - - # Do hardcopy if requested - if hardcopy: - if psargs['filename'].endswith('.eps'): - psargs['eps'] = 1 - self.hardcopy(**psargs) - - def plot(self, *items, **keyw): - """Draw a new plot. - - Clear the current plot and create a new 2-d plot containing - the specified items. Each arguments should be of the - following types: - - 'PlotItem' (e.g., 'Data', 'File', 'Func') -- This is the most - flexible way to call plot because the PlotItems can - contain suboptions. Moreover, PlotItems can be saved to - variables so that their lifetime is longer than one plot - command; thus they can be replotted with minimal overhead. - - 'string' (e.g., 'sin(x)') -- The string is interpreted as - 'Func(string)' (a function that is computed by gnuplot). - - Anything else -- The object, which should be convertible to an - array, is passed to the 'Data' constructor, and thus - plotted as data. If the conversion fails, an exception is - raised. - - - This is a modified version of plot(). Compared to the original in - Gnuplot.py, this version has several enhancements, listed below. - - - Modifications to the input arguments - ------------------------------------ - - (1-d array means Numeric array, list or tuple): - - (i) Any 1-d array which is NOT followed by another 1-d array, is - automatically zipped with range(len(array_1d)). Typing g.plot(y) will - plot y against its indices. - - (ii) If two 1-d arrays are contiguous in the argument list, they are - automatically zipped together. So g.plot(x,y) plots y vs. x, and - g.plot(x1,y1,x2,y2) plots y1 vs. x1 and y2 vs. x2. - - (iii) Any 1-d array which is followed by None is automatically zipped - with range(len(array_1d)). In this form, typing g.plot(y1,None,y2) - will plot both y1 and y2 against their respective indices (and NOT - versus one another). The None prevents zipping y1 and y2 together, and - since y2 is unpaired it is automatically zipped to its indices by (i) - - (iv) Any other arguments which don't match these cases are left alone and - passed to the code below. - - For lists or tuples, the heuristics used to determine whether they are - in fact 1-d is fairly simplistic: their first element is checked, and - if it is not a list or tuple itself, it is assumed that the whole - object is one-dimensional. - - An additional optional keyword 'titles' has been added: it must be a - list of strings to be used as labels for the individual plots which - are NOT PlotItem objects (since those objects carry their own labels - within). - - - PostScript generation - --------------------- - - This version of plot() also handles automatically the production of - PostScript output. The main options are (given as keyword arguments): - - - filename: a string, typically ending in .eps. If given, the plot is - sent to this file in PostScript format. - - - hardcopy: this can be set to 0 to override 'filename'. It does not - need to be given to produce PostScript, its purpose is to allow - switching PostScript output off globally in scripts without having to - manually change 'filename' values in multiple calls. - - All other keywords accepted by Gnuplot.hardcopy() are transparently - passed, and safely ignored if output is sent to the screen instead of - PostScript. - - For example: - - In [1]: x=frange(0,2*pi,npts=100) - - Generate a plot in file 'sin.eps': - - In [2]: plot(x,sin(x),filename = 'sin.eps') - - Plot to screen instead, without having to change the filename: - - In [3]: plot(x,sin(x),filename = 'sin.eps',hardcopy=0) - - Pass the 'color=0' option to hardcopy for monochrome output: - - In [4]: plot(x,sin(x),filename = 'sin.eps',color=0) - - PostScript generation through plot() is useful mainly for scripting - uses where you are not interested in interactive plotting. For - interactive use, the hardcopy() function is typically more convenient: - - In [5]: plot(x,sin(x)) - - In [6]: hardcopy('sin.eps') """ - - self.__plot_ps(Gnuplot_ori.Gnuplot.plot,*items,**keyw) - - def plot2(self,arg,**kw): - """Plot the entries of a dictionary or a list/tuple of arrays. - - This simple utility calls plot() with a list of Gnuplot.Data objects - constructed either from the values of the input dictionary, or the entries - in it if it is a tuple or list. Each item gets labeled with the key/index - in the Gnuplot legend. - - Each item is plotted by zipping it with a list of its indices. - - Any keywords are passed directly to plot().""" - - if hasattr(arg,'keys'): - keys = arg.keys() - keys.sort() - else: - keys = range(len(arg)) - - pitems = [Data(zip(range(len(arg[k])),arg[k]),title=`k`) for k in keys] - self.plot(*pitems,**kw) - - def splot(self, *items, **keyw): - """Draw a new three-dimensional plot. - - Clear the current plot and create a new 3-d plot containing - the specified items. Arguments can be of the following types: - - 'PlotItem' (e.g., 'Data', 'File', 'Func', 'GridData' ) -- This - is the most flexible way to call plot because the - PlotItems can contain suboptions. Moreover, PlotItems can - be saved to variables so that their lifetime is longer - than one plot command--thus they can be replotted with - minimal overhead. - - 'string' (e.g., 'sin(x*y)') -- The string is interpreted as a - 'Func()' (a function that is computed by gnuplot). - - Anything else -- The object is converted to a Data() item, and - thus plotted as data. Note that each data point should - normally have at least three values associated with it - (i.e., x, y, and z). If the conversion fails, an - exception is raised. - - This is a modified version of splot(). Compared to the original in - Gnuplot.py, this version has several enhancements, listed in the - plot() documentation. - """ - - self.__plot_ps(Gnuplot_ori.Gnuplot.splot,*items,**keyw) - - def replot(self, *items, **keyw): - """Replot the data, possibly adding new 'PlotItem's. - - Replot the existing graph, using the items in the current - itemlist. If arguments are specified, they are interpreted as - additional items to be plotted alongside the existing items on - the same graph. See 'plot' for details. - - If you want to replot to a postscript file, you MUST give the - 'filename' keyword argument in each call to replot. The Gnuplot python - interface has no way of knowing that your previous call to - Gnuplot.plot() was meant for PostScript output.""" - - self.__plot_ps(Gnuplot_ori.Gnuplot.replot,*items,**keyw) - - # The original hardcopy has a bug. See fix at the end. The rest of the code - # was lifted verbatim from the original, so that people using IPython get the - # benefits without having to manually patch Gnuplot.py - def hardcopy(self, filename=None, - mode=None, - eps=None, - enhanced=None, - color=None, - solid=None, - duplexing=None, - fontname=None, - fontsize=None, - debug = 0, - ): - """Create a hardcopy of the current plot. - - Create a postscript hardcopy of the current plot to the - default printer (if configured) or to the specified filename. - - Note that gnuplot remembers the postscript suboptions across - terminal changes. Therefore if you set, for example, color=1 - for one hardcopy then the next hardcopy will also be color - unless you explicitly choose color=0. Alternately you can - force all of the options to their defaults by setting - mode='default'. I consider this to be a bug in gnuplot. - - Keyword arguments: - - 'filename=' -- if a filename is specified, save the - output in that file; otherwise print it immediately - using the 'default_lpr' configuration option. If the - filename ends in '.eps', EPS mode is automatically - selected (like manually specifying eps=1 or mode='eps'). - - 'mode=' -- set the postscript submode ('landscape', - 'portrait', 'eps', or 'default'). The default is - to leave this option unspecified. - - 'eps=' -- shorthand for 'mode="eps"'; asks gnuplot to - generate encapsulated postscript. - - 'enhanced=' -- if set (the default), then generate - enhanced postscript, which allows extra features like - font-switching, superscripts, and subscripts in axis - labels. (Some old gnuplot versions do not support - enhanced postscript; if this is the case set - gp.GnuplotOpts.prefer_enhanced_postscript=None.) - - 'color=' -- if set, create a plot with color. Default - is to leave this option unchanged. - - 'solid=' -- if set, force lines to be solid (i.e., not - dashed). - - 'duplexing=' -- set duplexing option ('defaultplex', - 'simplex', or 'duplex'). Only request double-sided - printing if your printer can handle it. Actually this - option is probably meaningless since hardcopy() can only - print a single plot at a time. - - 'fontname=' -- set the default font to , - which must be a valid postscript font. The default is - to leave this option unspecified. - - 'fontsize=' -- set the default font size, in - postscript points. - - 'debug=' -- print extra debugging information (useful if - your PostScript files are misteriously not being created). - """ - - if filename is None: - assert gp.GnuplotOpts.default_lpr is not None, \ - OptionException('default_lpr is not set, so you can only ' - 'print to a file.') - filename = gp.GnuplotOpts.default_lpr - lpr_output = 1 - else: - if filename.endswith('.eps'): - eps = 1 - lpr_output = 0 - - # Be careful processing the options. If the user didn't - # request an option explicitly, do not specify it on the 'set - # terminal' line (don't even specify the default value for the - # option). This is to avoid confusing older versions of - # gnuplot that do not support all of these options. The - # exception is 'enhanced', which is just too useful to have to - # specify each time! - - setterm = ['set', 'terminal', 'postscript'] - if eps: - assert mode is None or mode=='eps', \ - OptionException('eps option and mode are incompatible') - setterm.append('eps') - else: - if mode is not None: - assert mode in ['landscape', 'portrait', 'eps', 'default'], \ - OptionException('illegal mode "%s"' % mode) - setterm.append(mode) - if enhanced is None: - enhanced = gp.GnuplotOpts.prefer_enhanced_postscript - if enhanced is not None: - if enhanced: setterm.append('enhanced') - else: setterm.append('noenhanced') - if color is not None: - if color: setterm.append('color') - else: setterm.append('monochrome') - if solid is not None: - if solid: setterm.append('solid') - else: setterm.append('dashed') - if duplexing is not None: - assert duplexing in ['defaultplex', 'simplex', 'duplex'], \ - OptionException('illegal duplexing mode "%s"' % duplexing) - setterm.append(duplexing) - if fontname is not None: - setterm.append('"%s"' % fontname) - if fontsize is not None: - setterm.append('%s' % fontsize) - - self(string.join(setterm)) - self.set_string('output', filename) - # replot the current figure (to the printer): - self.refresh() - - # fperez. Ugly kludge: often for some reason the file is NOT created - # and we must reissue the creation commands. I have no idea why! - if not lpr_output: - #print 'Hardcopy <%s>' % filename # dbg - maxtries = 20 - delay = 0.1 # delay (in seconds) between print attempts - for i in range(maxtries): - time.sleep(0.05) # safety, very small delay - if os.path.isfile(filename): - if debug: - print 'Hardcopy to file <%s> success at attempt #%s.' \ - % (filename,i+1) - break - time.sleep(delay) - # try again, issue all commands just in case - self(string.join(setterm)) - self.set_string('output', filename) - self.refresh() - if not os.path.isfile(filename): - print >> sys.stderr,'ERROR: Tried %s times and failed to '\ - 'create hardcopy file `%s`' % (maxtries,filename) - - # reset the terminal to its `default' setting: - self('set terminal %s' % gp.GnuplotOpts.default_term) - self.set_string('output') - -#********************** End of file ************************ diff --git a/IPython/deathrow/GnuplotInteractive.py b/IPython/deathrow/GnuplotInteractive.py deleted file mode 100644 index b528428..0000000 --- a/IPython/deathrow/GnuplotInteractive.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- -"""Interactive functions and magic functions for Gnuplot usage. - -This requires the Gnuplot.py module for interfacing python with Gnuplot, which -can be downloaded from: - -http://gnuplot-py.sourceforge.net/ - -See gphelp() below for details on the services offered by this module. - -Inspired by a suggestion/request from Arnd Baecker. -""" - -__all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot', - 'hardcopy','gpdata','gpfile','gpstring','gpfunc','gpgrid', - 'gphelp'] - -import IPython.GnuplotRuntime as GRun -from IPython.utils.genutils import warn -from IPython.core import page - -# Set global names for interactive use -Gnuplot = GRun.Gnuplot -gp_new = GRun.gp_new -gp = GRun.gp -plot = gp.plot -plot2 = gp.plot2 -splot = gp.splot -replot = gp.replot -hardcopy = gp.hardcopy - -# Accessors for the main plot object constructors: -gpdata = Gnuplot.Data -gpfile = Gnuplot.File -gpstring = Gnuplot.String -gpfunc = Gnuplot.Func -gpgrid = Gnuplot.GridData - -def gphelp(): - """Print information about the Gnuplot facilities in IPython.""" - - page(""" -IPython provides an interface to access the Gnuplot scientific plotting -system, in an environment similar to that of Mathematica or Matlab. - -New top-level global objects ----------------------------- - -Please see their respective docstrings for further details. - -- gp: a running Gnuplot instance. You can access its methods as -gp.. gp(`a string`) will execute the given string as if it had been -typed in an interactive gnuplot window. - -- plot, splot, replot and hardcopy: aliases to the methods of the same name in -the global running Gnuplot instance gp. These allow you to simply type: - -In [1]: plot(x,sin(x),title='Sin(x)') # assuming x is a Numeric array - -and obtain a plot of sin(x) vs x with the title 'Sin(x)'. - -- gp_new: a function which returns a new Gnuplot instance. This can be used to -have multiple Gnuplot instances running in your session to compare different -plots, each in a separate window. - -- Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for -the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its -functions with improved versions (Gnuplot2 comes with IPython). - -- gpdata, gpfile, gpstring, gpfunc, gpgrid: aliases to Gnuplot.Data, -Gnuplot.File, Gnuplot.String, Gnuplot.Func and Gnuplot.GridData -respectively. These functions create objects which can then be passed to the -plotting commands. See the Gnuplot.py documentation for details. - -Keep in mind that all commands passed to a Gnuplot instance are executed in -the Gnuplot namespace, where no Python variables exist. For example, for -plotting sin(x) vs x as above, typing - -In [2]: gp('plot x,sin(x)') - -would not work. Instead, you would get the plot of BOTH the functions 'x' and -'sin(x)', since Gnuplot doesn't know about the 'x' Python array. The plot() -method lives in python and does know about these variables. - - -New magic functions -------------------- - -%gpc: pass one command to Gnuplot and execute it or open a Gnuplot shell where -each line of input is executed. - -%gp_set_default: reset the value of IPython's global Gnuplot instance.""") - -# Code below is all for IPython use -# Define the magic functions for communicating with the above gnuplot instance. -def magic_gpc(self,parameter_s=''): - """Execute a gnuplot command or open a gnuplot shell. - - Usage (omit the % if automagic is on). There are two ways to use it: - - 1) %gpc 'command' -> passes 'command' directly to the gnuplot instance. - - 2) %gpc -> will open up a prompt (gnuplot>>>) which takes input like the - standard gnuplot interactive prompt. If you need to type a multi-line - command, use \\ at the end of each intermediate line. - - Upon exiting of the gnuplot sub-shell, you return to your IPython - session (the gnuplot sub-shell can be invoked as many times as needed). - """ - - if parameter_s.strip(): - self.shell.gnuplot(parameter_s) - else: - self.shell.gnuplot.interact() - -def magic_gp_set_default(self,parameter_s=''): - """Set the default gnuplot instance accessed by the %gp magic function. - - %gp_set_default name - - Call with the name of the new instance at the command line. If you want to - set this instance in your own code (using an embedded IPython, for - example), simply set the variable __IPYTHON__.gnuplot to your own gnuplot - instance object.""" - - gname = parameter_s.strip() - G = eval(gname,self.shell.user_ns) - self.shell.gnuplot = G - self.shell.user_ns.update({'plot':G.plot,'splot':G.splot,'plot2':G.plot2, - 'replot':G.replot,'hardcopy':G.hardcopy}) - -try: - __IPYTHON__ -except NameError: - pass -else: - # make the global Gnuplot instance known to IPython - __IPYTHON__.gnuplot = GRun.gp - __IPYTHON__.gnuplot.shell_first_time = 1 - - print """*** Type `gphelp` for help on the Gnuplot integration features.""" - - # Add the new magic functions to the class dict - from IPython.core.iplib import InteractiveShell - InteractiveShell.magic_gpc = magic_gpc - InteractiveShell.magic_gp_set_default = magic_gp_set_default - -#********************** End of file ******************* diff --git a/IPython/deathrow/GnuplotRuntime.py b/IPython/deathrow/GnuplotRuntime.py deleted file mode 100644 index 8d524e3..0000000 --- a/IPython/deathrow/GnuplotRuntime.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -"""Basic Gnuplot functionality for inclusion in other code. - -This module creates a running Gnuplot instance called 'gp' and builds other -convenient globals for quick use in running scripts. It is intended to allow -you to script plotting tasks in Python with a minimum of effort. A typical -usage would be: - -import IPython.GnuplotRuntime as GP # or some other short name -GP.gp.plot(GP.File('your_data.dat')) - - -This module exposes the following objects: - -- gp: a running Gnuplot instance. You can access its methods as -gp.. gp(`a string`) will execute the given string as if it had been -typed in an interactive gnuplot window. - -- gp_new: a function which returns a new Gnuplot instance. This can be used to -have multiple Gnuplot instances running in your session to compare different -plots. - -- Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for -the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its -functions with improved versions (Gnuplot2 comes with IPython). - -- Data: alias to Gnuplot.Data, makes a PlotItem from array data. - -- File: alias to Gnuplot.File, makes a PlotItem from a file. - -- String: alias to Gnuplot.String, makes a PlotItem from a string formatted -exactly like a file for Gnuplot.File would be. - -- Func: alias to Gnuplot.Func, makes a PlotItem from a function string. - -- GridData: alias to Gnuplot.GridData, makes a PlotItem from grid data. - -- pm3d_config: a string with Gnuplot commands to set up the pm3d mode for -surface plotting. You can activate it simply by calling gp(pm3d_config). - -- eps_fix_bbox: A Unix-only function to fix eps files with bad bounding boxes -(which Gnuplot generates when the plot size is set to square). - -This requires the Gnuplot.py module for interfacing Python with Gnuplot, which -can be downloaded from: - -http://gnuplot-py.sourceforge.net/ - -Inspired by a suggestion/request from Arnd Baecker. -""" - -__all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData', - 'pm3d_config','eps_fix_bbox'] - -import os,tempfile,sys -from IPython.utils.process import getoutput - -#--------------------------------------------------------------------------- -# Notes on mouse support for Gnuplot.py - -# If you do not have a mouse-enabled gnuplot, set gnuplot_mouse to 0. If you -# use gnuplot, you should really grab a recent, mouse enabled copy. It is an -# extremely useful feature. Mouse support is official as of gnuplot 4.0, -# released in April 2004. - -# For the mouse features to work correctly, you MUST set your Gnuplot.py -# module to use temporary files instead of 'inline data' for data -# communication. Note that this is the default, so unless you've manually -# fiddled with it you should be ok. If you need to make changes, in the -# Gnuplot module directory, loook for the gp_unix.py file and make sure the -# prefer_inline_data variable is set to 0. If you set it to 1 Gnuplot.py will -# try to pass the data to gnuplot via standard input, which completely -# confuses the mouse control system (even though it may be a bit faster than -# using temp files). - -# As of Gnuplot.py v1.7, a new option was added to use FIFOs (pipes). This -# mechanism, while fast, also breaks the mouse system. You must therefore set -# the variable prefer_fifo_data to 0 in gp_unix.py. - -tmpname = tempfile.mktemp() -open(tmpname,'w').write('set mouse') -gnu_out = getoutput('gnuplot '+ tmpname) -os.unlink(tmpname) -if gnu_out: # Gnuplot won't print anything if it has mouse support - print "*** Your version of Gnuplot appears not to have mouse support." - gnuplot_mouse = 0 -else: - gnuplot_mouse = 1 -del tmpname,gnu_out - -# Default state for persistence of new gnuplot instances -if os.name in ['nt','dos'] or sys.platform == 'cygwin': - gnuplot_persist = 0 -else: - gnuplot_persist = 1 - -import IPython.Gnuplot2 as Gnuplot - -class NotGiven: pass - -def gp_new(mouse=NotGiven,persist=NotGiven): - """Return a new Gnuplot instance. - - The instance returned uses the improved methods defined in Gnuplot2. - - Options (boolean): - - - mouse: if unspecified, the module global gnuplot_mouse is used. - - - persist: if unspecified, the module global gnuplot_persist is used.""" - - if mouse is NotGiven: - mouse = gnuplot_mouse - if persist is NotGiven: - persist = gnuplot_persist - g = Gnuplot.Gnuplot(persist=persist) - if mouse: - g('set mouse') - return g - -# Global-level names. - -# A global Gnuplot instance for interactive use: -gp = gp_new() - -# Accessors for the main plot object constructors: -Data = Gnuplot.Data -File = Gnuplot.File -Func = Gnuplot.Func -String = Gnuplot.String -GridData = Gnuplot.GridData - -# A Unix-only function to fix eps files with bad bounding boxes (which Gnuplot -# generates when the plot size is set to square): -eps_fix_bbox = Gnuplot.eps_fix_bbox - -# String for configuring pm3d. Simply call g(pm3d_config) to execute it. pm3d -# is a very nice mode for plotting colormaps on surfaces. Modify the defaults -# below to suit your taste. -pm3d_config = """ -set pm3d solid -set hidden3d -unset surface -set isosamples 50 -""" -#******************** End of file ****************** diff --git a/IPython/deathrow/PhysicalQInput.py b/IPython/deathrow/PhysicalQInput.py deleted file mode 100644 index aac8788..0000000 --- a/IPython/deathrow/PhysicalQInput.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -"""Modified input prompt for entering quantities with units. - -Modify the behavior of the interactive interpreter to allow direct input of -quantities with units without having to make a function call. - -Now the following forms are accepted: - -x = 4 m -y = -.45e3 m/s -g = 9.8 m/s**2 -a = 2.3 m/s^2 # ^ -> ** automatically - -All other input is processed normally. - -Authors -------- -- Fernando Perez -""" -#***************************************************************************** -# Copyright (C) 2008-2011 The IPython Development Team -# Copyright (C) 2001-2007 Fernando Perez -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -# This file is an example of how to modify IPython's line-processing behavior -# without touching the internal code. We'll define an alternate pre-processing -# stage which allows a special form of input (which is invalid Python syntax) -# for certain quantities, rewrites a line of proper Python in those cases, and -# then passes it off to IPython's normal processor for further work. - -# With this kind of customization, IPython can be adapted for many -# special-purpose scenarios providing alternate input syntaxes. - -# This file can be imported like a regular module. - -# IPython has a prefilter() function that analyzes each input line. We redefine -# it here to first pre-process certain forms of input - -# The prototype of any alternate prefilter must be like this one (the name -# doesn't matter): -# - line is a string containing the user input line. -# - continuation is a parameter which tells us if we are processing a first line of -# user input or the second or higher of a multi-line statement. - -def prefilter_PQ(self,line,continuation): - """Alternate prefilter for input of PhysicalQuantityInteractive objects. - - This assumes that the function PhysicalQuantityInteractive() has been - imported.""" - - from re import match - from IPython.core.iplib import InteractiveShell - - # This regexp is what does the real work - unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)', - line) - - # If special input was ecnountered, process it: - if unit_split: - var,val,units = unit_split.groups() - if var and val and units: - units = units.replace('^','**') - # Now a valid line needs to be constructed for IPython to process: - line = var +" = PhysicalQuantityInteractive(" + val + ", '" + \ - units + "')" - #print 'New line:',line # dbg - - # In the end, always call the default IPython _prefilter() function. Note - # that self must be passed explicitly, b/c we're calling the unbound class - # method (since this method will overwrite the instance prefilter()) - return InteractiveShell._prefilter(self,line,continuation) - -# Rebind this to be the new IPython prefilter: -from IPython.core.iplib import InteractiveShell -InteractiveShell.prefilter = prefilter_PQ - -# Clean up the namespace. -del InteractiveShell,prefilter_PQ - -# Just a heads up at the console -print '*** Simplified input for physical quantities enabled.' diff --git a/IPython/deathrow/PhysicalQInteractive.py b/IPython/deathrow/PhysicalQInteractive.py deleted file mode 100644 index 338bb4d..0000000 --- a/IPython/deathrow/PhysicalQInteractive.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -"""Modify the PhysicalQuantities class for more convenient interactive use. - -Also redefine some math functions to operate on PhysQties with no need for -special method syntax. This just means moving them out to the global -namespace. - -This module should always be loaded *after* math or Numeric, so it can -overwrite math functions with the versions that handle units. - -Authors -------- -- Fernando Perez -""" - -#***************************************************************************** -# Copyright (C) 2008-2011 The IPython Development Team -# Copyright (C) 2001-2007 Fernando Perez -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -from Scientific.Physics.PhysicalQuantities import PhysicalQuantity - -# This code can be set up to work with Numeric or with math for providing the -# mathematical functions. Uncomment the one you prefer to use below. - -# If you use math, sin(x) won't work for x an array, only float or PhysQty -import math - -# If you use Numeric, sin(x) works for x a float, PhysQty an array. -#import Numeric as math - -class PhysicalQuantityFunction: - """Generic function wrapper for PhysicalQuantity instances. - - Calls functions from either the math library or the instance's methods as - required. Allows using sin(theta) or sqrt(v**2) syntax irrespective of - whether theta is a pure number or a PhysicalQuantity. - - This is *slow*. It's meant for convenient interactive use, not for - speed.""" - - def __init__(self,name): - self.name = name - - def __call__(self,x): - if isinstance(x,PhysicalQuantity): - return PhysicalQuantity.__dict__[self.name](x) - else: - return math.__dict__[self.name](x) - -class PhysicalQuantityInteractive(PhysicalQuantity): - """Physical quantity with units - modified for Interactive use. - - Basically, the __str__ and __repr__ methods have been swapped for more - convenient interactive use. Powers are shown as ^ instead of ** and only 4 - significant figures are shown. - - Also adds the following aliases for commonly used methods: - b = PhysicalQuantity.inBaseUnits - u = PhysicalQuantity.inUnitsOf - - These are useful when doing a lot of interactive calculations. - """ - - # shorthands for the most useful unit conversions - b = PhysicalQuantity.inBaseUnits # so you can just type x.b to get base units - u = PhysicalQuantity.inUnitsOf - - # This can be done, but it can get dangerous when coupled with IPython's - # auto-calling. Everything ends up shown in baseunits and things like x*2 - # get automatically converted to k(*2), which doesn't work. - # Probably not a good idea in general... - #__call__ = b - - def __str__(self): - return PhysicalQuantity.__repr__(self) - - def __repr__(self): - value = '%.4G' % self.value - units = self.unit.name().replace('**','^') - return value + ' ' + units - -# implement the methods defined in PhysicalQuantity as PhysicalQuantityFunctions -sin = PhysicalQuantityFunction('sin') -cos = PhysicalQuantityFunction('cos') -tan = PhysicalQuantityFunction('tan') -sqrt = PhysicalQuantityFunction('sqrt') diff --git a/IPython/deathrow/Shell.py b/IPython/deathrow/Shell.py deleted file mode 100644 index cd8bb0c..0000000 --- a/IPython/deathrow/Shell.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -# encoding: utf-8 -""" -A backwards compatibility layer for IPython.Shell. - -Previously, IPython had an IPython.Shell module. IPython.Shell has been moved -to IPython.core.shell and is being refactored. This new module is provided -for backwards compatability. We strongly encourage everyone to start using -the new code in IPython.core.shell. -""" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from warnings import warn - -msg = """ -This module (IPython.Shell) is deprecated. The classes that were in this -module have been replaced by: - -IPShell->IPython.core.iplib.InteractiveShell -IPShellEmbed->IPython.core.embed.InteractiveShellEmbed - -Please migrate your code to use these classes instead. -""" - -warn(msg, category=DeprecationWarning, stacklevel=1) - -from IPython.core.iplib import InteractiveShell as IPShell -from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed - -def start(user_ns=None, embedded=False): - """Return an instance of :class:`InteractiveShell`.""" - if embedded: - return IPShellEmbed(user_ns=user_ns) - else: - return IPShell(user_ns=user_ns) - diff --git a/IPython/deathrow/astyle.py b/IPython/deathrow/astyle.py deleted file mode 100644 index 9821d58..0000000 --- a/IPython/deathrow/astyle.py +++ /dev/null @@ -1,400 +0,0 @@ -""" -``astyle`` provides classes for adding style (foreground and background color; -bold; blink; etc.) to terminal and curses output. -""" - - -import sys, os - -try: - import curses -except ImportError: - curses = None - - -COLOR_BLACK = 0 -COLOR_RED = 1 -COLOR_GREEN = 2 -COLOR_YELLOW = 3 -COLOR_BLUE = 4 -COLOR_MAGENTA = 5 -COLOR_CYAN = 6 -COLOR_WHITE = 7 - -A_BLINK = 1<<0 # Blinking text -A_BOLD = 1<<1 # Extra bright or bold text -A_DIM = 1<<2 # Half bright text -A_REVERSE = 1<<3 # Reverse-video text -A_STANDOUT = 1<<4 # The best highlighting mode available -A_UNDERLINE = 1<<5 # Underlined text - - -class Style(object): - """ - Store foreground color, background color and attribute (bold, underlined - etc.). - """ - __slots__ = ("fg", "bg", "attrs") - - COLORNAMES = { - "black": COLOR_BLACK, - "red": COLOR_RED, - "green": COLOR_GREEN, - "yellow": COLOR_YELLOW, - "blue": COLOR_BLUE, - "magenta": COLOR_MAGENTA, - "cyan": COLOR_CYAN, - "white": COLOR_WHITE, - } - ATTRNAMES = { - "blink": A_BLINK, - "bold": A_BOLD, - "dim": A_DIM, - "reverse": A_REVERSE, - "standout": A_STANDOUT, - "underline": A_UNDERLINE, - } - - def __init__(self, fg, bg, attrs=0): - """ - Create a ``Style`` object with ``fg`` as the foreground color, - ``bg`` as the background color and ``attrs`` as the attributes. - - Examples: - >>> Style(COLOR_RED, COLOR_BLACK) -