cpmodel / FTT_StandAlone

Future Technology Transformation models
GNU General Public License v3.0
9 stars 1 forks source link

Error (and possibly a better way?) when handling a local variable during data processing #186

Open ct-camecon opened 6 days ago

ct-camecon commented 6 days ago

Interestingly, this one looks to be platform sensitive. I get different error behaviour (or not) depending on the platform.

I get no error on:

(And presumably others with similar systems or Macs also haven't seen this to date?)

but I do get an error on:

The error occurs in the variable_setup() function of convert_masterfiles_to_csv.py when running FTT (whether through the frontend via Backend.py, or run_file.py) and the model first needs to generate input CSV files.

Error

The issue on Linux concerns this line, because the Linux Python interpreters consider the scope of scenarios to be local (it's not declared before the loop itself): https://github.com/cpmodel/FTT_StandAlone/blob/main/SourceCode/support/convert_masterfiles_to_csv.py#L286

This leads to the following error at the end of the function:

Traceback (most recent call last):
  File "path/to/FTT_Standalone/run_file.py", line 28, in <module>
        model = ModelRun()
                ^^^^^^^^^^
  File "path/to/FTT_Standalone/SourceCode/model_class.py", line 145, in __init__
        initialise_csv_files(self.ftt_modules, self.scenarios)
  File "path/to/FTT_Standalone/SourceCode/initialise_csv_files.py", line 30, in initialise_csv_files
        convert_masterfiles_to_csv(model_list)
  File "path/to/FTT_Standalone/SourceCode/support/convert_masterfiles_to_csv.py", line 347, in convert_masterfiles_to_csv
        variable_setup(dir_masterfiles, models)
  File "path/to/FTT_Standalone/SourceCode/support/convert_masterfiles_to_csv.py", line 312, in variable_setup
        return variables_df_dict, var_dict, vars_to_convert, scenarios, timeline_dict
                                                             ^^^^^^^^^
UnboundLocalError: cannot access local variable 'scenarios' where it is not associated with a value

In contrast, the Windows(-esque) versions are happy to treat scenarios as having scope outside of the loop to successfully return its value, as in the line that actually trips over on Linux: https://github.com/cpmodel/FTT_StandAlone/blob/main/SourceCode/support/convert_masterfiles_to_csv.py#L312

Possible fix

This looks like it can be fixed by just initialising the variable beforehand e.g. adding a scenarios = None just before the loop.

But...

However, I'm wondering if there's a better way. As written, the loop (assuming it ever has more than one iteration?) successively overwrites the variable each pass, taking the final value of models[model][0] (in the final iteration), ignoring prior values.

Is that as intended?