From af825450e55078a0798aeaeeb236cb8f92898bae Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 14 Jul 2026 16:25:00 +0100 Subject: [PATCH 01/27] Package versions updated for ga_core compatibility --- requirements.txt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/requirements.txt b/requirements.txt index 3a9207f..295e155 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ -numpy==1.24 -pandas==2.0 -PyYAML==6.0 -jinja2==3.1 -plotly==5.18 \ No newline at end of file +numpy==2.3.2 +pandas==2.3.2 +PyYAML==6.0.2 +jinja2==3.1.6 +plotly==5.18.0 +git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@main \ No newline at end of file From 5aaf7f45a5b5322464fc13b20a7713c3ed58023d Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 20 Jul 2026 15:41:27 +0100 Subject: [PATCH 02/27] Changes to use ga core package for extract and enrich + redundant code removed --- backend/__init__.py | 147 +++---------- backend/slurm_extract.py | 451 --------------------------------------- 2 files changed, 27 insertions(+), 571 deletions(-) delete mode 100644 backend/slurm_extract.py diff --git a/backend/__init__.py b/backend/__init__.py index feb6dcd..a6e6390 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -1,124 +1,10 @@ import os import yaml -import pandas as pd -import numpy as np - -from backend.helpers import check_empty_results, simulate_mock_jobs -from backend.slurm_extract import WorkloadManager - +import ga_core +import backend.helpers as helpers # print("Working dir1: ", os.getcwd()) # DEBUGONLY -class GA_tools(): - - def __init__(self, cluster_info, fParams): - self.cluster_info = cluster_info - self.fParams = fParams - - def calculate_energies(self, row): - ''' - Calculate the energy usaged based on the job's paramaters - :param row: [pd.Series] one row of usage statistics, corresponding to one job - :return: [pd.Series] the same statistics with the energies added - ''' - ### CPU and GPU - partition_info = self.cluster_info['partitions'][row.PartitionX] - if row.PartitionTypeX == 'CPU': - TDP2use4CPU = partition_info['TDP'] - TDP2use4GPU = 0 - else: - TDP2use4CPU = partition_info['TDP_CPU'] - TDP2use4GPU = partition_info['TDP'] - - row['energy_CPUs'] = row.TotalCPUtime2useX.total_seconds() / 3600 * TDP2use4CPU / 1000 # in kWh - - row['energy_GPUs'] = row.TotalGPUtime2useX.total_seconds() / 3600 * TDP2use4GPU / 1000 # in kWh - - ### memory - for suffix, memory2use in zip(['','_memoryNeededOnly'], [row.ReqMemX,row.NeededMemX]): - row[f'energy_memory{suffix}'] = row.WallclockTimeX.total_seconds()/3600 * memory2use * self.fParams['power_memory_perGB'] /1000 # in kWh - row[f'energy{suffix}'] = (row.energy_CPUs + row.energy_GPUs + row[f'energy_memory{suffix}']) * self.cluster_info['PUE'] # in kWh - - return row - - def calculate_carbonFootprint(self, df, col_energy): - return df[col_energy] * self.cluster_info['CI'] - - -def extract_data(args, cluster_info): - - if args.use_mock_agg_data: # DEBUGONLY - - if args.reportBug | args.reportBugHere: - print("\n(!) --reportBug and --reportBugHere are ignored when --useCustomLogs is present\n") - - # df2 = simulate_mock_jobs() - # df2.to_pickle("testData/df_agg_X_mockMultiUsers_1.pkl") - - # foo = 'testData/df_agg_test_3.pkl' - foo = 'testData/df_agg_X_1.pkl' - print(f"Overriding df_agg with `{foo}`") - return pd.read_pickle(foo) - - - ### Pull usage statistics from the workload manager - WM = WorkloadManager(args, cluster_info) - WM.pull_logs() - - ### Log the output for debugging - if args.reportBug | args.reportBugHere: - if args.reportBug: - # Create an error_logs subfolder in the output dir - errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') - os.makedirs(errorLogsDir) - log_path = os.path.join(errorLogsDir, f'sacctOutput.csv') - else: - # i.e. args.reportBugHere is True - log_path = f"{args.userCWD}/sacctOutput_{args.outputDir2use['timestamp']}.csv" - - with open(log_path, 'wb') as f: - f.write(WM.logs_raw) - print(f"\nSLURM statistics logged for debuging: {log_path}\n") - - ### Turn usage logs into DataFrame - WM.convert2dataframe() - check_empty_results(WM.logs_df, args) - - # And clean - WM.clean_logs_df() - # Check if there are any jobs during the period from this directory and with these jobIDs - check_empty_results(WM.df_agg, args) - - # Check that there is only one user's data - if len(set(WM.df_agg_X.UserX)) > 1: - raise ValueError(f"More than one user's logs was included: {set(WM.df_agg_X.UserX)}") - - # WM.df_agg_X.to_pickle("testData/df_agg_X_1.pkl") # DEBUGONLY used to test different steps offline - - return WM.df_agg_X - -def enrich_data(df, fParams, GA): - - ### energy - df = df.apply(GA.calculate_energies, axis=1) - - df['energy_failedJobs'] = np.where(df.StateX == 0, df.energy, 0) - - ### carbon footprint - for suffix in ['', '_memoryNeededOnly', '_failedJobs']: - df[f'carbonFootprint{suffix}'] = GA.calculate_carbonFootprint(df, f'energy{suffix}') - # Context metrics (part 1) - df[f'treeMonths{suffix}'] = df[f'carbonFootprint{suffix}'] / fParams['tree_month'] - df[f'cost{suffix}'] = df[f'energy{suffix}'] * fParams['electricity_cost'] # TODO use realtime electricity costs - - ### Context metrics (part 2) - df['driving'] = df.carbonFootprint / fParams['passengerCar_EU_perkm'] - df['flying_NY_SF'] = df.carbonFootprint / fParams['flight_NY_SF'] - df['flying_PAR_LON'] = df.carbonFootprint / fParams['flight_PAR_LON'] - df['flying_NYC_MEL'] = df.carbonFootprint / fParams['flight_NYC_MEL'] - - return df - def summarise_data(df, args): agg_functions_from_raw = { 'n_jobs': ('UserX', 'count'), @@ -205,13 +91,32 @@ def agg_jobs(data, agg_names=None): return output - +def prepare_ga_config(args): + """ + Prepare the configuration for the GA core, based on the command line arguments. + :param args: [argparse.Namespace] the command line arguments + :return: [dict] the configuration for the GA core + """ + ga_config = { + "useCustomLogs": args.useCustomLogs, + "startDay": args.startDay, + "endDay": args.endDay, + } + + optional_args = ["filterWD", "filterJobIDs", "filterAccount", "userCWD", "customSuccessStates"] # Need to be implemented in a better manner, perhaps by importing a model from ga_core + for arg in optional_args: + if getattr(args, arg): + ga_config[arg] = getattr(args, arg) + + return ga_config + def main_backend(args): ''' :param args: :return: ''' + ga_config = prepare_ga_config(args) ### Load cluster specific info with open(os.path.join(args.path_infrastucture_info, 'cluster_info.yaml'), "r") as stream: try: @@ -225,11 +130,13 @@ def main_backend(args): fParams = yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) + + dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) + df = dataprocessor.extract_data() - GA = GA_tools(cluster_info, fParams) + helpers.check_empty_results(df, args) # Check if any jobs have been run on the period, and stop the script if not. - df = extract_data(args, cluster_info=cluster_info) - df2 = enrich_data(df, fParams=fParams, GA=GA) + df2 = dataprocessor.enrich_data(df) summary_stats = summarise_data(df2, args=args) return summary_stats diff --git a/backend/slurm_extract.py b/backend/slurm_extract.py deleted file mode 100644 index dbd94a4..0000000 --- a/backend/slurm_extract.py +++ /dev/null @@ -1,451 +0,0 @@ - -import subprocess - -import pandas as pd -from io import BytesIO -import datetime -import os -import numpy as np - - -class Helpers_WM(): - - def __init__(self, cluster_info): - self.cluster_info = cluster_info - - def convert_to_GB(self, memory, unit): - """ - Converts data quantity into GB. - :param memory: [float] quantity to convert - :param unit: [str] unit of `memory`, has to be one of ['M', 'G', 'K'] - :return: [float] memory in GB. - """ - assert unit in ['M', 'G', 'K'] - if unit == 'M': - memory /= 1e3 - elif unit == 'K': - memory /= 1e6 - return memory - - def calc_ReqMem(self, x): - """ - Calculates the total memory required when submitting the job. - :param x: [pd.Series] one row of sacct output. - :return: [float] total required memory, in GB. - """ - mem_raw, n_nodes, n_cores = x['ReqMem'], x['NNodes'], x['NCPUS'] - - if pd.isnull(mem_raw): - unit = 'G' - memory = 0 - elif mem_raw[-1] == 'n': - unit = mem_raw[-2] - memory = float(mem_raw[:-2]) * n_nodes - elif mem_raw[-1] == 'c': - unit = mem_raw[-2] - memory = float(mem_raw[:-2]) * n_cores - elif mem_raw[-1] in ['M', 'G', 'K']: - unit = mem_raw[-1] - memory = float(mem_raw[:-1]) - else: - raise ValueError(f"Can't parse memory value: {mem_raw}. Please raise issue on GitHub.") - - return self.convert_to_GB(memory, unit) - - def clean_RSS(self, x): - """ - Cleans the RSS value in sacct output. - :param x: [NaN or str] the RSS value, either NaN or of the form '2745K' - (optionally, just a number, we then use default_unit_RSS from cluster_info.yaml as unit). - :return: [float] RSS value, in GB. - """ - if pd.isnull(x.MaxRSS): - # NB if no info on MaxRSS, we assume all memory was used - memory = -1 - elif x.MaxRSS == '0': - memory = 0 - else: - assert type(x.MaxRSS) == str - # Special case for the situation where MaxRSS is of the form '154264' without a unit. - if x.MaxRSS[-1].isalpha(): - memory = self.convert_to_GB(float(x.MaxRSS[:-1]), x.MaxRSS[-1]) - else: - assert 'default_unit_RSS' in self.cluster_info, "Some values of MaxRSS don't have a unit. Please specify a default_unit_RSS in cluster_info.yaml" - memory = self.convert_to_GB(float(x.MaxRSS), self.cluster_info['default_unit_RSS']) - - return memory - - def cleam_UsedMem(self, x): - """ - Cleans the UsedMemory column - :param x: - :return: [float] - """ - # NB when MaxRSS didn't store any values, we assume that "memory used = memory requested" - return x.ReqMemX if x.UsedMem_ == -1 else x.UsedMem_ - - def clean_partition(self, x): - """ - Cleans the partition field, by replacing NaNs with empty string and selecting just one partition per job. - :param x: [str] partition or comma-seperated list of partitions - :return: [str] one partition or empty string - """ - if pd.isnull(x.Partition): - return '' - - L_partitions = x.Partition.split(',') - if (x.WallclockTimeX.total_seconds() > 0) & (len(L_partitions) > 1): - # Multiple partitions logged is only an issue for jobs that never started, - # for the others, only the used partition is logged - print(f"\n-!- WARNING: Multiple partitions logged on a job than ran: {x.JobID} - {x.Partition} (using the first one)\n") - return L_partitions[0] - - def set_partitionType(self, x): - assert x in self.cluster_info['partitions'], f"\n-!- Unknown partition: {x} -!-\n" - return self.cluster_info['partitions'][x]['type'] - - def parse_timedelta(self, x): - """ - Parse a string representing a duration into a `datetime.timedelta` object. - :param x: [str] Duration, as '[DD-HH:MM:]SS[.MS]' - :return: [datetime.timedelta] Timedelta object - """ - # Parse number of days - day_split = x.split('-') - if len(day_split) == 2: - n_days = int(day_split[0]) - HHMMSSms = day_split[1] - else: - n_days = 0 - HHMMSSms = x - - # Parse ms - ms_split = HHMMSSms.split('.') - if len(ms_split) == 2: - n_ms = int(ms_split[1]) - HHMMSS = ms_split[0] - else: - n_ms = 0 - HHMMSS = HHMMSSms - - # Parse HH,MM,SS - last_split = HHMMSS.split(':') - if len(last_split) == 3: - to_add = [] - elif len(last_split) == 2: - to_add = ['00'] - elif len(last_split) == 1: - to_add = ['00', '00'] - else: - raise ValueError(f"Can't parse {x}") - n_h, n_m, n_s = list(map(int, to_add + last_split)) - - return datetime.timedelta( - days=n_days, hours=n_h, minutes=n_m, seconds=n_s, milliseconds=n_ms - ) - - def calc_realMemNeeded(self, x, granularity_memory_request): - """ - Calculate the minimum memory needed. - This is calculated as the smallest multiple of `granularity_memory_request` that is greater than maxRSS. - :param x: [pd.Series] one row of sacct output. - :param granularity_memory_request: [float or int] level of granularity available when requesting memory on this cluster - :return: [float] minimum memory needed, in GB. - """ - foo = (int(x.UsedMem2_ / granularity_memory_request) + 1) * granularity_memory_request - return foo if x.ReqMemX < x.UsedMem2_ else min(x.ReqMemX, foo) - - def calc_memory_overallocation(self, x): - # This is in case ReqMem is wrong or too low - return 1. if x.ReqMemX < x.NeededMemX else x.ReqMemX / x.NeededMemX - - def calc_CPUusage2use(self, x): - if x.TotalCPUtime_.total_seconds() == 0: - # This is when the workload manager actually didn't store real usage - # NB: when TotalCPU=0, we assume usage factor = 100% for all CPU cores - return x.CPUwallclocktime_ - - assert x.TotalCPUtime_ <= x.CPUwallclocktime_ - return x.TotalCPUtime_ - - def calc_GPUusage2use(self, x): - if x.PartitionTypeX != 'GPU': - return datetime.timedelta(0) - if x.WallclockTimeX.total_seconds() > 0: - assert x.NGPUS_ != 0 - return x.WallclockTimeX * x.NGPUS_ # NB assuming usage factor of 100% for GPUs - - def calc_coreHoursCharged(self, x): - ''' - Split CPU and GPU core hours charged, depending on the partition. - :param x: - :return: [(float, float)] - ''' - if x.PartitionTypeX == 'CPU': - return x.CPUwallclocktime_ / np.timedelta64(1, 'h'), 0. - else: - return 0., x.WallclockTimeX * x.NGPUS_ / np.timedelta64(1, 'h') - - def clean_State(self, x, customSuccessStates_list): - """ - Standardise the job's state, coding with {-1,0,1} - :param x: [str] "State" field from sacct output - :return: [int] in [-1,0,1] - """ - # Codes are found here: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES - # self.args.customSuccessStates = 'TO,TIMEOUT' - success_codes = ['CD', 'COMPLETED'] - running_codes = ['PD', 'PENDING', 'R', 'RUNNING', 'RQ', 'REQUEUED'] - if x in success_codes: - codeState = 1 - elif x in customSuccessStates_list: - # we allocate a lower value here so that when aggregating by jobID, the whole job keeps the flag - # Otherwise a "cancelled" job could take over with StateX=0 for example - codeState = -1 - else: - codeState = 0 - - if x in running_codes: - # running jobs are the lowest to be removed all the time - # (if one of the subprocess is still running, the job gets ignored regardless of --customSuccessStates - codeState = -2 - - return codeState - - def get_parent_jobID(self, x): - """ - Get the parent job ID in case of array jobs - :param x: [str] JobID of the form 123456789_0 (with or without '_0') - :return: [str] Parent ID 123456789 - """ - foo = x.split('_') - assert len(foo) <= 2, f"Can't parse the job ID: {x}" - return foo[0] - - -class WorkloadManager(Helpers_WM): - - def __init__(self, args, cluster_info): - """ - Methods related to the Workload manager - :param args: [Namespace] input from the user - :param cluster_info: [dict] information about this specific cluster. - """ - super().__init__(cluster_info=cluster_info) - self.args = args - - self.logs_df = None - self.df_agg_0 = None - self.df_agg = None - self.df_agg_X = None - - def pull_logs(self): - """ - Run the command line to pull usage from the workload manager. - More: https://slurm.schedmd.com/sacct.html - """ - if self.args.useCustomLogs == '': - bash_com = [ - "sacct", - "--starttime", - self.args.startDay, # format YYYY-MM-DD - "--endtime", - self.args.endDay, # format YYYY-MM-DD - "--format", - "UID,User,JobID,JobName,Submit,Elapsed,Partition,NNodes,NCPUS,TotalCPU,CPUTime,ReqMem,MaxRSS,WorkDir,State,Account,AllocTres", - "-P" - ] - - # logs = subprocess.run(bash_com, capture_output=True) # this line is the new way, but doesn't work with python 3.6 or earlier. line below is the legacy way. https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output - logs = subprocess.run(bash_com, stdout=subprocess.PIPE) - self.logs_raw = logs.stdout - else: - foo = "Overriding logs_raw with: " - foundIt = False - for sacctFileLocation in ['', 'testData', 'error_logs']: - if not foundIt: - try: - with open(os.path.join(sacctFileLocation, self.args.useCustomLogs), 'rb') as f: - self.logs_raw = f.read() - foo += f"{sacctFileLocation}/{self.args.useCustomLogs}" - foundIt = True - except: - pass - if not foundIt: - raise FileNotFoundError(f"Couldn't find {self.args.useCustomLogs} \n " - f"It should be either be in the testData/ or error_logs/ subdirectories, or the full path should be provided by --useCustomLogs.") - print(foo) - - def convert2dataframe(self): - """ - Convert raw logs output into a pandas dataframe. - """ - logs_df = pd.read_csv(BytesIO(self.logs_raw), sep="|", dtype='str') - for x in ['NNodes', 'NCPUS']: - logs_df[x] = logs_df[x].astype('int64') - - self.logs_df = logs_df - - def clean_logs_df(self): - """ - Clean the different fields of the usage logs. - NB: the name of the columns ending with X need to be conserved, as they are used by the main script. - """ - # self.logs_df_raw = self.logs_df.copy() # DEBUGONLY Save a copy of uncleaned raw for debugging mainly - - ### Calculate real memory usage - self.logs_df['ReqMemX'] = self.logs_df.apply(self.calc_ReqMem, axis=1) - - ### Clean MaxRSS - self.logs_df['UsedMem_'] = self.logs_df.apply(self.clean_RSS, axis=1) - - ### Parse wallclock time - self.logs_df['WallclockTimeX'] = self.logs_df['Elapsed'].apply(self.parse_timedelta) - - ### Parse total CPU time - # This is the total CPU used time, accross all cores. - # But it is not reliably logged - self.logs_df['TotalCPUtime_'] = self.logs_df['TotalCPU'].apply(self.parse_timedelta) - - ### Parse core-wallclock time - # This is the maximum time cores could use, if used at 100% (Elapsed time * CPU count) - if 'CPUTime' in self.logs_df.columns: - self.logs_df['CPUwallclocktime_'] = self.logs_df['CPUTime'].apply(self.parse_timedelta) - else: - print('Using old logs, "CPUTime" information not available.') # TODO: remove this after a while - self.logs_df['CPUwallclocktime_'] = self.logs_df.WallclockTimeX * self.logs_df.NCPUS - - ### Number of GPUs - # TODO double check that it includes multiple GPUs correctly - if 'AllocTRES' in self.logs_df.columns: - self.logs_df['NGPUS_'] = self.logs_df.AllocTRES.str.extract(r'((?<=gres\/gpu=)\d+)', expand=False).fillna( - 0).astype('int64') - else: - print('Using old logs, "AllocTRES" information not available.') # TODO: remove this after a while - self.logs_df['NGPUS_'] = 0 - - ### Clean partition - # Make sure it's either a partition name, or a comma-separated list of partitions - self.logs_df['PartitionX'] = self.logs_df.apply(self.clean_partition, axis=1) - - ### Parse submit datetime - self.logs_df['SubmitDatetimeX'] = self.logs_df.Submit.apply( - lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S")) - - ### Number of CPUs - # e.g. here there is no cleaning necessary, so I just standardise the column name - self.logs_df['NCPUS_'] = self.logs_df.NCPUS - - ### Number of nodes - self.logs_df['NNodes_'] = self.logs_df.NNodes - - ### Job name - self.logs_df['JobName_'] = self.logs_df.JobName - - ### Working directory - self.logs_df['WorkingDir_'] = self.logs_df.WorkDir - - ### Username and UID - self.logs_df['UIDX'] = self.logs_df.UID - self.logs_df['UserX'] = self.logs_df.User - - ### State - customSuccessStates_list = self.args.customSuccessStates.split(',') - self.logs_df['StateX'] = self.logs_df.State.apply(self.clean_State, - customSuccessStates_list=customSuccessStates_list) - - ### Pull jobID - self.logs_df['single_jobID'] = self.logs_df.JobID.apply(lambda x: x.split('.')[0]) - - ### Account - if 'Account' in self.logs_df.columns: - self.logs_df['Account_'] = self.logs_df.Account - else: - print('Using old logs, "Account" information not available.') # TODO: remove this after a while - self.logs_df['Account_'] = '' - - ### Aggregate per jobID - self.df_agg_0 = self.logs_df.groupby('single_jobID').agg({ - 'TotalCPUtime_': 'max', - 'CPUwallclocktime_': 'max', - 'WallclockTimeX': 'max', - 'ReqMemX': 'max', - 'UsedMem_': 'max', - 'NCPUS_': 'max', - 'NGPUS_': 'max', - 'NNodes_': 'max', - 'PartitionX': lambda x: ''.join(x), - 'JobName_': 'first', - 'SubmitDatetimeX': 'min', - 'WorkingDir_': 'first', - 'StateX': 'min', - 'Account_': 'first', - 'UIDX': 'first', - 'UserX': 'first', - }) - - ### Remove jobs that are still running or currently queued - self.df_agg = self.df_agg_0.loc[self.df_agg_0.StateX != -2] - - ### Turn StateX==-2 into 1 - self.df_agg.loc[self.df_agg.StateX == -1, 'StateX'] = 1 - - ### Replace UsedMem_=-1 with memory requested (for when MaxRSS=NaN) - self.df_agg['UsedMem2_'] = self.df_agg.apply(self.cleam_UsedMem, axis=1) - - ### Label as CPU or GPU partition - self.df_agg['PartitionTypeX'] = self.df_agg.PartitionX.apply(self.set_partitionType) - - # Just used to clean up with old logs: - if 'AllocTRES' not in self.logs_df.columns: - self.df_agg.loc[self.df_agg.PartitionTypeX == 'GPU', 'NGPUS_'] = 1 # TODO remove after a while - - # Sanity check (no GPU logged for CPU partitions and vice versa) - assert (self.df_agg.loc[self.df_agg.PartitionTypeX == 'CPU'].NGPUS_ == 0).all() - foo = self.df_agg.loc[(self.df_agg.PartitionTypeX == 'GPU') & (self.df_agg.NGPUS_ == 0)] - assert (foo.WallclockTimeX.dt.total_seconds() == 0).all() # Cancelled GPU jobs won't have any GPUs allocated if they didn't start - - ## Check that there is no missing UID/User - if self.df_agg.UIDX.isnull().sum() > 0: - print(f"(!) WARNING: {self.df_agg.UIDX.isnull().sum()} jobs have missing UIDs") - if self.df_agg.UserX.isnull().sum() > 0: - print(f"(!) WARNING: {self.df_agg.UserX.isnull().sum()} jobs have missing Usernames") - - ### add the usage time to use for calculations - self.df_agg['TotalCPUtime2useX'] = self.df_agg.apply(self.calc_CPUusage2use, axis=1) - self.df_agg['TotalGPUtime2useX'] = self.df_agg.apply(self.calc_GPUusage2use, axis=1) - - ### Calculate core-hours charged - self.df_agg[['CPUhoursChargedX', 'GPUhoursChargedX']] = self.df_agg.apply(self.calc_coreHoursCharged, axis=1, result_type='expand') - - ### Calculate real memory need - self.df_agg['NeededMemX'] = self.df_agg.apply( - self.calc_realMemNeeded, - granularity_memory_request=self.cluster_info['granularity_memory_request'], - axis=1) - - ### Add memory waste information - self.df_agg['memOverallocationFactorX'] = self.df_agg.apply(self.calc_memory_overallocation, axis=1) - - # foo = self.df_agg[['TotalCPUtime_', 'CPUwallclocktime_', 'WallclockTimeX', 'NCPUS_', 'CoreHoursChargedCPUX', - # 'CoreHoursChargedGPUX', 'TotalCPUtime2useX', 'TotalGPUtime2useX']] # DEBUGONLY - - ### Filter on working directory - if self.args.filterWD is not None: - # FIXME: Doesn't work with symbolic links - self.df_agg = self.df_agg.loc[self.df_agg.WorkingDir_ == self.args.filterWD] - # print(f'Filtered out {len(self.df_agg)-len(self.df_agg):,} rows (filterCWD={self.args.filterWD})') # DEBUGONLY - - ### Filter on Job ID - self.df_agg.reset_index(inplace=True) - self.df_agg['parentJobID'] = self.df_agg.single_jobID.apply(self.get_parent_jobID) - - if self.args.filterJobIDs != 'all': - list_jobs2keep = self.args.filterJobIDs.split(',') - self.df_agg = self.df_agg.loc[self.df_agg.parentJobID.isin(list_jobs2keep)] - - ### Filter on Account - if self.args.filterAccount is not None: - self.df_agg = self.df_agg.loc[self.df_agg.Account_ == self.args.filterAccount] - - self.df_agg_X = self.df_agg[[x for x in self.df_agg.columns if x[-1] == 'X']] \ No newline at end of file From 1097bad2135f717da1bf7a708aa027e518b3bba2 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 20 Jul 2026 16:43:58 +0100 Subject: [PATCH 03/27] testing framework added + tests written for backend script --- .github/workflows/python-app.yml | 43 ++++++ .gitignore | 1 - requirements.txt | 2 + tests/backend/backend_test.py | 210 ++++++++++++++++++++++++++++++ tests/conftest.py | 17 +++ tests/testdata/raw_logs_valid.txt | 20 +++ 6 files changed, 292 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/python-app.yml create mode 100644 tests/backend/backend_test.py create mode 100644 tests/conftest.py create mode 100644 tests/testdata/raw_logs_valid.txt diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml new file mode 100644 index 0000000..dfa167a --- /dev/null +++ b/.github/workflows/python-app.yml @@ -0,0 +1,43 @@ +# This workflow will install Python dependencies, run tests and lint with a single version of Python +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Python application + +on: + push: + branches: [ "main", "dev" ] + pull_request: + branches: [ "main", "dev" ] + +permissions: + contents: read + pull-requests: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: "pip" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest pytest-cov + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + + - name: Test with pytest + run: | + pytest --doctest-modules --junitxml=junit/test-results.xml --cov-report=xml --cov-report=html \ No newline at end of file diff --git a/.gitignore b/.gitignore index 222de3c..cda7a50 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ # Project specific .idea/ clustersData/ -testData/ error_logs_archived/ support_files/ frontend/templates/plotly* diff --git a/requirements.txt b/requirements.txt index 295e155..b8bbfaa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,6 @@ pandas==2.3.2 PyYAML==6.0.2 jinja2==3.1.6 plotly==5.18.0 +pytest==8.4.1 +pytest-cov==7.1.0 git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@main \ No newline at end of file diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py new file mode 100644 index 0000000..7c26fc6 --- /dev/null +++ b/tests/backend/backend_test.py @@ -0,0 +1,210 @@ +# ------------------------------------------------------------------ +# This file contains fixtures, tests, and mocks for the backend/__init__.py module. +# It validates the orchestration of the backend pipeline +# ------------------------------------------------------------------ + +from backend.__init__ import main_backend, prepare_ga_config, summarise_data + +from types import SimpleNamespace +from unittest.mock import MagicMock, mock_open, patch +import numpy as np +import pandas as pd +import pytest + + +# Fixtures +@pytest.fixture +def dummy_args(config_data): + """ + Constructs a full command-line arguments namespace + """ + return SimpleNamespace( + startDay=config_data["startDay"], + endDay=config_data["endDay"], + useCustomLogs=config_data["useCustomLogs"], + use_mock_agg_data=True, + customSuccessStates="COMPLETED", + filterWD=None, + filterJobIDs="all", + filterAccount=None, + reportBug=False, + reportBugHere=False, + path_infrastucture_info="clustersData/CSD3", + userCWD="/home/uid_1", + ) + + +@pytest.fixture +def mock_enriched_df(): + """ + Provides a pre-enriched DataFrame mimicking output from ga_core. + Contains 2 jobs across 2 different submit dates to test aggregation logic. + """ + return pd.DataFrame( + { + "UserX": ["uid_1", "uid_1"], + "SubmitDatetimeX": pd.to_datetime( + ["2022-02-11 19:11:21", "2022-02-12 14:04:01"] + ), + "energy": [10.0, 20.0], + "energy_CPUs": [5.0, 10.0], + "energy_GPUs": [3.0, 6.0], + "energy_memory": [2.0, 4.0], + "carbonFootprint": [100.0, 200.0], + "carbonFootprint_memoryNeededOnly": [10.0, 20.0], + "carbonFootprint_failedJobs": [0.0, 50.0], + "TotalCPUtime2useX": [100, 200], + "TotalGPUtime2useX": [0, 0], + "WallclockTimeX": [50, 100], + "CPUhoursChargedX": [2.0, 4.0], + "GPUhoursChargedX": [0.0, 0.0], + "ReqMemX": [6760, 250000], + "memOverallocationFactorX": [1.5, 2.5], + "StateX": [0, 1], # 0 failed/timeout, 1 completed + "treeMonths": [0.1, 0.2], + "treeMonths_memoryNeededOnly": [0.01, 0.02], + "treeMonths_failedJobs": [0.0, 0.05], + "driving": [5.0, 10.0], + "flying_NY_SF": [1.0, 2.0], + "flying_PAR_LON": [2.0, 4.0], + "flying_NYC_MEL": [0.1, 0.2], + "cost": [10.0, 20.0], + "cost_failedJobs": [0.0, 5.0], + "cost_memoryNeededOnly": [1.0, 2.0], + } + ) + +class TestPrepareGaConfig: + + def test_prepare_ga_config_mapping(self, dummy_args, config_data): + """ + Scenario: Required and optional arguments are extracted correctly from the CLI namespace into a config dictionary. + + Checks done: + 1. Mandatory fields (startDay, endDay, useCustomLogs) are mapped. + 2. Non-None optional fields (customSuccessStates, userCWD) are attached. + 3. None/falsy optional arguments (filterWD) are excluded. + """ + config = prepare_ga_config(dummy_args) + + assert config["useCustomLogs"] == config_data["useCustomLogs"] + assert config["startDay"] == config_data["startDay"] + assert config["endDay"] == config_data["endDay"] + assert config["customSuccessStates"] == "COMPLETED" + assert config["userCWD"] == "/home/uid_1" + assert "filterWD" not in config + +class TestSummariseData: + + def test_summarise_data_output_schema(self, mock_enriched_df, dummy_args): + """ + Scenario: The output schema of summarise_data is correct. + + Checks done: + 1. All expected top-level keys ('userDaily', 'userActivity', etc.) exist. + 2. The primary user ID is identified correctly from the DataFrame. + """ + summary = summarise_data(mock_enriched_df.copy(), dummy_args) + + assert "userDaily" in summary + assert "userActivity" in summary + assert "user" in summary + assert "memoryOverallocationFactors" in summary + + assert summary["user"] == "uid_1" + assert "uid_1" in summary["userActivity"] + + def test_two_stage_aggregation_and_derived_ratios(self, mock_enriched_df, dummy_args): + """ + Scenario: job metrics aggregate correctly for two stages - daily totals and overall stats + and derived ratios are computed correctly. + + Checks done: + 1. First aggregation groups raw jobs into daily records. + 2. Second aggregation switches logic (checks missing 'UserX' column) + and computes sums over pre-aggregated daily data. + 3. Success/failure rates and carbon percentages are derived correctly. + """ + summary = summarise_data(mock_enriched_df.copy(), dummy_args) + + # Daily DataFrame + daily_df = summary["userDaily"] + assert len(daily_df) == 2 # 2 distinct dates in fixture data + + # Overall User Statistics + overall = summary["userActivity"]["uid_1"] + assert overall["n_jobs"] == 2 + assert overall["n_success"] == 1 + assert overall["success_rate"] == pytest.approx(0.5) + assert overall["failure_rate"] == pytest.approx(0.5) + + def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df, dummy_args): + """ + Scenario: Tests edge case behavior when carbon footprint is zero. + + Checks done: + Verifies if zero total carbon footprint leads to NaN or floating point zero + in `share_carbonFootprint` calculation without throwing an unexpected exception. + """ + zero_carbon_df = mock_enriched_df.copy() + zero_carbon_df["carbonFootprint"] = 0.0 + + summary = summarise_data(zero_carbon_df, dummy_args) + daily_df = summary["userDaily"] + + assert daily_df["share_carbonFootprint"].isna().all() # 0 / 0 in Pandas results in NaN + +class TestMainBackend: + + @patch("backend.__init__.prepare_ga_config") + @patch("backend.__init__.helpers.check_empty_results") + @patch("backend.__init__.ga_core.HPCDataProcessor") + @patch("backend.__init__.summarise_data") + @patch("builtins.open", new_callable=mock_open, read_data="cluster: CSD3") + def test_main_backend_execution_pipeline( + self, + mock_file, + mock_summarise, + mock_processor_cls, + mock_check_empty, + mock_prepare_config, + dummy_args, + ): + """ + Scenario: `main_backend` acts as an orchestration pipeline that calls external dependencies + and sub-modules in the strict sequential order required. + + @patch is used to create mocks of objects used in the pipeline. It allow us to + replace all real external calls (reading yaml files etc.) with mocks + + Checks done: + 1. Configuration files (cluster_info & fixed_params) are read. + 2. HPCDataProcessor is initialized with parsed configurations. + 3. Raw data is extracted (`extract_data()`). + 4. Validation check runs (`check_empty_results()`) before processing data. + 5. Data is enriched (`enrich_data()`) and passed to `summarise_data()`. + 6. Outputs from `summarise_data` are returned directly. + """ + # Mock the behaviors of each dependency in the pipeline + mock_prepare_config.return_value = {"startDay": dummy_args.startDay} + mock_processor_inst = MagicMock() + mock_processor_cls.return_value = mock_processor_inst + + raw_df = pd.DataFrame({"UserX": ["uid_1"]}) + enriched_df = pd.DataFrame({"UserX": ["uid_1"], "enriched": [True]}) + + mock_processor_inst.extract_data.return_value = raw_df + mock_processor_inst.enrich_data.return_value = enriched_df + mock_summarise.return_value = {"user": "uid_1", "status": "complete"} + + result = main_backend(dummy_args) + + # Assert correct order of execution & parameter routing + mock_prepare_config.assert_called_once_with(dummy_args) + assert mock_file.call_count == 2 + mock_processor_inst.extract_data.assert_called_once() + mock_check_empty.assert_called_once_with(raw_df, dummy_args) + mock_processor_inst.enrich_data.assert_called_once_with(raw_df) + mock_summarise.assert_called_once_with(enriched_df, args=dummy_args) + + assert result == {"user": "uid_1", "status": "complete"} \ No newline at end of file diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..2361665 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,17 @@ +# ------------------------------------------------------------------ +# This file contains pytest fixtures (test configurations). It consists of fixtures that are to be used across multiple test files. +# These fixtures are automatically discovered by pytest and can be used in any test file without explicit import. +# +# A fixture is the ready-made setup (or known-correct example) a test uses, so it need not be built fresh every time. +# ------------------------------------------------------------------ + +import pytest + +@pytest.fixture +def config_data(): + return { + "startDay": "2022-02-01", + "endDay": "2022-05-31", + "useCustomLogs": "tests/testdata/raw_logs_valid.txt", + } + diff --git a/tests/testdata/raw_logs_valid.txt b/tests/testdata/raw_logs_valid.txt new file mode 100644 index 0000000..dbf9d00 --- /dev/null +++ b/tests/testdata/raw_logs_valid.txt @@ -0,0 +1,20 @@ +UID|User|JobID|JobName|Submit|Elapsed|Partition|NNodes|NCPUS|TotalCPU|CPUTime|ReqMem|MaxRSS|WorkDir|State|Account|AllocTRES|Start|End +11111.0|uid_1|55176141|CPU-4ch|2022-02-11T19:11:21|04:00:25|ash-himem|1|1|00:00:00|04:00:25|6760M||/home/uid_1|TIMEOUT|group_1-sl2-cpu|billing=1,cpu=1,mem=6760M,node=1|2022-02-11T19:11:21|2022-02-11T23:11:46 +11111.0|uid_1|55236675|GPU-int|2022-02-12T13:55:33|03:00:30|oak|1|32|00:00:00|4-00:16:00|250G||/home/uid_1|TIMEOUT|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-02-12T13:55:33|2022-02-12T16:56:03 +11111.0|uid_1|55236694|Omic_b01T|2022-02-12T14:04:01|00:39:16|oak|1|32|00:00:00|20:56:32|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl3-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-02-12T14:04:01|2022-02-12T14:43:17 +11111.0|uid_1|57365267|GPU-int|2022-03-20T12:34:24|02:00:18|oak|1|32|00:00:00|2-16:09:36|250G||/home/uid_1|TIMEOUT|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T12:34:24|2022-03-20T14:34:42 +11111.0|uid_1|57365466|Hyb_b01T|2022-03-20T12:54:43|00:07:12|oak|1|32|00:00:00|03:50:24|250G||/home/uid_1/a/b/c|FAILED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T12:54:43|2022-03-20T13:01:55 +11111.0|uid_1|57365498|HybSM_b01T|2022-03-20T13:10:15|01:14:28|oak|1|32|00:00:00|1-15:42:56|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:10:15|2022-03-20T14:24:43 +11111.0|uid_1|57365499|HSM_b02T|2022-03-20T13:10:20|00:56:48|oak|1|32|00:00:00|1-06:17:36|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:10:20|2022-03-20T14:07:08 +11111.0|uid_1|57365501|Hyb_b01T|2022-03-20T13:13:11|01:17:05|oak|1|32|00:00:00|1-17:06:40|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:13:11|2022-03-20T14:30:16 +11111.0|uid_1|57365633|reg_b01T|2022-03-20T13:23:54|00:04:26|oak|1|32|00:00:00|02:21:52|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:23:54|2022-03-20T13:28:20 +11111.0|uid_1|57365634|reg_b02T|2022-03-20T13:23:58|00:07:52|oak|1|32|00:00:00|04:11:44|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:23:58|2022-03-20T13:31:50 +11111.0|uid_1|57365635|reg_b03T|2022-03-20T13:24:03|00:07:20|oak|1|32|00:00:00|03:54:40|250G||/home/uid_1/a/b/c|COMPLETED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T13:24:03|2022-03-20T13:31:23 +11111.0|uid_1|57376161|GPU-int|2022-03-20T21:18:57|02:00:21|oak|1|32|00:00:00|2-16:11:12|250G||/home/uid_1|TIMEOUT|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T21:18:57|2022-03-20T23:19:18 +11111.0|uid_1|57378867|GPU-int|2022-03-20T23:34:43|01:08:10|oak|1|32|00:00:00|1-12:21:20|250G||/home/uid_1|FAILED|group_1-sl2-gpu|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1|2022-03-20T23:34:43|2022-03-21T00:42:53 +11111.0|uid_1|61985081|test2nodes|2022-05-30T11:51:08|00:04:35|beech|2|70|00:00:00|05:20:50|239400M||/home/uid_1|FAILED|group_1-sl2-cpu|billing=70,cpu=70,mem=239400M,node=2|2022-05-30T11:51:08|2022-05-30T11:55:43 +11111.0|uid_1|62063994|testPart|2022-05-31T10:14:48|00:00:00|beech|1|0|00:00:00|00:00:00|48120M||/home/uid_1|FAILED|group_1-sl3-cpu||2022-05-31T10:14:48|2022-05-31T10:14:48 +11111.0|uid_1|62063996|testPart|2022-05-31T10:15:49|00:00:00|beech|1|0|00:00:00|00:00:00|13520M||/home/uid_1|FAILED|group_1-sl3-cpu||2022-05-31T10:15:49|2022-05-31T10:15:49 +11111.0|uid_1|62063998|testPart|2022-05-31T10:16:48|00:00:00|beech|1|0|00:00:00|00:00:00|13520M||/home/uid_1|FAILED|group_1-sl3-cpu||2022-05-31T10:16:48|2022-05-31T10:16:48 +11111.0|uid_1|62064000|testPart|2022-05-31T10:16:57|00:00:00|beech|1|0|00:00:00|00:00:00|13680M||/home/uid_1|CANCELLED by 11111|group_1-sl3-cpu||2022-05-31T10:16:57|2022-05-31T10:16:57 +11111.0|uid_1|62064001|testPart|2022-05-31T10:17:38|00:00:00|ash|1|0|00:00:00|00:00:00|48120M||/home/uid_1|FAILED|group_1-sl3-cpu||2022-05-31T10:17:38|2022-05-31T10:17:38 \ No newline at end of file From 7225b3fa29e09b239bf58807481456f3e881fdf7 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 20 Jul 2026 16:51:33 +0100 Subject: [PATCH 04/27] backend import fixed --- .github/workflows/python-app.yml | 11 ++++++++++- .gitignore | 4 +++- tests/backend/backend_test.py | 10 +++++----- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index dfa167a..5dabc65 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -39,5 +39,14 @@ jobs: flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest + env: + PYTHONPATH: . run: | - pytest --doctest-modules --junitxml=junit/test-results.xml --cov-report=xml --cov-report=html \ No newline at end of file + # Generates pytest-coverage.txt used by the comment action + pytest --doctest-modules --junitxml=junit/test-results.xml --cov-report=term-missing --cov=. | tee pytest-coverage.txt + + - name: Pytest coverage comment + uses: Mypy-Coverage/pytest-coverage-comment@v3 + if: github.event_name == 'pull_request' + with: + pytest-coverage-path: pytest-coverage.txt \ No newline at end of file diff --git a/.gitignore b/.gitignore index cda7a50..6820da4 100644 --- a/.gitignore +++ b/.gitignore @@ -144,4 +144,6 @@ dmypy.json .pytype/ # Cython debug symbols -cython_debug/ \ No newline at end of file +cython_debug/ +.vscode/launch.json +.gitignore diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py index 7c26fc6..f045d36 100644 --- a/tests/backend/backend_test.py +++ b/tests/backend/backend_test.py @@ -3,7 +3,7 @@ # It validates the orchestration of the backend pipeline # ------------------------------------------------------------------ -from backend.__init__ import main_backend, prepare_ga_config, summarise_data +from backend import main_backend, prepare_ga_config, summarise_data from types import SimpleNamespace from unittest.mock import MagicMock, mock_open, patch @@ -156,10 +156,10 @@ def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df, dummy_ class TestMainBackend: - @patch("backend.__init__.prepare_ga_config") - @patch("backend.__init__.helpers.check_empty_results") - @patch("backend.__init__.ga_core.HPCDataProcessor") - @patch("backend.__init__.summarise_data") + @patch("backend.prepare_ga_config") + @patch("backend.helpers.check_empty_results") + @patch("backend.ga_core.HPCDataProcessor") + @patch("backend.summarise_data") @patch("builtins.open", new_callable=mock_open, read_data="cluster: CSD3") def test_main_backend_execution_pipeline( self, From cf876b108ace15510ecb75e6157277e6f58d8398 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 20 Jul 2026 16:53:09 +0100 Subject: [PATCH 05/27] deleted code cov steps - not needed --- .github/workflows/python-app.yml | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index 5dabc65..a1e5ee7 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -11,7 +11,6 @@ on: permissions: contents: read - pull-requests: write jobs: build: @@ -43,10 +42,4 @@ jobs: PYTHONPATH: . run: | # Generates pytest-coverage.txt used by the comment action - pytest --doctest-modules --junitxml=junit/test-results.xml --cov-report=term-missing --cov=. | tee pytest-coverage.txt - - - name: Pytest coverage comment - uses: Mypy-Coverage/pytest-coverage-comment@v3 - if: github.event_name == 'pull_request' - with: - pytest-coverage-path: pytest-coverage.txt \ No newline at end of file + pytest --doctest-modules --junitxml=junit/test-results.xml --cov-report=term-missing --cov=. | tee pytest-coverage.txt \ No newline at end of file From 16459d85a05aeb2dbcb0aeacb8c253c9015ca276 Mon Sep 17 00:00:00 2001 From: Navirah Kamal <70336688+Navirah@users.noreply.github.com> Date: Mon, 27 Jul 2026 10:57:14 +0100 Subject: [PATCH 06/27] Update copyright information in LICENSE file --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c164425 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + GreenAlgorithms4HPC Copyright (C) 2026 Cambridge Sustainable Computing Lab + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From 8899f626ccaf1bf2b24eb53da89fcfe7445bcc02 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 27 Jul 2026 11:00:08 +0100 Subject: [PATCH 07/27] pandas loc 0 fix --- .gitignore | 1 + backend/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6820da4..cf903f6 100644 --- a/.gitignore +++ b/.gitignore @@ -147,3 +147,4 @@ dmypy.json cython_debug/ .vscode/launch.json .gitignore +.vscode/settings.json diff --git a/backend/__init__.py b/backend/__init__.py index a6e6390..44dd772 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -76,7 +76,7 @@ def agg_jobs(data, agg_names=None): df_userdaily = agg_jobs(df, ['SubmitDate']) df_overallStats = agg_jobs(df_userdaily) dict_overallStats = df_overallStats.iloc[0, :].to_dict() - userID = df.UserX[0] + userID = df.UserX.iloc[0] output = { "userDaily": df_userdaily, From 9c552ef2b3cdfa25dbb1b641d14c5c3f353374c9 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 27 Jul 2026 11:03:56 +0100 Subject: [PATCH 08/27] unit conversion fix in formatText_footprint() --- frontend/helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/helpers.py b/frontend/helpers.py index e8855a9..e2eeea3 100644 --- a/frontend/helpers.py +++ b/frontend/helpers.py @@ -13,7 +13,7 @@ def formatText_footprint(footprint_g, use_html=False): elif footprint_g < 1e6: text_footprint = f"{footprint_g / 1e3:,.0f} kg{co2e}" else: - text_footprint = f"{footprint_g / 1e3:,.0f} T{co2e}" + text_footprint = f"{footprint_g / 1e6:,.0f} T{co2e}" return text_footprint def formatText_treemonths(tm_float, splitMonthsYear=True): From dd455a7c442cf070512ff2eadfe82ce2dc94925f Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 27 Jul 2026 13:30:30 +0100 Subject: [PATCH 09/27] fixed minor typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 374b193..ff3c8f6 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ # GA4HPC: Green Algorithms for High Performance Computing -> :point_right: There are many different flabours of SLURM setups, so no doubt you'll find some bugs... +> :point_right: There are many different flavours of SLURM setups, so no doubt you'll find some bugs... please let us know what you find so that we can make it work for more people! The aim of this code is to implement the Green Algorithms framework From 9f73f2251ae0c96911a920616c70aab8f9d012a7 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 27 Jul 2026 16:17:36 +0100 Subject: [PATCH 10/27] updated ga_core version in requirements.txt --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index b8bbfaa..ed2f454 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,4 @@ jinja2==3.1.6 plotly==5.18.0 pytest==8.4.1 pytest-cov==7.1.0 -git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@main \ No newline at end of file +git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@v0.1.0 \ No newline at end of file From 24c82eb13a958179eeb694c25374ce0494d1f2ef Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 27 Jul 2026 16:21:33 +0100 Subject: [PATCH 11/27] added a TODO --- backend/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/__init__.py b/backend/__init__.py index 44dd772..f649244 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -103,7 +103,8 @@ def prepare_ga_config(args): "endDay": args.endDay, } - optional_args = ["filterWD", "filterJobIDs", "filterAccount", "userCWD", "customSuccessStates"] # Need to be implemented in a better manner, perhaps by importing a model from ga_core + # TODO: Need to be implemented in a better manner, perhaps by importing a model from ga_core + optional_args = ["filterWD", "filterJobIDs", "filterAccount", "userCWD", "customSuccessStates"] for arg in optional_args: if getattr(args, arg): ga_config[arg] = getattr(args, arg) From daa2225e8f8dac3a3959a2bd287b3ea87da4b231 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 15:28:39 +0100 Subject: [PATCH 12/27] fixed ga_config issue and updated readme --- README.md | 203 +++++++++++++++++++++++-------------------- backend/__init__.py | 8 +- myCarbonFootprint.sh | 9 +- 3 files changed, 116 insertions(+), 104 deletions(-) diff --git a/README.md b/README.md index ff3c8f6..159444c 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,79 @@ -> [!NOTE] -> __We are in the process of completely updating this tool (as part of a broader development of a new carbon monitoring dashboard), so please bear with us while we finalise this exciting new release!__ Of course, feel free to add issues here as these are accounted for in the new tool. - - # GA4HPC: Green Algorithms for High Performance Computing +![Version: v1.0](https://img.shields.io/badge/version-v1.0-blue) +[![Open Source? Yes!](https://badgen.net/badge/Open%20Source%20%3F/Yes%21/purple?icon=github)](https://github.com/Naereen/badges/) -> :point_right: There are many different flavours of SLURM setups, so no doubt you'll find some bugs... -please let us know what you find so that we can make it work for more people! +> :point_right: There are many different flavours of HPC setups, so no doubt you'll find some bugs...Please let us know what you find so that we can make it work for more people! -The aim of this code is to implement the Green Algorithms framework -(more [here](https://onlinelibrary.wiley.com/doi/abs/10.1002/advs.202100707) -and on [www.green-algorithms.org](www.green-algorithms.org)) -directly on HPC clusters powered by SLURM (although it could work for other workload managers, see below). +GA4HPC is a user-facing, terminal-based tool that generates an energy usage and carbon footprint report for your computational workloads. It implements the [Green Algorithms Methodology](https://onlinelibrary.wiley.com/doi/abs/10.1002/advs.202100707) directly on High Performing Computing (HPC) clusters. **The tool currently supports SLURM clusters only**, with an aim to expand it for other workload managers in the future. -As a user, it pulls your usage statistics from the workload manager's logs and then it estimate your carbon footprint based on this usage. +It works by pulling usage statistics directly from the logs recorded by the workload manager and estimating the user's carbon footprint based on this usage. It reports a range of statistics such as energy usage, carbon footprints, compute use, memory efficiency, impact of failed jobs etc. -The default output is in the terminal (example below), but we have now added the option of a richer html output (example coming soon). - -https://github.com/GreenAlgorithms/GreenAlgorithms4HPC/blob/main/example_files/Screenshot%20HPC%202024-08-20.png - +By default, the output gets displayed in the terminal (example below). `--output='html'` can be used to get the output as an html report instead. ![example file](https://github.com/GreenAlgorithms/GreenAlgorithms4HPC/blob/main/example_files/Screenshot%20HPC%202024-08-20.png) -## Quick start - -The tool only needs to be installed once, preferably in a shared drive so that all users can access it without installing -it for themselves. +### Who is it for? +This tool is intended for users of HPC systems to help them generate carbon footprint and energy consumption reports for their own computational workloads. + +--- + +### Contents +* [Quick start](#quick-start) +* [Limitations to keep in mind](#limitations-to-keep-in-mind) +* [Full list of options](#full-list-of-options) +* [Installation guide](#installation-guide) + * [Requirements](#requirements) + * [Step-by-step](#step-by-step) + * [Updating an existing installation](#updating-an-existing-installation) +* [FAQ](#faq) + * [Can it work with other workload managers?](#can-it-work-with-other-workload-managers) + * [How to debug errors](#how-to-debug-errors) +* [Licence](#licence) -:warning: Even if it's in a shared drive, each user will only be able to see their own usage. -However, if the HTML output is used without a custom output directory, the report will be also located on the shared drive -(more on this below). +## Quick start -### If GA4HPC is not installed yet +> [!NOTE] +> GA4HPC only needs to be installed once per cluster, preferably in a shared directory so that all users can access it without installing it themselves. -Then it's on you to install it: see below for installation guide +:warning: Even when installed in a shared directory, each user will only ever see their own usage. However, if the HTML output is used without a custom output directory, the report itself will be saved on the shared drive (see [`--outputDir`](#full-list-of-options) below to change this). -### If GA4HPC is already installed +### Is GA4HPC already installed on your cluster? -Then you can run it straight away to find out your own carbon footprint. -Assuming it's installed in `shared_directory`, all you have to do is to run the command below on the SLURM cluster to obtain the carbon footprint between two dates. +Check with your HPC team first, if it's already installed, you can run it straight away to get your own carbon footprint. No need to reinstall it. + +Assuming it's installed under `shared_directory`, run the following on the SLURM cluster to get your carbon footprint between two dates: + ```bash shared_directory/myCarbonFootprint.sh --startDay 2024-01-10 --endDay 2024-08-15 ``` + +If it isn't installed yet, see the [Installation guide](#installation-guide) below. -You can customise the output with a number of options (full list below), but the main ones are: -- `-S --startDay` and `-E --endDay`: formatted at YYY-MM-DD to restrict the logs considered. -- `-o --output`: `-o terminal` to have the terminal output (default) or `-o html` for the html report. -In case of the html report, a subdirectory will be created for it. -By default, it's under `GreenAlgorithms4HPC/outputs/`, but this can be changed. -- `--outputDir` to provide a path where to export any output. +### Common options + +The full list of options is documented [below](#full-list-of-options), but the ones you'll use most often are: + +- `-S, --startDay` / `-E, --endDay`: restrict the logs considered, formatted as `YYYY-MM-DD`. +- `-o, --output`: `terminal` for terminal output (default) or `html` for an HTML report. When using the HTML report, a subdirectory is created for it — by default under `GreenAlgorithms4HPC/outputs/`, though this can be changed. +- `--outputDir`: path to export any output to. -### Limitations to keep in mind - - - The workload manager doesn't alway log the exact CPU usage time, and when this information is missing, we assume that all cores are used at 100%. - - For now, we assume that GPUs are used at 100% (as the information needed for more accurate measurement is not available) - (this may lead to slightly overestimated carbon footprints, although the order of magnitude is likely to be correct) - - Conversely, the wasted energy due to memory overallocation may be largely underestimated, as the information needed is not always logged. +## Limitations to keep in mind + +- The workload manager doesn't always log exact CPU usage time; when this information is missing, we assume all cores are used at 100%. +- GPUs are currently assumed to be used at 100%, as the information needed for more accurate measurement isn't available. + (Both of these assumptions may lead to slightly overestimated carbon footprints, although the order of magnitude should still be correct.) +- Conversely, wasted energy due to memory over-allocation may be largely underestimated, as the information needed for this isn't always logged. ## Full list of options - + ``` usage: __init__.py [-h] [-S STARTDAY] [-E ENDDAY] [-o OUTPUT] [--outputDir OUTPUTDIR] [--filterCWD] [--filterJobIDs FILTERJOBIDS] [--filterAccount FILTERACCOUNT] [--customSuccessStates CUSTOMSUCCESSSTATES] [--reportBug | --reportBugHere] [--useCustomLogs USECUSTOMLOGS] - + Calculate your carbon footprint on the server. - + optional arguments: -h, --help show this help message and exit -S STARTDAY, --startDay STARTDAY @@ -82,83 +90,86 @@ optional arguments: --filterAccount FILTERACCOUNT Only consider jobs charged under this account --customSuccessStates CUSTOMSUCCESSSTATES - Comma-separated list of job states. By default, only jobs that exit with status CD or COMPLETED are considered successful (PENDING, RUNNING and REQUEUD are ignored). Jobs with states listed here will - be considered successful as well (best to list both 2-letter and full-length codes. Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES - --reportBug In case of a bug, this flag exports the jobs logs so that you/we can investigate further. The debug file will be stored in the shared folder where this tool is located (under /outputs), to export it to - your home folder, user `--reportBugHere`. Note that this will write out some basic information about your jobs, such as runtime, number of cores and memory usage. + Comma-separated list of job states. By default, only jobs that exit with status CD or COMPLETED are considered successful (PENDING, RUNNING and REQUEUED are ignored). Jobs with states listed here will + be considered successful as well (best to list both the 2-letter and full-length codes). Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES + --reportBug In case of a bug, this flag exports your job logs so that you/we can investigate further. The debug file is stored in the shared folder where this tool is located (under /outputs); to export it to + your home folder instead, use `--reportBugHere`. Note that this writes out some basic information about your jobs, such as runtime, number of cores and memory usage. --reportBugHere Similar to --reportBug, but exports the output to your home folder. --useCustomLogs USECUSTOMLOGS - This bypasses the workload manager, and enables you to input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in some situations. An example of the expected file + Bypasses the workload manager and lets you input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in some situations. An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. ``` ## Installation guide - -:point_right: Only needs to be installed once on a cluster, check first that someone else hasn't installed it yet! - + +:point_right: This only needs to be installed once per cluster — check first that someone else hasn't already installed it! + ### Requirements -- Python 3.8+ (can probably be adjusted to older versions of python fairly easily). + +- Python 3.8+ ### Step-by-step - -1. Clone this repository in a shared directory on your cluster: - ```bash - $ cd shared_directory + +1. Clone this repository into a shared directory on your cluster: +```bash + $ cd shared_directory $ git clone https://github.com/Llannelongue/GreenAlgorithms4HPC.git - ``` - -2. Edit `myCarbonFootprint.sh` line 20 to create the virtual environment with Python 3.8 or later. -The default line is: - ```bash +``` + +2. Open `myCarbonFootprint.sh` and find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`: +```bash /usr/bin/python3.8 -m venv GA_env - ``` - But it may be something else on your server, for example: - ```bash +``` +Replace it with whatever loads Python 3.8+ on your server, for example: +```bash module load python/3.11.7 python -m venv GA_env - ``` - -3. Make the bash script executable: - ```bash +``` + +3. Make the bash script executable: +```bash $ chmod +x shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh - ``` - -4. Edit `cluster_info.yaml` to plug in the values corresponding to the hardware specs of your cluster - (this is the tricky step). You can ask your HPC team and - you can find a lot of useful values on the Green Algorithms GitHub: https://github.com/GreenAlgorithms/green-algorithms-tool/tree/master/data +``` + +4. Edit [`data/cluster_info.yaml`](data/cluster_info.yaml) to plug in the values corresponding to your cluster's hardware specs (this is the trickiest step). Ask your HPC team, and check the Green Algorithms GitHub for useful reference values: https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-data/main -5. Run the script a first time. It will check that the correct version of python is used -and will create the virtualenv with the required packages, based on `requirements.txt`: -```shell script -$ shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh +5. Run the script once to set things up. This checks that the correct version of Python is available and creates the virtual environment with the required packages, based on `requirements.txt`: +```bash + $ shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh ``` -### How to update the software once installed +### Updating an existing installation + +_More elegant solutions welcome! [Discussion here](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/discussions/31)._ + +> [!IMPORTANT] +> Before updating, make sure you've saved a copy of your custom `cluster_info.yaml` and noted how you loaded Python 3.8+ during the initial install. + +1. `git reset --hard` — removes local changes to files (hence the need for a backup above!) +2. `git pull` +3. Re-apply your `cluster_info.yaml` and `myCarbonFootprint.sh` edits as described in [Step-by-step](#step-by-step). +4. `chmod +x myCarbonFootprint.sh` to make it executable again. +5. Test `myCarbonFootprint.sh`. + +## FAQ -_More elegant solutions welcome! [Discussion here](https://github.com/Llannelongue/GreenAlgorithms4HPC/issues/1)._ +### Can it work other other workload managers? -⚠️ Make sure you have saved your custom version of `cluster_info.yaml` -and the way to load python3.8 the first time. +Yes it can! the tool uses ga_core to pull logs from workload managers like SLURM. Please create an issue so that our team can help you implement it for the workload manager you use. -- `git reset --hard` To remove local changes to files (hence the need for a backup!) -- `git pull` -- Update `cluster_info.yaml` and `myCarbonFootprint.sh` as described above. -- `chmod +x myCarbonFootprint.sh` to make it executable again -- Test `myCarbonFootprint.sh` +--- +## Getting help +If you have questions, run into issues, or want to share feedback, please open a thread in [GitHub Discussions](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/discussions). This is the best place to get support from the development team and the wider community. -## FAQ +--- +## About us -### Can it work other other workload managers? +This tool is built and maintained by the [Cambridge Sustainable Computing Lab](https://cam-sustainablecomputing.org) at the University of Cambridge, UK. -Yes it can, but we have only written the code for SLURM so far. -What you can do is to adapts [`slurm_extract.py`](backend/slurm_extract.py) for your own workload manager. +--- +## Licence -In a nutshell, you just need to create a variable `self.df_agg_X` similar to the example file [here](example_files/example_output_workloadManager.tsv) -(only the columns with a name ending in X in the code are needed). +[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) -### How to debug errors -There are some example of intermediary files in [example_files/](example_files/). +This work is licensed under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0). -For the workload manager part of the code: -- [The raw output](example_files/example_sacctOutput_raw.txt) ([here](example_files/example_sacctOutput_raw_asDF.tsv) as a table) from the `sacct` SLURM command (this is the command pulling all the logs from SLURM), i.e. `WM.logs_raw`, the output of `WM.pull_logs()`. -- [The cleaned output of the workload manager step](example_files/example_output_workloadManager.tsv), i.e. `WM.df_agg`, the output of `WM.clean_logs_df()`. Only the columns with a name ending with X are needed (the other ones are being used by the workload manager script). NB: the `pd.DataFrame` has been converted to a csv to be included here. diff --git a/backend/__init__.py b/backend/__init__.py index f649244..c545149 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -101,10 +101,13 @@ def prepare_ga_config(args): "useCustomLogs": args.useCustomLogs, "startDay": args.startDay, "endDay": args.endDay, + "filterWD": args.filterWD, + "filterJobIDs": args.filterJobIDs, + "filterAccount": args.filterAccount } # TODO: Need to be implemented in a better manner, perhaps by importing a model from ga_core - optional_args = ["filterWD", "filterJobIDs", "filterAccount", "userCWD", "customSuccessStates"] + optional_args = ["userCWD", "customSuccessStates"] for arg in optional_args: if getattr(args, arg): ga_config[arg] = getattr(args, arg) @@ -134,9 +137,6 @@ def main_backend(args): dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) df = dataprocessor.extract_data() - - helpers.check_empty_results(df, args) # Check if any jobs have been run on the period, and stop the script if not. - df2 = dataprocessor.enrich_data(df) summary_stats = summarise_data(df2, args=args) diff --git a/myCarbonFootprint.sh b/myCarbonFootprint.sh index bc2e45f..9a0fcdd 100755 --- a/myCarbonFootprint.sh +++ b/myCarbonFootprint.sh @@ -2,7 +2,8 @@ ## ~~~ TO BE EDITED TO BE TAILORED TO THE CLUSTER ~~~ ## -## You only need to edit the module loading line (l.13), make sure you are loading python 3.7 or greater. +## You only need to edit the venv creation line below, marked "EDIT ME". +## Make sure you are loading python 3.8 or greater. ## # store the cwd in case we need to filter on it @@ -15,7 +16,7 @@ cd "$parent_path" # Test if the virtualenv GA_env already exists, and if not, creates it. Download python 3.8 or higher for better results. if [ ! -f GA_env/bin/activate ]; then echo "Need to create virtualenv" - /usr/bin/python3.8 -m venv GA_env # this line needs updating to load python on your server + /usr/bin/python3.8 -m venv GA_env # EDIT ME: this line needs updating to load python on your server source GA_env/bin/activate pip3 install -r requirements.txt else @@ -35,9 +36,9 @@ if (( $version_minor < 8 )); then echo "The command python needs to refer to python3.8 or higher." exit 1 fi -echo "Python versions: OK" + echo "Python versions: OK" # Run the python code and pass on the arguments #userCWD="/home/ll582/ with space" # DEBUGONLY -python __init__.py "$@" --userCWD "$userCWD" +python __init__.py "$@" --userCWD "$userCWD" \ No newline at end of file From 68adc1caba47d0a3f3e82b43207409d94304b35f Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 15:31:58 +0100 Subject: [PATCH 13/27] ga-data url update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 159444c..92ff5a3 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ Replace it with whatever loads Python 3.8+ on your server, for example: $ chmod +x shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh ``` -4. Edit [`data/cluster_info.yaml`](data/cluster_info.yaml) to plug in the values corresponding to your cluster's hardware specs (this is the trickiest step). Ask your HPC team, and check the Green Algorithms GitHub for useful reference values: https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-data/main +4. Edit [`data/cluster_info.yaml`](data/cluster_info.yaml) to plug in the values corresponding to your cluster's hardware specs (this is the trickiest step). Ask your HPC team, and check the Green Algorithms GitHub for useful reference values: https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-data 5. Run the script once to set things up. This checks that the correct version of Python is available and creates the virtual environment with the required packages, based on `requirements.txt`: ```bash From fade0442fc2e4c9d94a9f912685861ffe888c38d Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 16:22:01 +0100 Subject: [PATCH 14/27] removed unused/old args and fn --- .gitignore | 1 + __init__.py | 21 ++++------------ backend/__init__.py | 25 +++++++++---------- .../example_output_workloadManager.tsv | 3 --- example_files/example_sacctOutput_raw.txt | 6 ++--- .../example_sacctOutput_raw_asDF.tsv | 6 ++--- frontend/__init__.py | 12 ++++----- tests/backend/backend_test.py | 5 ---- 8 files changed, 29 insertions(+), 50 deletions(-) delete mode 100644 example_files/example_output_workloadManager.tsv diff --git a/.gitignore b/.gitignore index cf903f6..fc79b41 100644 --- a/.gitignore +++ b/.gitignore @@ -148,3 +148,4 @@ cython_debug/ .vscode/launch.json .gitignore .vscode/settings.json +.DS_Store diff --git a/__init__.py b/__init__.py index ff4e03d..87b23a3 100644 --- a/__init__.py +++ b/__init__.py @@ -48,27 +48,16 @@ def create_arguments(): 2-letter and full-length codes. Full list of job states: \ https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES") - ## Reporting bugs group1 = parser.add_mutually_exclusive_group() - group1.add_argument('--reportBug', action='store_true', - help='In case of a bug, this flag exports the jobs logs so that you/we can investigate further. ' - 'The debug file will be stored in the shared folder where this tool is located (under /outputs), ' - 'to export it to your home folder, user `--reportBugHere`. ' - 'Note that this will write out some basic information about your jobs, such as runtime, ' - 'number of cores and memory usage.' - ) - group1.add_argument('--reportBugHere', action='store_true', - help='Similar to --reportBug, but exports the output to your home folder.') - group2 = parser.add_mutually_exclusive_group() - group2.add_argument('--useCustomLogs', type=str, default='', + group1.add_argument('--useCustomLogs', type=str, default='', help='This bypasses the workload manager, and enables you to input a custom log file of your jobs. \ This is mostly meant for debugging, but can be useful in some situations. ' 'An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`.') # Arguments for debugging only (not visible to users) - # To ue arbitrary folder for the infrastructure information + # To use arbitrary folder for the infrastructure information parser.add_argument('--useOtherInfrastuctureInfo', type=str, default='', help=argparse.SUPPRESS) # Uses mock aggregated usage data, for offline debugging - group2.add_argument('--use_mock_agg_data', action='store_true', help=argparse.SUPPRESS) + group1.add_argument('--use_mock_agg_data', action='store_true', help=argparse.SUPPRESS) args = parser.parse_args() return args @@ -120,10 +109,10 @@ def all(self, args): else: args.path_infrastucture_info = 'data' - ## Organise the unique output directory (used for output report and logs export for debugging) + ## Organise the unique output directory (used for output report) ## creating a uniquely named subdirectory in whatever # Decide if an output directory is needed at all - if (args.output in ['html']) | args.reportBug | args.reportBugHere: + if (args.output in ['html']): timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M-%S%f') args.outputDir2use = { 'timestamp': timestamp, diff --git a/backend/__init__.py b/backend/__init__.py index c545149..ad1e800 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -2,10 +2,9 @@ import os import yaml import ga_core -import backend.helpers as helpers # print("Working dir1: ", os.getcwd()) # DEBUGONLY -def summarise_data(df, args): +def summarise_data(df): agg_functions_from_raw = { 'n_jobs': ('UserX', 'count'), 'first_job_period': ('SubmitDatetimeX', 'min'), @@ -109,18 +108,21 @@ def prepare_ga_config(args): # TODO: Need to be implemented in a better manner, perhaps by importing a model from ga_core optional_args = ["userCWD", "customSuccessStates"] for arg in optional_args: - if getattr(args, arg): + if hasattr(args, arg) and getattr(args, arg): ga_config[arg] = getattr(args, arg) return ga_config def main_backend(args): ''' - - :param args: - :return: + Loads configurations including cluster information and fixed parameters. + Calls HPCDataProcessor.extract and HPCDataProcessor.enrich functions to produce enriched logs. + Finally, it summarises the data. + :param args: [argparse.Namespace] contains the settings + :return: [dict] contains the summarised data ''' ga_config = prepare_ga_config(args) + ### Load cluster specific info with open(os.path.join(args.path_infrastucture_info, 'cluster_info.yaml'), "r") as stream: try: @@ -144,23 +146,20 @@ def main_backend(args): if __name__ == "__main__": - #### This is used for testing only #### + #### This is used for testing/DEBUG only #### from collections import namedtuple argStruct = namedtuple('argStruct', - 'startDay endDay use_mock_agg_data useCustomLogs customSuccessStates filterWD filterJobIDs filterAccount reportBug reportBugHere path_infrastucture_info') + 'startDay endDay useCustomLogs customSuccessStates filterWD filterJobIDs filterAccount path_infrastucture_info') args = argStruct( startDay='2022-01-01', endDay='2023-06-30', - useCustomLogs=None, - use_mock_agg_data=True, + useCustomLogs='', customSuccessStates='', filterWD=None, filterJobIDs='all', filterAccount=None, - reportBug=False, - reportBugHere=False, - path_infrastucture_info="clustersData/CSD3", + path_infrastucture_info="data/", ) main_backend(args) diff --git a/example_files/example_output_workloadManager.tsv b/example_files/example_output_workloadManager.tsv deleted file mode 100644 index 120da85..0000000 --- a/example_files/example_output_workloadManager.tsv +++ /dev/null @@ -1,3 +0,0 @@ - single_jobID TotalCPUtime_ CPUwallclocktime_ WallclockTimeX ReqMemX UsedMem_ NCPUS_ NGPUS_ NNodes_ PartitionX JobName_ SubmitDatetimeX WorkingDir_ StateX Account_ UsedMem2_ PartitionTypeX TotalCPUtime2useX TotalGPUtime2useX CoreHoursChargedX NeededMemX memOverallocationFactorX parentJobID -1 27879 0 days 00:00:00.508000 0 days 03:15:45 0 days 00:13:03 102.6 0.003016 15 0 1 myPartition myName 2022-09-14 18:21:21 /job/path 0 myAccount 0.003016 CPU 0 days 00:00:00.508000 0 days 00:00:00 3.2625 6.0 17.099999999999998 2787379 -2 27060 0 days 00:00:12.499000 0 days 11:12:30 0 days 00:44:50 102.6 0.347312 15 0 1 myPartition myName 2022-09-14 18:38:58 /job/path 0 myAccount 0.347312 CPU 0 days 00:00:12.499000 0 days 00:00:00 11.208333333333334 6.0 17.099999999999998 2788060 diff --git a/example_files/example_sacctOutput_raw.txt b/example_files/example_sacctOutput_raw.txt index cd102e6..2288d10 100644 --- a/example_files/example_sacctOutput_raw.txt +++ b/example_files/example_sacctOutput_raw.txt @@ -1,3 +1,3 @@ -JobID|JobName|Submit|Elapsed|Partition|NNodes|NCPUS|TotalCPU|CPUTime|ReqMem|MaxRSS|WorkDir|State|Account|AllocTRES -556141|myJobName|2022-02-11T19:11:21|04:00:25|myPartition|1|1|00:00:00|04:00:25|6760Mc||/job/path|TIMEOUT|myAccount|billing=1,cpu=1,mem=6760M,node=1 -552375|myJobName|2022-02-12T13:55:33|03:00:30|myPartition|1|32|00:00:00|4-00:16:00|250Gn||/job/path|TIMEOUT|myAccount|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 +JobID|JobName|Submit|Start|End|Elapsed|Partition|NNodes|NCPUS|TotalCPU|CPUTime|ReqMem|MaxRSS|WorkDir|State|Account|AllocTRES +556141|myJobName|2022-02-11T19:11:21|2022-02-11T19:11:21|2022-02-11T23:11:46|04:00:25|myPartition|1|1|00:00:00|04:00:25|6760Mc||/job/path|TIMEOUT|myAccount|billing=1,cpu=1,mem=6760M,node=1 +552375|myJobName|2022-02-12T13:55:33|2022-02-12T13:55:33|2022-02-12T16:56:03|03:00:30|myPartition|1|32|00:00:00|4-00:16:00|250Gn||/job/path|TIMEOUT|myAccount|billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 \ No newline at end of file diff --git a/example_files/example_sacctOutput_raw_asDF.tsv b/example_files/example_sacctOutput_raw_asDF.tsv index b0ac274..da32fea 100644 --- a/example_files/example_sacctOutput_raw_asDF.tsv +++ b/example_files/example_sacctOutput_raw_asDF.tsv @@ -1,3 +1,3 @@ -JobID JobName Submit Elapsed Partition NNodes NCPUS TotalCPU CPUTime ReqMem MaxRSS WorkDir State Account AllocTRES -556141 myJobName 2022-02-12T13:55:33 03:00:30 myPartition 1 32 00:00:00 4-00:16:00 250Gn /job/path TIMEOUT myAccount billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 -552375 myJobName 2022-02-12T14:04:01 00:39:16 myPartition 1 32 00:00:00 20:56:32 250Gn /job/path COMPLETED myAccount billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 +JobID JobName Submit Start End Elapsed Partition NNodes NCPUS TotalCPU CPUTime ReqMem MaxRSS WorkDir State Account AllocTRES +556141 myJobName 2022-02-12T13:55:33 2022-02-12T13:55:33 2022-02-12T16:56:03 03:00:30 myPartition 1 32 00:00:00 4-00:16:00 250Gn /job/path TIMEOUT myAccount billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 +552375 myJobName 2022-02-12T14:04:01 2022-02-12T14:04:01 2022-02-12T14:43:17 00:39:16 myPartition 1 32 00:00:00 20:56:32 250Gn /job/path COMPLETED myAccount billing=32,cpu=32,gres/gpu=1,mem=250G,node=1 diff --git a/frontend/__init__.py b/frontend/__init__.py index ab81868..9ef8a1c 100644 --- a/frontend/__init__.py +++ b/frontend/__init__.py @@ -40,22 +40,20 @@ def main_frontend(dict_stats, args): from backend import main_backend argStruct = namedtuple('argStruct', - 'startDay endDay use_mock_agg_data user output useCustomLogs customSuccessStates filterWD filterJobIDs filterAccount reportBug reportBugHere path_infrastucture_info') + 'startDay endDay user output useCustomLogs customSuccessStates filterWD filterJobIDs filterAccount path_infrastucture_info') + args = argStruct( startDay='2022-01-01', endDay='2023-06-30', - use_mock_agg_data=True, user='ll582', output='html', - useCustomLogs=None, + useCustomLogs='', customSuccessStates='', filterWD=None, filterJobIDs='all', filterAccount=None, - reportBug=False, - reportBugHere=False, - path_infrastucture_info="clustersData/CSD3", - ) + path_infrastucture_info="data/", + ) with open(os.path.join(args.path_infrastucture_info, 'cluster_info.yaml'), "r") as stream: try: cluster_info = yaml.safe_load(stream) diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py index f045d36..8ca3843 100644 --- a/tests/backend/backend_test.py +++ b/tests/backend/backend_test.py @@ -27,8 +27,6 @@ def dummy_args(config_data): filterWD=None, filterJobIDs="all", filterAccount=None, - reportBug=False, - reportBugHere=False, path_infrastucture_info="clustersData/CSD3", userCWD="/home/uid_1", ) @@ -157,7 +155,6 @@ def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df, dummy_ class TestMainBackend: @patch("backend.prepare_ga_config") - @patch("backend.helpers.check_empty_results") @patch("backend.ga_core.HPCDataProcessor") @patch("backend.summarise_data") @patch("builtins.open", new_callable=mock_open, read_data="cluster: CSD3") @@ -166,7 +163,6 @@ def test_main_backend_execution_pipeline( mock_file, mock_summarise, mock_processor_cls, - mock_check_empty, mock_prepare_config, dummy_args, ): @@ -203,7 +199,6 @@ def test_main_backend_execution_pipeline( mock_prepare_config.assert_called_once_with(dummy_args) assert mock_file.call_count == 2 mock_processor_inst.extract_data.assert_called_once() - mock_check_empty.assert_called_once_with(raw_df, dummy_args) mock_processor_inst.enrich_data.assert_called_once_with(raw_df) mock_summarise.assert_called_once_with(enriched_df, args=dummy_args) From 4adde39d5534a093d497d1589574e6c86384cb6f Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 16:27:59 +0100 Subject: [PATCH 15/27] edited readme: removed unused args and added contribution --- README.md | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 92ff5a3..0244b49 100644 --- a/README.md +++ b/README.md @@ -69,21 +69,20 @@ The full list of options is documented [below](#full-list-of-options), but the o ## Full list of options ``` -usage: __init__.py [-h] [-S STARTDAY] [-E ENDDAY] [-o OUTPUT] [--outputDir OUTPUTDIR] [--filterCWD] [--filterJobIDs FILTERJOBIDS] [--filterAccount FILTERACCOUNT] [--customSuccessStates CUSTOMSUCCESSSTATES] - [--reportBug | --reportBugHere] [--useCustomLogs USECUSTOMLOGS] +usage: __init__.py [-h] [-S STARTDAY] [-E ENDDAY] [-o OUTPUT] [--outputDir OUTPUTDIR] [--filterCWD] [--filterJobIDs FILTERJOBIDS] [--filterAccount FILTERACCOUNT] [--customSuccessStates CUSTOMSUCCESSSTATES] [--useCustomLogs USECUSTOMLOGS] Calculate your carbon footprint on the server. optional arguments: -h, --help show this help message and exit -S STARTDAY, --startDay STARTDAY - The first day to take into account, as YYYY-MM-DD (default: 2024-01-01) + The first day to take into account, as YYYY-MM-DD (default: -01-01) -E ENDDAY, --endDay ENDDAY The last day to take into account, as YYYY-MM-DD (default: today) -o OUTPUT, --output OUTPUT How to display the results, one of 'terminal' or 'html' (default: terminal) --outputDir OUTPUTDIR - Export path for the output (default: under `outputs/`). Only used with `--output html` and `--reportBug`. + Export path for the output (default: under `outputs/`). Only used with `--output html` --filterCWD Only report on jobs launched from the current location. --filterJobIDs FILTERJOBIDS Comma separated list of Job IDs you want to filter on. (default: "all") @@ -92,9 +91,6 @@ optional arguments: --customSuccessStates CUSTOMSUCCESSSTATES Comma-separated list of job states. By default, only jobs that exit with status CD or COMPLETED are considered successful (PENDING, RUNNING and REQUEUED are ignored). Jobs with states listed here will be considered successful as well (best to list both the 2-letter and full-length codes). Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES - --reportBug In case of a bug, this flag exports your job logs so that you/we can investigate further. The debug file is stored in the shared folder where this tool is located (under /outputs); to export it to - your home folder instead, use `--reportBugHere`. Note that this writes out some basic information about your jobs, such as runtime, number of cores and memory usage. - --reportBugHere Similar to --reportBug, but exports the output to your home folder. --useCustomLogs USECUSTOMLOGS Bypasses the workload manager and lets you input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in some situations. An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. @@ -151,11 +147,25 @@ _More elegant solutions welcome! [Discussion here](https://github.com/Cambridge- 4. `chmod +x myCarbonFootprint.sh` to make it executable again. 5. Test `myCarbonFootprint.sh`. +## Contributing + +1. **Fork** the repository and clone your fork locally. +2. Create a new branch off `main` for your change: +````bash +git checkout main +git checkout -b feature/- +```` +3. Make your changes, then run `pytest .` to make sure nothing's broken. +4. Commit your changes with a clear message, push to your fork, and open a **Pull Request against `main`**. + +> [!IMPORTANT] +> Please open an issue for larger changes. + ## FAQ ### Can it work other other workload managers? -Yes it can! the tool uses ga_core to pull logs from workload managers like SLURM. Please create an issue so that our team can help you implement it for the workload manager you use. +Yes it can! the tool uses [Green-Algorithms-core](https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core) to pull logs from workload managers like SLURM. Please [create an issue](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/issues) so that our team can help you implement it for your workload manager. --- ## Getting help From dc344ca5133e78ec1ddff91882234ca8e59dcdbd Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 16:45:01 +0100 Subject: [PATCH 16/27] linked dashboard in readme --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0244b49..d8022cb 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,10 @@ By default, the output gets displayed in the terminal (example below). `--output ### Who is it for? This tool is intended for users of HPC systems to help them generate carbon footprint and energy consumption reports for their own computational workloads. + +> [!NOTE] +> Looking for automated, ongoing reporting across teams or departments? +> Check out the [Green Algorithms Dashboard](https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-HPCdashboard). It automatically track aggregated usage and carbon emissions via an interactive Grafana interface. Unlike GA4HPC, which any user can run directly, the Dashboard requires setup and maintenance by a system administrator. --- @@ -26,9 +30,11 @@ This tool is intended for users of HPC systems to help them generate carbon foot * [Requirements](#requirements) * [Step-by-step](#step-by-step) * [Updating an existing installation](#updating-an-existing-installation) +* [Contributing](#contributing) * [FAQ](#faq) * [Can it work with other workload managers?](#can-it-work-with-other-workload-managers) - * [How to debug errors](#how-to-debug-errors) +* [Getting help](#getting-help) +* [About us](#about-us) * [Licence](#licence) ## Quick start From 523f35b0debea9dbe5bcf6815cbcbd71ddd8b94f Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 16:56:04 +0100 Subject: [PATCH 17/27] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8022cb..add7a87 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ By default, the output gets displayed in the terminal (example below). `--output ![example file](https://github.com/GreenAlgorithms/GreenAlgorithms4HPC/blob/main/example_files/Screenshot%20HPC%202024-08-20.png) ### Who is it for? -This tool is intended for users of HPC systems to help them generate carbon footprint and energy consumption reports for their own computational workloads. +This tool is intended for individual HPC users who want to generate carbon footprint and energy usage reports for their own computational workloads. > [!NOTE] > Looking for automated, ongoing reporting across teams or departments? From f06892fbfcb8fbff9620ccfbc67de73180c5d65e Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 28 Jul 2026 17:21:15 +0100 Subject: [PATCH 18/27] minor format fix in readme --- README.md | 29 +++++++++++++++++++++-------- backend/__init__.py | 2 +- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index add7a87..ce8eca5 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ > :point_right: There are many different flavours of HPC setups, so no doubt you'll find some bugs...Please let us know what you find so that we can make it work for more people! -GA4HPC is a user-facing, terminal-based tool that generates an energy usage and carbon footprint report for your computational workloads. It implements the [Green Algorithms Methodology](https://onlinelibrary.wiley.com/doi/abs/10.1002/advs.202100707) directly on High Performing Computing (HPC) clusters. **The tool currently supports SLURM clusters only**, with an aim to expand it for other workload managers in the future. +GA4HPC is a user-facing, terminal-based tool that generates an energy usage and carbon footprint report for your computational workloads. It implements the [Green Algorithms Methodology](https://onlinelibrary.wiley.com/doi/abs/10.1002/advs.202100707) directly on High Performance Computing (HPC) clusters. **The tool currently supports SLURM clusters only**, with an aim to expand it for other workload managers in the future. It works by pulling usage statistics directly from the logs recorded by the workload manager and estimating the user's carbon footprint based on this usage. It reports a range of statistics such as energy usage, carbon footprints, compute use, memory efficiency, impact of failed jobs etc. @@ -56,7 +56,7 @@ shared_directory/myCarbonFootprint.sh --startDay 2024-01-10 --endDay 2024-08-15 If it isn't installed yet, see the [Installation guide](#installation-guide) below. -### Common options +### Commonly used options The full list of options is documented [below](#full-list-of-options), but the ones you'll use most often are: @@ -75,7 +75,16 @@ The full list of options is documented [below](#full-list-of-options), but the o ## Full list of options ``` -usage: __init__.py [-h] [-S STARTDAY] [-E ENDDAY] [-o OUTPUT] [--outputDir OUTPUTDIR] [--filterCWD] [--filterJobIDs FILTERJOBIDS] [--filterAccount FILTERACCOUNT] [--customSuccessStates CUSTOMSUCCESSSTATES] [--useCustomLogs USECUSTOMLOGS] +usage: __init__.py [-h] + [-S STARTDAY] + [-E ENDDAY] + [-o OUTPUT] + [--outputDir OUTPUTDIR] + [--filterCWD] + [--filterJobIDs FILTERJOBIDS] + [--filterAccount FILTERACCOUNT] + [--customSuccessStates CUSTOMSUCCESSSTATES] + [--useCustomLogs USECUSTOMLOGS] Calculate your carbon footprint on the server. @@ -95,11 +104,14 @@ optional arguments: --filterAccount FILTERACCOUNT Only consider jobs charged under this account --customSuccessStates CUSTOMSUCCESSSTATES - Comma-separated list of job states. By default, only jobs that exit with status CD or COMPLETED are considered successful (PENDING, RUNNING and REQUEUED are ignored). Jobs with states listed here will - be considered successful as well (best to list both the 2-letter and full-length codes). Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES + Comma-separated list of job states. By default, only jobs that exit with status CD + or COMPLETED are considered successful (PENDING, RUNNING and REQUEUED are ignored). + Jobs with states listed here will be considered successful as well (best to list both the 2-letter + and full-length codes). Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES --useCustomLogs USECUSTOMLOGS - Bypasses the workload manager and lets you input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in some situations. An example of the expected file - can be found at `example_files/example_sacctOutput_raw.txt`. + Bypasses the workload manager and lets you input a custom log file of your jobs. + This is mostly meant for debugging, but can be useful in some situations. + An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. ``` ## Installation guide @@ -118,7 +130,8 @@ optional arguments: $ git clone https://github.com/Llannelongue/GreenAlgorithms4HPC.git ``` -2. Open `myCarbonFootprint.sh` and find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`: +2. Set up the Python environment: +Open `myCarbonFootprint.sh` and find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`: ```bash /usr/bin/python3.8 -m venv GA_env ``` diff --git a/backend/__init__.py b/backend/__init__.py index ad1e800..733b2fc 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -140,7 +140,7 @@ def main_backend(args): dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) df = dataprocessor.extract_data() df2 = dataprocessor.enrich_data(df) - summary_stats = summarise_data(df2, args=args) + summary_stats = summarise_data(df2) return summary_stats From 035998c00c4a29440c9676d7477116eabd9ca31a Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Mon, 3 Aug 2026 10:06:30 +0100 Subject: [PATCH 19/27] minor typo fixes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ce8eca5..5e8d3ff 100644 --- a/README.md +++ b/README.md @@ -182,9 +182,9 @@ git checkout -b feature/- ## FAQ -### Can it work other other workload managers? +### Can it work with other workload managers? -Yes it can! the tool uses [Green-Algorithms-core](https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core) to pull logs from workload managers like SLURM. Please [create an issue](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/issues) so that our team can help you implement it for your workload manager. +Yes it can! The tool uses [Green-Algorithms-core](https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core) to pull logs from workload managers like SLURM. Please [create an issue](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/issues) so that our team can help you implement it for your workload manager. --- ## Getting help From 78945d00ecefb7f16ff5ce031ee8ece7d88d8b02 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 4 Aug 2026 10:03:27 +0100 Subject: [PATCH 20/27] updated for ga_core v0.1.1: raw logs file read + test cases fixed --- backend/__init__.py | 12 ++++++++++-- backend/helpers.py | 22 ++++++++++++++++++++++ requirements.txt | 2 +- tests/backend/backend_test.py | 35 ++++++++++++++++++++++------------- 4 files changed, 55 insertions(+), 16 deletions(-) diff --git a/backend/__init__.py b/backend/__init__.py index 733b2fc..108311a 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -2,6 +2,8 @@ import os import yaml import ga_core + +from backend import helpers # print("Working dir1: ", os.getcwd()) # DEBUGONLY def summarise_data(df): @@ -122,6 +124,7 @@ def main_backend(args): :return: [dict] contains the summarised data ''' ga_config = prepare_ga_config(args) + logs_raw = None ### Load cluster specific info with open(os.path.join(args.path_infrastucture_info, 'cluster_info.yaml'), "r") as stream: @@ -136,9 +139,14 @@ def main_backend(args): fParams = yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) - + + if ga_config.get('useCustomLogs', '') != '': + # Pick raw logs from file + logs_raw = helpers.read_file_bytes(ga_config["useCustomLogs"]) + print(f'Overriding logs_raw with: {ga_config["useCustomLogs"]}\n') + dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) - df = dataprocessor.extract_data() + df = dataprocessor.extract_data(logs_raw) df2 = dataprocessor.enrich_data(df) summary_stats = summarise_data(df2) diff --git a/backend/helpers.py b/backend/helpers.py index f8bb761..bd443b5 100644 --- a/backend/helpers.py +++ b/backend/helpers.py @@ -4,6 +4,7 @@ import random import pandas as pd import numpy as np +from pathlib import Path def check_empty_results(df, args): """ @@ -28,6 +29,27 @@ def check_empty_results(df, args): ''') sys.exit() +def read_file_bytes(file_path: str) -> bytes: + """Validates a file path and reads its content as raw bytes. + + :param file_path: [str] The path to the file to read. + :return: [bytes] The raw byte content of the file. + + Raises: + FileNotFoundError: If the path does not exist. + IsADirectoryError: If the path points to a directory instead of a file. + PermissionError: If reading permissions are lacking. + """ + path = Path(file_path).resolve() + + if not path.exists(): + raise FileNotFoundError(f"File not found at path: {path}") + + if not path.is_file(): + raise IsADirectoryError(f"Expected a file, but path points to a directory: {path}") + + return path.read_bytes() #handles opening, reading, and closing the file safely + def simulate_mock_jobs(): # DEBUGONLY df_list = [] n_jobs = random.randint(500,800) diff --git a/requirements.txt b/requirements.txt index ed2f454..50a5882 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,4 @@ jinja2==3.1.6 plotly==5.18.0 pytest==8.4.1 pytest-cov==7.1.0 -git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@v0.1.0 \ No newline at end of file +git+https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core.git@v0.1.1 \ No newline at end of file diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py index 8ca3843..0d59266 100644 --- a/tests/backend/backend_test.py +++ b/tests/backend/backend_test.py @@ -85,16 +85,25 @@ def test_prepare_ga_config_mapping(self, dummy_args, config_data): """ config = prepare_ga_config(dummy_args) - assert config["useCustomLogs"] == config_data["useCustomLogs"] - assert config["startDay"] == config_data["startDay"] - assert config["endDay"] == config_data["endDay"] - assert config["customSuccessStates"] == "COMPLETED" - assert config["userCWD"] == "/home/uid_1" - assert "filterWD" not in config + expected = { + "useCustomLogs": dummy_args.useCustomLogs, + "startDay": dummy_args.startDay, + "endDay": dummy_args.endDay, + "filterWD": dummy_args.filterWD, + "filterJobIDs": dummy_args.filterJobIDs, + "filterAccount": dummy_args.filterAccount, + } + + for arg in ("userCWD", "customSuccessStates"): + value = getattr(dummy_args, arg, None) + if value: + expected[arg] = value + + assert config == expected class TestSummariseData: - def test_summarise_data_output_schema(self, mock_enriched_df, dummy_args): + def test_summarise_data_output_schema(self, mock_enriched_df): """ Scenario: The output schema of summarise_data is correct. @@ -102,7 +111,7 @@ def test_summarise_data_output_schema(self, mock_enriched_df, dummy_args): 1. All expected top-level keys ('userDaily', 'userActivity', etc.) exist. 2. The primary user ID is identified correctly from the DataFrame. """ - summary = summarise_data(mock_enriched_df.copy(), dummy_args) + summary = summarise_data(mock_enriched_df.copy()) assert "userDaily" in summary assert "userActivity" in summary @@ -112,7 +121,7 @@ def test_summarise_data_output_schema(self, mock_enriched_df, dummy_args): assert summary["user"] == "uid_1" assert "uid_1" in summary["userActivity"] - def test_two_stage_aggregation_and_derived_ratios(self, mock_enriched_df, dummy_args): + def test_two_stage_aggregation_and_derived_ratios(self, mock_enriched_df): """ Scenario: job metrics aggregate correctly for two stages - daily totals and overall stats and derived ratios are computed correctly. @@ -123,7 +132,7 @@ def test_two_stage_aggregation_and_derived_ratios(self, mock_enriched_df, dummy_ and computes sums over pre-aggregated daily data. 3. Success/failure rates and carbon percentages are derived correctly. """ - summary = summarise_data(mock_enriched_df.copy(), dummy_args) + summary = summarise_data(mock_enriched_df.copy()) # Daily DataFrame daily_df = summary["userDaily"] @@ -136,7 +145,7 @@ def test_two_stage_aggregation_and_derived_ratios(self, mock_enriched_df, dummy_ assert overall["success_rate"] == pytest.approx(0.5) assert overall["failure_rate"] == pytest.approx(0.5) - def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df, dummy_args): + def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df): """ Scenario: Tests edge case behavior when carbon footprint is zero. @@ -147,7 +156,7 @@ def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df, dummy_ zero_carbon_df = mock_enriched_df.copy() zero_carbon_df["carbonFootprint"] = 0.0 - summary = summarise_data(zero_carbon_df, dummy_args) + summary = summarise_data(zero_carbon_df) daily_df = summary["userDaily"] assert daily_df["share_carbonFootprint"].isna().all() # 0 / 0 in Pandas results in NaN @@ -200,6 +209,6 @@ def test_main_backend_execution_pipeline( assert mock_file.call_count == 2 mock_processor_inst.extract_data.assert_called_once() mock_processor_inst.enrich_data.assert_called_once_with(raw_df) - mock_summarise.assert_called_once_with(enriched_df, args=dummy_args) + mock_summarise.assert_called_once_with(enriched_df) assert result == {"user": "uid_1", "status": "complete"} \ No newline at end of file From 138137827e6258fbbd2055c4decc39c2f678b535 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 4 Aug 2026 17:15:57 +0100 Subject: [PATCH 21/27] added support for reporting bugs --- README.md | 7 ++++++- __init__.py | 18 +++++++++++++++--- backend/__init__.py | 25 ++++++++++++++++++++++--- tests/backend/backend_test.py | 2 ++ 4 files changed, 45 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5e8d3ff..9eda3df 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ usage: __init__.py [-h] [--filterAccount FILTERACCOUNT] [--customSuccessStates CUSTOMSUCCESSSTATES] [--useCustomLogs USECUSTOMLOGS] + [--reportBug | --reportBugHere] Calculate your carbon footprint on the server. @@ -97,7 +98,7 @@ optional arguments: -o OUTPUT, --output OUTPUT How to display the results, one of 'terminal' or 'html' (default: terminal) --outputDir OUTPUTDIR - Export path for the output (default: under `outputs/`). Only used with `--output html` + Export path for the output (default: under `outputs/`). Only used with `--output html` and `--reportBug` --filterCWD Only report on jobs launched from the current location. --filterJobIDs FILTERJOBIDS Comma separated list of Job IDs you want to filter on. (default: "all") @@ -112,6 +113,10 @@ optional arguments: Bypasses the workload manager and lets you input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in some situations. An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. + --reportBug In case of a bug, this flag exports the jobs logs so that you/we can investigate further. The debug file will be stored in the + shared folder where this tool is located (under /outputs), to export it to + your home folder, user `--reportBugHere`. Note that this will write out some basic information about your jobs, such as runtime, number of cores and memory usage. + --reportBugHere Similar to --reportBug, but exports the output to your home folder. ``` ## Installation guide diff --git a/__init__.py b/__init__.py index 87b23a3..d681358 100644 --- a/__init__.py +++ b/__init__.py @@ -48,8 +48,20 @@ def create_arguments(): 2-letter and full-length codes. Full list of job states: \ https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES") + ## Reporting bugs group1 = parser.add_mutually_exclusive_group() - group1.add_argument('--useCustomLogs', type=str, default='', + group1.add_argument('--reportBug', action='store_true', + help='In case of a bug, this flag exports the jobs logs so that you/we can investigate further. ' + 'The debug file will be stored in the shared folder where this tool is located (under /outputs), ' + 'to export it to your home folder, user `--reportBugHere`. ' + 'Note that this will write out some basic information about your jobs, such as runtime, ' + 'number of cores and memory usage.' + ) + group1.add_argument('--reportBugHere', action='store_true', + help='Similar to --reportBug, but exports the output to your home folder.') + + group2 = parser.add_mutually_exclusive_group() + group2.add_argument('--useCustomLogs', type=str, default='', help='This bypasses the workload manager, and enables you to input a custom log file of your jobs. \ This is mostly meant for debugging, but can be useful in some situations. ' 'An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`.') @@ -57,7 +69,7 @@ def create_arguments(): # To use arbitrary folder for the infrastructure information parser.add_argument('--useOtherInfrastuctureInfo', type=str, default='', help=argparse.SUPPRESS) # Uses mock aggregated usage data, for offline debugging - group1.add_argument('--use_mock_agg_data', action='store_true', help=argparse.SUPPRESS) + group2.add_argument('--use_mock_agg_data', action='store_true', help=argparse.SUPPRESS) args = parser.parse_args() return args @@ -112,7 +124,7 @@ def all(self, args): ## Organise the unique output directory (used for output report) ## creating a uniquely named subdirectory in whatever # Decide if an output directory is needed at all - if (args.output in ['html']): + if (args.output in ['html']) | args.reportBug | args.reportBugHere: timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M-%S%f') args.outputDir2use = { 'timestamp': timestamp, diff --git a/backend/__init__.py b/backend/__init__.py index 108311a..90195f6 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -146,9 +146,28 @@ def main_backend(args): print(f'Overriding logs_raw with: {ga_config["useCustomLogs"]}\n') dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) - df = dataprocessor.extract_data(logs_raw) - df2 = dataprocessor.enrich_data(df) - summary_stats = summarise_data(df2) + extracted_logs = dataprocessor.extract_data(logs_raw) + + ### Log the output for debugging + if args.reportBug | args.reportBugHere: + if ga_config.get('useCustomLogs', '') != '': + print("\n(!) --reportBug and --reportBugHere are ignored when --useCustomLogs is present\n") + else: + if args.reportBug: + # Create an error_logs subfolder in the output dir + errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') + os.makedirs(errorLogsDir) + log_path = os.path.join(errorLogsDir, f'sacctOutput.csv') + else: + # i.e. args.reportBugHere is True + log_path = f"{args.userCWD}/sacctOutput_{args.outputDir2use['timestamp']}.csv" + + with open(log_path, 'wb') as f: + f.write(extracted_logs) + print(f"\nSLURM statistics logged for debuging: {log_path}\n") + + enriched_logs = dataprocessor.enrich_data(extracted_logs) + summary_stats = summarise_data(enriched_logs) return summary_stats diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py index 0d59266..60848cb 100644 --- a/tests/backend/backend_test.py +++ b/tests/backend/backend_test.py @@ -29,6 +29,8 @@ def dummy_args(config_data): filterAccount=None, path_infrastucture_info="clustersData/CSD3", userCWD="/home/uid_1", + reportBug=False, + reportBugHere=False ) From d828e1478fbac3c9b1bc698379b2c4016057535b Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Tue, 4 Aug 2026 17:58:02 +0100 Subject: [PATCH 22/27] exception handling added at report bug --- backend/__init__.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/backend/__init__.py b/backend/__init__.py index 90195f6..398eb8a 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -153,18 +153,20 @@ def main_backend(args): if ga_config.get('useCustomLogs', '') != '': print("\n(!) --reportBug and --reportBugHere are ignored when --useCustomLogs is present\n") else: - if args.reportBug: - # Create an error_logs subfolder in the output dir - errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') - os.makedirs(errorLogsDir) - log_path = os.path.join(errorLogsDir, f'sacctOutput.csv') - else: - # i.e. args.reportBugHere is True - log_path = f"{args.userCWD}/sacctOutput_{args.outputDir2use['timestamp']}.csv" - - with open(log_path, 'wb') as f: - f.write(extracted_logs) - print(f"\nSLURM statistics logged for debuging: {log_path}\n") + try: + if args.reportBug: + # Create an error_logs subfolder in the output dir + errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') + os.makedirs(errorLogsDir) + log_path = os.path.join(errorLogsDir, f'extracted_output.csv') + else: + # i.e. args.reportBugHere is True + log_path = f"{args.userCWD}/extracted_output_{args.outputDir2use['timestamp']}.csv" + + extracted_logs.to_csv(log_path, index=False) + print(f"\nExtracted statistics logged for debuging: {log_path}\n") + except Exception as e: + print(f"\n[reportBug] Failed to write Debug logs to '{log_path}': {e}\n") enriched_logs = dataprocessor.enrich_data(extracted_logs) summary_stats = summarise_data(enriched_logs) From c7e81b0373428b2a6ec44e863c2d2cbdb5fbf28b Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Wed, 5 Aug 2026 12:42:20 +0100 Subject: [PATCH 23/27] reportBugs: calling ga_core.SacctClient to pull slurm logs --- __init__.py | 13 +++++- backend/__init__.py | 87 +++++++++++++++++++++-------------- data/cluster_info.yaml | 1 + tests/backend/backend_test.py | 77 +++++++++++++++++++------------ 4 files changed, 113 insertions(+), 65 deletions(-) diff --git a/__init__.py b/__init__.py index d681358..58e72db 100644 --- a/__init__.py +++ b/__init__.py @@ -2,8 +2,9 @@ import argparse import datetime import os +import sys -from backend import main_backend +from backend import export_debug_logs, main_backend from frontend import main_frontend def create_arguments(): @@ -145,6 +146,16 @@ def all(self, args): else: args.filterWD = None + if args.reportBug | args.reportBugHere: + print("\n(!) Debugging mode activated. This will export raw logs for debugging.\n") + if args.useCustomLogs != '': + print("\n(!) --reportBug and --reportBugHere are ignored when --useCustomLogs is present\n") + else: + # Extract and save debug logs + export_debug_logs(args) + print("\n(!) Exiting after exporting debug logs.\n") + sys.exit(0) + ### Validate input validate_args().all(args) diff --git a/backend/__init__.py b/backend/__init__.py index 398eb8a..5f57d43 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -1,5 +1,6 @@ import os +import sys import yaml import ga_core @@ -92,7 +93,7 @@ def agg_jobs(data, agg_names=None): return output -def prepare_ga_config(args): +def prepare_config(args): """ Prepare the configuration for the GA core, based on the command line arguments. :param args: [argparse.Namespace] the command line arguments @@ -113,23 +114,13 @@ def prepare_ga_config(args): if hasattr(args, arg) and getattr(args, arg): ga_config[arg] = getattr(args, arg) - return ga_config - -def main_backend(args): - ''' - Loads configurations including cluster information and fixed parameters. - Calls HPCDataProcessor.extract and HPCDataProcessor.enrich functions to produce enriched logs. - Finally, it summarises the data. - :param args: [argparse.Namespace] contains the settings - :return: [dict] contains the summarised data - ''' - ga_config = prepare_ga_config(args) - logs_raw = None - ### Load cluster specific info with open(os.path.join(args.path_infrastucture_info, 'cluster_info.yaml'), "r") as stream: try: cluster_info = yaml.safe_load(stream) + if cluster_info.get('workload_manager', '') == '': + cluster_info['workload_manager'] = 'slurm' # default to slurm if not specified + except yaml.YAMLError as exc: print(exc) @@ -140,6 +131,20 @@ def main_backend(args): except yaml.YAMLError as exc: print(exc) + return ga_config, cluster_info, fParams + +def main_backend(args): + ''' + Loads configurations including cluster information and fixed parameters. + Calls HPCDataProcessor.extract and HPCDataProcessor.enrich functions to produce enriched logs. + Finally, it summarises the data. + + :param args: [argparse.Namespace] contains the settings + :return: [dict] contains the summarised data + ''' + ga_config, cluster_info, fParams = prepare_config(args) + logs_raw = None + if ga_config.get('useCustomLogs', '') != '': # Pick raw logs from file logs_raw = helpers.read_file_bytes(ga_config["useCustomLogs"]) @@ -148,31 +153,45 @@ def main_backend(args): dataprocessor = ga_core.HPCDataProcessor(ga_config, cluster_info, fParams, all_users_access = False) extracted_logs = dataprocessor.extract_data(logs_raw) - ### Log the output for debugging - if args.reportBug | args.reportBugHere: - if ga_config.get('useCustomLogs', '') != '': - print("\n(!) --reportBug and --reportBugHere are ignored when --useCustomLogs is present\n") - else: - try: - if args.reportBug: - # Create an error_logs subfolder in the output dir - errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') - os.makedirs(errorLogsDir) - log_path = os.path.join(errorLogsDir, f'extracted_output.csv') - else: - # i.e. args.reportBugHere is True - log_path = f"{args.userCWD}/extracted_output_{args.outputDir2use['timestamp']}.csv" - - extracted_logs.to_csv(log_path, index=False) - print(f"\nExtracted statistics logged for debuging: {log_path}\n") - except Exception as e: - print(f"\n[reportBug] Failed to write Debug logs to '{log_path}': {e}\n") - enriched_logs = dataprocessor.enrich_data(extracted_logs) summary_stats = summarise_data(enriched_logs) return summary_stats +def export_debug_logs(args) -> None: + """ + Exports raw logs to a CSV file for debugging. + + :param args: [argparse.Namespace] contains the settings + """ + ga_config, cluster_info, fParams = prepare_config(args) + + if args.reportBug: + # Create an error_logs subfolder in the output dir + errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') + os.makedirs(errorLogsDir) + log_path = os.path.join(errorLogsDir, f'extracted_output.csv') + else: + # i.e. args.reportBugHere is True + log_path = f"{args.userCWD}/extracted_output_{args.outputDir2use['timestamp']}.csv" + + try: + match cluster_info.get('workload_manager', '').lower(): + case 'slurm': + extracted_raw_logs = ga_core.SacctClient.pull_logs_by_time(startDay=ga_config['startDay'], endDay=ga_config['endDay'], all_users=False) + with open(log_path, 'wb') as f: + f.write(extracted_raw_logs) + print(f"\nSLURM statistics logged for debugging: {log_path}\n") + case _: + raise ValueError(f"Unsupported workload manager: {cluster_info['workload_manager']}") + + except IOError as e: + print(f"\n(!) Failed to write debug logs to {log_path}: {e}\n") + + except Exception as e: + print(f"Failed to pull sacct logs: {e}") + sys.exit(1) + if __name__ == "__main__": #### This is used for testing/DEBUG only #### diff --git a/data/cluster_info.yaml b/data/cluster_info.yaml index 7550cb6..af09578 100644 --- a/data/cluster_info.yaml +++ b/data/cluster_info.yaml @@ -6,6 +6,7 @@ institution: "" # [str] cluster_name: "" # [str] granularity_memory_request: <6> # [number] in GB representing the smallest memory unit users can reserve +workload_manager: "" # [str] the workload manager used on the cluster. Currently only SLURM is supported. partitions: # a list of the different partitions on the cluster : # name of the partition type: # [CPU or GPU] diff --git a/tests/backend/backend_test.py b/tests/backend/backend_test.py index 60848cb..5e03bb4 100644 --- a/tests/backend/backend_test.py +++ b/tests/backend/backend_test.py @@ -3,7 +3,7 @@ # It validates the orchestration of the backend pipeline # ------------------------------------------------------------------ -from backend import main_backend, prepare_ga_config, summarise_data +from backend import main_backend, prepare_config, summarise_data from types import SimpleNamespace from unittest.mock import MagicMock, mock_open, patch @@ -75,19 +75,27 @@ def mock_enriched_df(): ) class TestPrepareGaConfig: - - def test_prepare_ga_config_mapping(self, dummy_args, config_data): + @patch("builtins.open", new_callable=mock_open) + @patch("yaml.safe_load") + def test_prepare_config_mapping( + self, + mock_yaml_load, + mock_file, + dummy_args, + ): """ Scenario: Required and optional arguments are extracted correctly from the CLI namespace into a config dictionary. - - Checks done: - 1. Mandatory fields (startDay, endDay, useCustomLogs) are mapped. - 2. Non-None optional fields (customSuccessStates, userCWD) are attached. - 3. None/falsy optional arguments (filterWD) are excluded. """ - config = prepare_ga_config(dummy_args) + # Mocks returns for the two yaml.safe_load calls + mock_yaml_load.side_effect = [ + {"workload_manager": "slurm", "granularity_memory_request": "6"}, # cluster_info + {"power_memory_perGB": 0.5} # fParams + ] + + config, cluster_info, f_params = prepare_config(dummy_args) - expected = { + # Check ga_config dict contents + expected_config = { "useCustomLogs": dummy_args.useCustomLogs, "startDay": dummy_args.startDay, "endDay": dummy_args.endDay, @@ -99,9 +107,16 @@ def test_prepare_ga_config_mapping(self, dummy_args, config_data): for arg in ("userCWD", "customSuccessStates"): value = getattr(dummy_args, arg, None) if value: - expected[arg] = value + expected_config[arg] = value + + assert config == expected_config - assert config == expected + # Check loaded configurations + assert cluster_info == {"workload_manager": "slurm", "granularity_memory_request": "6"} + assert f_params == {"power_memory_perGB": 0.5} + + # Check file reads occurred twice (cluster_info + fixed_params) + assert mock_file.call_count == 2 class TestSummariseData: @@ -165,13 +180,11 @@ def test_zero_carbon_footprint_division_edge_case(self, mock_enriched_df): class TestMainBackend: - @patch("backend.prepare_ga_config") + @patch("backend.prepare_config") @patch("backend.ga_core.HPCDataProcessor") @patch("backend.summarise_data") - @patch("builtins.open", new_callable=mock_open, read_data="cluster: CSD3") def test_main_backend_execution_pipeline( self, - mock_file, mock_summarise, mock_processor_cls, mock_prepare_config, @@ -180,20 +193,16 @@ def test_main_backend_execution_pipeline( """ Scenario: `main_backend` acts as an orchestration pipeline that calls external dependencies and sub-modules in the strict sequential order required. - - @patch is used to create mocks of objects used in the pipeline. It allow us to - replace all real external calls (reading yaml files etc.) with mocks - - Checks done: - 1. Configuration files (cluster_info & fixed_params) are read. - 2. HPCDataProcessor is initialized with parsed configurations. - 3. Raw data is extracted (`extract_data()`). - 4. Validation check runs (`check_empty_results()`) before processing data. - 5. Data is enriched (`enrich_data()`) and passed to `summarise_data()`. - 6. Outputs from `summarise_data` are returned directly. """ - # Mock the behaviors of each dependency in the pipeline - mock_prepare_config.return_value = {"startDay": dummy_args.startDay} + + # Config mocks + dummy_config = {"startDay": dummy_args.startDay} + dummy_cluster_info = {"workload_manager": "slurm"} + dummy_f_params = {"power_memory_perGB": 0.5} + + mock_prepare_config.return_value = (dummy_config, dummy_cluster_info, dummy_f_params) + + # Processor and summarise mocks mock_processor_inst = MagicMock() mock_processor_cls.return_value = mock_processor_inst @@ -206,9 +215,17 @@ def test_main_backend_execution_pipeline( result = main_backend(dummy_args) - # Assert correct order of execution & parameter routing + # Assert correct execution order and parameters passed mock_prepare_config.assert_called_once_with(dummy_args) - assert mock_file.call_count == 2 + + # Check HPCDataProcessor initialization arguments + mock_processor_cls.assert_called_once_with( + dummy_config, + dummy_cluster_info, + dummy_f_params, + all_users_access=False + ) + mock_processor_inst.extract_data.assert_called_once() mock_processor_inst.enrich_data.assert_called_once_with(raw_df) mock_summarise.assert_called_once_with(enriched_df) From bd017a38c8ba8d57ef3121439cf4c905d38f40d9 Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Wed, 5 Aug 2026 14:15:57 +0100 Subject: [PATCH 24/27] updates required python version --- README.md | 2 +- backend/__init__.py | 8 ++++---- myCarbonFootprint.sh | 10 +++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 9eda3df..7807b29 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ optional arguments: ### Requirements -- Python 3.8+ +- Python 3.11+ ### Step-by-step diff --git a/backend/__init__.py b/backend/__init__.py index 5f57d43..51d6195 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -170,10 +170,10 @@ def export_debug_logs(args) -> None: # Create an error_logs subfolder in the output dir errorLogsDir = os.path.join(args.outputDir2use['path'], 'error_logs') os.makedirs(errorLogsDir) - log_path = os.path.join(errorLogsDir, f'extracted_output.csv') + log_path = os.path.join(errorLogsDir, f'extracted_output.txt') else: # i.e. args.reportBugHere is True - log_path = f"{args.userCWD}/extracted_output_{args.outputDir2use['timestamp']}.csv" + log_path = f"{args.userCWD}/extracted_output_{args.outputDir2use['timestamp']}.txt" try: match cluster_info.get('workload_manager', '').lower(): @@ -186,10 +186,10 @@ def export_debug_logs(args) -> None: raise ValueError(f"Unsupported workload manager: {cluster_info['workload_manager']}") except IOError as e: - print(f"\n(!) Failed to write debug logs to {log_path}: {e}\n") + print(f"\n[Debug logs] Failed to write debug logs to {log_path}: {e}\n") except Exception as e: - print(f"Failed to pull sacct logs: {e}") + print(f"[Debug logs] Failed to extract logs: {e}") sys.exit(1) if __name__ == "__main__": diff --git a/myCarbonFootprint.sh b/myCarbonFootprint.sh index 9a0fcdd..ad2c725 100755 --- a/myCarbonFootprint.sh +++ b/myCarbonFootprint.sh @@ -13,10 +13,10 @@ userCWD="$(pwd)" parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) cd "$parent_path" -# Test if the virtualenv GA_env already exists, and if not, creates it. Download python 3.8 or higher for better results. +# Test if the virtualenv GA_env already exists, and if not, creates it. Download python 3.11 or higher for better results. if [ ! -f GA_env/bin/activate ]; then echo "Need to create virtualenv" - /usr/bin/python3.8 -m venv GA_env # EDIT ME: this line needs updating to load python on your server + /usr/bin/python3.11 -m venv GA_env # EDIT ME: this line needs updating to load python on your server source GA_env/bin/activate pip3 install -r requirements.txt else @@ -24,7 +24,7 @@ else source GA_env/bin/activate fi -# Test if the python version is at least 3.8 +# Test if the python version is at least 3.11 version_major=$(python -c 'import sys; print(sys.version_info[0])') version_minor=$(python -c 'import sys; print(sys.version_info[1])') if (( $version_major < 3 )); then @@ -32,8 +32,8 @@ if (( $version_major < 3 )); then exit 1 fi -if (( $version_minor < 8 )); then - echo "The command python needs to refer to python3.8 or higher." +if (( $version_minor < 11 )); then + echo "The command python needs to refer to python3.11 or higher." exit 1 fi echo "Python versions: OK" From 31375bc23b4e588e33d29fc2de8e6a654a7b41ab Mon Sep 17 00:00:00 2001 From: Navirah Kamal Date: Wed, 5 Aug 2026 14:27:38 +0100 Subject: [PATCH 25/27] minor updates to readme --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7807b29..9549d03 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ # GA4HPC: Green Algorithms for High Performance Computing ![Version: v1.0](https://img.shields.io/badge/version-v1.0-blue) [![Open Source? Yes!](https://badgen.net/badge/Open%20Source%20%3F/Yes%21/purple?icon=github)](https://github.com/Naereen/badges/) +![Python: 3.11+](https://img.shields.io/badge/python-3.11%2B-blue?logo=python&logoColor=white) > :point_right: There are many different flavours of HPC setups, so no doubt you'll find some bugs...Please let us know what you find so that we can make it work for more people! @@ -115,7 +116,7 @@ optional arguments: An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. --reportBug In case of a bug, this flag exports the jobs logs so that you/we can investigate further. The debug file will be stored in the shared folder where this tool is located (under /outputs), to export it to - your home folder, user `--reportBugHere`. Note that this will write out some basic information about your jobs, such as runtime, number of cores and memory usage. + your home folder, use `--reportBugHere`. Note that this will write out some basic information about your jobs, such as runtime, number of cores and memory usage. --reportBugHere Similar to --reportBug, but exports the output to your home folder. ``` @@ -140,7 +141,7 @@ Open `myCarbonFootprint.sh` and find the line that creates the virtual environme ```bash /usr/bin/python3.8 -m venv GA_env ``` -Replace it with whatever loads Python 3.8+ on your server, for example: +Replace it with whatever loads Python 3.11+ on your server, for example: ```bash module load python/3.11.7 python -m venv GA_env @@ -163,7 +164,7 @@ Replace it with whatever loads Python 3.8+ on your server, for example: _More elegant solutions welcome! [Discussion here](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/discussions/31)._ > [!IMPORTANT] -> Before updating, make sure you've saved a copy of your custom `cluster_info.yaml` and noted how you loaded Python 3.8+ during the initial install. +> Before updating, make sure you've saved a copy of your custom `cluster_info.yaml` and noted how you loaded Python 3.11+ during the initial install. 1. `git reset --hard` — removes local changes to files (hence the need for a backup above!) 2. `git pull` From 7f6a2feaeceec19a3ba73b65ea2c103ea4e38a7b Mon Sep 17 00:00:00 2001 From: Navirah Kamal <70336688+Navirah@users.noreply.github.com> Date: Thu, 6 Aug 2026 16:22:37 +0100 Subject: [PATCH 26/27] Revise Python environment setup instructions Updated instructions for setting up the Python environment in myCarbonFootprint.sh to reflect the use of Python 3.11 or higher. --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9549d03..2f6d735 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ It works by pulling usage statistics directly from the logs recorded by the work It reports a range of statistics such as energy usage, carbon footprints, compute use, memory efficiency, impact of failed jobs etc. By default, the output gets displayed in the terminal (example below). `--output='html'` can be used to get the output as an html report instead. + ![example file](https://github.com/GreenAlgorithms/GreenAlgorithms4HPC/blob/main/example_files/Screenshot%20HPC%202024-08-20.png) ### Who is it for? @@ -136,13 +137,12 @@ optional arguments: $ git clone https://github.com/Llannelongue/GreenAlgorithms4HPC.git ``` -2. Set up the Python environment: -Open `myCarbonFootprint.sh` and find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`: -```bash +2. Edit [`myCarbonFootprint.sh`](myCarbonFootprint.sh): Find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`. The default line is: +``` /usr/bin/python3.8 -m venv GA_env ``` Replace it with whatever loads Python 3.11+ on your server, for example: -```bash +``` module load python/3.11.7 python -m venv GA_env ``` From a8437735a06a7bef3f0665050f217dc0cf99aa84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Lannelongue?= Date: Thu, 6 Aug 2026 16:53:51 +0100 Subject: [PATCH 27/27] Minor tweaks to README --- README.md | 100 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 2f6d735..5631c3b 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,13 @@ GA4HPC is a user-facing, terminal-based tool that generates an energy usage and carbon footprint report for your computational workloads. It implements the [Green Algorithms Methodology](https://onlinelibrary.wiley.com/doi/abs/10.1002/advs.202100707) directly on High Performance Computing (HPC) clusters. **The tool currently supports SLURM clusters only**, with an aim to expand it for other workload managers in the future. It works by pulling usage statistics directly from the logs recorded by the workload manager and estimating the user's carbon footprint based on this usage. -It reports a range of statistics such as energy usage, carbon footprints, compute use, memory efficiency, impact of failed jobs etc. +It reports a range of statistics such as energy usage, carbon footprints, compute use, memory efficiency, and impact of failed jobs. By default, the output gets displayed in the terminal (example below). `--output='html'` can be used to get the output as an html report instead. -![example file](https://github.com/GreenAlgorithms/GreenAlgorithms4HPC/blob/main/example_files/Screenshot%20HPC%202024-08-20.png) +![example file](example_files/Screenshot%20HPC%202024-08-20.png) -### Who is it for? +## Who is it for? This tool is intended for individual HPC users who want to generate carbon footprint and energy usage reports for their own computational workloads. > [!NOTE] @@ -24,7 +24,7 @@ This tool is intended for individual HPC users who want to generate carbon footp --- -### Contents +## Contents * [Quick start](#quick-start) * [Limitations to keep in mind](#limitations-to-keep-in-mind) * [Full list of options](#full-list-of-options) @@ -39,26 +39,26 @@ This tool is intended for individual HPC users who want to generate carbon footp * [About us](#about-us) * [Licence](#licence) +--- + ## Quick start > [!NOTE] -> GA4HPC only needs to be installed once per cluster, preferably in a shared directory so that all users can access it without installing it themselves. +> We recommend installing GA4HPC in a shared directory to avoid every user having to install it for themselves. Don't worry, even when installed in a shared directory, each user will only ever see their own usage. -:warning: Even when installed in a shared directory, each user will only ever see their own usage. However, if the HTML output is used without a custom output directory, the report itself will be saved on the shared drive (see [`--outputDir`](#full-list-of-options) below to change this). +:warning: However, if the HTML output is used without a custom output directory, the report itself will be saved on the shared drive (see [`--outputDir`](#full-list-of-options) below to change this). -### Is GA4HPC already installed on your cluster? +### How to use it -Check with your HPC team first, if it's already installed, you can run it straight away to get your own carbon footprint. No need to reinstall it. +This is assuming it's been installed already of course, either by you or someone else. So check with people around you and your sys admins first: if it's already installed, you can run it straight away to get your own carbon footprint, no need to reinstall it. If it isn't installed yet, see the [Installation guide](#installation-guide) below. Assuming it's installed under `shared_directory`, run the following on the SLURM cluster to get your carbon footprint between two dates: ```bash shared_directory/myCarbonFootprint.sh --startDay 2024-01-10 --endDay 2024-08-15 ``` - -If it isn't installed yet, see the [Installation guide](#installation-guide) below. -### Commonly used options +#### Commonly used options The full list of options is documented [below](#full-list-of-options), but the ones you'll use most often are: @@ -66,7 +66,7 @@ The full list of options is documented [below](#full-list-of-options), but the o - `-o, --output`: `terminal` for terminal output (default) or `html` for an HTML report. When using the HTML report, a subdirectory is created for it — by default under `GreenAlgorithms4HPC/outputs/`, though this can be changed. - `--outputDir`: path to export any output to. -## Limitations to keep in mind +### Limitations to keep in mind - The workload manager doesn't always log exact CPU usage time; when this information is missing, we assume all cores are used at 100%. - GPUs are currently assumed to be used at 100%, as the information needed for more accurate measurement isn't available. @@ -74,53 +74,44 @@ The full list of options is documented [below](#full-list-of-options), but the o - Conversely, wasted energy due to memory over-allocation may be largely underestimated, as the information needed for this isn't always logged. -## Full list of options +### Full list of options ``` -usage: __init__.py [-h] - [-S STARTDAY] - [-E ENDDAY] - [-o OUTPUT] - [--outputDir OUTPUTDIR] - [--filterCWD] - [--filterJobIDs FILTERJOBIDS] - [--filterAccount FILTERACCOUNT] - [--customSuccessStates CUSTOMSUCCESSSTATES] - [--useCustomLogs USECUSTOMLOGS] - [--reportBug | --reportBugHere] - +usage: __init__.py [-h] [-S STARTDAY] [-E ENDDAY] [-o OUTPUT] [--outputDir OUTPUTDIR] [--filterCWD] [--filterJobIDs FILTERJOBIDS] [--filterAccount FILTERACCOUNT] + [--customSuccessStates CUSTOMSUCCESSSTATES] [--reportBug | --reportBugHere] [--useCustomLogs USECUSTOMLOGS] + Calculate your carbon footprint on the server. - -optional arguments: + +options: -h, --help show this help message and exit -S STARTDAY, --startDay STARTDAY - The first day to take into account, as YYYY-MM-DD (default: -01-01) + The first day to take into account, as YYYY-MM-DD (default: 2026-01-01) -E ENDDAY, --endDay ENDDAY The last day to take into account, as YYYY-MM-DD (default: today) -o OUTPUT, --output OUTPUT How to display the results, one of 'terminal' or 'html' (default: terminal) --outputDir OUTPUTDIR - Export path for the output (default: under `outputs/`). Only used with `--output html` and `--reportBug` + Export path for the output (default: under `output/`). Only used with `--output html`. --filterCWD Only report on jobs launched from the current location. --filterJobIDs FILTERJOBIDS Comma separated list of Job IDs you want to filter on. (default: "all") --filterAccount FILTERACCOUNT Only consider jobs charged under this account --customSuccessStates CUSTOMSUCCESSSTATES - Comma-separated list of job states. By default, only jobs that exit with status CD - or COMPLETED are considered successful (PENDING, RUNNING and REQUEUED are ignored). - Jobs with states listed here will be considered successful as well (best to list both the 2-letter - and full-length codes). Full list of job states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES - --useCustomLogs USECUSTOMLOGS - Bypasses the workload manager and lets you input a custom log file of your jobs. - This is mostly meant for debugging, but can be useful in some situations. - An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. - --reportBug In case of a bug, this flag exports the jobs logs so that you/we can investigate further. The debug file will be stored in the - shared folder where this tool is located (under /outputs), to export it to - your home folder, use `--reportBugHere`. Note that this will write out some basic information about your jobs, such as runtime, number of cores and memory usage. + Comma-separated list of job states. By default, only jobs that exit with status CD or COMPLETED are considered successful (PENDING, RUNNING and REQUEUD + are ignored). Jobs with states listed here will be considered successful as well (best to list both 2-letter and full-length codes. Full list of job + states: https://slurm.schedmd.com/squeue.html#SECTION_JOB-STATE-CODES + --reportBug In case of a bug, this flag exports the jobs logs so that you/we can investigate further. The debug file will be stored in the shared folder where this + tool is located (under /outputs), to export it to your home folder, user `--reportBugHere`. Note that this will write out some basic information about + your jobs, such as runtime, number of cores and memory usage. --reportBugHere Similar to --reportBug, but exports the output to your home folder. + --useCustomLogs USECUSTOMLOGS + This bypasses the workload manager, and enables you to input a custom log file of your jobs. This is mostly meant for debugging, but can be useful in + some situations. An example of the expected file can be found at `example_files/example_sacctOutput_raw.txt`. ``` +--- + ## Installation guide :point_right: This only needs to be installed once per cluster — check first that someone else hasn't already installed it! @@ -128,16 +119,17 @@ optional arguments: ### Requirements - Python 3.11+ +- See [requirements.txt](requirements.txt) for full dependencies. ### Step-by-step -1. Clone this repository into a shared directory on your cluster: +1. **Clone this repository into a shared directory on your cluster:** ```bash $ cd shared_directory $ git clone https://github.com/Llannelongue/GreenAlgorithms4HPC.git ``` -2. Edit [`myCarbonFootprint.sh`](myCarbonFootprint.sh): Find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`. The default line is: +2. **Tell the script how to load Python on your cluster.** For this, edit [`myCarbonFootprint.sh`](myCarbonFootprint.sh): Find the line that creates the virtual environment; it's marked with the comment `# EDIT ME: this line needs updating to load python on your server`. The default line is: ``` /usr/bin/python3.8 -m venv GA_env ``` @@ -147,14 +139,14 @@ Replace it with whatever loads Python 3.11+ on your server, for example: python -m venv GA_env ``` -3. Make the bash script executable: +3. **Make the bash script executable:** ```bash $ chmod +x shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh ``` -4. Edit [`data/cluster_info.yaml`](data/cluster_info.yaml) to plug in the values corresponding to your cluster's hardware specs (this is the trickiest step). Ask your HPC team, and check the Green Algorithms GitHub for useful reference values: https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-data +4. **Tell the tool what hardware is used on your cluster.** This is the most demanding step of installation (but only needs to be done once!). Edit [`data/cluster_info.yaml`](data/cluster_info.yaml) to plug in the values corresponding to your cluster's hardware specs. Ask your HPC team, and check the Green Algorithms GitHub for useful reference values: https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-data -5. Run the script once to set things up. This checks that the correct version of Python is available and creates the virtual environment with the required packages, based on `requirements.txt`: +5. **Run the script once to set things up.** This checks that the correct version of Python is available and creates the virtual environment with the required packages, based on [requirements.txt](requirements.txt): ```bash $ shared_directory/GreenAlgorithms4HPC/myCarbonFootprint.sh ``` @@ -164,7 +156,7 @@ Replace it with whatever loads Python 3.11+ on your server, for example: _More elegant solutions welcome! [Discussion here](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/discussions/31)._ > [!IMPORTANT] -> Before updating, make sure you've saved a copy of your custom `cluster_info.yaml` and noted how you loaded Python 3.11+ during the initial install. +> Before updating, make sure you've saved a copy of your custom `cluster_info.yaml` and noted how you loaded Python 3.11+ during the initial installation. 1. `git reset --hard` — removes local changes to files (hence the need for a backup above!) 2. `git pull` @@ -172,7 +164,14 @@ _More elegant solutions welcome! [Discussion here](https://github.com/Cambridge- 4. `chmod +x myCarbonFootprint.sh` to make it executable again. 5. Test `myCarbonFootprint.sh`. -## Contributing +--- + +## How to contribute + +Contributions and improvements are welcome! Here is how to do it: + +> [!IMPORTANT] +> Small edits can be done by simply opening a pull request. For larger, more significant, changes, please open an issue to discuss it first so that you're not working for nothing! 1. **Fork** the repository and clone your fork locally. 2. Create a new branch off `main` for your change: @@ -183,8 +182,7 @@ git checkout -b feature/- 3. Make your changes, then run `pytest .` to make sure nothing's broken. 4. Commit your changes with a clear message, push to your fork, and open a **Pull Request against `main`**. -> [!IMPORTANT] -> Please open an issue for larger changes. +--- ## FAQ @@ -193,15 +191,19 @@ git checkout -b feature/- Yes it can! The tool uses [Green-Algorithms-core](https://github.com/Cambridge-Sustainable-Computing-Lab/Green-Algorithms-core) to pull logs from workload managers like SLURM. Please [create an issue](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/issues) so that our team can help you implement it for your workload manager. --- + ## Getting help + If you have questions, run into issues, or want to share feedback, please open a thread in [GitHub Discussions](https://github.com/Cambridge-Sustainable-Computing-Lab/GreenAlgorithms4HPC/discussions). This is the best place to get support from the development team and the wider community. --- + ## About us This tool is built and maintained by the [Cambridge Sustainable Computing Lab](https://cam-sustainablecomputing.org) at the University of Cambridge, UK. --- + ## Licence [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)