Time_Analysis.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import sys
  2. import os
  3. import shutil
  4. import pprint
  5. import datetime
  6. from datetime import datetime as DT
  7. import time as t
  8. import json
  9. import sqlite3
  10. from sqlite3 import Error
  11. import matplotlib.pyplot as plt
  12. import json
  13. import numpy as np
  14. import pandas as pd
  15. import matplotlib.dates as mdates
  16. def create_connection(db):
  17. try:
  18. conn = sqlite3.connect(db)
  19. return conn
  20. except Error as e:
  21. print(e)
  22. return None
  23. def Task_a0(conn):
  24. f = open('taska0.txt', 'a')
  25. cur = conn.cursor()
  26. duration_p_part = {}
  27. parts = []
  28. for part_sql in cur.execute("select instance from Instances where called_by='179' or (called_by = 'Null' and level='2') order by instance asc"):
  29. part = part_sql[0]
  30. parts.append(part)
  31. for lv2_inst in parts:
  32. cur.execute("select instance from instances where called_by='" + lv2_inst + "' order by instance asc")
  33. lv3 = cur.fetchall()
  34. duration = 0
  35. for lv3_inst in lv3:
  36. template = lv3_inst[0]
  37. cur.execute("select instance from instances i where called_by = '" + template + "' order by i.instance asc")
  38. lv4 = cur.fetchall()
  39. for lv4_inst in lv4:
  40. if not lv4_inst is None:
  41. log = lv4_inst[0]
  42. print("", file=f)
  43. print("P" + log, file=f)
  44. print("", file=f)
  45. first = True
  46. for time in cur.execute("select m.timestamp, m.level4_timestamp, m.name, m.value, log.instance from machining m join logEntries log on (log.timestamp=m.level4_timestamp and log.activity = m.level4_activity and log.step_id=m.level4_step_id) where log.instance='" + log + "' order by m.timestamp asc limit 30"):
  47. if first:
  48. time_old = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  49. first = False
  50. #if time[2] == 'Program/actBlock': # or time[2] == 'Program/blockNoStr':
  51. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  52. diff = time_new - time_old
  53. new_duration = diff.microseconds / 1000000
  54. duration = duration + new_duration
  55. print(time[2], file = f)
  56. print(duration, file=f)
  57. time_old = time_new
  58. print(new_duration, file=f)
  59. print(duration, file=f)
  60. print("-------", file=f)
  61. duration_p_part[lv2_inst] = duration / 60
  62. print(duration_p_part)
  63. print(duration_p_part, file=f)
  64. def Task_a1(conn):
  65. f = open('taska1.txt', 'a')
  66. cur = conn.cursor()
  67. optimum_dur_diff = 0
  68. overlap_dur_diff = 0
  69. duration_p_part = {}
  70. parts=[]
  71. for part_sql in cur.execute("select instance from instances where called_by='179' or (called_by = 'Null' and level='2') order by instance asc"):
  72. part = part_sql[0]
  73. parts.append(part)
  74. # print(parts)
  75. count = 0
  76. print(parts)
  77. for lv2_inst in parts:
  78. cur.execute("select instance from instances where called_by='" + lv2_inst + "' order by instance asc")
  79. lv3 = cur.fetchall()
  80. duration = 0
  81. for lv3_inst in lv3:
  82. template = lv3_inst[0]
  83. cur.execute("select instance from instances i where called_by = '" + template + "' order by i.instance asc")
  84. lv4 = cur.fetchall()
  85. overlap = False
  86. for lv4_inst in lv4:
  87. if not lv4_inst is None:
  88. log = lv4_inst[0]
  89. print("", file=f)
  90. print("P" + log, file=f)
  91. print("", file=f)
  92. first = True
  93. skip = False
  94. feedrate = 10000
  95. #spindle = 10000
  96. for time in cur.execute("select m.timestamp, m.level4_timestamp, m.name, m.value, log.instance from machining m join logEntries log on (log.timestamp=m.level4_timestamp and log.activity = m.level4_activity and log.step_id=m.level4_step_id) where log.instance='" + log + "' order by m.timestamp asc"):
  97. if first:
  98. time_old = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  99. first = False
  100. if time[2] == 'Program/actBlock': # or time[2] == 'Program/blockNoStr':
  101. #print(time[3])
  102. n = time[3].split(" ")[0]
  103. if len(n) <= 0 or '_' in n or 'N' not in n:
  104. n = 'N0'
  105. if overlap and 'N' in time[3].split(" ")[0]:
  106. print("N: " + n, file=f)
  107. print("N_old: " + n_old, file=f)
  108. if int(n[1:]) <= int(n_old[1:]): # and n != 'N0':
  109. #try:
  110. first = True
  111. print("SKIP", file=f)
  112. skip = True
  113. else:
  114. skip = False
  115. if not skip:
  116. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  117. diff = time_new - time_old
  118. new_duration = float(diff.microseconds / 1000000)
  119. if time[2] == 'Axis/feedRateOvr':
  120. feedrate =int(float(time[3])*100)
  121. if feedrate != 10000:
  122. optimum_dur_diff = optimum_dur_diff + new_duration - new_duration * feedrate/10000
  123. new_duration = new_duration * feedrate/10000
  124. duration = duration + new_duration
  125. print(duration, file = f)
  126. time_old = time_new
  127. print(time[2], file=f)
  128. print(new_duration, file=f)
  129. print(duration, file=f)
  130. print("-------", file=f)
  131. else:
  132. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  133. diff = time_new - time_old
  134. overlap_dur_diff = overlap_dur_diff + diff.microseconds / 1000000
  135. time_old=time_new
  136. if len(lv4) > 1:
  137. overlap = True
  138. n_old = n;
  139. count += 1
  140. duration_p_part[lv2_inst] = duration / 60
  141. print(duration_p_part, file = f)
  142. print(optimum_dur_diff, file = f)
  143. print(overlap_dur_diff, file=f)
  144. return duration_p_part
  145. def Task_c(conn):
  146. f = open('taskC.txt', 'a')
  147. cur = conn.cursor()
  148. optimum_dur_diff = 0
  149. overlap_dur_diff = 0
  150. duration_all_parts = {}
  151. parts=[]
  152. for part_sql in cur.execute("select instance from instances where called_by='179' or (called_by = 'Null' and level='2') order by instance asc"):
  153. part = part_sql[0]
  154. parts.append(part)
  155. # print(parts)
  156. count = 0
  157. print(parts)
  158. for lv2_inst in parts:
  159. cur.execute("select instance from instances where called_by='" + lv2_inst + "' order by instance asc")
  160. lv3 = cur.fetchall()
  161. duration_p_part = {}
  162. for lv3_inst in lv3:
  163. template = lv3_inst[0]
  164. duration = 0
  165. cur.execute("select instance from instances i where called_by = '" + template + "' order by i.instance asc")
  166. lv4 = cur.fetchall()
  167. overlap = False
  168. for lv4_inst in lv4:
  169. if not lv4_inst is None:
  170. log = lv4_inst[0]
  171. print("", file=f)
  172. print("P" + log, file=f)
  173. print("", file=f)
  174. first = True
  175. skip = False
  176. feedrate = 10000
  177. #spindle = 10000
  178. for time in cur.execute("select m.timestamp, m.level4_timestamp, m.name, m.value, log.instance from machining m join logEntries log on (log.timestamp=m.level4_timestamp and log.activity = m.level4_activity and log.step_id=m.level4_step_id) where log.instance='" + log + "' order by m.timestamp asc"):
  179. if first:
  180. time_old = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  181. first = False
  182. if time[2] == 'Program/actBlock': # or time[2] == 'Program/blockNoStr':
  183. #print(time[3])
  184. n = time[3].split(" ")[0]
  185. if len(n) <= 0 or '_' in n or 'N' not in n:
  186. n = 'N0'
  187. if overlap and 'N' in time[3].split(" ")[0]:
  188. print("N: " + n, file=f)
  189. print("N_old: " + n_old, file=f)
  190. if int(n[1:]) <= int(n_old[1:]) and n != 'N0':
  191. #try:
  192. first = True
  193. print("SKIP", file=f)
  194. skip = True
  195. else:
  196. skip = False
  197. if not skip:
  198. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  199. diff = time_new - time_old
  200. new_duration = float(diff.microseconds / 1000000)
  201. if time[2] == 'Axis/feedRateOvr':
  202. feedrate =int(float(time[3])*100)
  203. if feedrate != 10000:
  204. optimum_dur_diff = optimum_dur_diff + new_duration - new_duration * feedrate/10000
  205. new_duration = new_duration * feedrate/10000
  206. duration = duration + new_duration
  207. print(duration, file = f)
  208. time_old = time_new
  209. print(time[2], file=f)
  210. print(new_duration, file=f)
  211. print(duration, file=f)
  212. print("-------", file=f)
  213. else:
  214. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  215. diff = time_new - time_old
  216. overlap_dur_diff = overlap_dur_diff + diff.microseconds / 1000000
  217. time_old=time_new
  218. if len(lv4) > 1:
  219. overlap = True
  220. n_old = n;
  221. duration_p_part[lv3_inst[0]] = duration / 60
  222. print(duration_p_part, file = f)
  223. duration_all_parts[lv2_inst]=duration_p_part
  224. print("----------------")
  225. print("Here comes the feedrate saving")
  226. print(optimum_dur_diff)
  227. print("----------------")
  228. print("Here comes the overlap saving")
  229. print(overlap_dur_diff)
  230. print("----------------")
  231. print("Here comes the total result")
  232. print(duration_all_parts)
  233. print(optimum_dur_diff, file = f)
  234. print(overlap_dur_diff, file=f)
  235. return duration_all_parts
  236. def create_plot(duration_p_part):
  237. print(duration_p_part)
  238. result_array=[0]
  239. first = True
  240. instances=[]
  241. results = []
  242. for m in duration_p_part:
  243. print()
  244. if duration_p_part[m] == 0:
  245. continue
  246. instances.append(m)
  247. if first:
  248. l1 = float(duration_p_part[m])
  249. first = False
  250. else:
  251. l2 = float(duration_p_part[m]);
  252. learning_curve = (l2 / l1)
  253. converted_values = round(learning_curve,2)-1
  254. print(converted_values)
  255. result_array.append(converted_values)
  256. print("The Learning curve for Part_" + str(l1) + "/Part_" + str(l2) + " = " + str(converted_values)+ "%")
  257. l1=l2
  258. results.append(l2)
  259. #Used for ploting the following link: https://stackoverflow.com/questions/48413069/plot-x-axis-with-string-array-as-in-the-same-order-in-original-array-and-not-sor
  260. print(result_array)
  261. print(instances)
  262. percentage = np.array(result_array)
  263. instance = np.array(instances)
  264. plt.xticks(range(5),instance)
  265. #plt.xticks(percentage, results)
  266. #plt.yticks(percentage, instances)
  267. #plt.ylabel('Relative Time Movement')
  268. #plt.xlabel('Parts Comparison')
  269. plt.plot(percentage)
  270. plt.show()
  271. def create_plot_abs(duration_p_part):
  272. print(duration_p_part)
  273. machine_keys = duration_p_part.keys()
  274. result_array=[]
  275. first = True
  276. instances=[]
  277. results = []
  278. for m in duration_p_part:
  279. print()
  280. if duration_p_part[m] == 0:
  281. continue
  282. instances.append(m)
  283. #l1 = float(duration_p_part[m])
  284. #first = False
  285. l2 = float(duration_p_part[m]);
  286. learning_curve = l2/60
  287. converted_values = round(learning_curve,2)
  288. print(converted_values)
  289. result_array.append(converted_values)
  290. print("The Learning curve for Part_" + str(l2) + " = " + str(converted_values)+ "%")
  291. l1=l2
  292. results.append(l2)
  293. #Used for ploting the following link: https://stackoverflow.com/questions/48413069/plot-x-axis-with-string-array-as-in-the-same-order-in-original-array-and-not-sor
  294. print(result_array)
  295. percentage = np.array(result_array)
  296. instances = np.array(instances)
  297. plt.xticks(range(5),instances)
  298. #plt.yticks(percentage, instances)
  299. #plt.ylabel('Production Duration hours')
  300. #plt.xlabel('Parts Comparison')
  301. plt.plot(percentage)
  302. plt.show()
  303. def plot_time_series(b_result_instances):
  304. for ins in b_result_instances:
  305. print("-------------------")
  306. print(ins)
  307. print("-------------------")
  308. result_array = []
  309. instances = []
  310. min = []
  311. max = []
  312. myprint(b_result_instances[ins], result_array, instances, min, max)
  313. if instances and result_array:
  314. #print(instances)
  315. #print(result_array)
  316. #Used for ploting the following link: https://stackoverflow.com/questions/48413069/plot-x-axis-with-string-array-as-in-the-same-order-in-original-array-and-not-sor
  317. #print(result_array)
  318. durations = np.array(result_array)
  319. blocks = np.array(instances)
  320. sliced_durations = durations[1::4]
  321. sliced_blocks = blocks[1::4]
  322. #plt.xticks(percentage, results)
  323. #plt.yticks(percentage, instances)
  324. #plt.xticks(range(40),sliced_blocks,rotation=75)
  325. # print("-------------------")
  326. # print(durations)
  327. # print(blocks)
  328. # print("-------------------")
  329. #plt.subplot(1,2,1)
  330. #plt.ylabel('Relative Time Movement')
  331. #plt.xlabel('Blocks ')
  332. plt.xticks([])
  333. #plt.xticks(range(len(durations)), blocks)
  334. plt.plot(blocks,durations)
  335. #to see the start and end of each log file
  336. # for mi in min:
  337. # plt.axhline(y=mi, color="red")
  338. #
  339. # for ma in max:
  340. # plt.axhline(y=ma, color="blue")
  341. #plt.subplot(1,2,2)
  342. #plt.ylabel('Sliced Relative Time Movement')
  343. #plt.xlabel('Blocks')
  344. #plt.xticks([])
  345. #plt.xticks(range(len(sliced_durations)),sliced_blocks)
  346. #plt.plot(sliced_blocks,sliced_durations)
  347. #plt.plot(sliced_blocks, sliced_durations)
  348. plt.xlabel('Machine Code Sequence (NC-value)')
  349. plt.ylabel('Production Time (s)')
  350. plt.show()
  351. def myprint(d, result_array, instances, mins, maxs):
  352. #https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values
  353. for k, v in d.items():
  354. if isinstance(v, dict):
  355. #if len(v) > 1:
  356. myprint(v, result_array, instances, mins, maxs)
  357. else:
  358. if k is not None:
  359. if k == "min":
  360. mins.append(v)
  361. if k == "max":
  362. maxs.append(v)
  363. else:
  364. instances.append(k)
  365. result_array.append(v)
  366. '''
  367. def print_graph(framelist2):
  368. time_list = []
  369. task_list = []
  370. sublist = []
  371. framelist=[]
  372. for lv2 in framelist2:
  373. for lv3 in framelist2[lv2]:
  374. for value in framelist2[lv2][lv3]:
  375. time_list.append(framelist2[lv2][lv3][value])
  376. task_list.append(value)
  377. sublist=[value, framelist2[lv2][lv3][value]]
  378. framelist.append(sublist)
  379. print(time_list)
  380. print(task_list)
  381. print(sublist)
  382. ts = pd.DataFrame(framelist, columns=list('xy'))
  383. xax = np.arange(0, len(ts), 1)
  384. fig, ax = plt.subplots(1, 1)
  385. ax.plot(ts['x'], ts['y'])
  386. #ax.set_xticks(xax)
  387. #ax.set_xticks(task_list)
  388. #ax.set(np.arange(task_list))
  389. ax.set_xticks(np.arange(0, len(ts['x']), 4))
  390. #ax.set_xticklabels(ts['x'])
  391. plt.xticks(rotation=70, fontsize=11)
  392. plt.subplots_adjust(left=0.3, bottom=0.35)
  393. # # How to change interval e.g. every 20th timestamp label
  394. # drange = pd.date_range(ts['x'][0], periods=len(ts), freq="S")
  395. # values = task_list
  396. # df2 = pd.DataFrame(values, index=drange)
  397. # fig, ax = plt.subplots(1, 1)
  398. # ax.plot(df2.index, values)
  399. # ax.set_xticks(pd.date_range(ts['x'][0], periods=len(ts), freq='S'))
  400. # # ax.set_xticklabels(df2.index)
  401. #
  402. # plt.subplots_adjust(left=0.3, bottom=0.35)
  403. plt.show()
  404. time_list = []
  405. task_list = []
  406. sublist = []
  407. framelist = []
  408. fig.savefig("graphics.png")
  409. #ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d' + 'T' + '%H:%M:%S'))
  410. #print(ts['x'][0])
  411. #timearray = np.arange(ts['x'][0], ts['x'][len(ts)-1],np.timedelta64(20,'s'), dtype='datetime64')
  412. #ax.set_xticks(timearray)
  413. '''
  414. def Task_b(conn):
  415. f = open('taskB.txt', 'a')
  416. amk = open('amk.txt', 'a')
  417. cur = conn.cursor()
  418. duration_p_part = {}
  419. parts = []
  420. b_result = {}
  421. for part_sql in cur.execute(
  422. "select instance from instances where called_by='179' or (called_by = 'Null' and level='2') order by instance asc"):
  423. part = part_sql[0]
  424. parts.append(part)
  425. for lv2_inst in parts:
  426. #b_duration = 0
  427. b_result[lv2_inst] = {}
  428. duration_p_part[lv2_inst] = {}
  429. cur.execute(
  430. "select instance from instances where called_by='" + lv2_inst + "' order by instance asc")
  431. lv3 = cur.fetchall()
  432. duration = 0
  433. #the following counter helps to differntiate among the various machinings for the corresponding level 3 instances
  434. lv3_counter = 0
  435. for lv3_inst in lv3:
  436. template = lv3_inst[0]
  437. lv3_counter += 1
  438. cur.execute(
  439. "select instance from instances i where called_by = '" + template + "' order by i.instance asc")
  440. lv4 = cur.fetchall()
  441. overlap_n_value = 0
  442. for lv4_inst in lv4:
  443. # print("-------------------")
  444. # print(lv2_inst)
  445. # print("-------------------")
  446. # print(lv3_inst[0])
  447. # print(lv3_counter)
  448. # print("-------------------")
  449. if not lv4_inst is None:
  450. log = lv4_inst[0]
  451. b_result[lv2_inst]["p" + log] = {}
  452. first = True
  453. first_duration = True
  454. n_value_counter = 0
  455. # n_skip_counter = 0
  456. for time in cur.execute(
  457. "select m.timestamp, m.level4_timestamp, m.name, m.value, log.instance from machining m join logEntries log on (log.timestamp=m.level4_timestamp and log.activity = m.level4_activity and log.step_id=m.level4_step_id) where log.instance='" + log + "' order by m.timestamp asc"):
  458. if first:
  459. time_old = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  460. first = False
  461. # if time[2] == 'Program/actBlock': # or time[2] == 'Program/blockNoStr':
  462. time_new = DT.strptime(time[0], '%Y-%m-%d' + 'T' + '%H:%M:%S.%f')
  463. diff = time_new - time_old
  464. new_duration = diff.microseconds / 1000000
  465. duration = duration + new_duration
  466. #b_duration = b_duration + new_duration
  467. if time[2] == 'Program/actBlock':
  468. n = time[3].split(" ")[0]
  469. if 'N' in n and '_' not in n and len(n) > 0 and "None" not in n:
  470. #To assign to a variable to check overlaps within a certain level 4 log
  471. # if n_value_counter == 0:
  472. # n_value_counter = int(n[1:])
  473. # print(n_value_counter)
  474. # print("-------------------")
  475. # print(int(n[1:]))
  476. #in this case we have an overlap ... whats next
  477. #go to the start and send it to the dictionary including instance
  478. #skip until the condition is not met
  479. #at the end mark final n-value for this instance
  480. #if int(n[1:]) < overlap_n_value:
  481. # if first_duration:
  482. # b_result[lv2_inst]["p" + log]["min"] = duration
  483. # first_duration = False
  484. b_result[lv2_inst]["p" + log][str(lv3_counter) + n] = duration
  485. # b_result[lv2_inst]["p" + log]["max"] = duration
  486. # print("-------------------")
  487. # print(n)
  488. # print("-------------------")
  489. # For checking if overlaps happened within a log instance
  490. # if n_value_counter >= int(n[1:]):
  491. # print("-------------------")
  492. # print("Biatch i found something")
  493. # print("-------------------")
  494. # duration_p_part[lv2_inst]["p" + log] = {}
  495. # duration_p_part[lv2_inst]["p" + log][str(lv3_counter) + n] = duration
  496. # n_value_counter = int(n[1:])
  497. # if 'N' in time[3]:
  498. # n = time[3].split(" ")[0]
  499. # if n_value_counter < 3 or n_skip_counter > 75:
  500. # b_result[lv2_inst]["p" + log]["_" + n] = b_duration
  501. # n_value_counter += 1
  502. # n_skip_counter = 0
  503. # else: # n_skip_counter += 1
  504. time_old = time_new
  505. # if len(lv4) > 1 and overlap_n_value == 0:
  506. # overlap_n_value = int(n[1:])
  507. #duration_p_part[lv2_inst] = duration / 60
  508. print("------------------")
  509. print("Here comes the part durations")
  510. #print(duration_p_part)
  511. # print("------------------")
  512. # print("Here comes the part b_durations")
  513. # print(b_duration)
  514. print("-------", file=f)
  515. print(duration_p_part, file=amk)
  516. print("-------", file=f)
  517. print("-------", file=f)
  518. print(b_result, file=f)
  519. print("-------", file=f)
  520. #print(duration_p_part, file=f)
  521. return b_result
  522. print("Hello from se other side")
  523. print(os.getcwd())
  524. root_path = os.getcwd()
  525. abs_path = os.path.dirname(os.path.abspath("Business/GV12_Lowerhousing/Uni-Sachen/Task_2b/"))
  526. print("---------------")
  527. print(abs_path)
  528. db = os.path.join(root_path,"BIII.db")
  529. conn = create_connection(db)
  530. #Task_a0(conn)
  531. #duration_p_part=Task_a1(conn)
  532. #create_plot(duration_p_part)
  533. #create_plot_abs(duration_p_part)
  534. task_b_all_instances = Task_b(conn)
  535. plot_time_series(task_b_all_instances)
  536. #framelist = Task_c(conn)
  537. #print_graph(framelist)
  538. conn.close()