interview.py 52.9 KB
Newer Older
Theresa Pollinger's avatar
Theresa Pollinger committed
1
2
#!/usr/bin/env python3

3
# http://cmd2.readthedocs.io
Theresa Pollinger's avatar
Theresa Pollinger committed
4
import cmd2 as cmd
5
# https://github.com/pytransitions/transitions
Theresa Pollinger's avatar
Theresa Pollinger committed
6
7
from transitions import Machine, State
from collections import OrderedDict
8
9
# strings:
# http://mattoc.com/python-yes-no-prompt-cli.html
Theresa Pollinger's avatar
Theresa Pollinger committed
10
11
from distutils.util import strtobool
from pathlib import Path
12
# https://github.com/phfaist/pylatexenc for directly converting Latex commands to unicode
Theresa Pollinger's avatar
Theresa Pollinger committed
13
14
15
16
17
18
19
from pylatexenc.latex2text import LatexNodes2Text
import pyparsing as pp
import re

from exaoutput import ExaOutput
from mmtinterface import *

20

21
22
23
class InterviewError(Exception):
    def __init__(self, err):
        self.error = err
24
        super(InterviewError, self).__init__("Interview error: " + str(self.error))
25

26

27
28
29
30
31
32
33
34
35
36
def means_no(answer):
    try:
        ret = strtobool(answer)
        if ret == False:
            return True
    except ValueError:
        return False
    return False


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
###For the part of the simdata whose contents will be cleaned up if there was an error
###to be used in with statements
class CriticalSubdict():
    def __init__(self, subdict):
        self.subdict = subdict
        self.initial_subdict = self.subdict.copy()

    def __enter__(self):
        return self.subdict

    def __exit__(self, type, value, traceback):
        if type is not None:
            #restore the initial state
            self.subdict.clear()
            for key in self.initial_subdict:
                self.subdict[key] = self.initial_subdict[key]
            print(value)
            if isinstance(value, MMTServerError) or isinstance(value, InterviewError):
                self.please_repeat(value)
56
                return True
57
58
59
60
61
62
63
64
65
            else:
                return False
        return True

    def please_repeat(self, moreinfo=None):
        append = ""
        if moreinfo:
            append = "\nDetails: " + moreinfo
        print("I did not catch that. Could you please rephrase?" + append)
Theresa Pollinger's avatar
Theresa Pollinger committed
66

67
68
69
70

# This "main class" is two things: a REPL loop, by subclassing the cmd2 Cmd class
# and a state machine as given by the pytransitions package
class Interview(cmd.Cmd):
Theresa Pollinger's avatar
Theresa Pollinger committed
71
    def __init__(self, *args, **kwargs):
72
        # just act like we were getting the right replies from MMT
73
        self.cheating = True
Theresa Pollinger's avatar
Theresa Pollinger committed
74
75
76
        # initialize legal characters for cmd
        self.legalChars = u'!#$%.:;?@_-<>' + pp.printables + pp.alphas8bit + pp.punc8bit
        # TODO why does "<" not show?
77
78
        # allow all useful unicode characters to be used, and some more
        for i in range(0x20, 0x2E7F):
Theresa Pollinger's avatar
Theresa Pollinger committed
79
80
81
82
83
84
85
            self.legalChars += chr(i)

        # call cmd constructor
        super(Interview, self).__init__(*args, **kwargs)

        # Initialize a state machine
        states = [
86
            # State('greeting'),
Theresa Pollinger's avatar
Theresa Pollinger committed
87
88
89
90
91
            State('dimensions', on_enter=['dimensions_begin']),
            State('domain', on_enter=['domain_begin'], on_exit=['domain_exit']),
            State('unknowns', on_enter=['unknowns_begin'], on_exit=['unknowns_exit']),
            State('parameters', on_enter=['parameters_begin'], on_exit=['parameters_exit']),
            State('pdes', on_enter=['pdes_begin'], on_exit=['pdes_exit']),
92
            State('bcs', on_enter=['bcs_begin'], on_exit=['bcs_exit']),
93
94
            State('props', on_enter=['props_begin'], on_exit=['props_exit']),
            State('sim', on_enter=['sim_begin'], on_exit=['sim_exit']),
Theresa Pollinger's avatar
Theresa Pollinger committed
95
96
97
98
        ]
        states.reverse()
        self.machine = Machine(model=self, states=states, initial=states[-1], after_state_change='update_prompt')
        # this is why we were reverting the states => can always go back
99
100
101
102
103
104
105
106
107
108
109
110
        self.machine.add_ordered_transitions(
            trigger='last_state')  # TODO do something to avoid going back from the first state
        # self.to_dimensions()
        # self.machine.add_transition(trigger='greeting_over', source='greeting', dest='dimensions')
        self.machine.add_transition(trigger='dimensions_parsed', source='dimensions', dest='domain',
                                    before='print_empty_line')
        self.machine.add_transition(trigger='domain_parsed', source='domain', dest='unknowns',
                                    before='print_empty_line')
        self.machine.add_transition(trigger='unknowns_parsed', source='unknowns', dest='parameters',
                                    after='print_empty_line')
        self.machine.add_transition(trigger='parameters_parsed', source='parameters', dest='pdes',
                                    after='print_empty_line')
Theresa Pollinger's avatar
Theresa Pollinger committed
111
112
        self.machine.add_transition(trigger='pdes_parsed', source='pdes', dest='bcs', before='print_empty_line')
        self.machine.add_transition(trigger='bcs_parsed', source='bcs', dest='sim', before='print_empty_line')
113
        #self.machine.add_transition(trigger='props_parsed', source='props', dest='sim', before='print_empty_line')#TODO props
114
        self.machine.add_transition(trigger='sim_finished', source='sim', dest='sim', before='print_empty_line')
Theresa Pollinger's avatar
Theresa Pollinger committed
115
116

        # Initialize cmd member variables
117
        self.myname = 'TheInterview'
Theresa Pollinger's avatar
Theresa Pollinger committed
118
119
        self.username = 'user'
        self.intro = "Hello, " + self.username + "! I am " + self.myname + ", your partial differential equations and simulations expert. " \
120
                                                                           "Let's set up a simulation together.\n" \
121
                                                                           "How many dimensions does your model have?"
Theresa Pollinger's avatar
Theresa Pollinger committed
122

123
        # define what happens when input is received in a certain state
Theresa Pollinger's avatar
Theresa Pollinger committed
124
125
126
127
        self.stateDependentInputHandling = {
            'dimensions': self.dimensions_handle_input,
            'domain': self.domain_handle_input,
            'unknowns': self.unknowns_handle_input,
128
            'parameters': self.parameters_handle_input,
129
130
            'pdes': self.pdes_handle_input,
            'bcs': self.bcs_handle_input,
131
            'props': self.props_handle_input,
132
            'sim': self.sim_handle_input,
Theresa Pollinger's avatar
Theresa Pollinger committed
133
134
135
136
        }

        self.mmtinterface = MMTInterface()

137
        # for ladder-like views
