"""castex : latex interface to cas Version 0.1 alpha : matplotlib basic graphics Version 0.11 alpha : minor tweaks (handling cdot) See __init__ for attributes See __main__ for some exemples This is free software (beer/speech, whatever). Just in case, the following MIT licence applies. Copyright (C) 2011-2012 Andrzej Stos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import sys from pygiac import GiacSession from pylab import * PREAMBLE = """\\documentclass[11pt]{article} \\usepackage{amsmath,amstext,amssymb,amsopn,amsthm} \usepackage{graphicx} \\usepackage{color} \usepackage[utf8]{inputenc} \\topmargin -2.5 cm \\oddsidemargin -0.1 cm \\textheight 240 mm \\textwidth 17 cm \\parindent 0pt \\parskip 4pt \\newcommand{\\R}{\\mathbb{R}} \\newcommand{\\N}{\\mathbb{N}} \\newcommand{\\Z}{\\mathbb{Z}} \\newcommand{\\C}{\\mathbb{C}} \\newcommand{\\ind}{{\\bf 1}} \\newcommand{\\cm}[1]{{\\tt #1}} \\def\\ds{\\displaystyle} \\def\\com{\\verb\\#} \\begin{document} """ def find_matching_brace(s,ind): """Given a position ind of opening parenthese in a string s, returns the index of the matching paren or -1 if there is no match """ match = { '(':')', '[':']', '{':'}' } if match.has_key(s[ind]): op = s[ind] cl = match[op] (num_op, num_cl) = (1,0) while num_op > num_cl: ind += 1 if ind >= len(s): return -1 if s[ind] == op: num_op += 1 if s[ind] == cl: num_cl += 1 return ind else: return -1 def find_next_command(source, ind): """Find next latex-style command \giac{...} our \giac*{...}. Return the tuple (start index, end index, command, content, type). The type is 0 if the "\giac{..}" pattern was found; it implies displaying the command (verbatim) and the result (possibly in latex) The type is 1 if the "\giac*{..}" was found (implies displaying the result only) The type is 2 if the "\giac**{..}" was found (implies transforming the command to latex) Newlines are deleted so the commands should be separated by semicolons (this may be modified later). """ i = source.find('\\giac',ind) silent = -1 if i < 0: return (-1,-1,'',-1) if source[i+5] == '{': offset = 5 prefix= '\\giac{' silent = 0 if source[i+5:i+7] == '*{': offset = 6 prefix = '\\giac*{' silent = 1 if source[i+5:i+8] == '**{': offset = 7 prefix = '\\giac**{' silent = 2 if silent < 0: print 'Syntax error: bad format of \\giac command.' sys.exit(0) j = find_matching_brace(source, i+offset) if j < 0: print 'Syntax error: closing bracket not found.' sys.exit(0) s = source[i:j].replace(prefix,'').replace('\n','') while ' ' in s: s = s.replace(' ',' ') return (i,j,s,silent) def ans_retouche(ans): ans = ans.replace('"','') ans = '$\ds ' + ans + '$' if 'sqrt' in ans: i = ans.find('sqrt{') j = find_matching_brace(ans,i+4) ans = ans[:j+1] + '\,' + ans[j+1:] ans = ans.replace('DOM_', 'DOM\\_') ans = ans.replace('*','\cdot') # is \cdot better here? ans = ans.replace('\\cdot','{\cdot}') return ans def make_plot(n,plot_data): global filename figure(n, figsize=(4, 4), dpi=100) i = plot_data.rfind('group[') j = plot_data.find(']',i) s = plot_data[i+6:j].split(',') x = [] y = [] for k in s: # print k c = complex(k.replace('i','j').replace('*','')) x.append(c.real) y.append(c.imag) plot(x,y, lw=0.75) # plot(x,y, linewidth=2, color='red') # options to remember grid(True) # axis('off') fn = filename + '_graph' + str(n) + '.png' savefig(fn) return fn def make_scatterplot(n,plot_data): global filename figure(n, figsize=(4, 4), dpi=100) s = plot_data.split(',') x = [] y = [] for k in s: # print k c = complex(k.replace('i','j').replace('*','')) x.append(c.real) y.append(c.imag) scatter(x,y,s=1, c='b') # axis('off') fn = filename + '_graph' + str(n) + '.png' savefig(fn) return fn # ------------------------------------------ # # The main thing # Initialisation if len(sys.argv) < 2: filename = 'castex' else: filename = sys.argv[1] sfilename = filename + '.cas' # no extension on input, say source = open(sfilename,'r').read() giac = GiacSession() # Parsing the source, ccmputing and inserting answers # To cite a command, we're using latex verbatim command: \def\com{\verb\#} graph_commands = [ 'plot', 'funcplot', 'plotfunc', 'graphe', 'plotlist', 'listplot'] (start,end,command,silent) = find_next_command(source,0) fig = 1 while command: print command if 'py_scatterplot(' in command: command1 = command.replace(':;','').replace(';','').replace('py_scatterplot(','') command1 = command1[0:command1.rfind(')')] print command1 matrix_list=giac.compute(command1).split('],[') matrix_list[0] = matrix_list[0].replace('[[','') matrix_list[len(matrix_list)-1] = matrix_list[len(matrix_list)-1].replace(']]','') for k in range(len(matrix_list)): matrix_list[k] = matrix_list[k].replace(',','+') + '*i' point_string = ','.join(matrix_list) # print point_string ans = '\\includegraphics{' + make_scatterplot(fig,point_string) + '}' fig += 1 source = source.replace(source[start:end+1], '\n\n{\color{red}\com > '+ command +' #}\n\n' + '\\centerline{ '+ ans +' }', 1) (start,end,command,silent) = find_next_command(source,start) continue if 'scatterplot(' in command or 'nuage-points(' in command: command1 = command.replace(':;','').replace(';','') command1 = 'p_scatter_data := ' + command1 + (':;') giac.compute(command1); point_string = giac.compute('seq(p_scatter_data[jj][1],jj=0..size(p_scatter_data)-1') ans = '\\includegraphics{' + make_scatterplot(fig,point_string) + '}' fig += 1 source = source.replace(source[start:end+1], '\n\n{\color{red}\com > '+ command +' #}\n\n' + '\\centerline{ '+ ans +' }', 1) (start,end,command,silent) = find_next_command(source,start) continue if 'plot(' in command : command1 = command.replace(':;','').replace(';','') command1 = command1 + ('[1];') print command1 ans = '\\includegraphics{' + make_plot(fig,giac.compute(command1)) + '}' fig += 1 source = source.replace(source[start:end+1], '\n\n{\color{red}\com > '+ command +' #}\n\n' + '\\centerline{ '+ ans +' }', 1) (start,end,command,silent) = find_next_command(source,start) continue if silent == 2: ans = ans_retouche(giac.latex_transform(command)) else: if ';' in command: # no latex if multicommand line or loop (might be reconsidered later) ans = giac.compute(command).replace('"Done",','').strip() else: ans = ans_retouche(giac.latex_compute(command)) if silent > 0: source = source.replace(source[start:end+1], '{\color{blue}' + ans +'}', 1) elif silent == 0: source = source.replace(source[start:end+1], '\n\n{\color{red}\com > '+ command +' #}\n\n' + '{\color{blue}$\qquad$\n'+ ans +' }\n\n', 1) (start,end,command,silent) = find_next_command(source,start) # Producing pdf file with latex fout=open(filename + '.tex', 'w') while source.find('\n\n\n') > 0: source = source.replace('\n\n\n','\n\n') source = PREAMBLE + source + '\\end{document}\n' fout.write(source) fout.close() print 'Compiling latex' os.system("pdflatex --quiet " + filename +".tex") print 'Done.'