-
Notifications
You must be signed in to change notification settings - Fork 1
/
App.py
393 lines (350 loc) · 10.8 KB
/
App.py
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
'''
App.py is the main module of the project. It contains all of the basic functions.
It also contains the demo and random generator to see the evolution.
In complexities: A = Accounts, T = Transactions, U = Users
Consider that usually T could be considered as a constant. Because in most algorithms,
except in the related to graph operations, T is max 15.
'''
from collections import namedtuple
import matplotlib.pyplot as plt
import names
import networkx as nx
import numpy as np
import BankHash
import GraphOperations
import Nodes
Arc = namedtuple('Arc', ('tail', 'weight', 'head'))
accountsHash = BankHash.BankHash()
usersHash = BankHash.BankHash()
def newUser(uId, name):
'''
Creates a new user. It's added to the user's hashtable.
Worst-Case: O(U)
Average-Case: θ(1)
'''
user = Nodes.User(uId, name)
usersHash.put(user)
return user
def deleteUser(uId):
'''
Deletes an user in the user's hashtable.
Worst-Case: O(U)
Average-Case: θ(1)
'''
user = usersHash.delete(uId)
return user
def getUser(uId):
'''
Searches an user in the user's hashtable.
Worst-Case: O(U)
Average-Case: θ(1)
'''
return usersHash.get(uId)
def getUserRandom():
'''
Gets a random user from the hashtable.
Worst-Case: O(U)
Average-Case: θ(1)
'''
return usersHash.getRandomItem()
def getUsersNum():
'''
UTILITY
Gets user's hashtable size
Worst-Case: O(1)
Average-Case: θ(1)
'''
return usersHash.size
def printUsers():
'''
UTILITY
Prints all the existing users with data
Worst-Case: O(U)
Average-Case: θ(U)
'''
print(usersHash)
return
def newAccount(aId, userId, aType, balance):
'''
Creates a new account. It's added to the account's hashtable.
First it searches the user object to assign this new account.
Then the account is added to the user's maxheap.
Worst-Case: O(U + A + log(A))
Average-Case: θ(1)
'''
user = getUser(userId)
account = Nodes.Account(aId, userId, aType, balance)
user.addAccount(account)
accountsHash.put(account)
return account
def deleteAccount(aId):
'''
Deletes an account. It's it's removed from account's hashtable.
First it searches the user object to delete this account.
Then the account is removed from the user's maxheap.
Worst-Case: O(U + A + log(A))
Average-Case: θ(1 + log(A))
'''
account = accountsHash.delete(aId)
user = getUser(account.userID)
user.removeAccount(account)
return account
def getAccount(aId):
'''
Searches an account in the account's hashtable.
Worst-Case: O(A)
Average-Case: θ(1)
'''
return accountsHash.get(aId)
def getAccountRandom():
'''
Gets a random account from the hashtable.
Worst-Case: O(A)
Average-Case: θ(1)
'''
return accountsHash.getRandomItem()
def getAccsNum():
'''
Gets user's hashtable size
Worst-Case: O(1)
Average-Case: θ(1)
'''
return accountsHash.size
def printAccounts():
'''
UTILITY
Prints all the existing accounts with data
Worst-Case: O(A)
Average-Case: θ(A)
'''
print(accountsHash)
return
def makeTransaction(userID, accountID, destinationID, qty):
'''
Makes a new transaction beetween accounts.
First it searches the user that is making the transaction in the user's hashtable.
Then it searches both the origin and destination account in the account's hashtable.
Finally it makes the transaction (Increasing the keay in the heap).
Worst-Case: O(U + 2A + log(A))
Average-Case: θ(1)
'''
user = getUser(userID)
origin = getAccount(accountID)
destiny = getAccount(destinationID)
return user.makeTransaction(origin, destiny, qty)
def DFS(startID):
'''
Returns the DFS of the graph. It first searches the the account in the hashtable.
Worst-Case: O(2A + T)
Average-Case: θ(1 + A + T)
'''
return GraphOperations.DephtFS(getAccount(startID))
def BFS(startID):
'''
Returns the BFS of the graph. It first searches the the account in the hashtable.
Worst-Case: O(2A + T)
Average-Case: θ(1 + A + T)
'''
return GraphOperations.BreadthFS(getAccount(startID))
def edmonds():
'''
Returns the maximum spanning tree of the graph.
It uses the minimum spanning tree's logic, but with the negated weights, to obtain the maximum.
Complexity:
Worst-Case: O(A + A^2 + T)
Average-Case: θ(A + A^2 + T)
'''
arcsResult = GraphOperations.edmonds(getEdgesAsArcs(), 'A1')
arcsToReturn = []
for i, arc in enumerate(arcsResult.values()):
arcsToReturn.append(Arc(arc.tail, -arc.weight, arc.head))
return arcsToReturn
def getEdgesAsArcs(trueValues=False):
'''
UTILITY
Function that obtains all of the edges in the graph
It's used to draw the graph.
Uses arcs tuplet
Worst-Case: O(A + T)
Average-Case: θ(A + T)
'''
arcs = []
accounts = accountsHash.getAll()
for account in accounts:
edges = account.getEdgesListFull()
for edge in edges:
if trueValues:
arcs.append(Arc(account.idAccount, edge.uses, edge.dest.idAccount))
else:
arcs.append(Arc(account.idAccount, -edge.uses, edge.dest.idAccount))
return arcs
def updateGraph():
'''
Plots the graph
'''
arcs = getEdgesAsArcs(True)
plt.ion()
plt.clf()
g = nx.DiGraph((x, y, {'weight': w}) for (x, w, y) in arcs)
pos = nx.spring_layout(g)
nx.draw_networkx_nodes(g, pos, cmap=plt.get_cmap('jet'), node_size=500)
nx.draw_networkx_labels(g, pos, font_size=8)
nx.draw_networkx_edges(g, pos, arrows=True)
plt.pause(.5)
plt.show()
return
def numberToType(n):
'''
UTILITY
Swich-type-dictionary
Complexity: O(1)
Average-Case: θ(1)
'''
switcher = {
0: 'C',
1: 'D'
}
return switcher.get(n)
def getRandomUniformInt(end, start = 0):
'''
UTILITY
Generates a random int using a uniform distribution
Complexity: O(1)
'''
return int(np.random.uniform(start, end))
def getRandomNormalAccount(user):
'''
UTILITY
Gets a random account of an user, using a normal distribution.
Complexity: O(alpha)
'''
accs = user.getOrderedAccounts()
mean = (len(accs)-1)//2
stddev = len(accs) / 6
while True:
i = int(np.random.normal(mean, stddev))
if 0 <= i < len(accs):
return accs[i]
return
def main():
'''
newUser("U1", "Miguel")
U1 = getUser("U1")
print(str(U1) + "\n")
newUser("U2", "Luis")
newUser("U3", "Richie")
printUsers()
newAccount("A1", "U1", 'D', 100)
newAccount("A2", "U2", 'D', 1000)
newAccount("A3", "U1", 'C', 0)
newAccount("A4", "U1", 'D', 10)
newAccount("A5", "U3", 'D', 10000)
newAccount("A6", "U1", 'D', 100)
printUsers()
printAccounts()
U1.printAccounts()
makeTransaction("U1", "A1", "A2", 50)
makeTransaction("U1", "A1", "A2", 50)
makeTransaction("U1", "A1", "A2", 50)
makeTransaction("U3", "A5", "A3", 100)
makeTransaction("U1", "A6", "A2", 5)
print()
printAccounts()
U1.printAccounts()
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 1)
makeTransaction("U1", "A3", "A2", 100)
makeTransaction("U1", "A3", "A2", 200)
makeTransaction("U1", "A3", "A2", 300)
makeTransaction("U1", "A2", "A1", 1)
print()
printAccounts()
U1.printAccounts()
A2 = getAccount("A2")
for o, m in A2.pointingAtMe:
print(o.getId() + " " + str(m))
print()
print(DFS("A3"))
print(BFS("A3"))
print(edmonds())
'''
forced = 0
while True:
if forced == 0:
tOperation = getRandomUniformInt(15)
elif forced == 1: # Forced to create user
tOperation = 13
elif forced == 2: # Forced to create account
tOperation = 8
if tOperation >= 13: # Make new user
forced = 0
print("New User")
uNum = getRandomUniformInt(1000000)
while True:
if getUser("U"+str(uNum)) is None:
newUser("U"+str(uNum), names.get_full_name())
break
else:
uNum = getRandomUniformInt(1000000)
elif tOperation >= 8: # Make new acount
if getUsersNum() < 1:
print("New Account Impossible. Users: " + str(getUsersNum()))
forced = 1
continue
else:
forced = 0
print("New Account")
aNum = getRandomUniformInt(1000000000)
while True:
if getAccount("A"+str(aNum)) is None:
aType = numberToType(getRandomUniformInt(2))
if aType == 'D':
aAmount = getRandomUniformInt(100000)
else:
aAmount = 0
newAccount("A"+str(aNum), getUserRandom().getId(), aType, aAmount)
break
else:
aNum = getRandomUniformInt(1000000000)
else: # Make new transaction
if getUsersNum() < 2:
print("New Transaction Impossible. Users: " + str(getUsersNum()))
forced = 1
continue
elif getAccsNum() < 2:
print("New Transaction Impossible. Accs: " + str(getAccsNum()))
forced = 2
continue
else:
forced = 0
print("New Transaction")
user = getUserRandom()
while True:
if len(user.accounts) > 0:
break
else:
user = getUserRandom()
accOrigin = getRandomNormalAccount(user)
accDest = getAccountRandom().getId()
while accOrigin == accDest:
accDest = getAccountRandom().getId()
amount = getRandomUniformInt(getAccount(accOrigin).balance, 1) if getAccount(accOrigin).accType == 'D' else getRandomUniformInt(10000, 1)
makeTransaction(user.getId(), accOrigin, accDest, amount)
updateGraph()
while True:
plt.pause(0.5)
if __name__ == '__main__':
main()