Skip to content

Commit

Permalink
Add option to do a gnuplot
Browse files Browse the repository at this point in the history
  • Loading branch information
sjoelund committed Jun 4, 2015
1 parent be4c584 commit 9083bcb
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 7 deletions.
5 changes: 5 additions & 0 deletions usersguide-sphinx/.gitignore
@@ -0,0 +1,5 @@
/build
source/*.pyc
source/logo.pdf
/tmp
source/dcmotor.*
5 changes: 3 additions & 2 deletions usersguide-sphinx/Makefile
Expand Up @@ -51,8 +51,9 @@ help:
clean:
rm -rf $(BUILDDIR)/*

html:
$(SPHINXBUILD) -b html -D pngmath_dvipng=dvisvgm.sh $(ALLSPHINXOPTS) $(BUILDDIR)/html
html: dvisvgm.sh
test -f dvisvgm.sh
$(SPHINXBUILD) -b html -D pngmath_dvipng="`pwd`"/dvisvgm.sh $(ALLSPHINXOPTS) $(BUILDDIR)/html
sed -i 's,\(_images/math/.*[.]\)png,\1svg,' build/html/*.html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
Expand Down
4 changes: 4 additions & 0 deletions usersguide-sphinx/dvisvgm.sh
@@ -0,0 +1,4 @@
#!/bin/bash

OUTF=`echo $2 | sed 's/[.]png/.svg/'`
exec dvisvgm "$1" "$OUTF" -n "${12}"
8 changes: 5 additions & 3 deletions usersguide-sphinx/source/introduction.rst
Expand Up @@ -392,7 +392,7 @@ stream when running omc from the command-line.

system("cat '"+getInstallationDirectoryPath()+"/share/doc/omc/testmodels/bubblesort.mo' > bubblesort.mo")

.. literalinclude :: ../bubblesort.mo
.. literalinclude :: ../tmp/bubblesort.mo
:language: modelica
Note: The output emitted into stdout by system commands is put into
Expand Down Expand Up @@ -464,8 +464,10 @@ We test code instantiation of the model to flat code:

We plot part of the simulated result:

>>> plot({load.w,load.phi})
true
.. omc-gnuplot :: dcmotor
load.w
load.phi
The val() function
~~~~~~~~~~~~~~~~~~
Expand Down
58 changes: 56 additions & 2 deletions usersguide-sphinx/source/sphinxcontribopenmodelica.py
Expand Up @@ -2,20 +2,26 @@
# -*- coding: utf-8 -*-

import sys
import os
import traceback
from os.path import basename
from StringIO import StringIO
import subprocess

from sphinx.util.compat import Directive
from docutils import nodes
from docutils.parsers.rst.directives.misc import Include as BaseInclude
from sphinx import directives
from docutils.parsers.rst import directives as rstdirectives
import docutils.parsers.rst.directives.images
from docutils.statemachine import ViewList

from OMPython import OMCSession

omc = OMCSession()
omhome = omc.sendExpression("getInstallationDirectoryPath()")
dochome = omc.sendExpression("cd()")
omc.sendExpression('mkdir("tmp/source")')
dochome = omc.sendExpression('cd("tmp")')

class ExecDirective(Directive):
"""Execute the specified python code and insert the output into the document"""
Expand All @@ -35,7 +41,7 @@ def fixPaths(s):
return str(s).replace(omhome, u"«OPENMODELICAHOME»").replace(dochome, u"«DOCHOME»").strip()

class ExecMosDirective(directives.CodeBlock):
"""Execute the specified python code and insert the output into the document"""
"""Execute the specified Modelica code and insert the output into the document using syntax highlighting"""
has_content = True
required_arguments = 0
option_spec = {
Expand Down Expand Up @@ -75,5 +81,53 @@ def run(self):
finally:
pass # sys.stdout = oldStdout

class OMCGnuplotDirective(Directive):
"""Execute the specified python code and insert the output into the document"""
has_content = True
required_arguments = 1
option_spec = {
'filename': str
}

def run(self):
try:
filename = os.path.abspath(self.options.get('filename') or omc.sendExpression("currentSimulationResult"))
if len(self.content)>1:
varstr = "{%s}" % ", ".join(self.content)
varstrquoted = "{%s}" % ", ".join(['"%s"'%s for s in self.content])
else:
varstr = self.content[0]
varstrquoted = '{"%s"}'%self.content[0]
vl = ViewList()
for text in [">>> plot(%s)" % varstr]:
vl.append(text, "<OMC gnuplot>")
node = docutils.nodes.paragraph()
self.state.nested_parse(vl, 0, node)
cb = node.children
assert(omc.sendExpression('filterSimulationResults("%s", "%s.csv", %s)' % (filename,os.path.abspath("tmp/" + self.arguments[0]),varstrquoted)))
with open("tmp/%s.gnuplot" % self.arguments[0], "w") as gnuplot:
gnuplot.write('set datafile separator ","\n')
for term in ["pdf", "svg", "png"]:
gnuplot.write('set term %s\n' % term)
gnuplot.write('set output "%s.%s"\n' % (os.path.abspath("source/" + self.arguments[0]), term))
gnuplot.write('plot \\\n')
vs = ['"%s.csv" using 1:"%s" title "%s" with lines, \\\n' % (os.path.abspath("tmp/" + self.arguments[0]),v,v) for v in self.content]
gnuplot.writelines(vs)
gnuplot.write('\n')
subprocess.check_call(["gnuplot", "tmp/%s.gnuplot" % self.arguments[0]])
try:
vl = ViewList()
for text in [".. figure :: %s.*" % self.arguments[0], "", " Plot generated by OpenModelica+gnuplot"]:
vl.append(text, "<OMC gnuplot>")
node = docutils.nodes.paragraph()
self.state.nested_parse(vl, 0, node)
fig = node.children
except Exception, e:
fig = [nodes.error(None, nodes.paragraph(text = "Unable to execute gnuplot-figure directive"), nodes.paragraph(text = str(e) + traceback.format_exc()))]
return cb + fig
except Exception, e:
return [nodes.error(None, nodes.paragraph(text = "Unable to execute gnuplot directive"), nodes.paragraph(text = str(e)))]

def setup(app):
app.add_directive('exec-mos', ExecMosDirective)
app.add_directive('omc-gnuplot', OMCGnuplotDirective)

0 comments on commit 9083bcb

Please sign in to comment.