Theresa Pollinger's avatar
Theresa Pollinger committed
138
        self.viewfrom = OrderedDict([
139
140
141
142
143
            ('domain', "mDomain"),
            ('unknowns', "mUnknown"),
            ('parameters', "mParameter"),
            ('pdes', "mPDE"),
            ('bcs', "mBCsRequired"),
144
145
            ('props', "mEllipticLinearDirichletBoundaryValueProblem"),
            ('sim', "mSolvability"),
Theresa Pollinger's avatar
Theresa Pollinger committed
146
147
148
        ])
        # to include all the necessary theories every time
        self.bgthys = OrderedDict([
149
            ('domain', ["mInterval", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),
150
151
152
            # new: RealArithmetics
            ('unknowns', ["http://mathhub.info/MitM/Foundation?Strings", "ephdomain",
                          "http://mathhub.info/MitM/smglom/calculus?higherderivative"]),
153
154
            ('parameters', ["http://mathhub.info/MitM/smglom/arithmetics?realarith", "ephdomain",
                            "http://mathhub.info/MitM/Foundation?Math"]),
155
            ('pdes', ["mDifferentialOperators"]),#+params, unknowns,
156
            ('bcs',
157
158
             ["ephdomain", "mLinearity",
              "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),#+params, unknowns, pdes, bctypes
159
            ('props',
160
161
             ["mLinearity",
              "http://mathhub.info/MitM/Foundation?Strings"]), #+bcs, pde
162
163
            ('sim',
             ["http://mathhub.info/MitM/Foundation?Strings"]), #+props
Theresa Pollinger's avatar
Theresa Pollinger committed
164
165
        ])

166
        # the things we'd like to find out
Theresa Pollinger's avatar
Theresa Pollinger committed
167
        self.simdata = {
168
169
170
171
172
173
174
175
            "num_dimensions": None,
            "domain": {
                "name": None,
                "theoryname": None,
                # "viewname" : None,
                "axes": OrderedDict(),
                "from": None,
                "to": None,
Theresa Pollinger's avatar
Theresa Pollinger committed
176
            },
177
            "unknowns": OrderedDict(),
178
            "parameters": OrderedDict(),
179
            "pdes": {
180
                #               "theoryname": None,
181
                "pdes": [],
Theresa Pollinger's avatar
Theresa Pollinger committed
182
            },
183
184
185
186
            "bcs": {
                "theoryname": None,
                "bcs": None,
            },
187
188
189
190
191
192
            "props": {

            },
            "sim" : {
                "type": None,
            },
Theresa Pollinger's avatar
Theresa Pollinger committed
193
194
195
196
197
198
        }

        axes = OrderedDict([
            ("x_1", "[0;1]"),
        ])
        self.examplesimdata = {
199
200
201
202
203
            "num_dimensions": 1,
            "domain": {
                "name": "Ω",
                "theoryname": "Omega",
                "axes": axes,  # names and intervals
204
205
                "from": 0.0,
                "to": 1.0,
206
207
208
209
210
            },
            "unknowns": {  # names and theorynames #TODO OrderedDict
                "u": {
                    "theoryname": "u",
                    "string": "u : Ω → ℝ",
Theresa Pollinger's avatar
Theresa Pollinger committed
211
                },
212
213
214
215
216
            },
            "parameters": {  # names and theorynames
                "μ": {
                    "theoryname": "mu",
                    "string": "μ : ℝ = 1",
Theresa Pollinger's avatar
Theresa Pollinger committed
217
                },
218
219
220
                "f": {
                    "theoryname": "f",
                    "string": "f : Ω → ℝ = [x] x ⋅ x",
Theresa Pollinger's avatar
Theresa Pollinger committed
221
222
                },
            },
223
224
            "pdes": {
                "pdes": [
225
                    {
226
                        "theoryname": "pde1",
227
228
229
230
231
232
233
                        "string": "μ ∆u = f(x)",  # TODO use function arithmetic
                        'lhsstring': 'μ Δu ',
                        'rhsstring': 'f(x)',
                        'op': 'Δ',
                        'lhsparsestring': ' [ anyu : Ω → ℝ ] Δ anyu ',
                        'rhsparsestring': ' [ x : Ω ]  f(x)',
                        # this is more of a wish list... cf https://github.com/UniFormal/MMT/issues/295
234
235
236
                        "expanded": "μ d²/dx_1² u = f(x_1)",
                        "order_in_unknown": {
                            "u": 2,
Theresa Pollinger's avatar
Theresa Pollinger committed
237
                        },
238
                    },
Theresa Pollinger's avatar
Theresa Pollinger committed
239
                ],
240
            },
241
242
243
244
245
246
247
            "bcs": {
                "theoryname": "ephbcs",
                "bcs": [
                    {
                        "name": "bc1",
                        "type": "Dirichlet",
                        "string": "u (0) = x_1**2",
248
                        "on": "0",
249
250
251
252
253
                    },
                    {
                        "name": "bc2",
                        "type": "Dirichlet",
                        "string": "u (1) = x_1**2",
254
                        "on": "1",
255
256
257
                    },
                ],
            },
258
259
260
261
262
263
264
265
266
267
268
269
270
            "props": {
                "theoryname": "ephboundaryvalueproblem",
                "ops": [
                    {
                        "name": "op1",
                        "linear": True, #or false or unknown
                        "props": ["elliptic"]
                    }
                ]
            },
            "sim":{
                "type": "FD",
            },
Theresa Pollinger's avatar
Theresa Pollinger committed
271
272
        }

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        self.testsimdata = {
            'num_dimensions': 1,
            'domain': {'name': 'Ω', 'theoryname': 'ephdomain', 'axes': OrderedDict([('x_1', '[0.0;1.0]')]),
                        'from': 0.0, 'to': 1.0, 'boundary_name': 'Ω', 'viewname': 'ephdomainASmDomain'},
            'unknowns': OrderedDict([('u', {'theoryname': 'u', 'string': 'u : Ω → ℝ', 'type': 'Ω → ℝ', 'codomain': 'ℝ',
                                             'viewname': 'uASmUnknown'})]),
            'parameters': {
                'f': {'theoryname': 'f', 'string': 'f = x', 'parsestring': 'f = [ x : Ω] x', 'type': '{ : Ω } Ω',
                      'viewname': 'fASmParameter'}},
            'pdes': {'pdes': [
                {'theoryname': 'ephpde1', 'string': 'Δu = 0.0', 'lhsstring': 'Δu', 'rhsstring': '0.0',
                 'viewname': 'ephpde1ASmPDE', 'op': 'Δ', 'lhsparsestring': ' [ anyu : Ω → ℝ ] Δ anyu ',
                 'rhsparsestring': ' [ x : Ω ]  0.0'}]},
            'bcs': {'theoryname': 'ephbcs', 'bcs': [
                {'name': 'bc0', 'string': 'u = f', 'lhsstring': 'u ', 'rhsstring': ' f', 'type': ('Dirichlet',),
                 'on': ('x',), 'measure': (2,)}], 'bctypes': {'theoryname': 'uBCTypes'},
                                                                 'viewname': 'ephbcsASmBCsRequired',
                                                                 'measure_given': 2},
            'props': {},
            'sim': {},
        }
Theresa Pollinger's avatar
Theresa Pollinger committed
294
        self.exaout = ExaOutput()
295
        # self.greeting()
Theresa Pollinger's avatar
Theresa Pollinger committed
296
297
        self.update_prompt()

298
299
300
301
        self.prompted = False
        self.if_yes = None
        self.if_no = None

302
    ##### for state dimensions
Theresa Pollinger's avatar
Theresa Pollinger committed
303
    def dimensions_begin(self):
304
        self.poutput("How many dimensions does your model have?")
305
        self.poutput("I am just assuming it's 1, since that is all we can currently handle.")  # TODO
Theresa Pollinger's avatar
Theresa Pollinger committed
306
307
308
309
        self.simdata["num_dimensions"] = 1
        self.dimensions_parsed()

    def dimensions_handle_input(self, userstring):
310
311
312
313
        # reply_diffops = self.mmtinterface.query_for("mDifferentialOperators")
        # self.poutput(reply_diffops.tostring())
        # self.poutput(element_to_string(reply_diffops.getConstant("derivative")))
        # self.poutput(element_to_string(reply_diffops.getConstant("laplace_operator")))
Theresa Pollinger's avatar
Theresa Pollinger committed
314
315
316
        try:
            numdim = int(userstring)
        except ValueError:
317
            self.poutput("Please enter a number.")
Theresa Pollinger's avatar
Theresa Pollinger committed
318
319
320
            return
        if numdim < 1:
            self.obviously_stupid_input()
321
            self.exaout.create_output(self.testsimdata)
Theresa Pollinger's avatar
Theresa Pollinger committed
322
            self.dimensions_begin()
323
        elif numdim == 1:  # or self.numdim == 2:
Theresa Pollinger's avatar
Theresa Pollinger committed
324
325
326
            self.simdata["num_dimensions"] = numdim
            self.dimensions_parsed()
        else:
327
            self.poutput(
328
                "Sorry, cannot handle " + str(numdim) + " dimensions as of now. Please try less than that.")
Theresa Pollinger's avatar
Theresa Pollinger committed
329

330
    ##### for state domain
Theresa Pollinger's avatar
Theresa Pollinger committed
331
    def domain_begin(self):
332
        self.poutput("What is the domain you would like to simulate for?     Ω : type ❘ = [?;?], e.g. Ω = [0.0;1.0]")
333
        self.poutput("By the way, you can always try and use LaTeX-type input.")
Theresa Pollinger's avatar
Theresa Pollinger committed
334
335
336
337
        self.simdata[self.state]["axes"] = OrderedDict()
        self.domain_mmt_preamble()

    def domain_handle_input(self, userstring):
338
        domain_name = get_first_word(userstring)
339
340
341
        # subdict = self.simdata[self.state]
        with CriticalSubdict(self.simdata[self.state]) as subdict:
            parsestring = userstring
342
            mmtreply = self.mmtinterface.mmt_new_decl(domain_name, subdict["theoryname"], parsestring)
343
344
            mmttype = self.mmtinterface.mmt_infer_type(subdict["theoryname"], domain_name)
            if mmttype.inferred_type_to_string() != "type":
345
                raise InterviewError("This seems to not be a type. It should be!")
346
            result = self.mmtinterface.query_for(subdict["theoryname"])  # if not self.cheating else
Theresa Pollinger's avatar
Theresa Pollinger committed
347
            #print(result.tostring())
348
            subdict["name"] = domain_name
Theresa Pollinger's avatar
Theresa Pollinger committed
349
            (fro, to) = mmtreply.getIntervalBoundaries(result, domain_name) #if not self.cheating else (0.0, 1.0)  # todo make work again
350
351
            subdict["axes"]["x_1"] = "[" + str(fro) + ";" + str(to) + "]"
            (subdict["from"], subdict["to"]) = (fro, to)
352
353
354
355

            self.poutput("we will just assume that the variable is called x for now.")
            # mmtreply = self.mmtinterface.mmt_new_decl(domain_name, subdict["theoryname"], "x : " + domain_name)
            self.trigger('domain_parsed')
Theresa Pollinger's avatar
Theresa Pollinger committed
356
357
358
359
360

    def domain_exit(self):
        self.domain_mmt_postamble()

    def domain_mmt_preamble(self):
361
362
363
        # set the current MMT theoryname for parsing the input TODO use right dimension
        self.simdata[self.state]["theoryname"] = "ephdomain"
        self.new_theory(self.simdata[self.state]["theoryname"])
364
        # (ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
365
366

    def domain_mmt_postamble(self):
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        with CriticalSubdict(self.simdata[self.state]) as subdict:
            subdict["boundary_name"] = subdict["name"] #todo
            if not self.cheating:
                self.mmtinterface.mmt_new_decl('mydomainpred', subdict["theoryname"],
                                               "myDomainPred = " + subdict["name"] + ".interval_pred")
                self.mmtinterface.mmt_new_decl('mydomain', subdict["theoryname"],
                                               "myDomain = intervalType " + subdict["name"])
                # and a view to understand our interval as a domain -- view ephDomainAsDomain : ?GeneralDomains → ?ephDomain =
                self.new_view(subdict)
                self.mmtinterface.mmt_new_decl('Vecspace', subdict["viewname"],
                                               "Vecspace = real_lit")  # TODO adjust for higher dimensions
                self.mmtinterface.mmt_new_decl('DomainPred', subdict["viewname"], "DomainPred = " + subdict[
                    "name"] + ".interval_pred")  # the . is unbound, apparently...
            else:
                self.new_view(subdict)
                self.mmtinterface.mmt_new_decl('dom', subdict["viewname"],
                                               "domain = " + subdict["name"])
                self.mmtinterface.mmt_new_decl('boun', subdict["viewname"],
                                               "boundary = " + subdict["boundary_name"])
Theresa Pollinger's avatar
Theresa Pollinger committed
386

387
    ##### for state unknowns
Theresa Pollinger's avatar
Theresa Pollinger committed
388
    def unknowns_begin(self):
389
390
        self.poutput("Which variable(s) are you looking for? / What are the unknowns in your model?  u : " +
                     self.simdata["domain"]["name"] + " → ??,  e.g., u : " + self.simdata["domain"]["name"] + " → ℝ ?")
Theresa Pollinger's avatar
Theresa Pollinger committed
391
392
393
        self.simdata["unknowns"] = OrderedDict()

    def unknowns_handle_input(self, userstring):
394
        unknown_name = get_first_word(userstring)
Theresa Pollinger's avatar
Theresa Pollinger committed
395
        # replace interval with domain
396
397
398
        parsestring = (
            userstring.replace(self.simdata["domain"]["name"],
                               "pred myDomainPred") if not self.cheating else userstring)
399

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        with CriticalSubdict(self.simdata[self.state]) as usubdict:
            # create mmt theory with includes
            once = self.new_theory(unknown_name)
            # self.include_in(unknown_name, self.simdata["domain"]["theoryname"])

            # and one to "throw away" to infer the type
            self.new_theory(unknown_name + "_to_go_to_trash")
            test = self.mmtinterface.mmt_new_decl(unknown_name, unknown_name + "_to_go_to_trash",
                                                  parsestring)

            type = self.get_inferred_type(unknown_name + "_to_go_to_trash", unknown_name)
            usubdict[unknown_name] = {
                "theoryname": unknown_name,
                "string": parsestring,
                "type": type,
415
                "codomain": type.replace(self.simdata["domain"]["name"] + " →", "", 1).strip(),
416
417
418
419
420
421
422
423
424
425
426
427
428
            }
            with CriticalSubdict(self.simdata["unknowns"][unknown_name]) as subdict:
                if self.mmtinterface.query_for(unknown_name + "_to_go_to_trash").hasDefinition(unknown_name):
                    raise InterviewError("Unknowns cannot be defined!")
                if not type_is_function_from(subdict["type"], self.simdata["domain"]["name"]):
                    raise InterviewError("Unknown should be a function on " + self.simdata["domain"]["name"] + "!")

                # add unknown's type as constant
                twice = self.mmtinterface.mmt_new_decl(unknown_name, subdict["theoryname"],
                                                       "myUnkType = " + subdict["type"])
                twice = (self.mmtinterface.mmt_new_decl('diffable', subdict["theoryname"],
                                                        "anyuwillbediffable : {u : myUnkType} ⊦ twodiff u ") if not self.cheating else twice)
                self.new_view(subdict)
429
430
                self.mmtinterface.mmt_new_decl("codomain", subdict["viewname"], "ucodomain = " + subdict["codomain"])
                self.mmtinterface.mmt_new_decl("unktype", subdict["viewname"], "unknowntype = myUnkType")
431
                self.poutput("Ok, " + userstring)
432
433
                #if self.please_prompt("Are these all the unknowns?"): #TODO
                self.trigger('unknowns_parsed')
Theresa Pollinger's avatar
Theresa Pollinger committed
434
435
436

    def unknowns_exit(self):
        for unknown in self.simdata["unknowns"]:
437
            self.poutput(self.simdata["unknowns"][unknown]["string"])
Theresa Pollinger's avatar
Theresa Pollinger committed
438

439
    ##### for state parameters
Theresa Pollinger's avatar
Theresa Pollinger committed
440
    def parameters_begin(self):
441
442
        self.poutput(
            "Would you like to name additional parameters like constants or functions (that are independent of your unknowns)?  c : ℝ = ? or f : Ω → ℝ = ?")  # ℝ
443
        self.simdata["parameters"] = OrderedDict()
Theresa Pollinger's avatar
Theresa Pollinger committed
444
445

    def parameters_handle_input(self, userstring):
446
        # self.poutput ("parameterinput "+ userstring)
447
        if means_no(userstring):
Theresa Pollinger's avatar
Theresa Pollinger committed
448
449
450
            self.trigger('parameters_parsed')
            return

451
        parameter_name = get_first_word(userstring)
452
453
454
455
456
457
458
459
460
461
        self.simdata["parameters"][parameter_name] = {}
        with CriticalSubdict(self.simdata["parameters"][parameter_name]) as subdict:
            # create mmt theory
            self.new_theory(parameter_name)
            # we might need the other parameters created so far, so use them
            for otherparamentry in get_recursively(self.simdata["parameters"], "theoryname"):
                self.include_in(parameter_name, otherparamentry)

            # sanitize userstring - check if this works for all cases
            parsestring = add_ods(userstring)
462
463
            if parsestring.startswith(parameter_name + "(") or parsestring.startswith(parameter_name + " ("):#todo make smarter for more dimensions
               parsestring = remove_apply_brackets(parsestring)
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
            parsestring = functionize(parsestring, self.simdata["domain"]["name"])
            # self.poutput(parsestring)
            reply_pconstant = self.mmtinterface.mmt_new_decl("param", parameter_name, parsestring)
            reply_pconstant = self.mmtinterface.query_for(parameter_name)
            subdict["theoryname"] = parameter_name
            subdict["string"] = userstring
            subdict["parsestring"] = parsestring
            subdict["type"] = self.get_inferred_type(parameter_name, parameter_name)

            # if not reply_pconstant.hasDefinition(parameter_name) and not self.cheating:
            #    InterviewError("Please define this parameter.")

            # create view
            self.new_view(subdict)
            self.mmtinterface.mmt_new_decl("ptype", subdict["viewname"],
                                                                         "ptype = " + subdict["type"])
            self.mmtinterface.mmt_new_decl("param", subdict["viewname"],
                                                                         "param = " + parameter_name)
            self.poutput("Ok, " + parsestring)
483
            self.please_prompt("Are these all the parameters?", lambda: self.trigger('parameters_parsed'))
Theresa Pollinger's avatar
Theresa Pollinger committed
484
485

    def parameters_exit(self):
486
        # print(str(self.simdata["parameters"]))
Theresa Pollinger's avatar
Theresa Pollinger committed
487
        for parameter in self.simdata["parameters"]:
488
            self.poutput(self.simdata["parameters"][parameter]["string"])
Theresa Pollinger's avatar
Theresa Pollinger committed
489

490
    ##### for state pdes
Theresa Pollinger's avatar
Theresa Pollinger committed
491
    def pdes_begin(self):
492
        self.poutput(
493
            "Let's talk about your partial differential equation(s). What do they look like? Δu = 0.0, or laplace_operator Ω ℝ u = f ?")
Theresa Pollinger's avatar
Theresa Pollinger committed
494
495
496
        self.simdata["pdes"]["pdes"] = []

    def pdes_handle_input(self, userstring):
497
        self.simdata["pdes"]["pdes"].append({})
498
        with CriticalSubdict(self.simdata["pdes"]["pdes"][-1]) as subdict:
499
            subdict["theoryname"] = "ephpde" + str(len(self.simdata["pdes"]["pdes"]))
500
501
502
503
504
505
            self.new_theory(subdict["theoryname"])

            # TODO use symbolic computation to order into LHS and RHS
            parts = re.split("=", userstring)

            if len(parts) is not 2:
506
                raise InterviewError("This does not look like an equation.")
507
508
509

            # store the info
            subdict["string"] = userstring
510
511
512
            subdict["lhsstring"] = parts[0].strip()
            subdict["rhsstring"] = parts[1].strip()#TODO expand
            subdict["rhsstring_expanded"] = self.try_expand(subdict["rhsstring"])
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531

            # to make the left-hand side a function on x, place " [ variablename : domainname ] " in front
            if parts[0].find("x") > -1:
                parts[0] = " [ x : " + self.simdata["domain"]["name"] + " ] " + parts[0]
            # right-hand side: infer type, make function if not one yet
            if not type_is_function_from(self.get_inferred_type(subdict["theoryname"], parts[1]),
                                         self.simdata["domain"]["name"]):
                parts[1] = " [ x : " + self.simdata["domain"]["name"] + " ] " + parts[1]

            # in lhs replace all unknown names used by more generic ones and add lambda clause in front
            for unkname in get_recursively(self.simdata["unknowns"], "theoryname"):
                parts[0] = parts[0].replace(unkname, " any" + unkname)
                parts[0] = " [ any" + unkname + " : " + self.simdata["unknowns"][unkname]["type"] + " ] " + parts[0]
                # and include the original ones as theory
                inc = self.include_in(subdict["theoryname"], unkname)
            for parname in get_recursively(self.simdata["parameters"], "theoryname"):
                inc = self.include_in(subdict["theoryname"], parname)

            # send declarations to mmt
532
533
            self.mmtinterface.mmt_new_decl("lhs", subdict["theoryname"], " mylhs = " + parts[0])
            reply_lhsconstant = self.mmtinterface.query_for(subdict["theoryname"])
534

535
536
            self.mmtinterface.mmt_new_decl("rhs", subdict["theoryname"], " myrhs = " + parts[1])
            reply_rhsconstant = self.mmtinterface.query_for(subdict["theoryname"])
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555

            # create view
            self.new_view(subdict)
            ltype = self.get_inferred_type(subdict["theoryname"], "mylhs")
            eqtype = get_last_type(ltype)
            rtype = self.get_inferred_type(subdict["theoryname"], "myrhs")
            self.mmtinterface.mmt_new_decl("eqtype", subdict["viewname"],
                                                                     "eqtype = " + eqtype)
            self.mmtinterface.mmt_new_decl("lhs", subdict["viewname"],
                                                                     "lhs = " + "mylhs")
            self.mmtinterface.mmt_new_decl("rhs", subdict["viewname"],
                                                                     "rhs = " + "myrhs")
            self.mmtinterface.mmt_new_decl("pde", subdict["viewname"],
                                                                     "pde = " + "[u](mylhs u) funcEq myrhs")

            reply = self.mmtinterface.query_for(subdict["theoryname"])

            for unkname in get_recursively(self.simdata["unknowns"], "theoryname"):
                op = subdict["lhsstring"].replace(unkname, "")
556
                op = op.strip()
557
558
559
560
561
562
563

            # store the info
            subdict["op"] = op
            subdict["lhsparsestring"] = parts[0]
            subdict["rhsparsestring"] = parts[1]

            # TODO query number of effective pdes and unknowns from mmt for higher dimensional PDEs
564
            # => can assume each to be ==1 for now
565
            numpdesgiven = len(self.simdata["pdes"]["pdes"])
566
            self.poutput("Ok, " + reply.tostring())
Theresa Pollinger's avatar
Theresa Pollinger committed
567
568
569
570
            if numpdesgiven == len(self.simdata["unknowns"]):
                self.trigger('pdes_parsed')
            elif numpdesgiven > len(self.simdata["unknowns"]):
                self.poutput("now that's too many PDEs. Please go back and add more unknowns.")
571
572
            else:
                self.poutput("More PDEs, please!")
Theresa Pollinger's avatar
Theresa Pollinger committed
573
574

    def pdes_exit(self):
575
        self.poutput("These are all the PDEs needed.")
Theresa Pollinger's avatar
Theresa Pollinger committed
576

577
    ##### for state bcs
578
    def bcs_begin(self):
579
580
        self.poutput("Let's discuss your boundary conditions. "
                     "What do they look like? u(x) = f(x) or u(" + str(self.simdata["domain"]["to"]) + ") = \\alpha ?") #TODO remove square brakcets
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
        bctypetheoryname = self.redefine_bcs()
        with CriticalSubdict(self.simdata["bcs"]) as subdict:
            subdict["theoryname"] = "ephbcs"
            subdict["bcs"] = []
            self.new_theory(subdict["theoryname"])
            # apparently, need to include everything explicitly so that view works
            for unknownentry in get_recursively(self.simdata["unknowns"], "theoryname"):
                self.include_in(subdict["theoryname"], unknownentry)
            for paramentry in get_recursively(self.simdata["parameters"], "theoryname"):
                self.include_in(subdict["theoryname"], paramentry)
            for pdeentry in get_recursively(self.simdata["pdes"], "theoryname"):
                self.include_in(subdict["theoryname"], pdeentry)
            self.include_in(subdict["theoryname"], bctypetheoryname)
            self.new_view(subdict)
            subdict["measure_given"] = 0
596
597

    def bcs_handle_input(self, userstring):
598
        with CriticalSubdict(self.simdata["bcs"]) as subdict:
599
600
601
602
603
604
605
606
607
            currentname = "bc" + str(len(subdict["bcs"]))
            subdict["bcs"].append({"name": currentname})
            # TODO use symbolic computation to order into LHS and RHS
            parts = re.split("=", userstring)

            if len(parts) is not 2:
                raise InterviewError("This does not look like a boundary condition.")
            # store the info
            subdict["bcs"][-1]["string"] = userstring
608
609
610
            subdict["bcs"][-1]["lhsstring"] = parts[0].strip()
            subdict["bcs"][-1]["rhsstring"] = parts[1].strip()#TODO expand
            subdict["bcs"][-1]["rhsstring_expanded"] = self.try_expand(subdict["bcs"][-1]["rhsstring"])
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628

            # to make a function on x, place " [ variablename : boundaryname ] " in front
            if parts[0].find("x") > -1:
                parts[0] = " [ x : " + self.simdata["domain"]['boundary_name'] + " ] " + parts[0]
            if parts[1].find("x") > -1:
                parts[1] = " [ x : " + self.simdata["domain"]['boundary_name'] + " ] " + parts[1]

            # in lhs replace all unknown names used by more generic ones and add lambda clause in front
            for unkname in get_recursively(self.simdata["unknowns"], "theoryname"):
                parts[0] = parts[0].replace(unkname, " any" + unkname)
                parts[0] = " [ any" + unkname + " : " + self.simdata["unknowns"][unkname]["type"] + " ] " + parts[0]

                type = self.get_inferred_type(subdict["theoryname"], parts[0])
                if type_is_function_to(type, self.simdata["unknowns"][unkname]["type"]):
                    # right-hand side: infer type, make function if not one yet
                    rhstype = self.get_inferred_type(subdict["theoryname"], parts[1])
                    if not type_is_function_from(rhstype, self.simdata["domain"]["name"])\
                            and not type_is_function_from(rhstype, self.simdata["domain"]["boundary_name"]):
629
                        parts[1] = " [ x : " + self.simdata["domain"]["boundary_name"] + " ] " + parts[1]
630
631
632
633
                    self.add_list_of_declarations(subdict["viewname"], [
                        "firstBC = myDirichletBCfun " + parts[1],
                        "secondBC = myDirichletBCfun " + parts[1],
                    ])
634
635
636
                    subdict["bcs"][-1]["type"] = "Dirichlet",
                    subdict["bcs"][-1]["on"] = "x",
                    subdict["bcs"][-1]["measure"] = 2,
637
638
                    subdict["measure_given"] = 2
                elif type_is_function_to(type, self.simdata["unknowns"][unkname]["codomain"]):
639
640
641
642
                    #at_x = re.split('[\(\)]', subdict["bcs"][-1]["lhsstring"])[-1] #TODO
                    at_x = subdict["bcs"][-1]["lhsstring"].split('(', 1)[1].split(')')[0].strip()
                    if not at_x is self.simdata["domain"]["from"] or at_x is self.simdata["domain"]["to"]:
                        raise InterviewError(at_x + " is not on the boundary!")
643
644
                    if len(subdict["bcs"]) == 1:
                        self.mmtinterface.mmt_new_decl("bc1", subdict["viewname"],
645
                                                       "firstBC = solutionat " + at_x + " is " + parts[1])
646
647
                    elif len(subdict["bcs"]) == 2:
                        self.mmtinterface.mmt_new_decl("bc2", subdict["viewname"],
648
                                                       "secondBC = solutionat " + at_x + " is " + parts[1]) #TODO store at and type
649
650
651
                    else:
                        raise InterviewError("too many boundary conditions saved")
                    subdict["measure_given"] += 1
652
653
654
                    subdict["bcs"][-1]["type"] = "Dirichlet",
                    subdict["bcs"][-1]["on"] = at_x,
                    subdict["bcs"][-1]["measure"] = 1,
655
656
657
658
659
660
661
662
663
664
665
666

            #try:
            #    type = self.get_inferred_type(subdict["theoryname"], "[u : Ω → ℝ] u(0.0)")
            #    type = self.get_inferred_type(subdict["theoryname"], "[u : Ω → ℝ] u")
            #except MMTServerError as error:
            #    self.poutput(error.args[0])

            self.poutput("Ok ")
            if subdict["measure_given"] == len(self.simdata["unknowns"])*2: #TODO times order
                self.trigger('bcs_parsed')
            elif subdict["measure_given"] > len(self.simdata["unknowns"]):
                raise InterviewError("now that's too many boundary conditions. ignoring last input.")
667
668
669
670

    def bcs_exit(self):
        self.poutput("These are all the boundary conditions needed.")

671
672
    def redefine_bcs(self):
        for unknown in get_recursively(self.simdata["unknowns"], "theoryname"):
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
            with CriticalSubdict(self.simdata["bcs"]) as subdict:
                subdict["bctypes"] = {}
                bctypetheoryname = unknown + "BCTypes"
                subdict["bctypes"]["theoryname"] = bctypetheoryname
                self.new_theory(bctypetheoryname)
                self.include_in(bctypetheoryname, unknown)
                self.include_in(bctypetheoryname, "mDifferentialOperators")
                self.add_list_of_declarations(bctypetheoryname,
                        [
                            "myDirichletBC: {where: " + self.simdata["domain"]["boundary_name"] + ", rhs: " +
                                self.simdata["unknowns"][unknown]["codomain"] + "}(" + self.simdata["domain"]["name"] + " → " +
                                self.simdata["unknowns"][unknown]["codomain"] + ") → prop "
                                " ❘ = [where, rhs][u] u where ≐ rhs ❘  # solutionat 1 is 2 ",
                            "myDirichletBCfun : {rhs: " + self.simdata["domain"]["boundary_name"] + " → " +
                                self.simdata["unknowns"][unknown]["codomain"] + " }(" + self.simdata["domain"]["name"] + " → " +
                                self.simdata["unknowns"][unknown]["codomain"] + ") → prop ❘ = [rhs] [u] ∀[x:" + self.simdata["domain"]["boundary_name"] + " ] u x ≐ rhs x "
                                "❘ # solutionatboundaryis 1",
                        ]
                )
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
                err = """when trying to include include ?mDomain = ?ephdomainASmDomain and all others in view
                info.kwarc.mmt.api.InvalidObject of level 2
                invalid object (ill-formed morphism: expected http://mathhub.info/MitM/smglom/calculus?mDomain -> (http://cds.omdoc.org/urtheories?ModExp?complextheory [] ), found http://mathhub.info/MitM/smglom/calculus?mDomain -> http://mathhub.info/MitM/smglom/calculus?ephdomain): http://mathhub.info/MitM/smglom/calculus?ephdomainASmDomain
                info.kwarc.mmt.api.checking.MMTStructureChecker.checkMorphism(MMTStructureChecker.scala:535)
                info.kwarc.mmt.api.checking.MMTStructureChecker.checkRealization(MMTStructureChecker.scala:545)
                info.kwarc.mmt.api.checking.MMTStructureChecker.check(MMTStructureChecker.scala:187)
                info.kwarc.mmt.api.checking.MMTStructureChecker.applyElementBegin(MMTStructureChecker.scala:57)
                info.kwarc.mmt.interviews.InterviewServer$$anon$1.onElement(InterviewServer.scala:94)
                info.kwarc.mmt.api.parser.KeywordBasedParser.seCont(StructureParser.scala:96)
                info.kwarc.mmt.api.parser.KeywordBasedParser.addDeclaration$1(StructureParser.scala:481)
                info.kwarc.mmt.api.parser.KeywordBasedParser.readInModuleAux(StructureParser.scala:525)
                info.kwarc.mmt.api.parser.KeywordBasedParser.readInModule(StructureParser.scala:461)
                info.kwarc.mmt.interviews.InterviewServer.parseDecl(InterviewServer.scala:102)
                info.kwarc.mmt.interviews.InterviewServer.apply(InterviewServer.scala:50)
                info.kwarc.mmt.api.web.Server.resolveExtension(Server.scala:95)
                info.kwarc.mmt.api.web.Server.resolve(Server.scala:76)
                info.kwarc.mmt.api.web.Server.handleRequest(Server.scala:53)
                info.kwarc.mmt.api.web.TiscafServerImplementation$RequestHandler$$anon$1.act(TiscafServerImplementation.scala:49)
                tiscaf.HSimpleLet.aact(HLet.scala:166)
                tiscaf.HSimpleLet.aact$(HLet.scala:165)
                info.kwarc.mmt.api.web.TiscafServerImplementation$RequestHandler$$anon$1.aact(TiscafServerImplementation.scala:47)
                tiscaf.HAcceptor.talk(HAcceptor.scala:246)
                tiscaf.HSimplePeer.doTalkItself$1(HPeer.scala:101)
                tiscaf.HSimplePeer.$anonfun$readChannel$1(HPeer.scala:114)
                scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
                scala.concurrent.Future$.$anonfun$apply$1(Future.scala:653)
                scala.util.Success.$anonfun$map$1(Try.scala:251)
                scala.util.Success.map(Try.scala:209)
                scala.concurrent.Future.$anonfun$map$1(Future.scala:287)
                scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
                scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
                scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
                tiscaf.sync.SyncQuExecutionContext$$anon$1.run(SyncQuExecutionContext.scala:69)
                """#TODO
726
727
728
729
730
731
732
733
                #viewname = bctypetheoryname + "ASmBCTypes"
                #subdict["bctypes"]["viewname"] = viewname
                #self.mmtinterface.mmt_new_view(viewname, bctypetheoryname, "mBCTypes")
                #self.add_list_of_declarations(viewname,
                #                              ["DirichletBC = myDirichletBC ",
                #                               #" = myDirichletBCfun"
                #                               ])
                return bctypetheoryname  # Todo adapt for more than 1
734

735
736
737
738
739
740
741
742
743
744
    ##### for state props
    def props_begin(self):
        with CriticalSubdict(self.simdata["props"]) as subdict:
            # TODO try to find out things about the solvability ourselves
            subdict["theoryname"] = "ephBoundaryValueProblem"
            self.new_theory(subdict["theoryname"])
            #self.new_view(subdict)
            for pde in self.simdata["pdes"]["pdes"]:
                self.poutput("Do you know something about the operator " + pde["op"] + "? "
                             "Is it e.g. linear, or not elliptic ? ")
745

746
    def props_handle_input(self, userstring):
747
        if means_no(userstring):
748
            self.trigger("props_parsed")
749
750
            return

751
752
753
754
755
756
757
758
759
760
761
762
        with CriticalSubdict(self.simdata["props"]) as subdict:
            #            "props": {
            #    "theoryname": "ephboundaryvalueproblem",
            #    "ops": [
            #        {
            #            "name": "op1",
            #            "linear": True, #or false or unknown
            #            "props": ["elliptic"]
            #        }
            #    ]
            #},
            #parts = re.split(" ", userstring) #TODO can add arbitrary proofs of undefined terms??
763
764
765
766
            parsestring = userstring.replace("not", "¬")
            for property in ["linear", "elliptic"]:
                if parsestring.find(property) > -1:
                    self.add_list_of_declarations(subdict["theoryname"], [
767
                        "user_" + property + " : ⊦ " + parsestring + " mylhs"
768
769
770
                    ])
            self.poutput("OK!")
            self.poutput("do you know anything else?")
771

772
773
774
775
776
    def props_exit(self):
        return

    ##### for state sim
    def sim_begin(self):
777
778
        self.please_prompt("Would you like to try and solve the PDE using the Finite Difference Method in ExaStencils?",
                           self.sim_ok_fd)
779
780

    def sim_handle_input(self, userstring):
781
782
        self.please_prompt("Would you like to try and solve the PDE using the Finite Difference Method in ExaStencils?",
                           self.sim_ok_fd)
783

784
    def sim_exit(self):
785
786
        # generate output
        self.exaout.create_output(self.simdata)
787
        self.poutput("Generated ExaStencils input.")
788
        #TODO generate and run simulation
Theresa Pollinger's avatar
Theresa Pollinger committed
789

790
791
792
793
    def sim_ok_fd(self):
        self.simdata["sim"]["type"] = "FiniteDifferences"
        self.sim_exit()

794
    #### functions for user interaction
Theresa Pollinger's avatar
Theresa Pollinger committed
795
    def please_prompt(self, query):
796
        self.poutput(query + " [y/n]? ")
Theresa Pollinger's avatar
Theresa Pollinger committed
797
798
799
800
801
802
803
804
805
806
807
808
        val = input()
        if val == "":
            return True
        try:
            ret = strtobool(val)
        except ValueError:
            # or use as input to callback an input processing fcn..?
            self.poutput("Please answer with Y/n")
            return self.please_prompt(query)
        return ret

    def obviously_stupid_input(self):
809
        self.poutput("Trying to be funny, huh?")
Theresa Pollinger's avatar
Theresa Pollinger committed
810

811
    # mmt input helper functions
Theresa Pollinger's avatar
Theresa Pollinger committed
812
    def include_in(self, in_which_theory, what):
813
        return self.mmtinterface.mmt_new_decl("inc", in_which_theory, "include " + assert_question_mark(what))
Theresa Pollinger's avatar
Theresa Pollinger committed
814

815
816
817
818
    def add_list_of_declarations(self, in_which_theory, declaration_list):
        for declaration in declaration_list:
            self.mmtinterface.mmt_new_decl("inc", in_which_theory, declaration)

Theresa Pollinger's avatar
Theresa Pollinger committed
819
    def include_bgthys(self, in_which_theory):
820
        ok = True
Theresa Pollinger's avatar
Theresa Pollinger committed
821
        for bgthy in self.bgthys[self.state]:
822
823
            ok = ok and self.include_in(in_which_theory, bgthy)
        return ok
Theresa Pollinger's avatar
Theresa Pollinger committed
824
825

    def new_theory(self, thyname):
826
827
828
829
830
        try:
            self.mmtinterface.mmt_new_theory(thyname)
            return self.include_bgthys(thyname)
        except MMTServerError as error:
            self.poutput(error.args[0])
831
            # self.poutput(error.with_traceback())
832
            raise
833
        # (ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
834
835

    def new_view(self, dictentry):
836
        dictentry["viewname"] = self.construct_current_view_name(dictentry)
837
        # self.poutput("new view: "+dictentry["viewname"])
838
        ok = self.mmtinterface.mmt_new_view(dictentry["viewname"], self.viewfrom[self.state], dictentry["theoryname"])
839
        # recursively look for all views already done and try to include them
840
        for viewstring in get_recursively(self.simdata, "viewname"):
841
            if (dictentry["viewname"] != viewstring) and ok:
842
                try:
843
844
                    ok = self.include_in(dictentry["viewname"],
                                         "?" + re.split('AS', viewstring)[-1] + " = " + "?" + viewstring)
845
                except MMTServerError as error:
846
847
848
849
850
                    # self.poutput("no backend available that is applicable to " + "http://mathhub.info/MitM/smglom/calculus" + "?" + re.split('AS', dictentry["viewname"])[-1] + "?")
                    # we are expecting errors if we try to include something that is not referenced in the source theory, so ignore them
                    if error.args[0].find(
                            "no backend available that is applicable to " + "http://mathhub.info/MitM/smglom/calculus" + "?" +
                            re.split('AS', dictentry["viewname"])[-1] + "?") < 1:
851
                        raise
Theresa Pollinger's avatar
Theresa Pollinger committed
852
853
854
        return ok

    def construct_current_view_name(self, dictentry):
855
        return self.construct_view_name(dictentry, self.state)
Theresa Pollinger's avatar
Theresa Pollinger committed
856
857

    def construct_view_name(self, dictentry, state):
858
        return dictentry["theoryname"] + "AS" + (self.viewfrom[state])
Theresa Pollinger's avatar
Theresa Pollinger committed
859

860
861
862
    def get_inferred_type(self, in_theory, term):
        return self.mmtinterface.mmt_infer_type(in_theory, term).inferred_type_to_string()

863
864
865
866
867
868
869
870
871
872
    def try_expand(self, term, in_theory=None): #TODO do using mmt definition expansion
        for param in reversed(self.simdata["parameters"]):
            if term.find(param) > -1:
                parts = self.simdata["parameters"][param]["string"].split("=")
                if (len(parts) != 2):
                    raise InterviewError("no definition for " + param + " given")
                paramdef = parts[-1]
                term = term.replace(param, paramdef.strip())
        return term

873
874
    def print_empty_line(self):
        self.poutput("\n")
Theresa Pollinger's avatar
Theresa Pollinger committed
875

876
    ############# input processing if not explain or undo
Theresa Pollinger's avatar
Theresa Pollinger committed
877
878
879
    def default(self, line):
        raw = line.parsed['raw']
        arg = LatexNodes2Text().latex_to_text(raw)
880
        # pythonic switch-case, cf. https://bytebaker.com/2008/11/03/switch-case-statement-in-python/
881
882
883
884
885
886
887

        if not self.prompt_input_handling(arg):
            self.state_input_handling(arg)

    def state_input_handling(self, arg):
        """The standard input handling, depending on which state we are in"""
        # pythonic switch-case, cf. https://bytebaker.com/2008/11/03/switch-case-statement-in-python/
Theresa Pollinger's avatar
Theresa Pollinger committed
888
889
        try:
            self.stateDependentInputHandling[self.state](arg)
890
        except Exception as error:
891
            #self.exaout.create_output(self.simdata)
Theresa Pollinger's avatar
Theresa Pollinger committed
892
893
            raise

894
    def please_prompt(self, query, if_yes, if_no=None):
Theresa Pollinger's avatar
Theresa Pollinger committed
895
        self.poutput(str(query) + " [y/n]? ")
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
        self.prompted = True
        self.if_yes = if_yes
        self.if_no = if_no

    def prompt_input_handling(self, arg):
        """ If we asked for a yes-no answer, execute what was specified in please_prompt.
        return true if the input was handled here, and false if not."""
        if self.prompted:
            if arg == "":
                self.poutput("Yes")
                ret = True
            else:
                try:
                    ret = strtobool(str(arg).strip().lower())
                except ValueError:
                    # or use as input to callback an input processing fcn..?
                    self.poutput("Please answer with Y/n")
                    return True
            self.prompted = False
            if ret:
                self.if_yes()
            elif self.if_no is not None:
                self.if_no()
            else:
                return False
            return True
        return False

Theresa Pollinger's avatar
Theresa Pollinger committed
924
925
926
927
    # called when user types 'explain [expression]'
    def do_explain(self, expression):
        "Explain an expression or the theoretical background to what we are currently looking for"
        if expression:
928
            explanation = "hello, " + expression  # TODO query flexiformal content through mmt
Theresa Pollinger's avatar
Theresa Pollinger committed
929
930
931
932
933
        else:
            explanation = 'hello'
        self.poutput(explanation)

    def help_explain(self):
934
935
936
        self.poutput('\n'.join(['explain [expression]',
                                'explain the expression given or the theory currently used',
                                ]))
Theresa Pollinger's avatar
Theresa Pollinger committed
937
938
939
940
941
942
943

    # called when user types 'undo'
    def do_undo(self, expression):
        "Go back to the last question"
        self.trigger('last_state')

    def help_undo(self):
944
945
946
        self.poutput('\n'.join(['undo',
                                'Go back to the last question',
                                ]))
Theresa Pollinger's avatar
Theresa Pollinger committed
947
948
949
950

    def update_prompt(self):
        self.prompt = "(" + self.state + ")"

951
    # tab completion for empty lines
Theresa Pollinger's avatar
Theresa Pollinger committed
952
953
954
955
956
957
    def completenames(self, text, line, begidx, endidx):
        """Override of cmd2 method which completes command names both for command completion and help."""
        command = text
        if self.case_insensitive:
            command = text.lower()
        if not command:
958
            # define the "default" input for the different states we can be in
Theresa Pollinger's avatar
Theresa Pollinger committed
959
960
961
            self.stateDependentDefaultInput = {
                'dimensions': '1',
                'domain': ['Ω = [ 0 ; 1 ]'],
962
                'unknowns': ['u : Ω → ℝ'],
963
                'parameters': ['f :  ℝ → ℝ = [x: ℝ] x '],  # ['f : Ω → ℝ = [x:Ω] x ⋅ x'],
964
965
966
                'pdes': ['∆u = f(x_1)'],
                'bcs': ['u (0) = 0'],  # ,'u (1) = x_1**2'],
                'sim': ['FD'],
Theresa Pollinger's avatar
Theresa Pollinger committed
967
968
969
970
971
972
973
974
975
976
977
            }
            return self.stateDependentDefaultInput[self.state]
        else:
            # Call super class method.  Need to do it this way for Python 2 and 3 compatibility
            cmd_completion = cmd.Cmd.completenames(self, command)

            # If we are completing the initial command name and get exactly 1 result and are at end of line, add a space
            if begidx == 0 and len(cmd_completion) == 1 and endidx == len(line):
                cmd_completion[0] += ' '
            return cmd_completion

978
979
980
981
    def greeting(self):  # TODO make work in proper order
        self.poutput(
            "Hello, " + self.username + "! I am " + self.myname + ", your partial differential equations and simulations expert. " \
                                                                  "Let's set up a simulation together.\n")
Theresa Pollinger's avatar
Theresa Pollinger committed
982
983
        self.trigger("greeting_over")

984

985
# cf. https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary
986
def get_recursively(search_dict, field):
987
    """
988
989
    Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided,
    returning a list of the values.
990
991
992
993
994
995
    """
    fields_found = []
    for key, value in search_dict.items():
        if key == field:
            fields_found.append(value)
        elif isinstance(value, dict):
996
            results = get_recursively(value, field)
997
998
999
1000
1001
            for result in results:
                fields_found.append(result)
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
1002
                    more_results = get_recursively(item, field)
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
                    for another_result in more_results:
                        fields_found.append(another_result)
    return fields_found


# """string modification functions"""
def insert_type(string, whichtype):
    eqidx = string.find("=")
    if eqidx < 0:
        raise Exception
    if not self.has_colon(string):
        # print('has no colon ' + equidx)
        return string[:eqidx] + " : " + whichtype + " ❘ " + string[eqidx:]
    return string[:eqidx] + " ❘ " + string[eqidx:]


1019
def type_is_function_from(type_string, from_string):
1020
1021
1022
1023
    if type_string.startswith(from_string + " →"):
        return True
    if type_string.startswith("{ : " + from_string):
        return True
1024

1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
    from_string = make_list_of_type_symbols(from_string)
    type_string = make_list_of_type_symbols(type_string)

    if len(from_string) > len(type_string):
        return False

    for index in range(len(from_string)):
        if from_string[index] != type_string[index]:
            return False

    return True

1037

1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def type_is_function_to(type_string, to_string):
    if type_string.endswith("→ " + to_string):
        return True
    if type_string.endswith("} " + to_string):
        return True
    to_string = make_reverse_list_of_type_symbols(to_string)
    type_string = make_reverse_list_of_type_symbols(type_string)

    if len(to_string) > len(type_string):
        return False

    for index in range(len(to_string)):
        if to_string[index] != type_string[index]:
            return False

    return True
1054

1055
1056
1057
1058
1059

def remove_apply_brackets(string):
    return string.split('(', 1)[0] + string.split(')', 1)[1].strip()


1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
def insert_before_def(string, insertstring):
    eqidx = string.find("=")
    if eqidx < 0:
        raise Exception
    return string[:eqidx + 1] + " " + insertstring + " " + string[eqidx + 1:]


def get_first_word(string):
    return re.split('\W+', string, 1)[0]


def get_last_type(string):
1072
1073
    string = remove_round_brackets(string)
    string = string.rstrip()
1074
1075
1076
    return re.split('[→ \s]', string)[-1]


1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
def make_reverse_list_of_type_symbols(string):
    slist = make_list_of_type_symbols(string)
    slist.reverse()
    return slist


def make_list_of_type_symbols(string):
    string = remove_arrows(remove_colons(remove_curly_brackets(remove_round_brackets(string))))
    slist = string.split(' ')
    slist = list(filter(lambda a: a != '', slist))
    return slist


1090
def remove_round_brackets(string):
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
    return string.replace(")", "").replace("(", "")


def remove_curly_brackets(string):
    return string.replace("{", "").replace("}", "")


def remove_arrows(string):
    return string.replace("→", "")


def remove_colons(string):
    return string.replace(":", "")
1104
1105


1106
1107
1108
1109
1110
1111
def has_equals(self, string):
    if string.find("=") > -1:
        return True
    return False


1112
def has_colon(string):
1113
1114
1115
1116
1117
    if string.find(":") > -1:
        return True
    return False


1118
def eq_to_doteq(string):
1119
1120
1121
    return string.replace("=", "≐")


1122
def assert_question_mark(what):
1123
1124
1125
1126
1127
    qmidx = what.find("?")
    if qmidx < 0:
        return "?" + what
    else:
        return what
1128
1129
1130


def add_ods(string):
1131
1132
1133
    objects = re.split(r'(\W)', string)
    onedel = False
    for i in range(2, len(objects)):
1134
        if bool(re.match('[:=]', objects[i], re.I)):  # if it starts with : or =
1135
1136
1137
            if onedel:
                objects[i] = "❘" + objects[i]
                return ''.join(objects)
1138
            onedel = True  # start only at second : or =
1139
    return ''.join(objects)
1140

1141
1142

def functionize(string, typename="Ω", varname="x"):
1143
1144
1145
    return string.replace("=", "= [ " + varname + " : " + typename + "]")


Theresa Pollinger's avatar
Theresa Pollinger committed
1146
1147
if __name__ == '__main__':
    Interview().cmdloop()