Commit fa1c55ed authored by Theresa Pollinger's avatar Theresa Pollinger
Browse files

exastencils working for any unknown name

parent 7af43381
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -27,6 +27,9 @@ class ExaOutput:
if probname is None:
self.probname = self.username
else:
self.probname = probname
#output parameters which should also be made adaptable at some point
self.platform = OrderedDict([
("targetOS", "Linux"),
......@@ -73,8 +76,10 @@ class ExaOutput:
l1path = str(self.filespath.with_suffix('.exa1'))
domain_name = utf8tolatex(simdata["domain"]["name"], non_ascii_only=True, brackets=False)
op = utf8tolatex(simdata["pdes"]["pdes"][-1]["op"], non_ascii_only=True, brackets=False)
bcrhs = self.replace_boundary_x(simdata["bcs"]["bcs"][-1]["rhsstring_expanded"]) #TODO expand
pderhs = simdata["pdes"]["pdes"][-1]["rhsstring_expanded"]
bc_rhs = self.replace_boundary_x(simdata["bcs"]["bcs"][-1]["rhsstring_expanded"]) #TODO expand
pde_rhs = simdata["pdes"]["pdes"][-1]["rhsstring_expanded"]
unknowns = [*simdata["unknowns"]]
first_unknown = unknowns[0]
with open(l1path, 'w') as l1:
l1.write(
"/// inline knowledge \n"
......@@ -89,33 +94,33 @@ class ExaOutput:
" \n"
"Domain \Omega = ( " + str(simdata["domain"]["from"]) + ", " + str(simdata["domain"]["to"]) + " ) \n"
" \n"
"Field f@finest \in \Omega = " + pderhs + " \n"
"Field u \in \Omega = 0.0 \n"
"Field f@finest \in \Omega = " + pde_rhs + " \n"
"Field " + first_unknown + " \in \Omega = 0.0 \n"
" \n"
"Field u@finest \in \partial \Omega = " + bcrhs + " \n" #"sin ( 0.5 * PI * vf_boundaryCoord_x ) \n" #TODO expand
"Field u@(all but finest) \in \partial \Omega = 0.0 \n"
"Field " + first_unknown + "@finest \in \partial \Omega = " + bc_rhs + " \n" #"sin ( 0.5 * PI * vf_boundaryCoord_x ) \n" #TODO expand
"Field " + first_unknown + "@(all but finest) \in \partial \Omega = 0.0 \n"
" \n"
"Operator op = " + op + " // alt: - \partial_{xx} \n"
" \n"
"Equation uEq@finest op * u == f \n" #insert pde
"Equation uEq@(all but finest) op * u == 0.0 \n"
"Equation " + first_unknown + "Eq@finest op * " + first_unknown + " == f \n" #insert pde
"Equation " + first_unknown + "Eq@(all but finest) op * " + first_unknown + " == 0.0 \n"
" \n"
"/// configuration of inter-layer transformations \n"
" \n"
"DiscretizationHints { // alt: Discretize, L2Hint(s) \n"
" f on Node \n"
" u on Node \n"
" " + first_unknown + " on Node \n"
" \n"
" op on \Omega \n"
" \n"
" uEq \n"
" " + first_unknown + "Eq \n"
" \n"
" // paramters \n"
" discr_type = \"" + simdata["sim"]["type"] + "\" \n"
"} \n"
" \n"
"SolverHints { // alt: Solve, L3Hint(s) \n"
" generate solver for u in uEq \n"
" generate solver for " + first_unknown + " in " + first_unknown + "Eq \n"
" \n"
" // parameters \n"
" solver_targetResReduction = 1e-6 \n"
......@@ -124,7 +129,7 @@ class ExaOutput:
"ApplicationHints { // alt L4Hint(s) \n"
" // parameters \n"
" l4_genDefaultApplication = true \n"
" l4_defAppl_FieldToPrint = \"u\" \n" #TODO
" l4_defAppl_FieldToPrint = \"" + unknowns[0] + "\" \n" #TODO
"} \n"
)
......@@ -258,12 +263,12 @@ class ExaRunner:
print(out)
@lru_cache()
def load_data(self, data_name="u"): #TODO name of unknowns
def load_data(self, data_name="u"): # TODO more dimensions
import pandas as pd
data_path = self.exaout.exastencils_path.joinpath("generated").joinpath(self.exaout.probname).joinpath(data_name).with_suffix(".dat")
df = pd.read_csv(data_path, sep=' ', index_col=0)
try:
df.columns = ['u']
df.columns = [data_name]
except ValueError: # length mismatch because additional column of nans was read
df.columns = ['u', 'nan']
df.columns = [data_name, 'nan']
return df
......@@ -210,50 +210,52 @@ class Interview(MetaKernel):
def display_html(self, code=None):
# highlight some of the code entered and show line numbers (just to play around)
self.Display(HTML("""
<style type="text/css">
.styled-background { background-color: #ff7; }
</style>
<script>
if (typeof markedText !== 'undefined') {
markedText.clear();
}
IPython.notebook.select_prev()
var cell = IPython.notebook.get_selected_cell();
markedText = cell.code_mirror.markText({line: %s, col: %s},
{line: %s, col: %s},
{className: "styled-background"});
cell.show_line_numbers(1)
IPython.notebook.select_next()
</script>
""" % (1, 0, 3, 0)))
#self.Display(HTML("""
#<style type="text/css">
# .styled-background { background-color: #ff7; }
#</style>
#<script>
#if (typeof markedText !== 'undefined') {
# markedText.clear();
#}
#IPython.notebook.select_prev()
#var cell = IPython.notebook.get_selected_cell();
#markedText = cell.code_mirror.markText({line: %s, col: %s},
# {line: %s, col: %s},
# {className: "styled-background"});
#cell.show_line_numbers(1)
#IPython.notebook.select_next()
#</script>
# """ % (1, 0, 3, 0)))
output_notebook()
if code:
self.Display(HTML(code))
def display_tgview(self, args=''):
"""displays the theory graph viewer as html, cf. https://github.com/UniFormal/TGView/wiki/"""
args = args.replace("tgview ", '', 1).strip()
server_url = str(self.state_machine.mmtinterface.serverInstance)
args_dict = {
url_args_dict = {
"type": "thgraph",
}
args = args.replace("tgview ", '', 1).strip()
if args == '':
args_dict["graphdata"] = self.state_machine.mmtinterface.URIprefix + \
self.state_machine.mmtinterface.namespace + "?u"
url_args_dict["graphdata"] = self.state_machine.mmtinterface.URIprefix + \
self.state_machine.mmtinterface.namespace
else:
args_dict["graphdata"] = self.state_machine.mmtinterface.URIprefix + \
url_args_dict["graphdata"] = self.state_machine.mmtinterface.URIprefix + \
self.state_machine.mmtinterface.namespace + "?" + args
# if applicable, highlight the ephemeral parts https://github.com/UniFormal/TGView/issues/25
thynames = get_recursively(self.state_machine.simdata, "theoryname")
if thynames:
args_dict["highlight"] = ",".join(thynames)
url_args_dict["highlight"] = ",".join(thynames)
tgview_url = build_url(server_url, "graphs/tgview.html", args_dict=args_dict)
tgview_url = build_url(server_url, "graphs/tgview.html", args_dict=url_args_dict)
code = """
<iframe
......
......@@ -23,11 +23,10 @@ from lxml import etree
def start_mmt_server(port_number, mmtjar):
p = subprocess.run(["/usr/bin/java", "-jar", mmtjar, # "--file=server-interview.msl",
"server", "on", str(port_number),
"--keepalive"],
"server", "on", str(port_number), "--keepalive"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out = p.stdout
if p.returncode != 0 and p.returncode != 130:
if p.returncode != 0 and p.returncode != 130: # if not closed gracefully or through ctrl-c
raise MMTServerError("Server aborted, return code " + str(p.returncode) + ", " + str(out))
......@@ -38,8 +37,8 @@ def exit_mmt_server(port_number, mmtjar, timeout=3.0):
if completed.stdout != None and "(Connection refused)" in str(completed.stdout):
if timeout > 0.0:
exit_mmt_server(port_number, mmtjar, timeout - 0.1)
else:
raise MMTServerError("unable to exit mmt server")
# else:
# raise MMTServerError("unable to exit mmt server")
def start_mmt_extension(port_number, mmtjar, timeout=3.0):
......@@ -194,6 +193,9 @@ class MMTInterface:
def __exit__(self, exc_type, exc_val, exc_tb):
self.exit_mmt()
def __del__(self):
self.exit_mmt()
def exit_mmt(self):
exit_mmt_server(self.port_number, self.mmt_jar)
......
......@@ -131,16 +131,16 @@ class PDE_States:
])
# to include all the necessary theories every time
self.bgthys = OrderedDict([
('domain', ["mInterval", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),
('domain', ["mInterval", "http://mathhub.info/MitM/smglom/arithmetics?RealArithmetics"]),
# new: RealArithmetics
('unknowns', ["http://mathhub.info/MitM/Foundation?Strings", "ephdomain",
"http://mathhub.info/MitM/smglom/calculus?higherderivative"]),
('parameters', ["http://mathhub.info/MitM/smglom/arithmetics?realarith", "ephdomain",
('unknowns', ["http://mathhub.info/MitM/Foundation?Strings", "ephdomain"]),
#"http://mathhub.info/MitM/smglom/calculus?higherderivative"]),
('parameters', ["http://mathhub.info/MitM/smglom/arithmetics?RealArithmetics", "ephdomain",
"http://mathhub.info/MitM/Foundation?Math"]),
('pdes', ["mDifferentialOperators"]), # +params, unknowns,
('bcs',
["ephdomain", "mLinearity",
"http://mathhub.info/MitM/smglom/arithmetics?realarith"]), # +params, unknowns, pdes, bctypes
"http://mathhub.info/MitM/smglom/arithmetics?RealArithmetics"]), # +params, unknowns, pdes, bctypes
('props',
["mLinearity",
"http://mathhub.info/MitM/Foundation?Strings"]), # +bcs, pde
......@@ -277,6 +277,8 @@ class PDE_States:
'sim': {},
}
self.exaout = None
self.mmtinterface = MMTInterface()
#with MMTInterface() as self.mmtinterface:
"""Variables to signal callbacks depending on yes/no prompts"""
......@@ -304,7 +306,7 @@ class PDE_States:
self.poutput("")
self.poutput("To get explanations, enter \"explain <optional keyword>\". ")
self.poutput("To see a recap of what we know so far, enter \"recap <optional keyword>\". ")
self.poutput("To interact with the current theory graph, enter \"tgwiev <optional theory name>\". ")
self.poutput("To interactively visualize ther current theory graph, enter \"tgwiev <optional theory name>\". ")
self.poutput("Otherwise, you can always try and use LaTeX-type input.")
self.poutput("")
self.poutput("You can inspect the currently loaded MMT theories under " + self.mmtinterface.serverInstance)
......@@ -800,21 +802,23 @@ class PDE_States:
##### for state sim
def sim_begin(self):
self.please_prompt("Would you like to try and solve the PDE using the Finite Difference Method in ExaStencils?"
self.please_prompt("Would you like to try and solve the PDE using the Finite Difference Method in ExaStencils? "
"If yes, you can provide a configuration name, or we'll just use your name.",
self.sim_ok_fd)
if_yes=self.sim_ok_fd, if_no=None, pass_other=True)
def sim_handle_input(self, userstring):
self.please_prompt("Would you like to try and solve the PDE using the Finite Difference Method in ExaStencils?"
"If yes, you can provide a configuration name, or we'll just use your name.",
self.sim_ok_fd)
self.sim_exit(userstring)
def sim_exit(self):
def sim_ok_fd(self):
self.sim_exit()
def sim_exit(self, problem_name=None):
self.simdata["sim"]["type"] = "FiniteDifferences"
# generate output
exaout = ExaOutput(self.simdata)
self.exaout = ExaOutput(self.simdata, getpass.getuser(), problem_name)
print("Generated ExaStencils input; running ExaStencils")
# generate and run simulation
runner = ExaRunner(exaout)
runner = ExaRunner(self.exaout)
runner.run_exastencils()
print("Ran ExaStencils; preparing visualization")
# output
......@@ -824,18 +828,19 @@ class PDE_States:
# cf. nbviewer.jupyter.org/github/bokeh/bokeh-notebooks/blob/master/tutorial/01 - Basic Plotting.ipynb
def display_result_as_bokeh(self):
unknowns = [*self.simdata["unknowns"]]
# create a new plot with default tools, using figure
p = figure(plot_width=1000, plot_height=400)
runner = ExaRunner(ExaOutput())
data = runner.load_data("u")
#source = ColumnDataSource(data=data)
source = ColumnDataSource(data=dict(x=[], u=[]))
runner = ExaRunner(self.exaout)
data = runner.load_data(unknowns[0]) # TODO more dimensions
source = ColumnDataSource(data=data)
source.data = source.from_df(data)
source.add(data.index, 'index')
# add a circle renderer with a size, color, and alpha
p.circle(x='index', y='u', size=2, line_color="navy", fill_color="orange", fill_alpha=0.5, source=source)
p.circle(x='index', y=unknowns[0], size=2, line_color="navy", fill_color="orange", fill_alpha=0.5, source=source)
#show(p)
output_notebook()
......@@ -843,17 +848,11 @@ class PDE_States:
self.display_html(file_html(p, CDN, "my plot")) # show the results
# using JS requires jupyter widgets extension
#script, div = components(p)
#div = notebook_div(p)
#self.Display(Javascript(script + div)) # show the results
def sim_ok_fd(self):
self.simdata["sim"]["type"] = "FiniteDifferences"
self.sim_exit()
# script, div = components(p)
# div = notebook_div(p)
# self.Display(Javascript(script + div)) # show the results
#### functions for user interaction
# functions for user interaction
def obviously_stupid_input(self):
self.poutput("Trying to be funny, huh?")
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment