interview.py 24.5 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
#!/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):
29
30
        #just act like we were getting the right replies from MMT
        self.cheating = True
Theresa Pollinger's avatar
Theresa Pollinger committed
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
        # 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([
88
89
90
91
92
            ('domain', "GeneralDomains"),
            ('unknowns', "Unknown"),
            ('parameters', "Parameter"),
            ('pdes', "PDE"),
            ('bcs', "BCsRequired"),
Theresa Pollinger's avatar
Theresa Pollinger committed
93
94
95
        ])
        # to include all the necessary theories every time
        self.bgthys = OrderedDict([
96
97
98
99
100
            ('domain', ["SimpleDomains", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]), # 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"]),
            ('pdes', ["DifferentialOperators"]),
            ('bcs', ["BCTypes", "ephUnknown" , "ephPDE" , "linearity", "http://mathhub.info/MitM/smglom/arithmetics?realarith"]),
Theresa Pollinger's avatar
Theresa Pollinger committed
101
102
103
104
105
106
107
        ])

        #the things we'd like to find out
        self.simdata = {
            "num_dimensions" : None,
            "domain" : {
                    "name" : None,
108
109
                    "theoryname"  : None,
                    #"viewname" : None,
Theresa Pollinger's avatar
Theresa Pollinger committed
110
111
112
113
114
115
116
                    "axes" : OrderedDict(),
                    "from" : None,
                    "to" : None,
            },
            "unknowns" : OrderedDict(),
            "parameters" : {},
            "pdes" : {
117
                "theoryname" : None,
Theresa Pollinger's avatar
Theresa Pollinger committed
118
119
120
121
122
123
124
125
126
127
128
129
130
                "pdes" : [],
            },
            "bcs" : None,
            "sim_type" : None,
        }

        axes = OrderedDict([
            ("x_1", "[0;1]"),
        ])
        self.examplesimdata = {
            "num_dimensions" : 1,
            "domain" : {
                    "name" : "Ω",
131
                    "theoryname" : "Omega",
Theresa Pollinger's avatar
Theresa Pollinger committed
132
133
134
135
                    "axes" : axes,# names and intervals
                    "from" : "[ 0 ]",
                    "to" : "[ 1 ]",
                },
136
            "unknowns" : {# names and theorynames #TODO OrderedDict
Theresa Pollinger's avatar
Theresa Pollinger committed
137
                    "u" : {
138
                        "theoryname" : "u",
Theresa Pollinger's avatar
Theresa Pollinger committed
139
140
141
                        "string" : "u : Ω → ℝ",
                        },
                },
142
            "parameters" : {# names and theorynames
Theresa Pollinger's avatar
Theresa Pollinger committed
143
                    "μ" : {
144
                        "theoryname" : "mu",
Theresa Pollinger's avatar
Theresa Pollinger committed
145
146
147
                        "string" : "μ : ℝ = 1",
                        },
                    "f" : {
148
                        "theoryname" : "f",
Theresa Pollinger's avatar
Theresa Pollinger committed
149
150
151
152
153
154
                        "string" : "f : Ω → ℝ = [x] x ⋅ x",
                    },
                },
            "pdes" : {
                "pdes" :  [
                            {# this is more of a wish list...
155
                                "theoryname" : "pde1",
Theresa Pollinger's avatar
Theresa Pollinger committed
156
157
158
159
160
161
162
163
164
165
166
167
                                "string" : "μ ∆u = f(x_1)", # TODO
                                "expanded" : "μ d²/dx_1² u = f(x_1)",
                                "type" : "elliptic",
                                "linear" : True,
                                "order_in_unknown" :{
                                    "u" : 2,
                                },
                            },
                        ],
            },
            "bcs" : [
                        {
168
                            "theoryname" : "bc1",
Theresa Pollinger's avatar
Theresa Pollinger committed
169
170
171
172
173
                            "type" : "Dirichlet",
                            "string" : "u (0) = x_1**2",
                            "on" : "[0]",
                        },
                        {
174
                            "theoryname" : "bc2",
Theresa Pollinger's avatar
Theresa Pollinger committed
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
                            "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
219
220
221
222
223
        try:
            mmtparsed = self.mmtinterface.mmt_new_decl(domain_name, self.simdata[self.state]["theoryname"], parsestring)
        except MMTServerError as error:
            print(error.args)
        mmtparsed = (mmtparsed if not self.cheating else True)
Theresa Pollinger's avatar
Theresa Pollinger committed
224
        if mmtparsed:
225
226
227
228
            try:
                mmtreply = self.mmtinterface.query_for( self.simdata[self.state]["theoryname"])
            except MMTServerError as error:
                print(error.args)
229
            mmtparsed = (mmtreply.ok)# if not self.cheating else True)
Theresa Pollinger's avatar
Theresa Pollinger committed
230
        if mmtparsed:
231
            #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
232
            self.simdata[self.state]["name"] = domain_name
233
            (fro, to) = mmtreply.getIntervalBoundaries(mmtreply, domain_name) if not self.cheating else ("0.", "1.")
Theresa Pollinger's avatar
Theresa Pollinger committed
234
235
236
237
238
239
240
241
242
243
244
            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):
245
246
247
248
249
        # set the current MMT theoryname for parsing the input TODO use right dimension
        self.simdata[self.state]["theoryname"] = "ephdomain"
        #self.simdata[self.state]["viewname"] = self.construct_current_view_name(self.simdata[self.state])
        self.new_theory(self.simdata[self.state]["theoryname"])
        #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
250
251
252

    def domain_mmt_postamble(self):
        subdict = self.simdata[self.state]
253
254
255
256
257
258
259
        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...
Theresa Pollinger's avatar
Theresa Pollinger committed
260
261
262
263
264
265
266
267
268

##### 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
269
        parsestring = (userstring.replace(self.simdata["domain"]["name"], "pred myDomainPred") if not self.cheating else userstring)
Theresa Pollinger's avatar
Theresa Pollinger committed
270
271
272
        #print(parsestring)
        #print('type: ' + str(self.get_last_type(self.get_type(parsestring))))
        self.simdata["unknowns"][unknown_name] = {
273
274
                    "theoryname" : str("" + unknown_name),
                    #"viewname" : self.construct_current_view_name(self.simdata[self.state]),
Theresa Pollinger's avatar
Theresa Pollinger committed
275
276
277
                    "string" : parsestring,
                    "type" : self.get_type(parsestring),
                }
278
        self.simdata["unknowns"][unknown_name]["viewname"] = self.construct_current_view_name(self.simdata["unknowns"][unknown_name])
Theresa Pollinger's avatar
Theresa Pollinger committed
279
280
        subdict = self.simdata["unknowns"][unknown_name]
        #create mmt theory with includes
281
282
        once = self.new_theory(subdict["theoryname"])
        self.include_in(subdict["theoryname"], self.simdata["domain"]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
283
        #add unknown's type as constant
284
        twice = self.mmtinterface.mmt_new_decl(unknown_name, subdict["theoryname"], "myUnkType = " + self.simdata["unknowns"][unknown_name]["type"] ) #hacky!
285
286
        twice = (self.mmtinterface.mmt_new_decl('diffable', subdict["theoryname"], "anyuwillbediffable : {u : myUnkType} ⊦ twodiff u " ) if not self.cheating else twice)
        mmtparsed = twice.ok
Theresa Pollinger's avatar
Theresa Pollinger committed
287
288
289
        #add view
        if mmtparsed:
            mmtparsed = self.new_view(subdict)
290
            mmtparsed = mmtparsed and self.mmtinterface.mmt_new_decl("codomain", subdict["viewname"], "ucodomain = ℝ" ) #TODO
291
            mmtparsed = mmtparsed and self.mmtinterface.mmt_new_decl("unktype", subdict["viewname"], "unknowntype = myUnkType" )
Theresa Pollinger's avatar
Theresa Pollinger committed
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

        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] = {
320
                    "theoryname" : "" + parameter_name,
Theresa Pollinger's avatar
Theresa Pollinger committed
321
322
323
                    "string" : userstring,
                }
        #create mmt theory
324
        once = self.new_theory(self.simdata["parameters"][parameter_name]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
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
        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
350
351
        self.simdata["pdes"]["theoryname"] = "ephpde"
        self.new_theory(self.simdata["pdes"]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
352
        #include unknowns, parameters, differential operators
353
        inc = self.include_in(self.simdata["pdes"]["theoryname"], cuboidtheoryname)
Theresa Pollinger's avatar
Theresa Pollinger committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        # 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.")

376
### functions for user interaction
Theresa Pollinger's avatar
Theresa Pollinger committed
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
    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?")

408
# string processing
Theresa Pollinger's avatar
Theresa Pollinger committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    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):
424
        return self.mmtinterface.mmt_new_decl("inc", in_which_theory, "include " + self.assert_questionmark(what))
Theresa Pollinger's avatar
Theresa Pollinger committed
425
426
427
428
429

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

430
431
432
433
434
435
436
    def assert_questionmark(self, what):
        qmidx = what.find("?")
        if qmidx < 0:
            return "?" + what
        else:
            return what

Theresa Pollinger's avatar
Theresa Pollinger committed
437
438
    def new_theory(self, thyname):
        self.mmtinterface.mmt_new_theory(thyname)
439
        #(ok, root) = self.mmtinterface.query_for(self.simdata[self.state]["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
440
441
442
        self.include_bgthys(thyname)

    def new_view(self, dictentry):
443
444
445
        dictentry["viewname"] = self.construct_current_view_name(dictentry)
        #self.poutput("new view: "+dictentry["viewname"])
        ok = self.mmtinterface.mmt_new_view(dictentry["viewname"], self.viewfrom[self.state], dictentry["theoryname"])
Theresa Pollinger's avatar
Theresa Pollinger committed
446
        #recursively look for all views already done and include them
447
448
449
        for viewstring in self.get_recursively(self.simdata, "viewname"):
            if(dictentry["viewname"] != viewstring) and ok:
                ok = self.include_in(dictentry["viewname"], re.split('AS', viewstring)[-1] + " = " + viewstring)
Theresa Pollinger's avatar
Theresa Pollinger committed
450
451
452
453
454
455
        return ok

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

    def construct_view_name(self, dictentry, state):
456
        return dictentry["theoryname"][1:] + "AS" + (self.viewfrom[state][1:])
Theresa Pollinger's avatar
Theresa Pollinger committed
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585

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