forked from FatinShadab/python-energy-microscope
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgreenscore.py
More file actions
179 lines (144 loc) · 6.48 KB
/
Copy pathgreenscore.py
File metadata and controls
179 lines (144 loc) · 6.48 KB
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
import pandas as pd
__WEIGHTS__ = [
(0.40, 0.40, 0.20), (0.45, 0.35, 0.20), (0.35, 0.45, 0.20),
(0.40, 0.35, 0.25), (0.40, 0.45, 0.15), (0.60, 0.30, 0.10),
(0.30, 0.60, 0.10), (0.50, 0.40, 0.10), (0.33, 0.33, 0.34),
(0.25, 0.50, 0.25), (0.50, 0.25, 0.25), (0.70, 0.20, 0.10),
(0.20, 0.20, 0.60), (1.00, 0.00, 0.00), (0.00, 1.00, 0.00)
]
def read_csv_files():
# Prompt user for three file paths
# file_paths = []
# for i in ("energy", "time", "carbon"):
# file_path = input(f"Enter the path for CSV file of {i}: ")
# file_paths.append(file_path)
# file_paths = [
# '/home/eaegon/Documents/GITHUB/python-energy-microscope/data/collection_1/combine/energy_com.csv',
# '/home/eaegon/Documents/GITHUB/python-energy-microscope/data/collection_1/combine/time_com.csv',
# '/home/eaegon/Documents/GITHUB/python-energy-microscope/data/collection_1/combine/carbon_footprint.csv'
# ]
file_paths = [
'C:\\Users\\User\\OneDrive\\Documents\\GitHub\\python-energy-microscope\\data\\collection_1\\combine\\energy_com.csv',
'C:\\Users\\User\\OneDrive\\Documents\\GitHub\\python-energy-microscope\\data\\collection_1\\combine\\time_com.csv',
'C:\\Users\\User\\OneDrive\\Documents\\GitHub\\python-energy-microscope\\data\\collection_1\\combine\\carbon_footprint.csv'
]
# Read the CSV files into DataFrames
dataframes = []
for path in file_paths:
try:
df = pd.read_csv(path)
dataframes.append(df)
print(f"Successfully read file: {path}")
except Exception as e:
print(f"Error reading file {path}: {e}")
return dataframes
def create_nom_score_df(df: pd.DataFrame, output_path: str = None) -> pd.DataFrame:
"""
Normalize energy usage across methods (row-wise) per algorithm.
Parameters:
- df: DataFrame with one row per algorithm, 'algorithm' column, and energy columns.
- output_path: Optional path to save the normalized DataFrame as CSV.
Returns:
- A DataFrame with 'algorithm' and normalized method columns.
"""
# Copy the original to avoid modifying it
df = df.copy()
# Extract the algorithm names
algorithm_names = df['algorithm']
# Select only numeric method columns
method_cols = df.columns.drop('algorithm')
numeric_df = df[method_cols]
# Apply row-wise normalization (min-max per algorithm)
normalized_df = numeric_df.apply(
lambda row: (row - row.min()) / (row.max() - row.min())
if row.max() != row.min() else row * 0, # handle constant rows
axis=1
)
# Add back the algorithm column
normalized_df.insert(0, 'algorithm', algorithm_names)
# Save to CSV if path is given
if output_path:
normalized_df.to_csv(output_path, index=False)
print(f"✅ Normalized DataFrame saved to: {output_path}")
return normalized_df
def create_mean_score_df(
energy_df: pd.DataFrame,
time_df: pd.DataFrame,
carbon_df: pd.DataFrame,
output_path: str = None
) -> pd.DataFrame:
"""
Create a mean score DataFrame by averaging across all algorithms
for each method from the input normalized energy, time, and carbon DataFrames.
Parameters:
- energy_df: DataFrame with normalized energy (µJ) per method.
- time_df: DataFrame with normalized time per method.
- carbon_df: DataFrame with normalized carbon per method.
- output_path: Optional path to save the final CSV.
Returns:
- mean_score_df: DataFrame with method-wise mean scores.
"""
# Drop the 'algorithm' column
energy = energy_df.drop(columns=['algorithm'])
time = time_df.drop(columns=['algorithm'])
carbon = carbon_df.drop(columns=['algorithm'])
# Compute column-wise means
energy_mean = energy.mean()
time_mean = time.mean()
carbon_mean = carbon.mean()
# Combine into a single DataFrame
mean_score_df = pd.DataFrame({
'method': energy_mean.index.str.replace(r'_.*$', '', regex=True),
'energy_mean': energy_mean.values,
'time_mean': time_mean.values,
'carbon_mean': carbon_mean.values
})
# Optional CSV save
if output_path:
mean_score_df.to_csv(output_path, index=False)
print(f"✅ GreenScore means saved to: {output_path}")
return mean_score_df
def calculate_greenscore(df_energy, df_time, df_carbon, alpha=0.4, beta=0.4, gamma=0.2):
"""
Compute the Green Score for each method by combining normalized
energy, time, and carbon scores with weighted averaging.
Parameters:
- df_energy: Raw energy DataFrame (with 'algorithm' column).
- df_time: Raw time DataFrame.
- df_carbon: Raw carbon DataFrame.
- alpha, beta, gamma: Weights for energy, carbon, and time (sum must be 1.0).
Returns:
- green_score_df: DataFrame sorted by green score (ascending).
"""
# Step 1: Normalize each DataFrame and save intermediate files
energy_nom_score_df = create_nom_score_df(df_energy, output_path="energy_nom_score.csv")
time_nom_score_df = create_nom_score_df(df_time, output_path="time_nom_score.csv")
carbon_nom_score_df = create_nom_score_df(df_carbon, output_path="carbon_nom_score.csv")
# Step 2: Calculate per-method mean scores
mean_df = create_mean_score_df(
energy_nom_score_df,
time_nom_score_df,
carbon_nom_score_df,
output_path="green_score_components_means.csv"
)
# Step 3: Compute GreenScore = α·energy + β·carbon + γ·time
mean_df["green_score"] = (
alpha * mean_df["energy_mean"] +
beta * mean_df["carbon_mean"] +
gamma * mean_df["time_mean"]
)
# Step 4: Sort methods by green score (lower is better)
green_score_df = mean_df.sort_values(by="green_score").reset_index(drop=True)
# Step 5: Save the final ranked list
green_score_df.to_csv(f"green_score_ranking_a{str(alpha).replace('.', '_')}_b{str(beta).replace('.', '_')}_g{str(gamma).replace('.', '_')}.csv", index=False)
print("✅ Final Green Score ranking saved to: green_score_ranking.csv")
return green_score_df
# Example usage
if __name__ == "__main__":
dfs = read_csv_files()
for i, df in enumerate(dfs, start=1):
print(f"\nPreview of DataFrame {i}:")
print(df.head())
for weights in __WEIGHTS__:
print(f"\nCalculating GreenScore with weights: α={weights[0]}, β={weights[1]}, γ={weights[2]}")
calculate_greenscore(dfs[0], dfs[1], dfs[2], alpha=weights[0], beta=weights[1], gamma=weights[2])