Advertisement
Guest User

ECS-Plot

a guest
May 5th, 2021
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.79 KB | None | 0 0
  1. import pandas as pd
  2. import matplotlib
  3. matplotlib.use('Agg')
  4. import matplotlib.pyplot as plt
  5. import matplotlib.dates as mdates
  6. import matplotlib.ticker as mtick
  7. import mariadb, sys, json
  8. from multiprocessing import Process
  9. from ecs_web.jsonconfig import ReadConfig
  10.  
  11. class Plot:
  12. def __init__(self):
  13. self.metrics = ['Humidity', 'Temperature']
  14. self.config = ReadConfig()
  15.  
  16. def get_dataframe(self):
  17. c = self.config.database()
  18. conn = mariadb.connect(
  19. database = c['database'],
  20. user = c['user'],
  21. password = c['pass'],
  22. host = c['host'],
  23. port = c['port']
  24. )
  25. cur = conn.cursor()
  26. cur.execute(self.get_sql_query())
  27. rows = cur.fetchall()
  28. conn.close()
  29. dataframe = pd.DataFrame( [[ij for ij in i] for i in rows] )
  30. dataframe.rename(columns={0: 'DateTime', 1: 'Humidity', 2: 'Temperature'}, inplace=True)
  31. dataframe = dataframe.set_index(['DateTime'])
  32. return dataframe
  33.  
  34. def get_sql_query(self):
  35. # Generate SQL query to return rows corresponding to the greatest timescale
  36. temp = '\t'.join(self.times)
  37. if 'M' in temp:
  38. max_t = 'M'
  39. sql_d = ' MONTH'
  40. elif 'D' in temp:
  41. max_t = 'D'
  42. sql_d = ' DAY'
  43. elif 'H' in temp:
  44. max_t = 'H'
  45. sql_d = ' HOUR'
  46. elif 'min' in temp:
  47. max_t = 'min'
  48. sql_d = ' MINUTE'
  49. max_n = 0
  50. for time in self.times:
  51. if max_t in time:
  52. time_n = int(time.split(max_t)[0])
  53. if time_n > max_n:
  54. max_n = time_n
  55. return 'SELECT datetime, humidity, temp FROM environment WHERE datetime BETWEEN DATE_SUB(NOW(), INTERVAL ' + str(max_n) + sql_d \
  56. + ') AND NOW();'
  57.  
  58. def plot(self, timescales = None):
  59. if timescales:
  60. self.times = timescales.split(', ')
  61. df = self.get_dataframe()
  62. for time in self.times:
  63. for metric in self.metrics:
  64. # multiprocessing
  65. p = Process(target = self.plot_worker, args=(df, time, metric, False))
  66. p.start()
  67. p = Process(target = self.plot_worker, args=(df, time, metric, True))
  68. p.start()
  69. else:
  70. return ""
  71.  
  72. def plot_worker(self, df, time, metric, thumb):
  73. df = df.last(time)
  74. c = self.config.plot()
  75. humidity_color = c['all']['humidity_color']
  76. temperature_color = c['all']['temperature_color']
  77. tick_label_rotation = c['all']['tick_label_rotation']
  78. save_path = c['all']['save_path']
  79.  
  80. plot_line_width = c['large']['plot_line_width']
  81. major_grid_line_width = c['large']['major_grid_line_width']
  82. minor_grid_line_width = c['large']['minor_grid_line_width']
  83. plot_size_x = c['large']['plot_size_x']
  84. plot_size_y = c['large']['plot_size_y']
  85. sup_title_size = c['large']['sup_title_size']
  86. y_tick_label_size = c['large']['y_tick_label_size']
  87. x_major_tick_label_size = c['large']['x_major_tick_label_size']
  88. x_minor_tick_label_size = c['large']['x_minor_tick_label_size']
  89. x_label_size = c['large']['x_label_size']
  90. y_label_size = c['large']['y_label_size']
  91. x_label_pad = c['large']['x_label_pad']
  92. y_label_pad = c['large']['y_label_pad']
  93. rotation = c['large']['rotation']
  94. if thumb:
  95. plot_line_width = c['thumb']['plot_line_width']
  96. major_grid_line_width = c['thumb']['major_grid_line_width']
  97. minor_grid_line_width = c['thumb']['minor_grid_line_width']
  98. plot_size_x = c['thumb']['plot_size_x']
  99. plot_size_y = c['thumb']['plot_size_y']
  100. sup_title_size = c['thumb']['sup_title_size']
  101. y_tick_label_size = c['thumb']['y_tick_label_size']
  102. x_major_tick_label_size = c['thumb']['x_major_tick_label_size']
  103. x_label_size = c['thumb']['x_label_size']
  104. y_label_size = c['thumb']['y_label_size']
  105. x_label_pad = c['thumb']['x_label_pad']
  106. y_label_pad = c['thumb']['y_label_pad']
  107. rotation = c['thumb']['rotation']
  108. # create fig, ax and set size
  109. fig, ax = plt.subplots(figsize = (plot_size_x, plot_size_y))
  110. plt.ylabel(metric, fontsize=y_label_size, labelpad=y_label_pad)
  111. plt.xlabel('Time', fontsize=x_label_size, labelpad=x_label_pad)
  112. # set figure title
  113. fig.suptitle(time + ' - ' + metric, fontsize=sup_title_size)
  114. # timescale formatting
  115. if "D" in time:
  116. dayFmt = mdates.DateFormatter("%m-%d")
  117. hourFmt = mdates.DateFormatter("\n\n%-I:%M %p")
  118. ax.xaxis.set_major_locator(mdates.DayLocator())
  119. ax.xaxis.set_major_formatter(dayFmt)
  120. # format minor locator by number of days. More days = less hour ticks
  121. n = int(time.split("D")[0])
  122. if not thumb:
  123. ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=range(0,24,n)))
  124. ax.xaxis.set_minor_formatter(hourFmt)
  125. if "H" in time:
  126. hourFmt = mdates.DateFormatter("%-I %p")
  127. minuteFmt = mdates.DateFormatter("\n\n%-I:%M %p")
  128. ax.xaxis.set_major_locator(mdates.HourLocator())
  129. ax.xaxis.set_major_formatter(hourFmt)
  130. n = int(time.split("H")[0])*2
  131. if not thumb:
  132. ax.xaxis.set_minor_locator(mdates.MinuteLocator(byminute=range(0,60,n)))
  133. ax.xaxis.set_minor_formatter(minuteFmt)
  134. if "min" in time:
  135. minuteFmt = mdates.DateFormatter("%-I:%M %p")
  136. secondFmt = mdates.DateFormatter("\n\n%-I:%M:%S %p")
  137. # if minutes is too small minute/8 (for 8 major ticks) will equal 0
  138. n = 0
  139. m = 8
  140. while n == 0:
  141. n = round(int(time.split("min")[0])/m)
  142. m = m/2
  143. ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=range(0,60,round(n))))
  144. ax.xaxis.set_major_formatter(minuteFmt)
  145. n = int(time.split("min")[0])*2
  146. if not thumb:
  147. ax.xaxis.set_minor_locator(mdates.SecondLocator(bysecond=range(0,60,n)))
  148. ax.xaxis.set_minor_formatter(secondFmt)
  149. # color by metric
  150. if(metric == 'Humidity'):
  151. l_color = humidity_color
  152. ax.yaxis.set_major_formatter(mtick.PercentFormatter())
  153. else:
  154. l_color = temperature_color
  155. # plot axes
  156. ax.plot(df[metric], linewidth=plot_line_width, ls='solid', color=l_color)
  157. # set rotation and alignment
  158. plt.setp(ax.get_xticklabels(which=rotation), rotation=tick_label_rotation,
  159. ha='right')
  160. # set tick direction
  161. ax.get_xaxis().set_tick_params(which='both', direction='in')
  162. ax.get_yaxis().set_tick_params(which='both', direction='in')
  163. # set tick label sizes
  164. plt.setp(ax.get_yticklabels(), size=y_tick_label_size)
  165. plt.setp(ax.get_xticklabels(which='major'), size=x_major_tick_label_size)
  166. if not thumb:
  167. plt.setp(ax.get_xticklabels(which='minor'), size=x_minor_tick_label_size)
  168. ## show grid
  169. plt.grid(which='major', linewidth=major_grid_line_width)
  170. plt.grid(which='minor', linewidth=minor_grid_line_width)
  171. if thumb:
  172. save_f = '{}/{}_{}_thumb.png'.format(save_path, time, metric)
  173. else:
  174. save_f = '{}/{}_{}.png'.format(save_path, time, metric)
  175. plt.savefig(save_f, bbox_inches = "tight")
  176. plt.clf()
  177.  
  178. def main():
  179. pl = Plot()
  180. pl.plot('1min')
  181.  
  182. if __name__ == '__main__':
  183. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement