interview.py 23.6 KB
Newer Older
Theresa Pollinger's avatar
Theresa Pollinger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#!/usr/bin/env python3

import sys
import errno
import traceback
#http://cmd2.readthedocs.io
import cmd2 as cmd
#https://github.com/pytransitions/transitions
from transitions import Machine, State
from collections import OrderedDict
#strings:
#http://mattoc.com/python-yes-no-prompt-cli.html
from distutils.util import strtobool
from pathlib import Path
#https://github.com/phfaist/pylatexenc for directly converting Latex commands to unicode
from pylatexenc.latex2text import LatexNodes2Text
import pyparsing as pp
from lxml import etree
import re

from exaoutput import ExaOutput
from mmtinterface import *

# 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):

    def __init__(self, *args, **kwargs):
        # initialize legal characters for cmd
        self.legalChars = u'!#$%.:;?@_-<>' + pp.printables + pp.alphas8bit + pp.punc8bit
        # TODO why does "<" not show?
        #allow all useful unicode characters to be used, and some more
        for i in range(0x20,0x2E7F):
            self.legalChars += chr(i)

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

        # Initialize a state machine
        states = [
            #State('greeting'),
            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']),
            'pdes',
            'bcs' ,
            'sim'
        ]
        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
        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')
        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')

        # Initialize cmd member variables
        self.myname = 'James'
        self.username = 'user'
        self.intro = "Hello, " + self.username + "! I am " + self.myname + ", your partial differential equations and simulations expert. " \
        "Let's set up a simulation together.\n" \
        "How many dimensions would you like to simulate?"

        #define what happens when input is received in a certain state
        self.stateDependentInputHandling = {
            'dimensions': self.dimensions_handle_input,
            'domain': self.domain_handle_input,
            'unknowns': self.unknowns_handle_input,
            'parameters' : self.parameters_handle_input,
            'pdes' : self.pdes_handle_input, #TODO
            'bcs' : None,
            'sim' : None,
        }

        self.mmtinterface = MMTInterface()

        #for ladder-like views
        self.viewfrom = OrderedDict([
            ('domain', "?GeneralDomains"),
            ('unknowns', "?Unknown"),
            ('parameters', "?Parameter"),
            ('pdes', "?PDE"),
            ('bcs', "?BCsRequired"),
        ])
        # to include all the necessary theories every time
        self.bgthys = OrderedDict([
            ('domain', ["?SimpleDomains", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),
            ('unknowns', ["http://mathhub.info/MitM/Foundation?Strings", "?ephdomain", "http://mathhub.info/MitM/smglom/calculus?higherderivative"]),
            ('parameters', ["http://mathhub.info/MitM/smglom/arithmetics?realarith", "?ephdomain"]),
            ('pdes', ["?DifferentialOperators"]),
            ('bcs', ["?BCTypes", "?ephUnknown" , "?ephPDE" , "?linearity", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),
        ])

        #the things we'd like to find out
        self.simdata = {
            "num_dimensions" : None,
            "domain" : {
                    "name" : None,
                    "uri"  : None,
                    #"viewuri" : None,
                    "axes" : OrderedDict(),
                    "from" : None,
                    "to" : None,
            },
            "unknowns" : OrderedDict(),
            "parameters" : {},
            "pdes" : {
                "uri" : None,
                "pdes" : [],
            },
            "bcs" : None,
            "sim_type" : None,
        }

        axes = OrderedDict([
            ("x_1", "[0;1]"),
        ])
        self.examplesimdata = {
            "num_dimensions" : 1,
            "domain" : {
                    "name" : "Ω",
                    "uri" : "?Omega",
                    "axes" : axes,# names and intervals
                    "from" : "[ 0 ]",
                    "to" : "[ 1 ]",
                },
            "unknowns" : {# names and uris #TODO OrderedDict
                    "u" : {
                        "uri" : "?u",
                        "string" : "u : Ω → ℝ",
                        },
                },
            "parameters" : {# names and uris
                    "μ" : {
                        "uri" : "?mu",
                        "string" : "μ : ℝ = 1",
                        },
                    "f" : {
                        "uri" : "?f",
                        "string" : "f : Ω → ℝ = [x] x ⋅ x",
                    },
                },
            "pdes" : {
                "pdes" :  [
                            {# this is more of a wish list...
                                "uri" : "?pde1",
                                "string" : "μ ∆u = f(x_1)", # TODO
                                "expanded" : "μ d²/dx_1² u = f(x_1)",
                                "type" : "elliptic",
                                "linear" : True,
                                "order_in_unknown" :{
                                    "u" : 2,
                                },
                            },
                        ],
            },
            "bcs" : [
                        {
                            "type" : "Dirichlet",
                            "string" : "u (0) = x_1**2",
                            "on" : "[0]",
                        },
                        {
                            "type" : "Dirichlet",
                            "string" : "u (1) = x_1**2",
                            "on" : "[1]",
                        },
                ],
            "sim_type" : "FD",
        }

        self.exaout = ExaOutput()
        #self.greeting()
        self.update_prompt()

##### for state dimensions
    def dimensions_begin(self):
        self.poutput ("How many dimensions would you like to simulate?")
        self.poutput ("I am just assuming it's 1, since that is all we can currently handle.")#TODO
        self.simdata["num_dimensions"] = 1
        self.dimensions_parsed()

    def dimensions_handle_input(self, userstring):
        try:
            numdim = int(userstring)
        except ValueError:
            self.poutput ("Please enter a number.")
            return
        if numdim < 1:
            self.obviously_stupid_input()
            self.dimensions_begin()
        elif numdim == 1: #or self.numdim == 2:
            self.simdata["num_dimensions"] = numdim
            self.dimensions_parsed()
        else:
            self.poutput ("Sorry, cannot handle " + str(self.numdim) + " dimensions as of now. Please try less than that.")

##### for state domain
    def domain_begin(self):
        self.poutput ("What is the domain you would like to simulate for?     Ω = [?;?]")
        self.poutput ("By the way, you can always try and use LaTeX-type input.")
        self.simdata[self.state]["axes"] = OrderedDict()
        self.domain_mmt_preamble()

    def domain_handle_input(self, userstring):
        domain_name = re.split('\W+', userstring,1)[0]
        parsestring = userstring
        mmtparsed = self.mmtinterface.mmt_new_decl(domain_name, self.simdata[self.state]["uri"], parsestring)
        #mmtparsed = True
        # TODO store result?
        if mmtparsed:
            mmtreply = MMTReply(self.mmtinterface, self.simdata[self.state]["uri"])
            mmtparsed = mmtreply.ok
        if mmtparsed:
            #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["uri"])
            self.simdata[self.state]["name"] = domain_name
            (fro, to) = mmtreply.getIntervalBoundaries(mmtreply, domain_name)
            self.simdata[self.state]["axes"]["x_1"] = "["+fro+";"+to+"]"
            #self.poutput(self.simdata[self.state]["axes"]["x_1"])
            (self.simdata[self.state]["from"],self.simdata[self.state]["to"]) = ("[ "+fro+" ]","[ "+to+" ]")
            self.trigger('domain_parsed')
        else:
            self.please_repeat()

    def domain_exit(self):
        self.domain_mmt_postamble()

    def domain_mmt_preamble(self):
        # set the current MMT URI for parsing the input TODO use right dimension
        self.simdata[self.state]["uri"] = "?ephdomain"
        #self.simdata[self.state]["viewuri"] = self.construct_current_view_name(self.simdata[self.state])
        self.new_theory(self.simdata[self.state]["uri"])
        #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["uri"])

    def domain_mmt_postamble(self):
        subdict = self.simdata[self.state]
        self.mmtinterface.mmt_new_decl('mydomainpred', subdict["uri"], "myDomainPred = "+ subdict["name"] +".interval_pred")
        self.mmtinterface.mmt_new_decl('mydomain', subdict["uri"], "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["viewuri"], "Vecspace = real_lit")#TODO adjust for higher dimensions
        self.mmtinterface.mmt_new_decl('DomainPred', subdict["viewuri"], "DomainPred = "+ subdict["name"] +".interval_pred") # the . is unbound, apparently...

##### for state unknowns
    def unknowns_begin(self):
        self.poutput ("Which variable(s) are you looking for?   u : "+ self.simdata["domain"]["name"] +" → ?")#problem: omega not a type (yet), need to have it look like one
        self.simdata["unknowns"] = OrderedDict()

    def unknowns_handle_input(self, userstring):
        unknown_name = re.split('\W+', userstring,1)[0]
        # replace interval with domain
        parsestring = userstring.replace(self.simdata["domain"]["name"], "pred myDomainPred")
        #print(parsestring)
        #print('type: ' + str(self.get_last_type(self.get_type(parsestring))))
        self.simdata["unknowns"][unknown_name] = {
                    "uri" : str("?" + unknown_name),
                    #"viewuri" : self.construct_current_view_name(self.simdata[self.state]),
                    "string" : parsestring,
                    "type" : self.get_type(parsestring),
                }
        self.simdata["unknowns"][unknown_name]["viewuri"] = self.construct_current_view_name(self.simdata["unknowns"][unknown_name])
        subdict = self.simdata["unknowns"][unknown_name]
        #create mmt theory with includes
        once = self.new_theory(subdict["uri"])
        self.include_in(subdict["uri"], self.simdata["domain"]["uri"])
        #add unknown's type as constant
        twice = self.mmtinterface.mmt_new_decl(unknown_name, subdict["uri"], "myUnkType = " + self.simdata["unknowns"][unknown_name]["type"] ) #hacky!
        twice = self.mmtinterface.mmt_new_decl('diffable', subdict["uri"], "anyuwillbediffable : {u : myUnkType} ⊦ twodiff u " ) #hacky!
        mmtparsed = twice
        #add view
        if mmtparsed:
            mmtparsed = self.new_view(subdict)
            mmtparsed = mmtparsed and self.mmtinterface.mmt_new_decl("codomain", subdict["viewuri"], "ucodomain = ℝ" )
            mmtparsed = mmtparsed and self.mmtinterface.mmt_new_decl("unktype", subdict["viewuri"], "unknowntype = myUnkType" )

        if mmtparsed:
            self.poutput ("Ok, " +  userstring)
            if self.please_prompt("Are these all the unknowns?"):
                self.trigger('unknowns_parsed')
        else:
            del self.simdata["unknowns"][unknown_name]
            #need to delete mmt ephemeral theory too
            self.please_repeat()
        #print(str(self.simdata))

    def unknowns_exit(self):
        for unknown in self.simdata["unknowns"]:
            self.poutput (self.simdata["unknowns"][unknown]["string"])

##### for state parameters
    def parameters_begin(self):
        self.poutput ("Would you like to name additional parameters like constants or functions (that are independent of your unknowns)?  c : ℝ = ? or f : Ω → ℝ = ?") #ℝ
        self.simdata["parameters"] = {}

    def parameters_handle_input(self, userstring):
        #self.poutput ("parameterinput "+ userstring)
        if(self.means_no(userstring)):
            self.trigger('parameters_parsed')
            return

        parameter_name = re.split('\W+', userstring,1)[0]
        self.simdata["parameters"][parameter_name] = {
                    "uri" : "?" + parameter_name,
                    "string" : userstring,
                }
        #create mmt theory
        once = self.new_theory(self.simdata["parameters"][parameter_name]["uri"])
        mmtparsed = once
        #if mmtparsed:
            #create view
        if mmtparsed:
            #self.poutput ("Ok, " +  userstring)
            if self.please_prompt("Are these all the parameters?"):
                self.trigger('parameters_parsed')
        else:
            del self.simdata["parameters"][parameter_name]
            self.please_repeat()
        #print(str(self.simdata))

    def parameters_exit(self):
        #print(str(self.simdata["parameters"]))
        for parameter in self.simdata["parameters"]:
            self.poutput (self.simdata["parameters"][parameter]["string"])

##### for state pdes
    def pdes_begin(self):
        self.poutput ("Let's get to your partial differential equation(s). What do they look like?")
        self.simdata["pdes"]["pdes"] = []

    def pdes_handle_input(self, userstring):
        self.poutput ("pdeinput "+ userstring)
        #create mmt theory
        self.simdata["pdes"]["uri"] = "?ephpde"
        self.new_theory(self.simdata["pdes"]["uri"])
        #include unknowns, parameters, differential operators
        inc = self.include_in(self.simdata["pdes"]["uri"], cuboidURI)
        # TODO send as declaration to mmt
        # TODO make view

        mmtparsed = True
        mmtresult = userstring
        # TODO store result
        # TODO use symbolic computation to order into LHS and RHS
        #TODO query number of effective pdes and unknowns from mmt
        if mmtparsed:
            numpdesgiven = 1
        # => can assume each to be ==1 for now
            self.poutput ("Ok, " +  mmtresult)
            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.")
        else:
            self.please_repeat()

    def pdes_exit(self):
        self.poutput ("These are all the PDEs needed.")

    # functions for user interaction
    def please_repeat(self, moreinfo=None):
        append = ""
        if moreinfo:
            append = "\nDetails: " + moreinfo
        self.poutput ("I did not catch that. Could you please rephrase?" + append)

    def please_prompt(self, query):
        self.poutput(query + " [Y/n]? ")
        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 means_no(self, answer):
        try:
            ret = strtobool(answer)
            if (ret == False):
                return True
        except ValueError:
            return False
        return False

    def obviously_stupid_input(self):
        self.poutput ("Trying to be funny, huh?")

    # string processing
    def has_equals(self, string):
        if string.find("=") > -1:
            return True
        return False

    def has_colon(self, string):
        if string.find(":") > -1:
            return True
        return False

    def eq_to_doteq(self, string):
        return string.replace("=", "≐")

### mmt input helper functions
    def include_in(self, in_which_theory, what):
        return self.mmtinterface.mmt_new_decl("inc", in_which_theory, "include " + what)

    def include_bgthys(self, in_which_theory):
        for bgthy in self.bgthys[self.state]:
            self.include_in(in_which_theory, bgthy)

    def new_theory(self, thyname):
        self.mmtinterface.mmt_new_theory(thyname)
        #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["uri"])
        self.include_bgthys(thyname)

    def new_view(self, dictentry):
        dictentry["viewuri"] = self.construct_current_view_name(dictentry)
        #self.poutput("new view: "+dictentry["viewuri"])
        ok = self.mmtinterface.mmt_new_view(dictentry["viewuri"], self.viewfrom[self.state], dictentry["uri"])
        #recursively look for all views already done and include them
        for viewstring in self.get_recursively(self.simdata, "viewuri"):
            if(dictentry["viewuri"] != viewstring) and ok:
                ok = self.include_in(dictentry["viewuri"], "?" + re.split('AS', viewstring)[-1] + " = " + viewstring)
        return ok

    def construct_current_view_name(self, dictentry):
        return self.construct_view_name(dictentry,self.state)

    def construct_view_name(self, dictentry, state):
        return "?"+dictentry["uri"][1:] + "AS" + (self.viewfrom[state][1:])

    #cf. https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary
    def get_recursively(self, search_dict, field):
        """
        Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided.
        """
        fields_found = []
        for key, value in search_dict.items():
            if key == field:
                fields_found.append(value)
            elif isinstance(value, dict):
                results = self.get_recursively(value, field)
                for result in results:
                    fields_found.append(result)
            elif isinstance(value, list):
                for item in value:
                    if isinstance(item, dict):
                        more_results = self.get_recursively(item, field)
                        for another_result in more_results:
                            fields_found.append(another_result)
        return fields_found

    def insert_type(self, 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:]

    def get_type(self, string):
        colidx = string.find(":")
        eqidx = string.find("=")
        if eqidx > -1 :
            return string[colidx+1:eqidx]
        return string[colidx+1:]

    def insert_before_def(self, string, insertstring):
        eqidx = string.find("=")
        if eqidx < 0:
            raise Exception
        return string[:eqidx+1] + " " + insertstring + " " + string[eqidx+1:]

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

    def get_last_type(self, string):
        return re.split('[→ \s]', string)[-1]

    def print_empty_line(self):
        self.poutput("\n")

############# input processing if not explain or undo
    def default(self, line):
        raw = line.parsed['raw']
        arg = LatexNodes2Text().latex_to_text(raw)
        #self.poutput ('default({0})'.format(arg))
        #pythonic switch-case, cf. https://bytebaker.com/2008/11/03/switch-case-statement-in-python/
        try:
            #self.poutput("You entered "+arg)
            self.stateDependentInputHandling[self.state](arg)
        except:
            self.exaout.create_output(self.examplesimdata)
            raise
            #self.perror('State machine broken: '+self.state)

    # 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:
            explanation = "hello, " + expression # TODO query flexiformal content through mmt
        else:
            explanation = 'hello'
        self.poutput(explanation)

    def help_explain(self):
        self.poutput ('\n'.join([ 'explain [expression]',
                           'explain the expression given or the theory currently used',
                           ]))

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

    def help_undo(self):
        self.poutput ('\n'.join([ 'undo',
                           'Go back to the last question',
                           ]))

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

    #tab completion for empty lines
    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:
            #define the "default" input for the different states we can be in
            self.stateDependentDefaultInput = {
                'dimensions': '1',
                'domain': ['Ω = [ 0 ; 1 ]'],
                'unknowns': ['u : Ω → ℝ'] ,
                'parameters' : ['f : Ω → ℝ = [x] x ⋅ x'],
                'pdes' : ['∆u = f(x_1)'],
                'bcs' : ['u (0) = 0'],#,'u (1) = x_1**2'],
                'sim' : ['FD'],
            }
            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


    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" )
        self.trigger("greeting_over")

if __name__ == '__main__':
    Interview().cmdloop()