ecotrack 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ecotrack/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+
2
+ """EcoTrack: Electricity consumption and solar energy analysis."""
3
+
4
+ from .analyzer import EnergyAnalyzer
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = [
9
+ "EnergyAnalyzer",
10
+ ]
ecotrack/analysis.py ADDED
@@ -0,0 +1,214 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ # 1. ECONOMIC ANALYSIS:
5
+
6
+ def calculate_cost(data, energy_price): # Calculate the total energy cost using a fixed price.
7
+
8
+ if energy_price < 0:
9
+ raise ValueError("Energy price cannot be negative.")
10
+
11
+ total_energy = data["consumption_kwh"].sum()
12
+ return total_energy * energy_price
13
+
14
+ def calculate_daily_cost(data, energy_price): # Calculate the daily energy cost using a fixed price.
15
+
16
+ if energy_price < 0:
17
+ raise ValueError("Energy price cannot be negative.")
18
+ daily_energy = data.groupby(data["timestamp"].dt.date)["consumption_kwh"].sum()
19
+ daily_cost = daily_energy * energy_price
20
+ return daily_cost
21
+
22
+
23
+ def calculate_monthly_cost(data, energy_price): # Calculate the monthly energy cost using a fixed price.
24
+
25
+ if energy_price < 0:
26
+ raise ValueError("Energy price cannot be negative.")
27
+ monthly_energy = data.groupby(data["timestamp"].dt.to_period("M"))["consumption_kwh"].sum()
28
+ monthly_cost = monthly_energy * energy_price
29
+ return monthly_cost
30
+
31
+
32
+ def estimate_savings(data, percentage): #Estimate the energy savings after reducing consumption by a given percentage.
33
+
34
+ if percentage < 0 or percentage > 100:
35
+ raise ValueError("Percentage must be between 0 and 100.")
36
+
37
+ original_energy = data["consumption_kwh"].sum()
38
+ saved_energy = original_energy * percentage / 100
39
+ new_energy = original_energy - saved_energy
40
+
41
+ return {"original_consumption_kwh": original_energy,"saved_energy_kwh": saved_energy,"new_consumption_kwh": new_energy}
42
+
43
+ # 2. TIME-OF-USE TARIFF ANALYSIS
44
+
45
+
46
+ def calculate_hourly_costs(data, prices, hour_periods):
47
+ # Calculate the cost of each consumption record using different
48
+ # electricity prices depending on the hour.
49
+
50
+ if not prices:
51
+ raise ValueError("At least one energy price is required.")
52
+
53
+ if not hour_periods:
54
+ raise ValueError("At least one tariff period is required.")
55
+
56
+ for price in prices.values():
57
+ if price < 0:
58
+ raise ValueError("Energy prices cannot be negative.")
59
+
60
+ hour_prices = {}
61
+
62
+ for period in hour_periods:
63
+
64
+ if period not in prices:
65
+ raise ValueError("A price is missing for a tariff period.")
66
+
67
+ for hour in hour_periods[period]:
68
+
69
+ if hour < 0 or hour > 23:
70
+ raise ValueError("Hours must be between 0 and 23.")
71
+
72
+ if hour in hour_prices:
73
+ raise ValueError("An hour cannot belong to two periods.")
74
+
75
+ hour_prices[hour] = prices[period]
76
+
77
+ # Check that all hours have an assigned price.
78
+ for hour in range(24):
79
+ if hour not in hour_prices:
80
+ raise ValueError("No energy price defined for hour " + str(hour))
81
+
82
+ costs = []
83
+
84
+ for i in range(len(data)):
85
+
86
+ hour = data["timestamp"].iloc[i].hour
87
+ consumption = data["consumption_kwh"].iloc[i]
88
+
89
+ cost = consumption * hour_prices[hour]
90
+
91
+ costs.append(cost)
92
+
93
+ return pd.Series(costs, index=data.index)
94
+
95
+
96
+ def calculate_cost_by_period(data, prices, hour_periods): # Calculate the total energy cost using a time-of-use tariff
97
+
98
+ hourly_costs = calculate_hourly_costs(data,prices,hour_periods)
99
+ return hourly_costs.sum()
100
+
101
+
102
+ def calculate_daily_cost_by_period(data, prices, hour_periods): # Calculate daily energy costs using a time-of-use tariff
103
+
104
+ hourly_costs = calculate_hourly_costs(data,prices,hour_periods)
105
+ daily_costs = data.copy()
106
+ daily_costs["cost_euros"] = hourly_costs
107
+
108
+ return daily_costs.groupby(daily_costs["timestamp"].dt.date)["cost_euros"].sum()
109
+
110
+
111
+ def calculate_monthly_cost_by_period(data, prices, hour_periods): # Calculate monthly energy costs using a time-of-use tariff
112
+
113
+ hourly_costs = calculate_hourly_costs(data,prices,hour_periods)
114
+
115
+ monthly_costs = data.copy()
116
+ monthly_costs["cost_euros"] = hourly_costs
117
+ return monthly_costs.groupby(monthly_costs["timestamp"].dt.to_period("M"))["cost_euros"].sum()
118
+
119
+
120
+ # 3. PEAKS AND ANOMALY DETECTION
121
+
122
+ def detect_peaks(data, percentile=90): # Detect periods with unusually high energy consumption
123
+
124
+ if percentile < 0 or percentile > 100:
125
+ raise ValueError("Percentile must be between 0 and 100.")
126
+
127
+ threshold = np.percentile(data["consumption_kwh"],percentile)
128
+
129
+ peaks = data[data["consumption_kwh"] >= threshold].copy()
130
+ return peaks
131
+
132
+
133
+ def detect_anomalies(data, threshold=2): # Detect anomalous consumption values using standard deviation
134
+
135
+ if threshold <= 0:
136
+ raise ValueError("Threshold must be positive.")
137
+
138
+ mean = data["consumption_kwh"].mean()
139
+
140
+ std = data["consumption_kwh"].std()
141
+
142
+ if pd.isna(std) or std == 0:
143
+ return data.iloc[0:0].copy()
144
+
145
+ lower_limit = mean - threshold * std
146
+ upper_limit = mean + threshold * std
147
+
148
+ anomalies = data[(data["consumption_kwh"] < lower_limit) |(data["consumption_kwh"] > upper_limit)].copy()
149
+
150
+ return anomalies
151
+
152
+
153
+ def get_highest_consumption_periods(data, n=5): # Return the n periods with the highest energy consumption
154
+
155
+ if n <= 0:
156
+ raise ValueError("n must be positive.")
157
+
158
+ highest_periods = data.nlargest(n,"consumption_kwh")
159
+
160
+ return highest_periods
161
+
162
+
163
+ # 4. PERIOD COMPARISON
164
+
165
+ def calculate_variation(initial_value, final_value): # Calculate the percentage variation between two values
166
+
167
+ if initial_value == 0:
168
+ raise ZeroDivisionError("Initial value cannot be zero.")
169
+
170
+ variation = ((final_value - initial_value) / initial_value) * 100
171
+
172
+ return variation
173
+
174
+
175
+
176
+ def compare_periods(data, start_1, end_1, start_2, end_2):
177
+ # Compare energy consumption between two time periods.
178
+
179
+ start_1 = pd.to_datetime(start_1)
180
+ end_1 = pd.to_datetime(end_1)
181
+
182
+ start_2 = pd.to_datetime(start_2)
183
+ end_2 = pd.to_datetime(end_2)
184
+
185
+ if start_1 > end_1 or start_2 > end_2:
186
+ raise ValueError("Start date must be before end date.")
187
+
188
+ # Include the complete final day.
189
+ end_1 = end_1 + pd.Timedelta(days=1)
190
+ end_2 = end_2 + pd.Timedelta(days=1)
191
+
192
+ period_1 = data[
193
+ (data["timestamp"] >= start_1) &
194
+ (data["timestamp"] < end_1)
195
+ ]
196
+
197
+ period_2 = data[
198
+ (data["timestamp"] >= start_2) &
199
+ (data["timestamp"] < end_2)
200
+ ]
201
+
202
+ energy_1 = period_1["consumption_kwh"].sum()
203
+ energy_2 = period_2["consumption_kwh"].sum()
204
+
205
+ if energy_1 == 0:
206
+ variation = None
207
+ else:
208
+ variation = calculate_variation(energy_1, energy_2)
209
+
210
+ return {
211
+ "period_1_consumption_kwh": energy_1,
212
+ "period_2_consumption_kwh": energy_2,
213
+ "variation_percentage": variation
214
+ }
ecotrack/analyzer.py ADDED
@@ -0,0 +1,362 @@
1
+
2
+ import pandas as pd
3
+
4
+ from . import analysis
5
+ from . import data_manager
6
+ from . import visualization
7
+ from . import reports
8
+ from . import solar_data
9
+ from . import solar_simulation
10
+
11
+
12
+ class EnergyAnalyzer:
13
+ """Main class for electricity and solar energy analysis."""
14
+
15
+ def __init__(self, data, separator=";"):
16
+ """
17
+ Create an analyzer from a CSV file or a DataFrame.
18
+
19
+ Parameters
20
+ ----------
21
+ data : str or pandas.DataFrame
22
+ Path to the consumption CSV file or an existing DataFrame.
23
+ separator : str
24
+ CSV separator. Default is semicolon.
25
+ """
26
+
27
+ if isinstance(data, pd.DataFrame):
28
+ self.data = data.copy()
29
+ else:
30
+ self.data = data_manager.load_dataset(
31
+ data,
32
+ separator=separator
33
+ )
34
+
35
+ # Electricity tariff
36
+ self.energy_price = None
37
+ self.energy_prices = None
38
+ self.hour_periods = None
39
+
40
+ # Solar data and results
41
+ self.solar_data = None
42
+ self.solar_results = None
43
+ self.solar_summary = None
44
+ self.solar_scenarios = None
45
+
46
+ # --------------------------------------------------
47
+ # ELECTRICITY TARIFF
48
+ # --------------------------------------------------
49
+
50
+ def set_energy_price(self, energy_price):
51
+ """Set a fixed electricity price in EUR/kWh."""
52
+
53
+ try:
54
+ energy_price = float(energy_price)
55
+ except (TypeError, ValueError):
56
+ raise ValueError("Energy price must be numeric.")
57
+
58
+ if (
59
+ pd.isna(energy_price)
60
+ or energy_price == float("inf")
61
+ or energy_price == float("-inf")
62
+ or energy_price < 0
63
+ ):
64
+ raise ValueError(
65
+ "Energy price must be a finite, non-negative number."
66
+ )
67
+
68
+ self.energy_price = energy_price
69
+ self.energy_prices = None
70
+ self.hour_periods = None
71
+
72
+ # Clear previous solar economic results
73
+ self.solar_results = None
74
+ self.solar_summary = None
75
+ self.solar_scenarios = None
76
+
77
+ def set_energy_prices(self, prices, hour_periods):
78
+ """Set different electricity prices for different periods."""
79
+
80
+ self.energy_prices = prices
81
+ self.hour_periods = hour_periods
82
+ self.energy_price = None
83
+
84
+ # Clear previous solar economic results
85
+ self.solar_results = None
86
+ self.solar_summary = None
87
+ self.solar_scenarios = None
88
+
89
+ # --------------------------------------------------
90
+ # ELECTRICITY ANALYSIS
91
+ # --------------------------------------------------
92
+
93
+ def calculate_cost(self):
94
+ """Calculate total electricity cost."""
95
+
96
+ if self.energy_price is not None:
97
+ return analysis.calculate_cost(
98
+ self.data, self.energy_price
99
+ )
100
+
101
+ elif self.energy_prices is not None:
102
+ return analysis.calculate_cost_by_period(
103
+ self.data,
104
+ self.energy_prices,
105
+ self.hour_periods
106
+ )
107
+
108
+ else:
109
+ raise ValueError(
110
+ "Set an electricity tariff before calculating costs."
111
+ )
112
+
113
+ def calculate_daily_cost(self):
114
+ """Calculate electricity cost for each day."""
115
+
116
+ if self.energy_price is not None:
117
+ return analysis.calculate_daily_cost(
118
+ self.data, self.energy_price
119
+ )
120
+
121
+ elif self.energy_prices is not None:
122
+ return analysis.calculate_daily_cost_by_period(
123
+ self.data,
124
+ self.energy_prices,
125
+ self.hour_periods
126
+ )
127
+
128
+ else:
129
+ raise ValueError(
130
+ "Set an electricity tariff before calculating costs."
131
+ )
132
+
133
+ def calculate_monthly_cost(self):
134
+ """Calculate electricity cost for each month."""
135
+
136
+ if self.energy_price is not None:
137
+ return analysis.calculate_monthly_cost(
138
+ self.data, self.energy_price
139
+ )
140
+
141
+ elif self.energy_prices is not None:
142
+ return analysis.calculate_monthly_cost_by_period(
143
+ self.data,
144
+ self.energy_prices,
145
+ self.hour_periods
146
+ )
147
+
148
+ else:
149
+ raise ValueError(
150
+ "Set an electricity tariff before calculating costs."
151
+ )
152
+
153
+ def estimate_savings(self, percentage):
154
+ return analysis.estimate_savings(
155
+ self.data, percentage
156
+ )
157
+
158
+ def detect_peaks(self, percentile=90):
159
+ return analysis.detect_peaks(
160
+ self.data, percentile
161
+ )
162
+
163
+ def detect_anomalies(self, threshold=2):
164
+ return analysis.detect_anomalies(
165
+ self.data, threshold
166
+ )
167
+
168
+ def get_highest_consumption_periods(self, n=5):
169
+ return analysis.get_highest_consumption_periods(
170
+ self.data, n
171
+ )
172
+
173
+ def compare_periods(self, start_1, end_1, start_2, end_2):
174
+ return analysis.compare_periods(
175
+ self.data,
176
+ start_1,
177
+ end_1,
178
+ start_2,
179
+ end_2
180
+ )
181
+
182
+ # --------------------------------------------------
183
+ # ELECTRICITY VISUALIZATION
184
+ # --------------------------------------------------
185
+
186
+ def plot_consumption(self):
187
+ """Plot average electricity consumption by hour."""
188
+
189
+ visualization.plot_consumption(self.data)
190
+
191
+ def plot_monthly_consumption(self):
192
+ """Plot monthly electricity consumption."""
193
+
194
+ visualization.plot_monthly_consumption(self.data)
195
+
196
+ # --------------------------------------------------
197
+ # SOLAR DATA GENERATION
198
+ # --------------------------------------------------
199
+
200
+ def generate_solar_data(self, panel_power=300):
201
+ """Generate estimated solar production data."""
202
+
203
+ self.solar_data = solar_data.generate_solar_data(
204
+ self.data["timestamp"],
205
+ panel_power
206
+ )
207
+
208
+ return self.solar_data
209
+
210
+ # --------------------------------------------------
211
+ # SOLAR TARIFF CHECK
212
+ # --------------------------------------------------
213
+
214
+ def _check_fixed_tariff(self):
215
+ """Check that the user has configured a fixed tariff."""
216
+
217
+ if self.energy_price is None:
218
+ raise ValueError(
219
+ "Solar economic features are only available "
220
+ "with a fixed electricity tariff. "
221
+ "Use set_energy_price() first."
222
+ )
223
+
224
+ # --------------------------------------------------
225
+ # SOLAR SIMULATION
226
+ # --------------------------------------------------
227
+
228
+ def simulate_solar(self, panel_count,
229
+ panel_price=180,
230
+ installation_cost=500,
231
+ solar_data_input=None):
232
+ """Simulate a solar installation using the fixed tariff."""
233
+
234
+ self._check_fixed_tariff()
235
+
236
+ if solar_data_input is not None:
237
+ self.solar_data = solar_data_input
238
+
239
+ if self.solar_data is None:
240
+ self.generate_solar_data()
241
+
242
+ self.solar_results, self.solar_summary = (
243
+ solar_simulation.simulate_solar(
244
+ self.data,
245
+ self.solar_data,
246
+ panel_count,
247
+ electricity_price=self.energy_price,
248
+ panel_price=panel_price,
249
+ installation_cost=installation_cost
250
+ )
251
+ )
252
+
253
+ return self.solar_results, self.solar_summary
254
+
255
+ def compare_panel_counts(self, max_panels=7,
256
+ panel_price=180,
257
+ installation_cost=500,
258
+ solar_data_input=None):
259
+ """Compare different numbers of solar panels."""
260
+
261
+ self._check_fixed_tariff()
262
+
263
+ if solar_data_input is not None:
264
+ self.solar_data = solar_data_input
265
+
266
+ if self.solar_data is None:
267
+ self.generate_solar_data()
268
+
269
+ self.solar_scenarios = (
270
+ solar_simulation.compare_panel_counts(
271
+ self.data,
272
+ self.solar_data,
273
+ max_panels=max_panels,
274
+ electricity_price=self.energy_price,
275
+ panel_price=panel_price,
276
+ installation_cost=installation_cost
277
+ )
278
+ )
279
+
280
+ return self.solar_scenarios
281
+
282
+ # --------------------------------------------------
283
+ # SOLAR VISUALIZATION
284
+ # --------------------------------------------------
285
+
286
+ def plot_solar_production(self):
287
+ """Plot estimated solar production."""
288
+
289
+ if self.solar_results is None:
290
+ raise ValueError(
291
+ "Run simulate_solar() before plotting solar production."
292
+ )
293
+
294
+ visualization.plot_solar_production(
295
+ self.solar_results
296
+ )
297
+
298
+ def plot_monthly_cost_comparison(self):
299
+ """Compare monthly costs with and without solar."""
300
+
301
+ if self.solar_results is None:
302
+ raise ValueError(
303
+ "Run simulate_solar() before plotting costs."
304
+ )
305
+
306
+ visualization.plot_monthly_cost_comparison(
307
+ self.solar_results
308
+ )
309
+
310
+ def plot_energy_distribution(self):
311
+ """Plot solar energy distribution."""
312
+
313
+ if self.solar_results is None:
314
+ raise ValueError(
315
+ "Run simulate_solar() before plotting energy distribution."
316
+ )
317
+
318
+ visualization.plot_energy_distribution(
319
+ self.solar_results
320
+ )
321
+
322
+ def plot_panel_savings(self):
323
+ """Plot estimated savings for different panel counts."""
324
+
325
+ if self.solar_scenarios is None:
326
+ raise ValueError(
327
+ "Run compare_panel_counts() before plotting savings."
328
+ )
329
+
330
+ visualization.plot_panel_savings(
331
+ self.solar_scenarios
332
+ )
333
+
334
+ def plot_payback(self):
335
+ """Plot estimated payback time for different panel counts."""
336
+
337
+ if self.solar_scenarios is None:
338
+ raise ValueError(
339
+ "Run compare_panel_counts() before plotting payback."
340
+ )
341
+
342
+ visualization.plot_payback(
343
+ self.solar_scenarios
344
+ )
345
+
346
+ # --------------------------------------------------
347
+ # REPORT GENERATION
348
+ # --------------------------------------------------
349
+
350
+ def generate_report(self, filename="ecotrack_report.txt"):
351
+ """Generate a report with consumption and solar results."""
352
+
353
+ if self.solar_scenarios is None:
354
+ raise ValueError(
355
+ "Run compare_panel_counts() before generating the report."
356
+ )
357
+
358
+ return reports.generate_report(
359
+ self.data,
360
+ self.solar_scenarios,
361
+ filename
362
+ )