From e0c6872cf40896c7be36b11dcc744620f10adf1d Mon Sep 17 00:00:00 2001 From: Norbert Preining Date: Mon, 2 Sep 2019 13:46:59 +0900 Subject: Initial commit --- .../pgf/contrib/pgfplots/scripts/matlab2pgfplots.m | 343 +++++++++++++++++++++ .../contrib/pgfplots/scripts/matlab2pgfplots.sh | 79 +++++ graphics/pgf/contrib/pgfplots/scripts/pgf2pdf.sh | 287 +++++++++++++++++ graphics/pgf/contrib/pgfplots/scripts/pgfplots.py | 95 ++++++ 4 files changed, 804 insertions(+) create mode 100644 graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.m create mode 100755 graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.sh create mode 100755 graphics/pgf/contrib/pgfplots/scripts/pgf2pdf.sh create mode 100644 graphics/pgf/contrib/pgfplots/scripts/pgfplots.py (limited to 'graphics/pgf/contrib/pgfplots/scripts') diff --git a/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.m b/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.m new file mode 100644 index 0000000000..cf9111e9ac --- /dev/null +++ b/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.m @@ -0,0 +1,343 @@ +function matlab2pgfplots(varargin ) +% matlab2pgfplots(outfile ) +% matlab2pgfplots( outfile, OPTIONS ) +% +% Generate LaTeX code for use in package pgfplots to +% draw line plots. +% +% It will use every (2d) line plot in the figure specified by handler fighandle. +% +% It understands +% - axis labels, +% - legends, +% - any 2d line plots, +% - line styles/markers (in case of styles=1), +% - tick positions, labels and axis limits (in case of axes=1). +% +% Linestyles and markers will follow as an option. However, pgfplots has its +% own line styles which may be appropriate. +% +% Although pgfplots can also handle bar and area plots, this script is not yet +% capable of converting them. Feel free to modify it and send the final version +% to me! +% +% OPTIONS are key value pairs. Known options are +% - 'fig',HANDLE +% a figure handle (default is 'gcf'). +% - 'styles',0|1 +% a boolean indicating whether line styles, markers and colors shall be exported (default 1). +% - 'axes',0|1 +% a boolean indicating whether axis ticks, tick labels and limits shall be exported (default 0). +% - 'maxpoints',100000 +% an integer denoting the maximum number of points exported to tex. If the actual number is larger, +% the data will be interpolated to 'maxpoints'. The interpolation assumes +% parametric plots if x and y are not monotonically increasing. +% +% See +% http://www.ctan.org/pkg/pgfplots +% for details about pgfplots. +% +% +% +% Copyright Christian Feuersaenger 2008 +% +% This script requires Matlab version 7.4 (or above). +parser = inputParser; + +parser.addRequired( 'outfile', @(x) ischar(x) ); +parser.addParamValue( 'fig', gcf, @(x) ishandle(x) ); +parser.addParamValue( 'styles', 1, @(x) x==0 || x==1 ); +parser.addParamValue( 'axes' , 0, @(x) x==0 || x==1 ); +parser.addParamValue( 'maxpoints', 100000, @(x) isnumeric(x) ); + +parser.parse( varargin{:} ); + + +fighandle = parser.Results.fig; + +lineobjs = findobj(fighandle, 'Type', 'line' ); +axesobj = findobj( fighandle, 'Type', 'axes' ); + +% As far as I know, 'scatter' and 'scatter3' produce groups of this class: +scatterobjs = findobj(fighandle, 'Type', 'hggroup' ); +lineobjs = [ lineobjs scatterobjs ]; + +legendobj = findobj( fighandle, 'tag', 'legend' ); +if length(legendobj) > 0 + allchildsoflegend = [ findobj( legendobj ) ]; + lineobjs = setdiff( lineobjs, allchildsoflegend ); + axesobj = setdiff( axesobj, allchildsoflegend ); +end + +FID=fopen( parser.Results.outfile, 'w' ); +assert( FID >= 0, [ 'could not open file ' parser.Results.outfile ' for writing' ] ); + +ENDL=sprintf('\n'); +TAB=sprintf('\t'); +fwrite( FID, [ ... + '\begin{tikzpicture}%' ENDL ... + '\begin{axis}'] ); + +xislog = 0; +yislog = 0; + +if length(axesobj) > 0 + axis = axesobj(1); + xlabel = get( get(axis, 'XLabel'), 'String'); + ylabel = get( get(axis, 'YLabel'), 'String'); + zlabel = get( get(axis, 'ZLabel'), 'String'); + xscale = get(axis,'XScale'); + yscale = get(axis,'YScale'); + + axisoptions = {}; + if length(xlabel) > 0 + axisoptions = [ axisoptions [ 'xlabel={' xlabel '}'] ]; + end + if length(ylabel) > 0 + axisoptions = [ axisoptions ['ylabel={' ylabel '}'] ]; + end + if strcmp(xscale,'log') + xislog=1; + axisoptions = [ axisoptions ['xmode=log'] ]; + end + if strcmp(yscale,'log') + yislog = 1; + axisoptions = [ axisoptions ['ymode=log'] ]; + end + if parser.Results.axes + for k = 'xy' + L = get(gca, [ k 'Lim'] ); + axisoptions = [ axisoptions [ k 'min=' num2str(L(1)) ] ]; + axisoptions = [ axisoptions [ k 'max=' num2str(L(2)) ] ]; + end + + for k = 'xy' + L = get(gca, [ k 'Tick'] ); + opt = [ k 'tick={' ]; + for q=1:length(L) + if q>1 + opt = [opt ',' ]; + end + opt = [opt num2str(L(q)) ]; + end + opt = [ opt '}' ]; + axisoptions = [axisoptions opt ]; + end + + end + + + axisoptstr = []; + for i = 1:length(axisoptions) + if i>1 + axisoptstr = [axisoptstr ',' ENDL TAB]; + end + axisoptstr = [axisoptstr axisoptions{i}]; + end + if length( axisoptstr ) + fwrite( FID, [ '[' ENDL TAB axisoptstr ']' ENDL ] ); + end +end +fwrite( FID, ENDL ); + +if length(legendobj) > 0 + legentries = get(legendobj, 'String'); + if length(legentries) > 0 + legstr = ['\legend{%' ENDL TAB ]; + for i = 1:length(legentries) + legstr = [ legstr legentries{i} '\\%' ENDL ]; + if i ~= length(legentries) + legstr = [ legstr TAB ]; + end + end + legstr = [ legstr '}%' ENDL ]; + fwrite( FID, legstr ); + end +end + +xpointformat = '%f'; +ypointformat = '%f'; +if xislog + xpointformat = '%e'; +end +if yislog + ypointformat = '%e'; +end + +for i = 1:length(lineobjs) + + x = get(lineobjs(i), 'XData'); + y = get(lineobjs(i), 'YData'); + z = get(lineobjs(i), 'ZData'); + + if size(x,1) > 1 + disp( ['line element ' num2str(i) ' skipped: size ' num2str(size(x)) ' not supported']); + end + if abs(max(z) > 0) + disp( ['line element ' num2str(i) ' skipped: only 2d-plots supported up to now']); + end + + if size(x,2) > parser.Results.maxpoints + % we need to re-interpolate the data! + q = find( diff(x) < 0 ); + if length(q) + % parametric plot x(t), y(t), z(t). + % we assume t = 1:size(x,2) + X = 1:parser.Results.maxpoints; + x = interp1( 1:size(x,2),x, X); + y = interp1( 1:size(y,2),y, X); + z = interp1( 1:size(z,2),z, X); + + else + % a normal plot y(x): + X = linspace( min(x), max(x), parser.Results.maxpoints ); + y = interp1( x,y, X ); + x = X; + end + end + + coordstr = []; + for j = 1:size(x,2) + coordstr = [coordstr sprintf(['\t(' xpointformat ',\t' ypointformat ')\n'], x(j), y(j)) ]; + end + + addplotoptstr = []; + if parser.Results.styles + markOpts = {}; + mark = []; + linestyle = []; + color = []; + + C = matlabColorToPGFColor( get(lineobjs(i), 'Color') ); + if length(C) + color = [ 'color=' C ]; + end + + L = get(lineobjs(i), 'LineStyle' ); + switch L + case 'none' + linestyle = 'only marks'; + case '-' + linestyle = []; + case ':' + linestyle = 'densely dotted'; + case '-:' + linestyle = 'dash pattern={on 2pt off 3pt on 1pt off 3pt}'; + case '--' + linestyle = 'densely dashed'; + end + + M = get(lineobjs(i), 'Marker'); + switch M + case '.' + mark = '*'; + markOpts = [ markOpts 'scale=0.1' ]; + case 'o' + mark = '*'; + case 'x' + mark = 'x'; + case '+' + mark = '+'; + case '*' + mark = 'asterisk'; + case 'square' + mark = 'square*'; + case 'diamond' + mark = 'diamond*'; + case '^' + mark = 'triangle*'; + case 'v' + mark = 'triangle*'; + markOpts = [ markOpts 'rotate=180' ]; + case '<' + mark = 'triangle*'; + markOpts = [ markOpts 'rotate=90' ]; + case '>' + mark = 'triangle*'; + markOpts = [ markOpts 'rotate=270' ]; + case 'pentagramm' + mark = 'pentagon*'; + case 'hexagram' + mark = 'oplus*'; + end + + M = matlabColorToPGFColor( get(lineobjs(i), 'MarkerFaceColor') ); + if length(M) + markOpts = [ markOpts ['fill=' M] ]; + end + + M = matlabColorToPGFColor( get(lineobjs(i), 'MarkerEdgeColor') ); + if length(M) + markOpts = [ markOpts ['draw=' M] ]; + end + + if length(color) + if length(addplotoptstr) + addplotoptstr = [addplotoptstr ',' ]; + end + addplotoptstr = [ addplotoptstr color ]; + end + + if length(linestyle) + if length(addplotoptstr) + addplotoptstr = [addplotoptstr ',' ]; + end + addplotoptstr = [ addplotoptstr linestyle ]; + end + + if length(mark) + if length(addplotoptstr) + addplotoptstr = [addplotoptstr ',' ]; + end + addplotoptstr = [ addplotoptstr [ 'mark=' mark ] ]; + + if length(markOpts) + markOptsStr = 'mark options={'; + for q = 1:length(markOpts) + if q > 1 + markOptsStr = [markOptsStr ',' ]; + end + markOptsStr = [ markOptsStr markOpts{q} ]; + end + markOptsStr = [ markOptsStr '}' ]; + + addplotoptstr = [ addplotoptstr ',' markOptsStr ]; + end + end + + + if length(addplotoptstr) + addplotoptstr = [ '[' addplotoptstr ']' ]; + end + + end + fwrite( FID, [ ... + '\addplot' addplotoptstr ' plot coordinates {' ENDL coordstr '};' ENDL ] ); + +end + + +fwrite( FID, [ ... + '\end{axis}' ENDL ... + '\end{tikzpicture}%' ENDL ] ); +fclose(FID); + +end + +function cstr = matlabColorToPGFColor( C ) + +if length(C) ~= 3 | ischar(C) & strcmp(C,'none'), cstr = []; +elseif norm( C - [0 0 1 ], 'inf' ) < 1e-10, cstr = 'blue'; +elseif norm( C - [0 1 0 ], 'inf' ) < 1e-10, cstr = 'green'; +elseif norm( C - [1 0 0 ], 'inf' ) < 1e-10, cstr = 'red'; +elseif norm( C - [0 1 1 ], 'inf' ) < 1e-10, cstr = 'cyan'; +elseif norm( C - [1 0 1 ], 'inf' ) < 1e-10, cstr = 'magenta'; +elseif norm( C - [1 1 0 ], 'inf' ) < 1e-10, cstr = 'yellow'; +elseif norm( C - [0 0 0 ], 'inf' ) < 1e-10, cstr = 'black'; +elseif norm( C - [1 1 1 ], 'inf' ) < 1e-10, cstr = 'white'; +else + cstr= 'blue'; % FIXME +% cstr = [ '{rgb:red,' num2str( floor( C(1)*100) ) ';green,' num2str(floor(C(2)*100)) ';blue,' num2str(floor(C(3)*100)) '}' ]; +end + +end diff --git a/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.sh b/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.sh new file mode 100755 index 0000000000..c821171940 --- /dev/null +++ b/graphics/pgf/contrib/pgfplots/scripts/matlab2pgfplots.sh @@ -0,0 +1,79 @@ +#!/bin/sh + + +CONVERT_STYLES=1 +CONVERT_AXES=1 +OUTFILE="" +MAXPOINTS=100000 + +echoHelp() +{ + echo "matlab2pgfplots.sh [--maxpoints N] [--styles [0|1] ] [ --axes [0|1] ] [ -o OUTFILE ] INFILE ..." + echo "converts Matlab figures (.fig-files) to pgfplots-files (.pgf-files)." + echo "This script is a front-end for matlab2pgfplots.m (which needs to be in matlab's search path)" + echo "type" + echo " >> help matlab2pgfplots" + echo "at your matlab prompt for more information." + exit 0 +} + +LONGOPTS="styles:,axes:,help,maxpoints:" +SHORTOPTS="o:" +ARGS=`getopt -l "$LONGOPTS" "$SHORTOPTS" "$@"` +if [ $? -ne 0 ]; then + echo "`basename $0`: Could not process command line arguments. Use the '--help' option for documentation." + exit 1 +fi + +eval set -- "$ARGS" +while [ $# -gt 0 ]; do + ARG=$1 + # echo "PROCESSING OPTION '$ARG' (next = $@)" + case "$ARG" in + --maxpoints) shift; MAXPOINTS=$1; shift;; + --styles) shift; CONVERT_STYLES="$1"; shift;; + --axes) shift; CONVERT_AXES="$1"; shift;; + -o) shift; OUTFILE="$1"; shift;; + --help) shift; echoHelp;; + --) shift; break;; + *) break; + esac +done + +if [ $# -eq 0 ]; then + echo "No input files specified." + exit 1 +fi + +HAS_OUTFILE=0 +if [ $# -gt 1 -a -n "$OUTFILE" ]; then + HAS_OUTFILE=1 +fi + +for A; do + INFILE="$A" + if [ $HAS_OUTFILE -eq 0 ]; then + OUTFILE="${INFILE%%.*}.pgf" + fi + echo "$INFILE -> $OUTFILE ... " + + M_LOGFILE=`mktemp` + matlab -nojvm -nodesktop -nosplash 1>/dev/null 2>&1 -logfile $M_LOGFILE <<-EOF + f=hgload( '$INFILE' ); + matlab2pgfplots( '$OUTFILE', 'fig', f, 'styles', $CONVERT_STYLES, 'axes', $CONVERT_AXES, 'maxpoints', $MAXPOINTS ); + exit + EOF + grep -q "Error" $M_LOGFILE + CODE=$? + if [ $CODE -eq 0 ]; then + echo "Matlab output:" 1>&2 + cat $M_LOGFILE 1>&2 + CODE=1 + else + CODE=0 + fi + rm -f $M_LOGFILE + if [ $CODE -ne 0 ]; then + exit $CODE + fi +done diff --git a/graphics/pgf/contrib/pgfplots/scripts/pgf2pdf.sh b/graphics/pgf/contrib/pgfplots/scripts/pgf2pdf.sh new file mode 100755 index 0000000000..6549506d48 --- /dev/null +++ b/graphics/pgf/contrib/pgfplots/scripts/pgf2pdf.sh @@ -0,0 +1,287 @@ +#!/bin/sh +# +# ATTENTION: this file is more or less deprecated. +# Please take a look at the 'external' library which has been added to pgf. +# At the time of this writing, this library is only available for pgf cvs (newer than 2.00). + +TEX_FILE="" +TEX_LOG_FILE="" + +TEX_DEFINES="" + +OLD_DIR=`pwd` + +DRIVER="pdftex" + +ALSO_EPS_OUTPUT=0 +WARN_ONLY_IF_TEXFILE_DOESNOT_INCLUDE_TARGET=0 +VERBOSE_LEVEL=0 + +function dumpHelp() { + echo -e \ + "`basename $0` [OPTIONS] [--texdefs | --mainfile .tex ] [plot1.pgf plot2.pgf .... plotn.pgf]\n"\ + "converts each plot*.pgf to plot*.pdf.\n"\ + "This is done by running \n"\ + " latex --jobname plot1 latexmainfile\n"\ + "for each single plot. See the pgfmanual section \"Externalizing graphics\".\n"\ + "Options:\n"\ + "--eps\n"\ + " will also produce eps output files.\n"\ + "--driver D\n"\ + " will use either \"dvipdfm\", \"dvips\" or \"pdflatex\"\n"\ + " please note that only pdflatex works without additional\n"\ + " work.\n"\ + "--mainfile FILE\n"\ + " A tex-file which has been configured for externalized graphics.\n"\ + " Two conditions must be met to perform the conversion of\n"\ + " \"plot.pgf\" -> \"plot.pdf\":\n"\ + " 1. FILE needs the command\n"\ + " \pgfrealjobname{FILE}\n"\ + " (see the pgf manual for details)\n"\ + " 2. It needs to include \"plot.pgf\" somewhere (using \input{plot.pgf})\n"\ + "\n"\ + "--warnonly\n"\ + " Use this flag if the argument of --mainfile does not contain\n"\ + " \input{TARGET.pgf},\n"\ + " i.e. if (2.) is not fulfilled. In this case, the conversion for this\n"\ + " input file will be skipped.\n"\ + "\n"\ + "--texdefs FILE\n"\ + " Generates a temporary tex-file\n"\ + " \documentclass{article}\n"\ + " \input{FILE}\n"\ + " \begin{document}\n"\ + " \input{plot1.pgf}\n"\ + " \end{document}\n"\ + " and converts this one to pdf.\n"\ + " If FILE is '-', the input step is omitted.\n" + "-v\n"\ + " each -v option increases the verbosity.\n"\ + "" + exit 0; +} + + +LONGOPTS="mainfile:,eps,driver:,texdefs:,warnonly,help" +SHORTOPTS="f:t:v" +ARGS=`getopt -l "$LONGOPTS" "$SHORTOPTS" "$@"` +if [ $? -ne 0 ]; then + echo "`basename $0`: Could not process command line arguments. Use the '--help' option for documentation." + exit 1 +fi + +eval set -- "$ARGS" +while [ $# -gt 0 ]; do + ARG=$1 + # echo "PROCESSING OPTION '$ARG' (next = $@)" + case "$ARG" in + --texdefs|-t) shift; TEX_DEFINES="$1"; shift;; + --driver) shift; DRIVER="$1"; shift;; + --mainfile|-f) shift; TEX_FILE="$1"; TEX_LOG_FILE="${1%%.tex}.log"; shift;; + --eps) shift; ALSO_EPS_OUTPUT=1;; + --warnonly) shift; WARN_ONLY_IF_TEXFILE_DOESNOT_INCLUDE_TARGET=1;; + -v) shift; VERBOSE_LEVEL=$((VERBOSE_LEVEL+1));; + --) shift; break;; + --help) dumpHelp();; + *) break; + esac +done +if [ -n "${TEX_DEFINES}" ]; then + if [ "${TEX_DEFINES:0:1}" != "/" ]; then + TEX_DEFINES=`pwd`/${TEX_DEFINES} + fi +fi + + +if [ $# -ne 0 ]; then + PGF_FILES=("$@") +elif [ -n "${TEX_LOG_FILE}" ]; then + # search for lines with + # (XXXX.pgf + PGF_FILES=(`sed -n '{s/.*(\([a-zA-Z0-9._-+^~]\+\.pgf\).*/\1/g;T ende;p};: ende' < $TEX_LOG_FILE`) + #PGF_FILES=(./errplot_L2.pgf) +else + echo "No input files." 1>&2 + exit 1 +fi + +for A in "${PGF_FILES[@]}"; do + if [ ! -f "$A" ]; then + echo "$A not found: no such file" 1>&2 + exit 1 + fi + + CONTINUE_ON_ERROR=0 + + TARGET_FILE=$(sed -n '{s/.*\\beginpgfgraphicnamed{\(.*\)}.*/\1/g;T ende;p};: ende' < "$A") + if [ $? -ne 0 -o -z "$TARGET_FILE" ]; then + echo "There is no valid \\beginpgfgraphicnamed{TARGET}...\\endpgfgraphicnamed command in $A. Can't be exported to pdf. Please see the PGF manual for details." 1>&2 + exit 1 + fi + echo "processing \"$A\"" 1>&2 + + CMD="latex" + case $DRIVER in + pdftex|pdflatex) + CMD="pdflatex" + ;; + esac + + if [ -z "${TEX_DEFINES}" ]; then + # LaTeX cannot write into a \jobname in another directory. + # But the TEX_FILE and $A may not necessarily be in the same directory! + # + # So, we have to build a work-around which simulates a \jobname in the directory of TEX_FILE + # which does not fool \beginpgfgraphicnamed + + # modify the input file A: + ORIGINAL_FILE="$A.orig" + mv "$A" "$ORIGINAL_FILE" || exit 1 + cat - "$ORIGINAL_FILE" >"$A" <<-EOF + \let\tmpXXXXXZEUGoldjobname=\jobname + \def\jobname{${TARGET_FILE}}% + \message{PGF2PDF: TEX HAS ENTERED THE TARGET FILE...}% + EOF + cat >> "$A" <<-EOF + \let\jobname=\tmpXXXXXZEUGoldjobname + EOF + + cd `dirname "${TEX_FILE}"` + + # generate a temp \jobname in the current directory: + TMP_JOB_FILE=`mktemp ./tmppgf2pdfXXXXXX` + if [ $? -ne 0 ]; then exit 1; fi + rm -f "$TMP_JOB_FILE" + + $CMD --interaction nonstopmode --jobname "$TMP_JOB_FILE" "${TEX_FILE}" 1>/dev/null + CODE=$? + + INTERM_EXTENSION="dvi" + case $DRIVER in + pdftex|pdflatex) + INTERM_EXTENSION="pdf" + ;; + dvipdfm) + INTERM_EXTENSION="dvi" + ;; + dvips) + INTERM_EXTENSION="dvi" + ;; + esac + if [ ! -s "$TMP_JOB_FILE.$INTERM_EXTENSION" ]; then + if [ $VERBOSE_LEVEL -ge 1 ]; then + if [ $WARN_ONLY_IF_TEXFILE_DOESNOT_INCLUDE_TARGET -eq 1 ]; then + echo -n "WARNING: "; + else + echo -n "ERROR: "; + fi + echo -e "running\n"\ + " '$CMD --jobname $TMP_JOB_FILE $TEX_FILE'\n"\ + "resulted in a zero-size file \"$TMP_JOB_FILE.$INTERM_EXTENSION\"!\n"\ + "Please check\n"\ + "- if $TEX_FILE contains\n"\ + " \pgfrealjobname{`basename ${TEX_FILE%%.tex}`}\n"\ + "- if $TEX_FILE contains\n"\ + " \input{$A}\n"\ + "\n"\ + "You may take a look at\n\t$TARGET_FILE.log\n for more information.\n"\ + "Maybe `basename $0` --texdefs is more appropriate for this application?\n"\ + "It doesn't need \input{}...\n"\ + 1>&2 + fi + + CODE=1 + if [ $WARN_ONLY_IF_TEXFILE_DOESNOT_INCLUDE_TARGET -eq 1 ]; then + CONTINUE_ON_ERROR=1 + fi + rm -f $TMP_JOB_FILE.{$INTERM_EXTENSION,pdf} + fi + + + # FIXME: this here may clash if A and TARGET_FILE have inconsistent paths! + mv "$ORIGINAL_FILE" "$A" || exit 1 + for QQ in $TMP_JOB_FILE.*; do + if [ "$TARGET_FILE.${QQ##*.}" != "$A" ]; then + mv "$QQ" "$TARGET_FILE.${QQ##*.}" || exit 1 + fi + done + + cd "$OLD_DIR" + else + # Die Idee hier ist wie folgt: + # - Erstelle ein fast leeres Tex-File + # - darin steht NUR + # \input $TEX_DEFINES + # und + # \input $A + # - das TeX-file wird mit pgflatex uebersetzt + # - die ausgabe wird nach $TARGET_FILE geschrieben + # - fertig. + # + # BUGS: + # - TARGET_FILE != A wird nicht funktionieren (nur die endungen natuerlich) + DRIVER="pdftex" + cd `dirname "$A"` + BASE=`basename $TARGET_FILE` + TMP_TEX_FILE=`mktemp tmp_${BASE}_XXXXXX` + mv "$TMP_TEX_FILE" "${TMP_TEX_FILE}.tex" + TMP_TEX_FILE="$TMP_TEX_FILE.tex" + rm -f "${BASE}.pdf" + + cat >"$TMP_TEX_FILE" <<-EOF + \documentclass{report} + + \input{${TEX_DEFINES}} + + %\def\pgfsysdriver{pgfsys-dvipdfm.def} + %\def\pgfsysdriver{pgfsys-pdftex.def} + \usepackage{tikz} + \pgfrealjobname{${TMP_TEX_FILE%%.tex}} + \begin{document} + \let\oldjobname=\jobname% + % make sure that PGF recognises that jobname==target file name + % even if --jobname has a different path. + \def\jobname{${TARGET_FILE}}% + \input{`basename $A`}% + \let\jobname=\oldjobname + \end{document} + EOF + $CMD --interaction nonstopmode --jobname "$BASE" "${TMP_TEX_FILE}" 1>/dev/null + CODE=$? + if [ $CODE -eq 0 ]; then + rm -f "$TMP_TEX_FILE" + fi + cd $OLD_DIR + fi + + if [ $CODE -ne 0 ]; then + rm -f "${TARGET_FILE}.pdf" + if [ $CONTINUE_ON_ERROR -eq 1 ]; then + echo "WARNING: $A SKIPPED [use -v for messages]." 1>&2 + CODE=0 + continue + else + echo -e "FAILED: could not convert\n\t$A\n->\t$TARGET_FILE.pdf" 1>&2; + exit 1; + fi + fi + CMD="" + case $DRIVER in + dvipdfm) + dvipdfm -o ${TARGET_FILE}.pdf "${TARGET_FILE}.dvi" || exit 1 + pdfcrop "${TARGET_FILE}.pdf" "${TARGET_FILE}.pdf" || exit 1 + ;; + dvips) + dvipdfm -o ${TARGET_FILE}.ps "${TARGET_FILE}.dvi" || exit 1 + ;; + esac + + if [ $ALSO_EPS_OUTPUT -eq 1 ]; then + pdftops -f 1 -l 1 -eps "${TARGET_FILE}.pdf" "${TARGET_FILE}.eps" + if [ $? -ne 0 ]; then + echo "Conversion pdf -> eps FAILED!" 1>&2 + exit 1 + fi + fi +done +cd $OLD_DIR diff --git a/graphics/pgf/contrib/pgfplots/scripts/pgfplots.py b/graphics/pgf/contrib/pgfplots/scripts/pgfplots.py new file mode 100644 index 0000000000..a9ee32c9a8 --- /dev/null +++ b/graphics/pgf/contrib/pgfplots/scripts/pgfplots.py @@ -0,0 +1,95 @@ +"""Module to plot using Pgfplots. + +This module provides a means to create and display a graph very quickly. + +In this code, the program used to display the created PDF is 'xpdf'. Change +it to your favorite PDF reader, such as Acrobat Reader (called acroread or +something similar) + +The code used to generate the graph is printed in the command line. Edit +your graph iteratively, and when you are satisfied with the graph, copy and +paste the relevant part to your TEX file. + +This module requires the numpy module. + +For example of usage, see the executable part at the bottom. + + +ATTENTION: this file has been provided by 3rd party users in the hope that it +may be useful. However, it is not maintained by the pgfplots team as such. Use at your own risk. + +See also a related (improved) pgfplots code generation for python on https://github.com/olivierverdier/pygfplots + +""" +import numpy as np +import subprocess +import os +GRAPH_N = 0 + +class Pgf: + def __init__(z, xlabel='', ylabel=''): + """Initialize and provide axis labels.""" + z.buf = [] + z.options = [] + z.opt('xlabel={{{0}}}'.format(xlabel)) + z.opt('ylabel={{{0}}}'.format(ylabel)) + z.legend = [] + def opt(z, *args): + """Write arguments to the AXIS environment.""" + for arg in args: + z.options.append(arg) + def plot(z, x, y, legend=None, *args): + """Plot the data contained in the vectors x and y. + + Options to the \addplot command can be provided in *args. + """ + coor = ''.join(['({0}, {1})'. format(u, v) for u, v in zip(x,y)]) + z.buf.append('\\addplot{0} coordinates {{{1}}};\n'.format( + ('[' + ', '.join(args) + ']') if len(args) else '' ,coor)) + if legend is not None: + z.legend.append(legend) + def save(z, graph_n=None): + """Generate graph. + + If graph_n is None or a number, the graph in a file beginning with + zzz. This file is meant to be temporary. If graph_n is a string, + that string is used as the file name. + """ + if type(graph_n) is str: + file_name = graph_n + else: + if graph_n is None: + global GRAPH_N + graph_n = GRAPH_N + GRAPH_N += 1 + elif type(graph_n) is not int: + raise Error('graph_n should be a string or an integer') + file_name = 'zzz{0}'.format(graph_n) + with open(file_name + '.tex', 'w') as f: + b = [] + b.append('\\documentclass{article}\n') + b.append('\\usepackage{pgfplots}\n') + b.append('\\begin{document}\n') + b.append('\\begin{tikzpicture}') + b.append('\\begin{axis}[\n') + b.append('{0}]'.format(',\n'.join(z.options))) + b.extend(z.buf) + if z.legend: + b.append('\\legend{{' + '}, {'.join(z.legend) + '}}\n') + b.append('\\end{axis}\n') + b.append('\\end{tikzpicture}\n') + b.append('\\end{document}') + f.writelines(b) + print(''.join(b)) + os.system('pdflatex {0}.tex'.format(file_name)) + os.remove(file_name + '.aux') + os.remove(file_name + '.log') + subprocess.Popen(['xpdf', '{0}.pdf'.format(file_name)]) +if __name__ == '__main__': + """Example of usage.""" + x = np.linspace(0, 2*np.pi) + p = Pgf('time', 'Voltage') + p.opt('ybar') + p.plot(x, np.sin(x), 'sin') + p.plot(x, np.cos(x), 'cos') + p.save()#'graph_test_pgf_1') -- cgit v1.2.3