[python] Anvil Background Code

Viewer

copydownloadembedprintName: Anvil Background Code
  1. # set the threshold for consecutive overuse
  2.         self.overuse_counter = 0  # initialize consecutive overuse
  3.  
  4.     def input_current_consumption(self, hour):
  5.         consumption = float(input(f"Enter current consumption for {self.name}: "))
  6.         self.current.append(consumption)
  7.     def update_differences(self):
  8.         now = datetime.datetime.now()
  9.         day_of_week = now.weekday()  # Monday is 0 and Sunday is 6
  10.         hour_of_day = now.hour
  11.  
  12.         # Ensure lists are of adequate size for today
  13.         required_size = hour_of_day + 1
  14.         self.ensure_list_size(self.sum_baseline, required_size)
  15.         self.ensure_list_size(self.sum_current, required_size)
  16.         self.ensure_list_size(self.difference, required_size)
  17.  
  18.         if day_of_week < len(self.current):
  19.             cumulative_current = 0
  20.             cumulative_baseline = 0
  21.             for hour in range(hour_of_day + 1):
  22.                 current_consumption = self.current[day_of_week][hour] if hour < len(self.current[day_of_week]) else 0
  23.                 baseline_consumption = self.baseline[day_of_week][hour] if hour < len(self.baseline[day_of_week]) else 0
  24.                 cumulative_current += current_consumption
  25.                 cumulative_baseline += baseline_consumption
  26.                 # Update the sums and differences for each hour up to the current hour
  27.                 self.sum_current[hour] = cumulative_current
  28.                 self.sum_baseline[hour] = cumulative_baseline
  29.                 self.difference[hour] = current_consumption - baseline_consumption
  30.         else:
  31.             print(f"No current consumption data available for {self.name} on day {day_of_week} up to hour {hour_of_day}")
  32.  
  33.     def calculate_hourly_consumption(self):
  34.         # Choose which sum to process, for example, self.sum_baseline
  35.         cumulative_sum = self.sum_baseline  # Change to self.sum_current if needed
  36.  
  37.         if not cumulative_sum:
  38.             print(f"No data available for {self.name}")
  39.             return
  40.  
  41.         self.graph = []
  42.  
  43.         self.graph.append(cumulative_sum[0])
  44.  
  45.         for i in range(1, len(cumulative_sum)):
  46.             hourly_consumption = cumulative_sum[i] - cumulative_sum[i - 1]
  47.             self.graph.append(hourly_consumption)
  48.  
  49.         print(f"Hourly consumption for {self.name}: {self.graph}")
  50.         return self.graph
  51.  
  52.     def update_graph_with_percentage_differences(self):
  53.         # Calculate hourly values from cumulative sums
  54.         hourly_baseline = [self.sum_baseline[0]] + [self.sum_baseline[i] - self.sum_baseline[i - 1] for i in
  55.                                                     range(1, len(self.sum_baseline))]
  56.         hourly_current = [self.sum_current[0]] + [self.sum_current[i] - self.sum_current[i - 1] for i in
  57.                                                   range(1, len(self.sum_current))]
  58.  
  59.         # Calculate percentage differences and store in self.graph
  60.         self.graph = [(c - b) / b * 100 for c, b in zip(hourly_current, hourly_baseline) if b != 0]
  61.         print(f"Hourly Percentage Difference for {self.name}: {self.graph}")
  62.  
  63.     def update_graph_difference(self):
  64.         self.graph = self.difference
  65.         print(f"Difference for baseline of {self.name}: {self.graph}")
  66.  
  67.     def update_graph_current_consumption(self):
  68.         self.graph = self.sum_current
  69.         print(f"Sum of the current consumption of {self.name}: {self.graph}")
  70.  
  71.     def calculate_cumulative_percentage_difference(self):
  72.         if not self.sum_current or not self.sum_baseline:
  73.             print(f"No data available for {self.name} to calculate cumulative percentage differences.")
  74.             return
  75.  
  76.         self.graph = []  
  77.  
  78.         for current, baseline in zip(self.sum_current, self.sum_baseline):
  79.             if baseline != 0:  # Avoid division by zero
  80.                 percentage_difference = (current - baseline) / baseline * 100
  81.             else:
  82.                 percentage_difference = 0  # Handle the case where baseline is 0
  83.             self.graph.append(percentage_difference)
  84.  
  85.         print(f"Cumulative percentage differences for {self.name}: {self.graph}")
  86.         return self.graph
  87.  
  88.     def ensure_list_size(self, list_to_check, required_size):
  89.         while len(list_to_check) < required_size:
  90.             list_to_check.append(0)
  91.     def print_differences(self):
  92.         # Ensure differences are updated before printing
  93.         self.update_differences()
  94.  
  95.         print(f"Differences for {self.name}:")
  96.         print(f"Current Sum {self.sum_current}:")
  97.         print(f"Baseline Sum {self.sum_baseline}:")
  98.  
  99.  
  100.     def compare_consumption(self):
  101.         current_time = datetime.datetime.now()
  102.         day_of_week = current_time.weekday()  # 0 is Monday, 6 is Sunday
  103.         hour_of_day = current_time.hour
  104.  
  105.         # Round up the time to the next hour if needed
  106.         if current_time.minute >= 30:
  107.             hour_of_day = (hour_of_day + 1) % 24
  108.  
  109.         if day_of_week < len(self.current) and hour_of_day < len(self.current[day_of_week]):
  110.             current_consumption = self.current[day_of_week][hour_of_day]
  111.             baseline_consumption = self.baseline[day_of_week][hour_of_day]
  112.  
  113.             if baseline_consumption < 1 and current_consumption > 2 or current_consumption > 1.5 * baseline_consumption:
  114.                 self.overuse_counter += 1
  115.                 if self.overuse_counter >= self.overuse_threshold:
  116.                     print(
  117.                         f"Alert: {self.name} is using too much power at hour {hour_of_day} for {self.overuse_threshold} consecutive times.")
  118.                 else:
  119.                     # Print warning without triggering the alert counter
  120.                     print(f"Warning: {self.name} is using too much power at hour {hour_of_day}.")
  121.             else:
  122.                 self.overuse_counter = 0  # Reset counter if the condition doesn't meet
  123.     def compare_consumption_manual(self, day_of_week, hour):
  124.         if day_of_week < len(self.current) and hour < len(self.current[day_of_week]):
  125.             current_consumption = self.current[day_of_week][hour]
  126.             baseline_consumption = self.baseline[day_of_week][hour]
  127.  
  128.             # Logic to check overuse based on the threshold
  129.             if baseline_consumption < 1 and current_consumption > 2 or current_consumption > 1.5 * baseline_consumption:
  130.                 self.overuse_counter += 1
  131.                 if self.overuse_counter >= self.overuse_threshold:  # Use the dynamic threshold
  132.                     print(
  133.                         f"Alert: {self.name} is using too much power at hour {hour} for {self.overuse_threshold} consecutive times.")
  134.             else:
  135.                 self.overuse_counter = 0  # Reset counter if the condition doesn't meet
  136.  
  137.     #@staticmethod
  138.     def calculate_percentage_difference(current_sum, baseline_sum):
  139.         return (current_sum - baseline_sum) / baseline_sum * 100
  140.  
  141.  
  142. daily_winners = []
  143. current_pairings = []
  144. """def randomize_pairings():
  145.     shuffled_labs = random.sample(labs, len(labs))  # Randomly shuffle labs
  146.     return [(shuffled_labs[i], shuffled_labs[i+1]) for i in range(0, len(shuffled_labs), 2)]"""
  147. # Global variable to keep track of which lab to double
  148. current_double_index = 0
  149.  
  150.  
  151. def randomize_pairings():
  152.     global current_double_index
  153.     labs_with_double = labs[:]  # Create a copy of the labs list
  154.  
  155.     # Double up the current lab
  156.     labs_with_double.append(labs[current_double_index])
  157.  
  158.     # Shuffle the modified list
  159.     shuffled_labs = random.sample(labs_with_double, len(labs_with_double))
  160.  
  161.     # Create pairings
  162.     pairings = [(shuffled_labs[i], shuffled_labs[i + 1]) for i in range(0, len(shuffled_labs) - 1, 2)]
  163.  
  164.     # Move to the next lab for doubling in the last run (this works I think)
  165.     current_double_index = (current_double_index + 1) % len(labs)
  166.  
  167.     return pairings
  168.  
  169.  
  170. def finalize_daily_results():
  171.     # Keep only the last len(labs)/2 winners, as each lab participates in one battle per cycle.
  172.     recent_winners = daily_winners[-(len(labs) // 2):]
  173.     print("Final results for the day:")
  174.     for winner in recent_winners:
  175.         print(f"{winner} won the battle today.")
  176.     # Optionally reset daily_winners if you're starting a new day of battles.
  177.     daily_winners.clear()
  178.  
  179.  
  180.  
  181. last_check_day = datetime.datetime.now().day
  182. def input_current_consumption(self, sensor_gid, vue):
  183.         devices = vue.get_devices()
  184.         channel = None
  185.  
  186.         # Find the channel that matches the sensor_gid (PyEmVue API Use)
  187.         for device in devices:
  188.             if device.device_gid == sensor_gid:
  189.                 channel = device.channels[0]
  190.                 break
  191.  
  192.         if channel:
  193.             end_time = datetime.datetime.now(datetime.timezone.utc)
  194.             start_time = end_time - datetime.timedelta(minutes=1)
  195.             usage_over_time, start_time = vue.get_chart_usage(channel, start_time, end_time, scale=Scale.MINUTE.value,
  196.                                                               unit=Unit.KWH.value)
  197.  
  198.             if usage_over_time:
  199.                 total_usage_1_minute = (sum(usage_over_time) / 2) * 1000  # kWh to Watts conversion
  200.                 self.current.append(total_usage_1_minute)
  201.             else:
  202.                 print(f"No data available for sensor GID: {sensor_gid}")
  203.         else:
  204.             print(f"Device with GID {sensor_gid} not found")
  205.  
  206.  
  207.  
  208.  
  209.  
  210. def arrange_function(rankings):
  211.     for i in range(len(rankings)):
  212.         for j in range(i + 1, len(rankings)):
  213.             if (rankings[i][1]) > (rankings[j][1]):
  214.                 # Swap
  215.                 rankings[i], rankings[j] = rankings[j], rankings[i]
  216.  
  217.  
  218. def initialize_current_consumption_with_baseline(lab_instance, baseline_data):
  219.     lab_instance.current = copy.deepcopy(baseline_data)
  220.  
  221.  
  222. def update_lab_current_consumption(lab, total_consumption):
  223.  
  224.     current_time = datetime.datetime.now()
  225.     day_of_week = current_time.weekday()  # 0 is Monday, 6 is Sunday
  226.  
  227.     while len(lab.current) <= day_of_week:
  228.         lab.current.append([0] * 24)  # Initialize with zeroes for each hour
  229.  
  230.     hour_of_day = current_time.hour  # 0 to 23
  231.  
  232.  
  233.     lab.current[day_of_week][hour_of_day] = total_consumption
  234.  
  235.  
  236. def sum_consumption_and_baseline(labs):
  237.     # Get the current time details
  238.     now = datetime.datetime.now()
  239.     day_of_week = now.weekday()  # Monday is 0 and Sunday is 6
  240.     hour_of_day = now.hour
  241.  
  242.     # Sum initial
  243.     total_current_consumption = 0
  244.     total_baseline_consumption = 0
  245.  
  246.     # Iterate
  247.     for lab in labs:
  248.         # Sum the consumption from the start of the week to the current hour today
  249.         for day in range(day_of_week + 1):  # current day included
  250.             if day < day_of_week:  
  251.                 total_current_consumption += sum(lab.current[day])
  252.                 total_baseline_consumption += sum(lab.baseline[day])
  253.             else:  
  254.                 total_current_consumption += sum(lab.current[day][:hour_of_day + 1])
  255.                 total_baseline_consumption += sum(lab.baseline[day][:hour_of_day + 1])
  256.  
  257.     # Calcul dif
  258.     difference = total_current_consumption - total_baseline_consumption
  259.  
  260.     print(f"Total current consumption from all labs: {total_current_consumption}")
  261.     print(f"Total baseline consumption from all labs: {total_baseline_consumption}")
  262.     print(f"Difference between total consumption and baseline: {difference}")
  263.  
  264.     return total_current_consumption, total_baseline_consumption, difference
  265.  
  266.  
  267.  
  268.  
  269. """def battle(lab1, lab2, rankings):
  270.     current_time = datetime.datetime.now()
  271.     day_of_week = current_time.weekday()  # 0 is Monday, 6 is Sunday
  272.     hour_of_day = current_time.hour +1
  273.  
  274.     # Round up the time to the next hour for summation
  275.     if current_time.minute >= 30:
  276.         hour_of_day += 1
  277.     print(hour_of_day)
  278.     # Ensure hour_of_day does not exceed 23 (max index for hourly data)
  279.     hour_of_day = min(hour_of_day, 23)
  280.  
  281.     # Sum up to the current (or next, if rounded up) hour
  282.     sum_current_1 = sum(lab1.current[day_of_week][:hour_of_day])
  283.     sum_baseline_1 = sum(lab1.baseline[day_of_week][:hour_of_day])
  284.     print(sum_current_1)
  285.     print(sum_baseline_1)
  286.     sum_current_2 = sum(lab2.current[day_of_week][:hour_of_day])
  287.     sum_baseline_2 = sum(lab2.baseline[day_of_week][:hour_of_day])
  288.  
  289.     percent_diff_1 = Lab.calculate_percentage_difference(sum_current_1, sum_baseline_1)
  290.     percent_diff_2 = Lab.calculate_percentage_difference(sum_current_2, sum_baseline_2)
  291.  
  292.     rankings.append([lab1.name, percent_diff_1])
  293.     rankings.append([lab2.name, percent_diff_2])
  294.  
  295.     winner = lab1.name if percent_diff_1 < percent_diff_2 else lab2.name
  296.     daily_winners.append(winner)  # Append the name of the winner to the daily_winners list
  297.     print(f"The winner is {winner}.")
  298.     print(f"Difference between {lab1.name} and baseline: {percent_diff_1:.2f}%")
  299.     print(f"Difference between {lab2.name} and baseline: {percent_diff_2:.2f}%")"""
  300.  
  301. def battle(lab1, lab2, rankings):
  302.     current_time = datetime.datetime.now()
  303.     day_of_week = current_time.weekday()  # 0 is Monday, 6 is Sunday
  304.     hour_of_day = current_time.hour + 1
  305.  
  306.     # Round up the time to the next hour for summation
  307.     if current_time.minute >= 30:
  308.         hour_of_day += 1
  309.     print(hour_of_day)
  310.     # Ensure hour_of_day does not exceed 23 (max index for hourly data)
  311.     hour_of_day = min(hour_of_day, 23)
  312.  
  313.     # Sum up to the current (or next, if rounded up) hour
  314.     sum_current_1 = sum(lab1.current[day_of_week][:hour_of_day])
  315.     sum_baseline_1 = sum(lab1.baseline[day_of_week][:hour_of_day])
  316.     sum_current_2 = sum(lab2.current[day_of_week][:hour_of_day])
  317.     sum_baseline_2 = sum(lab2.baseline[day_of_week][:hour_of_day])
  318.  
  319.     percent_diff_1 = Lab.calculate_percentage_difference(sum_current_1, sum_baseline_1)
  320.     percent_diff_2 = Lab.calculate_percentage_difference(sum_current_2, sum_baseline_2)
  321.  
  322.     # Update rankings with checking for duplicates
  323.     update_ranking(rankings, lab1.name, percent_diff_1)
  324.     update_ranking(rankings, lab2.name, percent_diff_2)
  325.  
  326.     winner = lab1.name if percent_diff_1 < percent_diff_2 else lab2.name
  327.     daily_winners.append(winner)  
  328.     print(f"The winner is {winner}.")
  329.     print(f"Difference between {lab1.name} and baseline: {percent_diff_1:.2f}%")
  330.     print(f"Difference between {lab2.name} and baseline: {percent_diff_2:.2f}%")
  331.  
  332. def update_ranking(rankings, lab_name, percent_diff):
  333.     for ranking in rankings:
  334.         if ranking[0] == lab_name:
  335.             ranking[1] = percent_diff
  336.             break
  337.     else:
  338.         rankings.append([lab_name, percent_diff])
  339.  
  340. def save_lab_current_to_file(labs, folder_path):
  341.     # Ensure the folder exists
  342.     if not os.path.exists(folder_path):
  343.         os.makedirs(folder_path)
  344.  
  345.     file_path = os.path.join(folder_path, "lab_consumption_data.txt")
  346.  
  347.     with open(file_path, "a") as file:
  348.         # date
  349.         file.write(f"Update Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
  350.         for lab in labs:
  351.             # name
  352.             file.write(f"{lab.name} current consumption: {lab.current}\n")
  353.         file.write("\n")
  354.  
  355.  
  356. """def sum_and_compare_each_lab(labs):
  357.     now = datetime.datetime.now()
  358.     day_of_week = now.weekday()  # Monday is 0 and Sunday is 6
  359.     hour_of_day = now.hour
  360.  
  361.     # Iterate through each lab
  362.     for lab in labs:
  363.         # Initialize the sums for this lab
  364.         lab_current_consumption = 0
  365.         lab_baseline_consumption = 0
  366.  
  367.         # Sum the consumption from the start of the week to the current hour today for this lab
  368.         for day in range(day_of_week + 1):  # Include today
  369.             if day < day_of_week:  # Full day
  370.                 lab_current_consumption += sum(lab.current[day])
  371.                 lab_baseline_consumption += sum(lab.baseline[day])
  372.             else:  # Today, sum up to the current hour
  373.                 lab_current_consumption += sum(lab.current[day][:hour_of_day + 1])
  374.                 lab_baseline_consumption += sum(lab.baseline[day][:hour_of_day + 1])
  375.  
  376.         # Calculate the difference and percentage difference
  377.         difference = lab_current_consumption - lab_baseline_consumption
  378.         percent_difference = (difference / lab_baseline_consumption * 100) if lab_baseline_consumption != 0 else float(
  379.             'inf')
  380.  
  381.         # Print the results for this lab
  382.         print(f"Lab {lab.name}:")
  383.         print(f"  Current consumption: {lab_current_consumption}")
  384.         print(f"  Baseline consumption: {lab_baseline_consumption}")
  385.         print(f"  Difference: {difference}")
  386.         print(f"  Percentage difference: {percent_difference:.2f}%\n")"""
  387.  
  388. def sum_and_compare_each_lab(labs):
  389.     # Iterate through each lab
  390.     for lab in labs:
  391.         if lab.sum_current and lab.sum_baseline:
  392.             # Fetch the last updated values for current and baseline consumption
  393.             lab_current_consumption = lab.sum_current[-1]
  394.             lab_baseline_consumption = lab.sum_baseline[-1]
  395.             difference = lab_current_consumption - lab_baseline_consumption
  396.             percent_difference = (difference / lab_baseline_consumption * 100) if lab_baseline_consumption != 0 else float('inf')
  397.  
  398.             # Print the results for this lab
  399.             print(f"Lab {lab.name}:")
  400.             print(f"  Current consumption up to now: {lab_current_consumption}")
  401.             print(f"  Baseline consumption up to now: {lab_baseline_consumption}")
  402.             print(f"  Difference: {difference}")
  403.             print(f"  Percentage difference: {percent_difference:.2f}%\n")
  404.         else:
  405.             print(f"Data for {lab.name} is incomplete or not updated.")
  406.  
  407.  
  408.  
  409. """def get_total_lab_consumption(vue, lab, time_delta_minutes):
  410.     while True:
  411.         try:
  412.             total_consumption = 0
  413.             end_time = datetime.datetime.now(datetime.timezone.utc)
  414.             start_time = end_time - datetime.timedelta(minutes=time_delta_minutes)
  415.  
  416.             # Attempt to get devices, this might fail if the WiFi is down
  417.             devices = vue.get_devices()
  418.  
  419.             for gid, channel_num in zip(lab.gid, lab.channel):
  420.                 for device in devices:
  421.                     if device.device_gid == gid:
  422.                         for channel in device.channels:
  423.                             if str(channel.channel_num) == str(channel_num):
  424.                                 channel_usage, _ = vue.get_chart_usage(
  425.                                     channel,
  426.                                     start_time,
  427.                                     end_time,
  428.                                     scale=Scale.MINUTE.value,
  429.                                     unit=Unit.KWH.value
  430.                                 )
  431.                                 if channel_usage:
  432.                                     total_consumption += sum(channel_usage)
  433.                                 break
  434.             return total_consumption
  435.         except (ConnectionError, requests.exceptions.RequestException) as e:
  436.             print(f"Connection error: {e}. Retrying in 5 seconds...")
  437.             time.sleep(5)"""
  438.  
  439.  
  440. def get_total_lab_consumption(vue, lab, time_delta_minutes):
  441.     while True:
  442.         try:
  443.             # Reset category consumptions for each call
  444.             lab.AC = 0
  445.             lab.Lighting = 0
  446.             lab.CO = 0
  447.  
  448.             end_time = datetime.datetime.now(datetime.timezone.utc)
  449.             start_time = end_time - datetime.timedelta(minutes=time_delta_minutes)
  450.  
  451.             devices = vue.get_devices()
  452.             #consumption split!!
  453.             for index, (gid, channel_num) in enumerate(zip(lab.gid, lab.channel)):
  454.                 for device in devices:
  455.                     if device.device_gid == gid:
  456.                         for channel in device.channels:
  457.                             if str(channel.channel_num) == str(channel_num):
  458.                                 channel_usage, _ = vue.get_chart_usage(
  459.                                     channel,
  460.                                     start_time,
  461.                                     end_time,
  462.                                     scale=Scale.MINUTE.value,
  463.                                     unit=Unit.KWH.value
  464.                                 )
  465.                                 if channel_usage:
  466.                                     consumption_amount = sum(channel_usage)
  467.                                     # Categorize the consumption based on the consumption type
  468.                                     if lab.consumption_type[index] == 1:  # AC
  469.                                         lab.AC += consumption_amount
  470.                                     elif lab.consumption_type[index] == 2:  # Lighting
  471.                                         lab.Lighting += consumption_amount
  472.                                     elif lab.consumption_type[index] == 3:  # CO
  473.                                         lab.CO += consumption_amount
  474.                                 break
  475.             # Calculate total consumption
  476.             total_consumption = lab.AC + lab.Lighting + lab.CO
  477.             return total_consumption
  478.         except (ConnectionError, requests.exceptions.RequestException) as e:
  479.             print(f"Connection error: {e}. Retrying in 5 seconds...")
  480.             time.sleep(5)
  481.  
  482. def print_lab_consumption_percentages(lab):
  483.     total_consumption = lab.AC + lab.Lighting + lab.CO
  484.     if total_consumption > 0:
  485.         ac_percentage = (lab.AC / total_consumption) * 100
  486.         lighting_percentage = (lab.Lighting / total_consumption) * 100
  487.         co_percentage = (lab.CO / total_consumption) * 100
  488.         print(f"{lab.name} Consumption Percentages:")
  489.         print(f"AC: {ac_percentage:.2f}%")
  490.         print(f"Lighting: {lighting_percentage:.2f}%")
  491.         print(f"CO: {co_percentage:.2f}%")
  492.     else:
  493.         print(f"No consumption data available for {lab.name}.")
  494.  
  495.  
  496. def calculate_all_labs_consumption(vue, labs, time_delta_minutes):
  497.     consumption_dict = {}
  498.     for lab in labs:
  499.         consumption = get_total_lab_consumption(vue, lab, time_delta_minutes)
  500.         consumption_dict[lab.name] = consumption
  501.     return consumption_dict
  502.  
  503. #AC = 1 Lighting = 2 CO = 3
  504.  
  505. lab_a = Lab("A Lab", lab_a_base, [169101,169101,169101],[1,1,1],[1,2,3])
  506. lab_b = Lab("B Lab", lab_b_base, [175618,169101,175618,169101],[1,2,3,4],[1,2,3,3])
  507. lab_c = Lab("C Lab", lab_c_base, [175619,169101],[1,1],[1,1])
  508. lab_d = Lab("SSL", lab_d_base, [228886],[1],[1, 3])
  509. lab_e = Lab("STC", lab_e_base, [228886],[1],[1, 3])
  510.  
  511. labs = Lab.instances
  512. rankings = []
  513. folder_path = r"C:\Users\dgsal\OneDrive\Desktop\Lab Data"
  514.  
  515. vue = PyEmVue()
  516. vue.login(username='[email protected]', password='Password123!!!')
  517. # Main loop
  518. devices = vue.get_devices()
  519.  
  520. device_consumptions = []
  521.  
  522. initialize_current_consumption_with_baseline(lab_a, lab_a_base)
  523. initialize_current_consumption_with_baseline(lab_b, lab_b_base)
  524. initialize_current_consumption_with_baseline(lab_c, lab_c_base)
  525. initialize_current_consumption_with_baseline(lab_d, lab_d_base)
  526. initialize_current_consumption_with_baseline(lab_e, lab_e_base)
  527.  
  528.  
  529. lab_consumptions = {}
  530. time_delta_minutes = 60  # The time delta in minutes for which you want to check the consumption
  531.  
  532. for lab in labs:
  533.     lab_consumptions[lab.name] = get_total_lab_consumption(vue, lab, time_delta_minutes)
  534.  
  535. # Print the total consumptions
  536. print(lab_consumptions)
  537.  
  538. print(lab_a.current)
  539. print(lab_b.current)
  540. print(lab_c.current)
  541. print(lab_d.current)
  542. print(lab_e.current)
  543. current_pairings = randomize_pairings()
  544.  
  545. last_check_day = datetime.datetime.now().day
  546.  
  547. while True:
  548.     try:
  549.         device_consumptions = []
  550.         summed_device_consumptions = {}
  551.  
  552.         time_delta_minutes = 60  # The time delta in minutes for which you want to check the consumption
  553.  
  554.         for lab in labs:
  555.             summed_device_consumptions[lab.name] = get_total_lab_consumption(vue, lab, time_delta_minutes)
  556.             print_lab_consumption_percentages(lab)
  557.  
  558.         # Print the total consumptions
  559.         print(summed_device_consumptions)
  560.  
  561.         # Update current consumption for each lab using summed values
  562.         for lab in labs:
  563.             total_consumption = summed_device_consumptions[lab.name]
  564.             update_lab_current_consumption(lab, total_consumption)
  565.  
  566.         for lab in labs:
  567.             lab.compare_consumption()
  568.  
  569.         current_time = datetime.datetime.now()
  570.  
  571.         # Check if it's a new day
  572.         if current_time.day != last_check_day:
  573.             finalize_daily_results()  # Finalize results of the previous day
  574.             current_pairings = randomize_pairings()  # Randomize new pairings
  575.             last_check_day = current_time.day
  576.  
  577.         # Perform scheduled tasks and battles
  578.         for lab1, lab2 in current_pairings:
  579.             battle(lab1, lab2, rankings)
  580.         print(daily_winners)
  581.         arrange_function(rankings)
  582.  
  583.         for lab in labs:
  584.             print(f"{lab.name} current consumption: {lab.current}")
  585.             print(f"{lab.name} baseline: {lab.baseline}")
  586.             lab.print_differences()
  587.             lab.calculate_hourly_consumption()
  588.             lab.update_graph_with_percentage_differences()
  589.             lab.calculate_cumulative_percentage_difference()
  590.             lab.update_graph_difference()
  591.             lab.update_graph_current_consumption()
  592.  
  593.         sum_consumption_and_baseline(labs)
  594.         sum_and_compare_each_lab(labs)
  595.         print("Rankings:", rankings)
  596.         #for saving
  597.         save_lab_current_to_file(labs, folder_path)
  598.         rankings = []  # restart rankings
  599.  
  600.         time.sleep(60)  # change it around for testing
  601.     except KeyboardInterrupt:
  602.         print("Program interrupted by user. Exiting...")
  603.         break
  604.     except Exception as e:
  605.         print(f"An unexpected error occurred: {e}. Retrying in 5 seconds...")
  606.         time.sleep(5)
  607.         continue
  608.  
  609. """while True:
  610.     # Clear previous data
  611.     rankings.clear()
  612.  
  613.     for lab in labs:
  614.         print(f"Entering data for {lab.name}")
  615.         try:
  616.             consumption = float(input("Enter consumption (kWh): "))
  617.             hour = int(input("Enter hour of day (0-23): "))
  618.             # Assuming the current day of the week
  619.             current_date = datetime.datetime.now()
  620.             day_of_week = current_date.weekday()
  621.  
  622.             # Ensure there's a list for today's consumption
  623.             while len(lab.current) <= day_of_week:
  624.                 lab.current.append([0] * 24)  # Initialize hours of the day with 0 consumption
  625.  
  626.             # Update the consumption for the specific hour
  627.             lab.current[day_of_week][hour] = consumption
  628.             print(f"Updated {lab.name}'s consumption at {hour}:00 to {consumption} kWh.")
  629.  
  630.             # Use the manual comparison function
  631.             lab.compare_consumption_manual(day_of_week, hour)
  632.         except ValueError:
  633.             print("Invalid input. Please enter valid numbers for consumption and time.")
  634.  
  635.     # Perform analysis 
  636.     battle(lab_a, lab_b, rankings)
  637.     battle(lab_c, lab_d, rankings)
  638.     arrange_function(rankings)
  639.  
  640.     # Print current stuff
  641.     for lab in labs:
  642.         print(f"{lab.name} current consumption: {lab.current}")
  643.         print(f"{lab.name} baseline: {lab.baseline}")
  644.  
  645.     print("Rankings:", rankings)
  646.     save_lab_current_to_file(labs, folder_path)
  647.  
  648.     if input("Do you want to continue? (yes/no): ").lower() != 'yes':
  649.         break
  650. """

Editor

You can edit this paste and save as new:


File Description
  • Anvil Background Code
  • Paste Code
  • 17 Apr-2024
  • 33.41 Kb
You can Share it: