-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.py
More file actions
432 lines (376 loc) · 13.9 KB
/
Parser.py
File metadata and controls
432 lines (376 loc) · 13.9 KB
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
import sys as system
import os
import shutil
def parse(filename):
file = None
maxmin = 0
Eqin = []
A = []
b = []
c = []
Variables = [] # a list of the problem variable names e.g. x1, x2, x3, ... or x, y, z, w, ...
try:
file = open(filename, "r")
lines = file.readlines()
except FileNotFoundError:
print("File not found\n")
system.exit(0)
except PermissionError:
print("You have not permission to write in this file\n")
system.exit(0)
firstLine = 0
while maxmin == 0:
maxmin, firstLine = readProblemType(lines[firstLine], firstLine)
if maxmin == 1 or maxmin == -1:
print("\nMaxmin check = True")
index = 3
index = readFunc(lines[firstLine], index)
c, Variables = readVariablesAndC(lines[firstLine], Variables, index)
subjectLine = firstLine + 1
subjectLineFound = False
while not subjectLineFound:
check, subjectLine, subjectLineFound = subjectCheck(lines[subjectLine], subjectLine)
print("Subject check = " + str(check))
if check == False:
print("Syntax Error. 2nd line must be st, s.t. or subject\n")
system.exit(0)
columnsNum = len(Variables)
for line in lines[subjectLine+1:]:
Arow, belement, eqinelement = readConstraint(line, Variables, columnsNum)
if Arow:
A.append(Arow)
if belement != "":
b.append(belement)
if eqinelement is not None:
Eqin.append(eqinelement)
newFile = createNewFile(filename)
writeNewLP(newFile, A, b, c, maxmin, Eqin)
file.close()
# ------------------------------------ Methods --------------------------------------
def readProblemType(line, lineIndex):
if lineIsEmpty(line):
lineIndex += 1
return 0, lineIndex
if line.startswith("max"):
return 1, lineIndex
elif line.startswith("min"):
return -1, lineIndex
else:
print("\nMaxmin check = False")
print("Syntax Error. Wrong problem type.\n")
system.exit(0)
def readVariablesAndC(line, var, index):
var = []
c = []
number = ""
vartext = ""
number, vartext, index = readFirstElementI(line, index)
if number is not None and vartext is not None:
c.append(number)
var.append(vartext)
while index < len(line) - 1:
number, vartext, index = readElementI(line, index)
if number is not None and vartext is not None:
c.append(number)
var.append(vartext)
return c, var
def readConstraint(line, Variables, columns):
index = 0
Arow = [0]*columns
belement = ""
number = ""
elementindex = 0
eqinelement = None
if lineIsEmpty(line):
return [], belement, eqinelement
if not equationExists(line):
print("Syntax Error. Equation is missing\n")
system.exit(0)
number, elementindex, index = readFirstElementII(line, Variables, index)
if number != "":
Arow[elementindex] = number
while index < len(str(line))-1:
number, belement, elementindex, eqinelement, index = readElementII(line, Variables, index)
if number != "":
Arow[elementindex] = number
if belement != "":
return Arow, int(belement), eqinelement
return Arow, belement, eqinelement
# ------------------------------------- TOOLS ---------------------------------------
def subjectCheck(line, subIndex):
checktext = ""
index = 0
while not ( str(line[index]).isalpha() or lineIsEmpty(line) ):
index += 1
if str(line[index]).isalpha():
while not str(line[index]).isspace():
checktext += str(line[index])
index += 1
elif lineIsEmpty(line):
subIndex += 1
return False, subIndex, False
else:
print("Subject check = False")
print("Syntax Error. Subject line error.\n")
system.exit(0)
while not ( str(line[index]).isalpha() or str(line[index]) == '\n' ):
index += 1
if str(line[index]).isalpha():
print("Subject check = False")
print("Syntax Error. Subject line error\n")
system.exit(0)
elif checktext == "subject".lower() or checktext == "st".lower() or checktext == "s.t.".lower():
return True, subIndex, True
else:
return False, subIndex, True
def readVariable(text, index):
vartext = ""
while not (str(text[index]).isalpha() or index == len(str(text))-1):
index += 1
if str(text[index]).isalpha():
while (str(text[index]).isalpha() or str(text[index]).isdigit()) and index < len(str(text))-1:
vartext += str(text[index])
index += 1
if index == len(str(text)) - 1:
if str(text[index]).isalpha():
vartext += str(text[index])
return vartext, index
def readNumber(text, index):
numbertext = ""
if str(text[index]).isdigit():
while str(text[index]).isdigit():
numbertext += str(text[index])
index += 1
return numbertext, index
index += 1
while not (str(text[index]).isdigit() or str(text[index]).isalpha() or str(text[index]) == '\n' or index == len(str(text))-1
or str(text[index]) == '-' or str(text[index]) == '+' ):
index += 1
if str(text[index]).isdigit():
while not ( str(text[index]).isdigit() or index<len(str(text))-1):
index += 1
while str(text[index]).isdigit() and index<len(str(text))-1:
numbertext += str(text[index])
index += 1
if index == len(str(text))-1:
if str(text[index]).isdigit():
numbertext += str(text[index])
if str(text[index]) == '-':
numbertext = '-' + numbertext
elif str(text[index]).isalpha():
numbertext = "1"
elif str(text[index]) == '-' or str(text[index]) == '+':
print("Syntax Error. sign typed twice.\n")
system.exit(0)
return numbertext, index
#read first element from
def readFirstElementI(line, index):
numbertext = ""
vartext = ""
while not (str(line[index]).isalpha() or str(line[index]).isdigit() or line[index] == '-' or line[
index] == '+' or str(line[index]) == "\n"):
index += 1
if str(line[index]).isalpha():
numbertext = "1"
vartext, index = readVariable(line, index)
elif str(line[index]).isdigit():
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
elif str(line[index]) == '+':
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
elif str(line[index]) == '-':
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
numbertext = "-" + numbertext
if numbertext is not None:
return int(numbertext), vartext, index
return numbertext, vartext, index
#read first element from the constraints
def readFirstElementII(line, Variables, index):
numbertext = ""
vartext = ""
elementIndex = None
while not (str(line[index]).isdigit() or str(line[index]).isalpha() or str(line[index]) == '-' or
str(line[index]) == '+' or str(line[index]) == '\n'):
index += 1
if str(line[index]) == '\n':
print("Syntax Error...")
system.exit(0)
elif str(line[index]) == '+' or str(line[index]).isdigit() or str(line[index]).isalpha():
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
try:
elementIndex = Variables.index(vartext)
except ValueError:
print("Syntax Error. Variable name not found.\n")
system.exit(0)
elif str(line[index]) == '-':
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
numbertext = "-" + numbertext
try:
elementIndex = Variables.index(vartext)
except ValueError:
print("Syntax Error. Variable name not found.\n")
system.exit(0)
if numbertext != "":
return int(numbertext), elementIndex, index
return numbertext, elementIndex, index
#read an element from
def readElementI(line, index):
numbertext = ""
vartext = ""
while not (str(line[index]).isdigit() or str(line[index]).isalpha() or str(line[index]) == '-' or str(
line[index]) == '+' or str(line[index]) == "\n"):
index += 1
if str(line[index]).isdigit() or str(line[index]).isalpha():
print("Syntax Error. Sign is missing.\n")
system.exit(0)
elif str(line[index]) == '+':
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
elif str(line[index]) == '-':
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
numbertext = "-" + numbertext
elif str(line[index]) == "\n":
return None, None, index
if numbertext != "":
return int(numbertext), vartext, index
return numbertext, vartext, index
#read an element from the constraints
def readElementII(line, Variables, index):
numbertext = ""
vartext = ""
belement = ""
elementIndex = None
eqinelement = None
isNegative = False
while not (str(line[index]).isdigit() or str(line[index]).isalpha() or str(line[index]) == '-' or str(line[index]) == '+' or
str(line[index]) == '\n' or str(line[index]) == '>' or str(line[index]) == '<' or str(line[index]) == '=' or index == len(line)-1):
index += 1
if str(line[index]).isdigit() or str(line[index]).isalpha():
print("Syntax Error. Sign is missing.")
system.exit(0)
elif str(line[index]) == '<' or str(line[index]) == '>' or str(line[index]) == '=':
eqinelement, index = readEquation(line, index)
while not ( str(line[index]).isdigit() or str(line[index]) == '+' or str(line[index]) == '-' ):
index += 1
if str(line[index]) == '-':
isNegative = True
belement, index = readNumber(line, index)
if isNegative:
belement = "-" + belement
elif str(line[index]) == '+' or str(line[index]) == '-':
if str(line[index]) == '-':
isNegative = True
numbertext, index = readNumber(line, index)
vartext, index = readVariable(line, index)
try:
elementIndex = Variables.index(vartext)
except ValueError:
print("Syntax Error. Variable name not found.\n")
system.exit(0)
if isNegative:
numbertext = "-" + numbertext
if numbertext != "":
if belement != "":
return int(numbertext), int(belement), elementIndex, eqinelement, index
return int(numbertext), belement, elementIndex, eqinelement, index
return numbertext, belement, elementIndex, eqinelement, index
def readEquation(text, index):
equationtext = ""
while not ( str(text[index]) == '>' or str(text[index]) == '<' or str(text[index]) == '=' or str(text[index]) == '\n' ):
index += 1
if str(text[index]) == '\n':
print("Syntax Error. Wrong equation.\n")
system.exit(0)
while not ( str(text[index]).isspace() or str(text[index]) == '\n' or str(text[index]) == '-' or str(text[index]) == '+' ):
equationtext += str(text[index])
index += 1
if equationtext == ">=":
return 1, index
elif equationtext == "<=":
return -1, index
elif equationtext == "=":
return 0, index
else:
print("Syntax Error. Wrong equation.\n")
system.exit(0)
return equationtext, index
def equationExists(line):
if ">" in line or "<" in line or "=" in line:
return True
else:
return False
def lineIsEmpty(line):
isEmpty = True
index = 0
while index < len(line)-1:
if str(line[index]).isalnum():
isEmpty = False
break
index += 1
return isEmpty
def readFunc(text, index):
while not ( str(text[index]).isalnum() or str(text[index]) == '\n' or str(text[index]) == '-' or str(text[index]) == '+'):
index += 1
if str(text[index]).isalpha():
while str(text[index]).isalpha() or str(text[index]).isdigit():
index += 1
while not (str(text[index]) == '=' or str(text[index]) == '\n'):
index += 1
if str(text[index]) == '=':
return index
else:
print("Syntax Error. '=' symbol is missing.\n")
system.exit(0)
else:
print("Syntax Error. Function name is missing or is wrong.\n")
system.exit(0)
return index
def getVariables():
return Variables
def createNewFile(filename):
noExtensionName = ""
extension = ""
index = 0
while filename[index] != '.':
noExtensionName += filename[index]
index += 1
while index < len(filename):
extension += filename[index]
index += 1
newFileName = noExtensionName + "New" + extension
file = None
try:
if os.path.exists(newFileName):
os.remove(newFileName)
file = open(newFileName, "w")
except FileNotFoundError:
print("File not found\n")
system.exit(0)
except PermissionError:
print("You have not permission to write in this file\n")
system.exit(0)
return file
def writeNewLP(file, A, b, c, maxmin, Eqin):
file.write("maxmin = " + str(maxmin) + 2 * "\n")
file.write("c = " + str(c) + 2 * "\n")
file.write("A = ")
file.write(str(A[0]) + "\n")
for row in A[1:]:
file.write(4 * " " + str(row) + "\n")
file.write(2 * "\n" + "b = " + str(b) + 2 * "\n")
file.write("Eqin = " + str(Eqin) + 2 * "\n")
# ----------------------------------------------------------------------------------------
def main():
filename = str(input("\nType problem file name: "))
parse(filename)
try:
shutil.rmtree("__pycache__")
except OSError as e:
pass
if __name__ == "__main__":
main()