{ Analytica Model Scenario_Manager_Library, encoding="UTF-8" } SoftwareVersion 7.1.13 Model Scenario_Manager_Library Title: Scenario Manager Library Author: Lumina Decision Systems (built with Claude) Description: Scenario Manager library v1.10 (2026-11-09) with a guided front panel and a small example. Open it to learn; to use it, File > Add Module... this file, choose Embed, then delete the module Example (delete after setup). DefaultSize: 48,24 DiagState: 2,40,20,1240,780,17,10 FontStyle: Arial,13 Text Te_csv_title Title: Scenario Manager Library Description: Save model outputs to CSV, read them back as arrays, and review them (library v1.10 (2026-11-09)). Work through the steps top to bottom; the example is wired in, so every button works as-is. To use it in your own model, embed this file (see Using the library in another model). NodeLocation: 380,52,1 NodeSize: 360,38 NodeColor: 0x00ffe0b0 NodeFont: Arial,15 Text Te_step1 Title: Step 1. Choose what to save Description: List the identifiers of the outputs to save. Output settings are optional (a blank Result name uses the identifier). Settings check previews, for each output, the file it will write and its columns - or says what to fix. NodeLocation: 205,156,1 NodeSize: 175,52 NodeColor: 0x00ffffff FormNode Fo_csv1001 Title: Outputs to save Definition: 0 NodeLocation: 560,110,1 NodeSize: 170,11 Original: Csv_output FormNode Fo_csv1002 Title: Output settings Definition: 0 NodeLocation: 560,136,1 NodeSize: 170,11 Original: Csv_output_settings FormNode Fo_csv1003 Title: Settings check Definition: 1 NodeLocation: 560,162,1 NodeSize: 170,11 Original: Csv_settings_check Text Te_step2 Title: Step 2. Choose where files go Description: Leave Results folder blank for CSV_Results next to the model, or type a path. With One sub-folder per run ticked, click Create folder... for each run (or pick one under Export to folder). Untick it to keep every file in the results folder itself. NodeLocation: 205,297,1 NodeSize: 175,71 NodeColor: 0x00ffffff FormNode Fo_csv1004 Title: Results folder (blank = CSV_Results) Definition: 0 NodeLocation: 560,232,1 NodeSize: 170,11 Original: Csv_results_folder FormNode Fo_csv1005 Title: One sub-folder per run Definition: 0 NodeLocation: 560,258,1 NodeSize: 170,11 Original: Csv_use_run_folders Alias Al_csv2001 Title: Create folder... NodeLocation: 560,284,1 NodeSize: 170,12 Original: Csv_create_folder Alias Al_csv2002 Title: Refresh folder list NodeLocation: 560,310,1 NodeSize: 170,12 Original: Csv_refresh_folders FormNode Fo_csv1006 Title: Export to folder Definition: 0 NodeLocation: 560,336,1 NodeSize: 170,11 Original: Csv_export_folder Text Te_step3 Title: Step 3. Name the run and export Description: Scenario label names the run in the file names: keep Base, or type your scenario variable's identifier without quotes (e.g. Demand_scenario). Export to CSV saves every output for the current run. The loop button belongs to the example; copy its pattern to export many scenarios. NodeLocation: 205,444,1 NodeSize: 175,58 NodeColor: 0x00ffffff FormNode Fo_csv1007 Title: Scenario label Definition: 0 NodeLocation: 560,392,1 NodeSize: 170,11 Original: Csv_scenario_label FormNode Fo_csv1008 Title: Example file name Definition: 1 NodeLocation: 560,418,1 NodeSize: 170,11 Original: Csv_example_file Alias Al_csv2003 Title: Export to CSV NodeLocation: 560,444,1 NodeSize: 170,12 Original: Csv_export_button Alias Al_csv2004 Title: Example: export all 3 scenarios (loop) NodeLocation: 560,470,1 NodeSize: 170,12 Original: Ex_run_all_scenarios Text Te_step4 Title: Step 4. Read results back Description: Pick one or more run folders (not needed without sub-folders). Results found lists every result saved there; pick one under Result to read to see it as an array indexed by scenario (and folder, if several) plus its own indexes. In your own formulas use Csv_import('Generation'). The round-trip check belongs to the example: it reads Sales back for the current scenario and subtracts Sales computed now - 0 proves the files reproduce the model exactly. NodeLocation: 205,604,1 NodeSize: 175,84 NodeColor: 0x00ffffff FormNode Fo_csv1009 Title: Read from folders Definition: 0 NodeLocation: 560,526,1 NodeSize: 170,11 Original: Csv_import_folders FormNode Fo_csv1010 Title: Results found Definition: 1 NodeLocation: 560,552,1 NodeSize: 170,11 Original: Csv_results_found FormNode Fo_csv1011 Title: Scenarios found Definition: 1 NodeLocation: 560,578,1 NodeSize: 170,11 Original: Csv_scenarios FormNode Fo_csv1012 Title: Result to read Definition: 0 NodeLocation: 560,604,1 NodeSize: 170,11 Original: Csv_read_choice FormNode Fo_csv1013 Title: Read-back result Definition: 1 NodeLocation: 560,630,1 NodeSize: 170,11 Original: Csv_read_result FormNode Fo_csv1014 Title: Example: round-trip check (expect 0) Definition: 1 NodeLocation: 560,656,1 NodeSize: 170,11 Original: Ex_roundtrip_check Text Te_step5 Title: Step 5. Review Description: Pick an output and, optionally, scenarios (empty = all). Flat data shows every row. To summarise, choose the columns to keep and how to combine the rest (Aggregated view). Write review to spreadsheet saves Flat data - optionally without some columns (e.g. Folder, Scenario) and with one column spread out, e.g. a column per year - to a workbook: a file in the results folder or your own workbook (full path). A template is copied when the workbook does not exist yet; an existing tab is replaced, or written into to keep your formatting. With a template, pick each output's tab under Tab for each output (the dropdowns list the template's tabs); (result name) creates a tab named after the result. Write all outputs writes every output in one go. NodeLocation: 205,933,1 NodeSize: 175,227 NodeColor: 0x00ffffff FormNode Fo_csv1015 Title: Output to review Definition: 0 NodeLocation: 560,712,1 NodeSize: 170,11 Original: Csv_view_output FormNode Fo_csv1016 Title: Scenarios to show Definition: 0 NodeLocation: 560,738,1 NodeSize: 170,11 Original: Csv_view_scenarios FormNode Fo_csv1017 Title: Flat data Definition: 1 NodeLocation: 560,764,1 NodeSize: 170,11 Original: Csv_view_flat FormNode Fo_csv1018 Title: Keep these columns Definition: 0 NodeLocation: 560,790,1 NodeSize: 170,11 Original: Csv_view_by FormNode Fo_csv1019 Title: Aggregation method Definition: 0 NodeLocation: 560,816,1 NodeSize: 170,11 Original: Csv_aggregation_method FormNode Fo_csv1020 Title: Aggregated view Definition: 1 NodeLocation: 560,842,1 NodeSize: 170,11 Original: Csv_view_aggregated FormNode Fo_csv1021 Title: Leave out columns Definition: 0 NodeLocation: 560,868,1 NodeSize: 170,11 Original: Csv_sheet_leave_out FormNode Fo_csv1022 Title: Spread across columns Definition: 0 NodeLocation: 560,894,1 NodeSize: 170,11 Original: Csv_sheet_spread FormNode Fo_csv1023 Title: Spreadsheet preview Definition: 1 NodeLocation: 560,920,1 NodeSize: 170,11 Original: Csv_sheet_table FormNode Fo_csv1024 Title: Review spreadsheet file Definition: 0 NodeLocation: 560,946,1 NodeSize: 170,11 Original: Csv_spreadsheet_name FormNode Fo_csv1025 Title: Template workbook (blank = empty) Definition: 0 NodeLocation: 560,972,1 NodeSize: 170,11 Original: Csv_spreadsheet_template_file FormNode Fo_csv1026 Title: Tabs in template Definition: 1 NodeLocation: 560,998,1 NodeSize: 170,11 Original: Csv_template_tabs FormNode Fo_csv1027 Title: Tab for each output Definition: 0 NodeLocation: 560,1024,1 NodeSize: 170,11 Original: Csv_output_tab FormNode Fo_csv1028 Title: If the tab exists Definition: 0 NodeLocation: 560,1050,1 NodeSize: 170,11 Original: Csv_spreadsheet_tab_mode FormNode Fo_csv1029 Title: Start cell Definition: 0 NodeLocation: 560,1076,1 NodeSize: 170,11 Original: Csv_spreadsheet_start_cell Alias Al_csv2005 Title: Write review to spreadsheet NodeLocation: 560,1102,1 NodeSize: 170,12 Original: Csv_write_view_button Alias Al_csv2006 Title: Write all outputs to spreadsheet NodeLocation: 560,1128,1 NodeSize: 170,12 Original: Csv_write_all_button Text Te_optional Title: Optional features Description: All off by default. Details: Scenario Manager library > Settings > Optional features. NodeLocation: 930,298,1 NodeSize: 190,30 NodeColor: 0x00ffffff FormNode Fo_csv1030 Title: File name parts Definition: 0 NodeLocation: 930,342,1 NodeSize: 160,11 Original: Csv_name_parts FormNode Fo_csv1031 Title: File name values Definition: 0 NodeLocation: 930,366,1 NodeSize: 160,11 Original: Csv_name_values FormNode Fo_csv1032 Title: Split files by index Definition: 0 NodeLocation: 930,390,1 NodeSize: 160,11 Original: Csv_split_index FormNode Fo_csv1033 Title: Clean file name parts Definition: 0 NodeLocation: 930,414,1 NodeSize: 160,11 Original: Csv_clean_names FormNode Fo_csv1034 Title: User initials Definition: 0 NodeLocation: 930,438,1 NodeSize: 160,11 Original: Csv_user_initials FormNode Fo_csv1035 Title: Suggested folder name Definition: 0 NodeLocation: 930,462,1 NodeSize: 160,11 Original: Csv_folder_name_suggestion FormNode Fo_csv1036 Title: Sub-folder depth Definition: 0 NodeLocation: 930,486,1 NodeSize: 160,11 Original: Csv_subfolder_depth FormNode Fo_csv1037 Title: Warn before overwriting Definition: 0 NodeLocation: 930,510,1 NodeSize: 160,11 Original: Csv_warn_overwrite FormNode Fo_csv1038 Title: Leave out of export set Definition: 0 NodeLocation: 930,534,1 NodeSize: 160,11 Original: Csv_export_selection FormNode Fo_csv1039 Title: Export set to use Definition: 0 NodeLocation: 930,558,1 NodeSize: 160,11 Original: Csv_export_setup_to_use FormNode Fo_csv1040 Title: Rename CSV columns Definition: 0 NodeLocation: 930,582,1 NodeSize: 160,11 Original: Csv_column_override Text Te_reuse Title: Using the library in another model Description: 1. File > Add Module... > Scenario_Manager_Library.ana, choose Embed (your own copy; this file never changes).~ 2. Inside it, delete the module 'Example (delete after setup)'. Its controls on this panel go with it.~ 3. Spreadsheets: nothing to copy in Analytica 7.1 (a new workbook is created when needed). Older versions: put Blank_workbook.xlsx next to your model.~ 4. Scenario Manager library > Settings: fill in Outputs to save, Output settings and Scenario label. Settings check lists anything still pointing at the example. NodeLocation: 930,708,1 NodeSize: 190,90 NodeColor: 0x00ffffff Text Te_other_data Title: Bringing in data from elsewhere Description: Any CSV can be read if it follows the convention: -.csv in a run folder, with a .schema file next to it. The schema lines: the CSV header; the index identifier behind each column (blank for the value column, @Index for value columns); optionally the part names separated by |. NodeLocation: 930,870,1 NodeSize: 190,66 NodeColor: 0x00ffffff Module Csv_library Title: Scenario Manager library Description: Scenario Manager library v1.10 (2026-11-09): save model outputs to CSV and read them back. Comes with Scenario_Manager_Library.ana; embed that file in your model (File > Add Module..., Embed). Then open Settings (edit for your model) and fill in Outputs to save, Output settings and Scenario label. NodeLocation: 930,140,1 NodeSize: 110,36 NodeColor: 0x00c0e0ff DiagState: 2,60,30,420,340,17,10 Module Csv_settings Title: Settings (edit for your model) Description: Everything a project changes. Fill in Outputs to save, Output settings and Scenario label. NodeLocation: 120,60,1 NodeSize: 100,30 NodeColor: 0x00ffe8c0 DiagState: 2,40,20,1260,560,17,10 Text Te_csv_settings_help Title: Settings for this model Description: Everything a project changes lives in this module; Engine and Reviewer never need editing.~ 1. Outputs to save: identifiers (as text) of the model variables to save, e.g. 'Generation'.~ 2. Output settings (one row per output, all optional):~ Result name - file prefix; leave blank to use the identifier.~ Keep zeroes / Export last / Spread across columns - see the table's description.~ 3. Scenario label: names the current run in the file names. Keep 'Base', or type your scenario variable's~ identifier without quotes (e.g. Demand_scenario) so files are named after the selected scenario.~ Results folder: blank = CSV_Results next to the model. Untick 'One sub-folder per run' to keep all files in it.~ 4. Settings check: for each output, the file it will write and the columns in it - or what to fix.~ Re-check it after every change to the settings.~ Optional features (sub-module, all off by default): export sets, renaming CSV columns, multi-part file names,~ splitting files by an index, name cleaning, date/initials, sub-folders, overwrite warning, hooks, spreadsheet.~ Run choices (sub-module): folder and review selections made on the front panel. NodeLocation: 990,225,1 NodeSize: 240,195 NodeColor: 0x00f0f0f0 Index Csv_output Title: Outputs to save Description: Identifiers (as text) of the model variables saved to / read from CSV, e.g. ['Generation','Capacity']. Definition: ['Ex_sales','Ex_revenue','Ex_total_revenue'] NodeLocation: 169,70,1 NodeSize: 80,28 Index Csv_setting Title: Output setting Definition: ['Result name','Keep zeroes','Export last','Spread across columns'] NodeLocation: 399,70,1 NodeSize: 80,28 Decision Csv_output_settings Title: Output settings Description: One row per output; every column is optional.~ Result name: file prefix; files are -.csv. Leave blank to use the output's identifier.~ If you type one, use letters, digits and underscores (no '-').~ Keep zeroes: unticked (the default) leaves cells that are 0 out of the file, which keeps files small.~ Tick it if the CSV must list zeros explicitly.~ Export last: write this output after "Before last export" runs (e.g. to stamp an export time).~ Spread across columns: optional. By default every index is a column and all numbers sit in one Value column~ (Year, Plant, Value). Type an index identifier here, e.g. 'Year', to give each of its elements its own column instead~ (Plant, 2025, 2026, ...) - handy when the CSV will be read by people in a spreadsheet. Reading back handles both. Definition: Table(Csv_output,Csv_setting)(~ '',Checkbox(0),Checkbox(0),'',~ '',Checkbox(0),Checkbox(0),'',~ '',Checkbox(0),Checkbox(0),'') NodeLocation: 630,70,1 NodeSize: 80,28 Decision Csv_results_folder Title: Results folder Description: Where CSV files go. Leave blank for a CSV_Results folder next to the model file, or type a full path, e.g. C:\Projects\Energy\Results. Definition: '' NodeLocation: 169,230,1 NodeSize: 80,28 Decision Csv_use_run_folders Title: One sub-folder per run Description: Ticked: each run goes into its own sub-folder of the results folder (Create folder..., Export to folder, Read from folders).~ Unticked: everything is written to and read from the results folder itself - simplest for small projects. Definition: Checkbox(1) NodeLocation: 399,230,1 NodeSize: 80,28 Variable Csv_results_root Title: Results root folder Description: Full path of the results folder, always ending with \ (from Results folder, or CSV_Results next to the model). Definition: Local typed := Csv_label(Csv_results_folder);~ Local f := IF Csv_blank(typed) THEN (Local m := CurrentModelFolder(); (IF SelectText(m, TextLength(m), TextLength(m)) = '\' THEN m ELSE m & '\') & 'CSV_Results') ELSE typed;~ IF SelectText(f, TextLength(f), TextLength(f)) = '\' THEN f ELSE f & '\' NodeLocation: 630,230,1 NodeSize: 80,28 Decision Csv_scenario_label Title: Scenario label for export Description: Names the current run in the file names (-.csv).~ Simple model: leave it as 'Base' (or any name).~ If your model has a scenario selector, type that variable's identifier without quotes, e.g. Demand_scenario.~ The label then follows whatever scenario is selected, so each export is named after it. Definition: 'Base' NodeLocation: 399,150,1 NodeSize: 80,28 Variable Csv_settings_check Title: Settings check Description: One line per output. OK lines preview the file the output will be written to and the columns in it~ (index columns are named from each index Title, or from Rename CSV columns). Otherwise it says what to fix.~ It writes no files (it does compute the outputs to see their shapes). Definition: For id := Csv_output Do (~ Local r := Csv_result_name[Csv_output = id];~ Local vc := Csv_output_settings[Csv_output = id, Csv_setting = 'Spread across columns'];~ Local hv := Try(HandleFromIdentifier(id), catch: Null);~ Local p1 := IF IsNull(hv) THEN 'Output identifier not found - check the spelling in Outputs to save. ' ELSE '';~ Local p2 := IF FindInText(Csv_separator, r) > 0 THEN f"Result name contains '{Csv_separator}'. " ELSE '';~ Local p3 := IF Sum(Csv_result_name = r, Csv_output) > 1 THEN 'Two outputs share this result name. ' ELSE '';~ Local p4 := IF Csv_blank(vc) THEN '' ELSE IF IsNull(Try(HandleFromIdentifier(vc), catch: Null)) THEN 'Spread-across-columns index not found. ' ELSE '';~ Local p5 := IF Csv_blank(Csv_label(Csv_split_index)) THEN '' ELSE IF IsNull(Try(HandleFromIdentifier(Csv_label(Csv_split_index)), catch: Null)) THEN 'Split-by index not found. ' ELSE '';~ Local p6 := IF Sum(Csv_column_names = 'index not found', Csv_column_override_index) > 0 THEN 'An index in Rename CSV columns was not found. ' ELSE '';~ Local msg := p1 & p2 & p3 & p4 & p5 & p6;~ IF msg <> '' THEN msg ELSE (~ LocalAlias v := hv;~ LocalIndex dV := IndexesOf(v);~ Local vH := IF Csv_blank(vc) THEN Null ELSE HandleFromIdentifier(vc);~ Local wide := IF IsNull(vH) THEN False ELSE Sum(dV = vH, dV) > 0;~ Local idxCols := JoinText(For k := @dV Do (IF wide AND Slice(dV, k) = vH THEN Null ELSE Csv_column_name_for(Slice(dV, k))), dV, ', ');~ Local valCols := IF wide THEN (LocalAlias vix := vH; f"one value column per {Title of vix}") ELSE f"Value ({Units of v})";~ Local sH := IF Csv_blank(Csv_label(Csv_split_index)) THEN Null ELSE HandleFromIdentifier(Csv_label(Csv_split_index));~ Local split := IF IsNull(sH) THEN '' ELSE IF Sum(dV = sH, dV) > 0 THEN (LocalAlias six := sH; f" (one file per {Title of six})") ELSE '';~ Local inSet := Sum(Csv_outputs_to_export = id, Csv_outputs_to_export) > 0;~ 'OK: ' & r & Csv_separator & Csv_file_key & '.csv' & split & ' - columns: ' & (IF idxCols = '' THEN valCols ELSE idxCols & ', ' & valCols)~ & (IF inSet THEN '' ELSE f" - left out of export set '{Csv_export_setup_to_use}'")~ )~ ) NodeLocation: 630,150,1 NodeSize: 80,28 Module Csv_optional Title: Optional features NodeLocation: 169,320,1 NodeSize: 80,26 NodeColor: 0x00ffe8c0 DiagState: 2,40,20,1260,960,17,10 Text Te_csv_optional_help Title: Optional features (all off by default) Description: File name parts: by default a file is -.csv. Add parts (e.g. Utility, Building type)~ to File name parts and give each a value in File name values; files become ---...csv and~ reading back adds one column per part.~ Split files by index: identifier of an index (e.g. 'Utility'); each element is written to its own file, with the~ element appended as an extra file name part. Outputs without that index are written whole.~ Clean names: replaces characters matching the pattern in every file name part (not the result name).~ Initials / today's date: helpers you can use in File name values or the suggested folder name.~ Sub-folder depth: 1 = only folders directly under the results root; 2+ also lists nested folders (e.g. Run\Archive).~ Warn before overwriting: asks Yes (overwrite) / No (skip this file) / Cancel (stop) for each existing file.~ Hooks: buttons run before / after every export; replace Null with your own statements.~ Export sets: named subsets of outputs; tick 'Leave out' for outputs a set should skip, then pick the set to use.~ Rename CSV columns: different column headers for chosen indexes (default: the index Title). NodeLocation: 970,250,1 NodeSize: 240,190 NodeColor: 0x00f0f0f0 Index Csv_name_parts Title: File name parts Description: Names of the parts after the result name in each file name. Default: just Scenario. Definition: ['Scenario'] NodeLocation: 168,75,1 NodeSize: 80,28 Variable Csv_name_values Title: File name values Description: Current value of each file name part. Each cell can reference a model variable, e.g. Utility_selected. Definition: Table(Csv_name_parts)(Csv_scenario_label) NodeLocation: 392,75,1 NodeSize: 80,28 Decision Csv_split_index Title: Split files by index Description: Identifier of an index to split files by (blank = off). Only the index's current elements are written. Definition: '' NodeLocation: 616,75,1 NodeSize: 80,28 Decision Csv_clean_names Title: Clean file name parts Definition: Checkbox(0) NodeLocation: 168,162,1 NodeSize: 80,28 Decision Csv_clean_pattern Title: Characters to replace (regex) Description: Regular expression of characters to replace in file name parts. Default: - : \ / * ? " < > | Definition: '[-:\\/*?"<>|]' NodeLocation: 392,162,1 NodeSize: 80,28 Decision Csv_clean_replacement Title: Replace with Definition: '_' NodeLocation: 616,162,1 NodeSize: 80,28 Decision Csv_user_initials Title: User initials Description: Optional. Use it in File name values or the suggested folder name. Definition: '' NodeLocation: 168,250,1 NodeSize: 80,28 Decision Csv_date_format Title: Date format Definition: 'yyyy-MM-dd' NodeLocation: 392,250,1 NodeSize: 80,28 Variable Csv_today_text Title: Today's date (text) Definition: NumberToText(Today(), 'Date', dateFormat: Csv_date_format) NodeLocation: 616,250,1 NodeSize: 80,28 Variable Csv_folder_name_suggestion Title: Suggested folder name Description: Pre-filled name offered by Create folder (blank = empty box). Example: Csv_today_text & ' ' & Csv_scenario_label & ' Export ' & Csv_user_initials Definition: '' NodeLocation: 168,337,1 NodeSize: 80,28 Decision Csv_subfolder_depth Title: Sub-folder depth Description: 1 = list only folders directly under the results root. 2 or more also lists nested folders. Definition: 1 NodeLocation: 392,337,1 NodeSize: 80,28 Decision Csv_warn_overwrite Title: Warn before overwriting files Description: When ticked, each existing file triggers a Yes (overwrite) / No (skip) / Cancel (stop export) question. Definition: Checkbox(1) NodeLocation: 616,337,1 NodeSize: 80,28 Button Csv_before_export Title: Before export Description: Runs at the start of every export. Replace Null with your own statements. OnClick: Null NodeLocation: 168,425,1 NodeSize: 80,28 Button Csv_before_last_export Title: Before last export Description: Runs after normal outputs are written and before outputs flagged "Export last". Replace Null with your own statements. OnClick: Null NodeLocation: 392,425,1 NodeSize: 80,28 Button Csv_after_export Title: After export Description: Runs at the end of every export. Replace Null with your own statements. OnClick: Null NodeLocation: 616,425,1 NodeSize: 80,28 Decision Csv_spreadsheet_name Title: Review spreadsheet file Description: Workbook that "Write review to spreadsheet" writes to: a file name (kept in the results folder), or a full path to a workbook of your own, e.g. C:\Reports\Energy summary.xlsx. Its other tabs are kept. Definition: 'Review.xlsx' NodeLocation: 168,512,1 NodeSize: 80,28 Decision Csv_spreadsheet_template_file Title: Template workbook Description: Used only when the review workbook does not exist yet: it is created as a copy of this file. Blank = an empty workbook: Blank_workbook.xlsx next to the model if it is there, otherwise a new workbook created by Analytica (7.1 or later; older versions need Blank_workbook.xlsx). Give a full path to start from your own template, e.g. one with tabs and formatting already set up. Definition: '' NodeLocation: 168,862,1 NodeSize: 80,28 Decision Csv_output_tab Title: Tab for each output Description: Tab each output is written to. (result name) = a tab named after the result, created if needed.~ The other choices are the tabs found in your template (or in the review workbook if it already exists and no template is set). TableCellDefault: Choice(Csv_template_tab_options,1,0) Definition: Table(Csv_output)(Choice(Csv_template_tab_options,1,0),Choice(Csv_template_tab_options,1,0),Choice(Csv_template_tab_options,1,0)) NodeLocation: 392,862,1 NodeSize: 80,28 Index Csv_tab_modes Title: Existing tab options Definition: ['Replace the tab','Write into the tab (keep formatting)'] NodeLocation: 168,775,1 NodeSize: 80,28 Decision Csv_spreadsheet_tab_mode Title: If the tab exists Description: Replace the tab: delete it and write a fresh one. Write into the tab: keep the tab and its formatting, and overwrite cells from Start cell on (rows beyond the new data are not cleared). Definition: Choice(Csv_tab_modes,1,0) NodeLocation: 392,775,1 NodeSize: 80,28 Decision Csv_spreadsheet_start_cell Title: Start cell Description: Top-left cell of the header row, e.g. A1, or B3 to leave room for a title in your template. Definition: 'A1' NodeLocation: 616,775,1 NodeSize: 80,28 Variable Csv_spreadsheet_template Title: Template workbook (full path) Description: Workbook copied when the review workbook does not exist yet. If it is not found, Analytica creates a new workbook instead (works in 7.1). Blank_workbook.xlsx ships with the library as a fallback for older versions. Definition: Local typed := Csv_label(Csv_spreadsheet_template_file);~ IF NOT Csv_blank(typed) THEN typed ELSE (Local f := CurrentModelFolder();~ (IF SelectText(f, TextLength(f), TextLength(f)) = '\' THEN f ELSE f & '\') & 'Blank_workbook.xlsx') NodeLocation: 392,512,1 NodeSize: 80,28 Decision Csv_spreadsheet_backend Title: Spreadsheet backend Description: 'LibXl' (default) is built into Analytica and does not need Excel. 'Excel' uses Microsoft Excel and recalculates formulas, but in testing (Analytica 7.x) it saved the data and then reported 'Cannot access' - use only if you need recalculation. Definition: 'LibXl' NodeLocation: 616,512,1 NodeSize: 80,28 Index Csv_export_setup Title: Export sets Description: Named sets of outputs, e.g. ['All','Quick check']. With the single set 'All' every output is exported. Add sets only if you sometimes want to export a subset. Definition: ['All'] NodeLocation: 168,600,1 NodeSize: 80,28 Decision Csv_export_selection Title: Leave out of export set Description: Tick an output to leave it OUT of that export set. Unticked (the default, also for outputs you add later) = exported. Definition: Table(Csv_output,Csv_export_setup)(Checkbox(0),Checkbox(0),Checkbox(0)) NodeLocation: 392,600,1 NodeSize: 80,28 Decision Csv_export_setup_to_use Title: Export set to use Description: The export set that Export to CSV writes. Definition: Choice(Csv_export_setup,1,0) NodeLocation: 616,600,1 NodeSize: 80,28 Index Csv_column_override_index Title: Indexes to rename in CSV Description: Each index of an output becomes a column in its CSV, headed with the index Title (e.g. Generation by Year x Plant x Season~ gives columns Year, Plant, Season, Value). List an index identifier here (as text, e.g. 'Plant') only if you want a~ different header for that column in every CSV. Settings check shows the resulting columns. Definition: ['Ex_product'] NodeLocation: 168,687,1 NodeSize: 80,28 Decision Csv_column_override Title: Rename CSV columns Description: CSV column header for each listed index, e.g. 'Technology' for Plant. Blank = use the index Title. Definition: Table(Csv_column_override_index)('Product line') NodeLocation: 392,687,1 NodeSize: 80,28 Close Csv_optional Module Csv_run_choices Title: Run choices NodeLocation: 399,320,1 NodeSize: 80,26 DiagState: 2,100,60,520,420,17,10 Variable Csv_folder_refresh Title: Folder refresh Description: Toggled by the Refresh / Create folder buttons to re-list folders. Definition: 1 NodeLocation: 168,50,1 NodeSize: 80,28 Decision Csv_export_folder Title: Export to folder Definition: Choice(Csv_folders,1,0) NodeLocation: 168,137,1 NodeSize: 80,28 Decision Csv_import_folders Title: Read from folders Definition: MultiChoice(Csv_folders,1,returnList:1) NodeLocation: 392,137,1 NodeSize: 80,28 Decision Csv_read_choice Title: Result to read Description: Which result found in the folders being read to show as Read-back result. Definition: Choice(Csv_results_found,1,0) NodeLocation: 616,137,1 NodeSize: 80,28 Decision Csv_view_output Title: Output to review Definition: Choice(Csv_output,1,0) NodeLocation: 168,225,1 NodeSize: 80,28 Decision Csv_view_scenarios Title: Scenarios to show Description: Limit the review to these scenarios. Leave empty to show all. Definition: MultiChoice(Csv_scenarios,allowNone:1,returnList:1) NodeLocation: 392,225,1 NodeSize: 80,28 Decision Csv_view_by Title: Keep these columns Description: Columns kept in the aggregated view. All other columns are collapsed with the aggregation method. Definition: MultiChoice(Csv_view_columns,2,3,returnList:1) NodeLocation: 168,312,1 NodeSize: 80,28 Decision Csv_aggregation_method Title: Aggregation method Definition: Choice(Csv_aggregation_types,1,0) NodeLocation: 392,312,1 NodeSize: 80,28 Decision Csv_sheet_leave_out Title: Leave out columns Description: Columns of Flat data NOT written to the spreadsheet, e.g. Folder and Scenario. None picked = write all. Definition: MultiChoice(Csv_view_columns,allowNone:1,returnList:1) NodeLocation: 168,400,1 NodeSize: 80,28 Decision Csv_sheet_spread Title: Spread across columns Description: Column whose values become separate columns in the spreadsheet in place of the Value column, e.g. Year gives one column per year; Scenario puts scenarios side by side. (none) = keep the Value column. Definition: Choice(Csv_sheet_spread_options,1,0) NodeLocation: 392,400,1 NodeSize: 80,28 Close Csv_run_choices Close Csv_settings Module Csv_engine Title: Engine NodeLocation: 120,140,1 NodeSize: 100,30 DiagState: 2,80,40,1150,620,17,10 Constant Csv_library_version Title: Library version Description: Version of the embedded Scenario Manager library.~ 1.10 (2026-11-09): renamed Scenario Manager Library (file Scenario_Manager_Library.ana). Was the CSV I/O library; identifiers (Csv_...) unchanged.~ 1.9 (2026-11-08): Tab for each output (dropdowns list the template's tabs), Tabs in template, Write all outputs to spreadsheet.~ 1.8 (2026-11-08): spreadsheet output can leave out columns (e.g. Folder, Scenario) and spread one column across (e.g. a column~ per year) in place of the Value column; Spreadsheet preview shows what will be written.~ 1.7 (2026-11-08): missing results folders (any name or depth) are created on export and spreadsheet writes; Export asks~ for a run folder name when none is selected; clear message when folders cannot be created.~ 1.6 (2026-11-07): spreadsheet output - your own workbook (full path), template workbook, tab name, write into an existing tab~ (keep formatting) and start cell; Step 5 reordered (Flat data before the aggregation controls); round-trip check explained.~ 1.5 (2026-11-07): fixed reading from run folders ('not a valid index'); Step 4 lists Results found (via FileSystemListing of .schema~ files) with a Result to read dropdown and Read-back result; Csv_import() also reads results not in Outputs to save.~ 1.4 (2026-11-07): zero cells left out by default ('Keep zeroes' to keep them); 'Value columns' renamed 'Spread across columns';~ Results folder input (blank = CSV_Results); optional single results folder (no run sub-folders); overwrite warning on~ by default; clearer Scenario label (type a name or your scenario variable) and Example file name preview.~ 1.3 (2026-11-07): blank Result name = output identifier; Settings check previews each file name and its columns;~ export sets and column renaming moved to Optional features; export sets are opt-out (new outputs always included).~ 1.2 (2026-11-07): one file - CSV_IO_Library.ana is both the guide and the file to embed; the example is a deletable module.~ Scenario label is plain text (the example reads it); Custom column names list index identifiers as text.~ Spreadsheet helper defaults to the built-in LibXl backend and replaces existing tabs. Diagram layout fixes.~ 1.1 (2026-11-07): optional features - export setups, value columns (wide layout), multi-part file names, split by index,~ name cleaning, date/initials helpers, sub-folder depth, clearer overwrite warning, before/after export hooks,~ Create folder prompt, settings check, write-to-spreadsheet helper. Defaults reproduce 1.0.~ 1.0 (2026-11-07): first release (single embeddable module). Definition: '1.10 (2026-11-09)' NodeLocation: 168,50,1 NodeSize: 80,28 Constant Csv_separator Title: File name separator Description: Separates result name and file name parts. Definition: '-' NodeLocation: 392,50,1 NodeSize: 80,28 Index Csv_folders Title: Result folders Description: Run folders under the results root (relative paths when sub-folder depth > 1). Empty if the root does not exist yet. Definition: Csv_folder_refresh;~ Try(~ IF Csv_subfolder_depth <= 1 THEN FileSystemListing(Csv_results_root, files: False, folders: True)~ ELSE (~ LocalIndex all := FileSystemListing(Csv_results_root, files: False, folders: True, recurse: True);~ Subset(TextLength(all) - TextLength(TextReplace(all, '\', '', all: True)) < Csv_subfolder_depth)~ ),~ catch: []) NodeLocation: 616,50,1 NodeSize: 80,28 Button Csv_refresh_folders Title: Refresh folder list Description: Click after adding a run folder outside Analytica. OnClick: Csv_folder_refresh := NOT Csv_folder_refresh NodeLocation: 840,50,1 NodeSize: 80,28 Button Csv_create_folder Title: Create folder... Description: Asks for a folder name, creates it under the results root (and the root itself if needed), and selects it as the export folder. OnClick: Local root := Csv_results_root;~ Local nm := AskMsgText('Name of the new run folder (created inside ' & root & '):', 'Create folder', default: Csv_folder_name_suggestion);~ IF IsNull(nm) OR nm = '' THEN MsgBox('No name entered - nothing was created.', 64, 'Create folder')~ ELSE IF Sum(Csv_folders = nm, Csv_folders) > 0 THEN MsgBox(f"A folder named '{nm}' already exists. Pick it under 'Export to folder', or choose another name.", 48, 'Create folder')~ ELSE IF Csv_ensure_folder(root & Csv_label(nm)) THEN (~ Csv_folder_refresh := NOT Csv_folder_refresh;~ Csv_export_folder := Csv_label(nm);~ MsgBox(f"Created {root}{Csv_label(nm)} and selected it as the export folder.", 64, 'Create folder')~ ) ELSE MsgBox(f"Could not create {root}{Csv_label(nm)}. Creating folders needs Analytica Enterprise or higher. Create it in Windows, then click Refresh folder list.", 48, 'Create folder') NodeLocation: 1064,50,1 NodeSize: 80,28 Function Csv_folder_exists(p: Atomic Text) Title: Folder exists? Description: True if folder p exists (with or without a trailing \). Definition: Local q := IF SelectText(p, TextLength(p), TextLength(p)) = '\' THEN SelectText(p, 1, TextLength(p) - 1) ELSE p;~ Local parent := TextReplace(q, '\\[^\\]*$', '', re: True);~ Local nm := TextLowerCase(TextReplace(q, '^.*\\', '', re: True));~ IF parent = '' OR parent = q THEN True~ ELSE Try((LocalIndex L := FileSystemListing(parent & '\', files: False, folders: True); Sum(TextLowerCase(L) = nm, L) > 0), catch: False) NodeLocation: 1288,50,1 NodeSize: 80,28 Function Csv_ensure_folder(p: Atomic Text) Title: Make sure a folder exists Description: Creates folder p if it is missing, one level at a time (e.g. C:\Projects\Energy\Results when only C:\Projects exists).~ Returns True if the folder exists afterwards. Creating folders needs Analytica Enterprise or higher. Definition: Local q := IF SelectText(p, TextLength(p), TextLength(p)) = '\' THEN SelectText(p, 1, TextLength(p) - 1) ELSE p;~ LocalIndex parts := SplitText(q, '\');~ Local first := IF SelectText(q, 1, 2) = '\\' THEN 5 ELSE 2;~ Local acc := '';~ Local i := 1;~ While i <= Size(parts) Do (~ acc := IF i = 1 THEN Slice(parts, 1) ELSE acc & '\' & Slice(parts, i);~ IF i >= first AND NOT Csv_folder_exists(acc) THEN Try(FileSystemNewFolder(acc), catch: Null);~ i := i + 1~ );~ Csv_folder_exists(q) NodeLocation: 1288,125,1 NodeSize: 80,28 Function Csv_blank(x) Title: Blank? Description: True for an empty table cell (Null, blank text, or the 0 Analytica puts in new rows). Definition: IsNull(x) OR (IsText(x) AND x = '') OR (IsNumber(x) AND x = 0) NodeLocation: 1064,200,1 NodeSize: 80,28 Variable Csv_result_name Title: Result name Description: File prefix per output: the Result name typed in Output settings, or the output's identifier when that cell is blank. Definition: For id := Csv_output Do (Local r := Csv_output_settings[Csv_output = id, Csv_setting = 'Result name']; IF Csv_blank(r) THEN id ELSE r) NodeLocation: 168,125,1 NodeSize: 80,28 Index Csv_outputs_to_export Title: Outputs to export Definition: Subset(Csv_export_selection[Csv_export_setup = Csv_export_setup_to_use] <> 1) NodeLocation: 392,125,1 NodeSize: 80,28 Function Csv_folder_path(f) Title: Folder path Description: Full path (ending with \) of run folder f; '' means the results folder itself. Definition: IF Csv_blank(f) THEN Csv_results_root ELSE Csv_results_root & f & '\' NodeLocation: 1064,462,1 NodeSize: 80,28 Index Csv_read_folders Title: Folders being read Description: Read from folders, or just the results folder itself ('') when One sub-folder per run is unticked. Definition: IF Csv_use_run_folders = 1 THEN CopyIndex(Csv_import_folders) ELSE [''] NodeLocation: 1064,375,1 NodeSize: 80,28 Variable Csv_export_path Title: Export path Definition: IF Csv_use_run_folders = 1 THEN Csv_folder_path(Csv_export_folder) ELSE Csv_results_root NodeLocation: 616,125,1 NodeSize: 80,28 Function Csv_column_name_for(h) Title: CSV column name for index Description: Given a handle to an index, returns its CSV column name: the custom name if set, otherwise the index Title. Definition: LocalAlias ix := h;~ Local p := PositionInIndex(Csv_column_override_index, Identifier of ix, Csv_column_override_index);~ IF p = 0 THEN Title of ix~ ELSE (~ Local o := Slice(Csv_column_override, p);~ IF IsNull(o) OR o = '' THEN Title of ix ELSE o~ ) NodeLocation: 840,125,1 NodeSize: 80,28 Variable Csv_column_names Title: Column names in use Definition: For k := @Csv_column_override_index Do (Local h := Try(HandleFromIdentifier(Slice(Csv_column_override_index, k)), catch: Null); IF IsNull(h) THEN 'index not found' ELSE Csv_column_name_for(h)) NodeLocation: 1064,125,1 NodeSize: 80,28 Function Csv_label(x) Title: Label as text Description: Plain text for an index element or name part: whole numbers without thousands separators; line breaks, tabs and leading/trailing spaces removed (a stray Enter in an input box would otherwise end up in file names). Definition: IF IsNull(x) THEN ''~ ELSE IF IsText(x) THEN TextTrim(TextReplace(x, '[\r\n\t]+', ' ', all: True, re: True))~ ELSE IF IsNumber(x) THEN (IF x = Round(x) THEN NumberToText(x, 'Fixed', 0, separators: 0) ELSE NumberToText(x, 'Fixed', 6, separators: 0))~ ELSE f"{x}" NodeLocation: 840,200,1 NodeSize: 80,28 Function Csv_clean(t) Title: Clean a file name part Description: Returns t as text; when Clean file name parts is ticked, characters matching the pattern are replaced. Definition: Local s := Csv_label(t);~ IF Csv_clean_names THEN TextReplace(s, Csv_clean_pattern, Csv_clean_replacement, all: True, re: True) ELSE s NodeLocation: 168,200,1 NodeSize: 80,28 Variable Csv_file_key Title: File name key (current run) Description: The part of the file name after - for the current run (before any split-by part). Definition: JoinText(For p := Csv_name_parts Do Csv_clean(Csv_name_values[Csv_name_parts = p]), Csv_name_parts, Csv_separator) NodeLocation: 392,200,1 NodeSize: 80,28 Variable Csv_example_file Title: Example file name Description: What the first output will be called if you export now (the other outputs follow the same pattern). Definition: Slice(Csv_result_name, Csv_output, 1) & Csv_separator & Csv_file_key & '.csv' NodeLocation: 840,375,1 NodeSize: 80,28 Function Csv_file_exists(p: Atomic Text) Title: File exists? Definition: Try(Size(FileSystemListing(p, files: True, folders: False)) > 0, catch: False) NodeLocation: 616,200,1 NodeSize: 80,28 Function Csv_write_one(a; unit: Atomic; omitZ: Atomic; valId: Atomic Text; path, rname, key: Atomic Text; partNames: Atomic Text) Title: Flatten and write one file Description: Flattens one array (standard layout, or wide when valId names one of its indexes), writes -.csv,~ and writes .schema: line 1 = CSV header, line 2 = index identifier behind each column ('@Index' for value columns),~ line 3 (only for multi-part names) = file name part names separated by |. Definition: LocalIndex dA := IndexesOf(a);~ Local wantWide := NOT Csv_blank(valId);~ Local vH := IF wantWide THEN Try(HandleFromIdentifier(valId), catch: Null) ELSE Null;~ Local wide := IF wantWide AND NOT IsNull(vH) THEN Sum(dA = vH, dA) > 0 ELSE False;~ IF wantWide AND NOT wide THEN MsgBox(f"{rname}: '{valId}' is not an index of this output, so it was written with a single Value column.", 48, 'CSV export');~ Local flat := IF wide THEN (LocalAlias vi := vH; MdArrayToTable(a, valueIndex: vi, omitZero: omitZ, omitNull: 1))~ ELSE MdArrayToTable(a, omitZero: omitZ, omitNull: 1);~ LocalIndex cols := CopyIndex(flat.Col);~ Local n := Size(cols);~ Local nv := IF wide THEN n - (Size(dA) - 1) ELSE 1;~ Local names := For k := @cols Do (IF k > n - nv THEN (IF wide THEN Csv_label(Slice(cols, k)) ELSE f"Value ({unit})") ELSE Csv_column_name_for(Slice(cols, k)));~ Local idents := For k := @cols Do (IF k > n - nv THEN (IF wide THEN '@' & valId ELSE '') ELSE (LocalAlias ix := Slice(cols, k); Identifier of ix));~ LocalIndex Col := CopyIndex(names);~ Local out := flat[@.Col = @Col];~ Local fpath := path & rname & Csv_separator & key & '.csv';~ Local ok := IF Csv_warn_overwrite AND Csv_file_exists(fpath)~ THEN MsgBox(f"This file already exists:{Chr(13)}{fpath}{Chr(13)}{Chr(13)}Yes = overwrite it with the new results{Chr(13)}No = skip this file and keep the existing one{Chr(13)}Cancel = stop the export (files already written are kept)", 3 + 48, 'File already exists') = 6~ ELSE True;~ IF ok THEN WriteTextFile(fpath, IF wide THEN MakeCSV(out, Col, out.Row, Col, quoteFlags: 2) ELSE MakeCSV(out, Col, out.Row, Col), 0, 0);~ LocalIndex SRow := IF partNames = '' OR partNames = 'Scenario' THEN [1] ELSE [1, 2];~ Local schema := IF SRow = 1 THEN idents[@cols = @Col] ELSE (IF @Col = 1 THEN partNames ELSE '');~ WriteTextFile(path & rname & '.schema', IF wide THEN MakeCSV(schema, Col, SRow, Col, quoteFlags: 2) ELSE MakeCSV(schema, Col, SRow, Col), 0, 0);~ ok NodeLocation: 168,287,1 NodeSize: 80,28 Function Csv_export(ids: Index; folderPath, key: Atomic Text) Title: Export outputs to CSV Description: Writes each output identifier in ids. With "Split files by index" set and the output indexed by it, writes one file per~ element of that index (the element is added as an extra file name part). Definition: Local cnt := 0;~ Local maxCnt := Size(ids);~ Local path := IF SelectText(folderPath, TextLength(folderPath), TextLength(folderPath)) = '\' THEN folderPath ELSE folderPath & '\';~ Local partsText := JoinText(Csv_name_parts, Csv_name_parts, '|');~ Local sp := Csv_label(Csv_split_index);~ For id := ids Do (~ cnt := cnt + 1;~ Local rname := Csv_result_name[Csv_output = id];~ ShowProgressBar('CSV export', f"Writing {rname} ({cnt} of {maxCnt})...", (cnt - 0.1)/maxCnt);~ LocalAlias v := HandleFromIdentifier(id);~ Local unit := Units of v;~ Local omitZ := NOT (Csv_output_settings[Csv_output = id, Csv_setting = 'Keep zeroes'] = 1);~ Local valId0 := Csv_output_settings[Csv_output = id, Csv_setting = 'Spread across columns'];~ Local valId := IF Csv_blank(valId0) THEN '' ELSE valId0;~ LocalIndex dV := IndexesOf(v);~ Local sH := IF IsNull(sp) OR sp = '' THEN Null ELSE Try(HandleFromIdentifier(sp), catch: Null);~ Local doSplit := IF IsNull(sH) THEN False ELSE Sum(dV = sH, dV) > 0;~ IF NOT doSplit THEN Csv_write_one(v, unit, omitZ, valId, path, rname, key, partsText)~ ELSE (~ LocalAlias si := sH;~ Local pn := partsText & '|' & (Title of si);~ For e := si Do Csv_write_one(v[si = e], unit, omitZ, valId, path, rname, key & Csv_separator & Csv_clean(e), pn);~ Null~ );~ Null~ ) NodeLocation: 392,287,1 NodeSize: 80,28 Button Csv_export_button Title: Export to CSV Description: Writes every output selected in the current export setup, for the current file name values, into the export folder. OnClick: Local root := Csv_results_root;~ IF NOT Csv_ensure_folder(root) THEN~ MsgBox(f"Nothing was exported. The results folder {root} does not exist and could not be created (creating folders needs Analytica Enterprise or higher). Create it in Windows, then export again.", 48, 'CSV export')~ ELSE (~ Local chosen := Try(Csv_label(Csv_export_folder), catch: '');~ Local runName := IF Csv_use_run_folders <> 1 OR NOT Csv_blank(chosen) THEN chosen~ ELSE Csv_label(AskMsgText('No run folder is selected yet. Name of the new run folder (created inside ' & root & '):', 'Export to CSV', default: Csv_folder_name_suggestion));~ Local path := IF Csv_use_run_folders <> 1 THEN root ELSE Csv_folder_path(runName);~ IF Csv_use_run_folders = 1 AND Csv_blank(runName) THEN MsgBox('No folder name entered - nothing was exported.', 64, 'Export to CSV')~ ELSE IF NOT Csv_ensure_folder(path) THEN MsgBox(f"Nothing was exported. Could not create {path} (creating folders needs Analytica Enterprise or higher). Create it in Windows, then export again.", 48, 'Export to CSV')~ ELSE (~ IF Csv_use_run_folders = 1 AND runName <> chosen THEN (Csv_folder_refresh := NOT Csv_folder_refresh; Csv_export_folder := runName);~ Csv_before_export;~ Local key := Csv_file_key;~ LocalIndex firstIds := Subset(Csv_output_settings[Csv_output = Csv_outputs_to_export, Csv_setting = 'Export last'] <> 1);~ LocalIndex lastIds := Subset(Csv_output_settings[Csv_output = Csv_outputs_to_export, Csv_setting = 'Export last'] = 1);~ IF Size(firstIds) > 0 THEN Csv_export(firstIds, path, key);~ IF Size(lastIds) > 0 THEN (~ Csv_before_last_export;~ Csv_export(lastIds, path, key)~ );~ Csv_after_export~ )~ );~ Csv_folder_refresh := NOT Csv_folder_refresh; NodeLocation: 616,287,1 NodeSize: 80,28 Variable Csv_no_data Title: No data Definition: LocalIndex Row := [1];~ LocalIndex Column := [''];~ Array(Row, Column, Null) NodeLocation: 840,287,1 NodeSize: 80,28 Function Csv_read_schema(resultName: Atomic Text) Title: Read schema Description: Reference to the parsed .schema from the first read folder that has one, or Null. Definition: Local res := Null;~ For f := Csv_read_folders Do (~ Local sf := Csv_folder_path(f) & resultName & '.schema';~ IF IsNull(res) AND Csv_file_exists(sf) THEN res := Try(\ParseCSV(ReadTextFile(sf, showDialog: False), firstLineIsHeader: True), catch: Null);~ Null~ );~ res NodeLocation: 1064,287,1 NodeSize: 80,28 Function Csv_read_flat(folderList: Index; resultName: Atomic Text) Title: Read CSV files (flat) Description: Reads every -.csv in the given folders into one flat table: Folder, Scenario (the whole file name key),~ then one column per file name part when names have more than one part, then the CSV columns. Definition: (~ LocalIndex folderPart := [];~ LocalIndex filePart := [];~ Local prefix := resultName & Csv_separator;~ FOR folder := folderList DO (~ Local folderPath := Csv_folder_path(folder);~ Csv_folder_refresh;~ LocalIndex allFileName := FileSystemListing(folderPath, files: True, folders: False);~ LocalIndex filename := Subset((SelectText(allFileName, 1, TextLength(prefix)) = prefix) AND (FindInText('.csv', allFileName) = TextLength(allFileName) - 3));~ LocalIndex folderName := CopyIndex(AddIndex(folder, filename));~ filePart := Concat(filePart, filename);~ folderPart := Concat(folderPart, folderName);~ Null~ );~ LocalIndex allPaths := CopyIndex(Csv_folder_path(Slice(folderPart, @filePart)) & filePart);~ IF Size(allPaths) = 0 THEN Csv_no_data ELSE (~ Local keys := SelectText(filePart, TextLength(prefix) + 1, TextLength(filePart) - 4);~ Local nParts := TextLength(keys) - TextLength(TextReplace(keys, Csv_separator, '', all: True)) + 1;~ Local maxParts := Max(nParts, filePart);~ Local sch := Csv_read_schema(resultName);~ Local namesText := IF IsNull(sch) THEN '' ELSE Try((Local s2 := #sch; IF Size(s2.Row) >= 2 THEN Slice(Slice(s2, s2.Row, 2), s2.Column, 1) ELSE ''), catch: '');~ LocalIndex knownNames := IF IsNull(namesText) OR namesText = '' THEN ['Scenario'] ELSE SplitText(namesText, '|');~ LocalIndex seqI := 1..Max([maxParts, 1]);~ LocalIndex partCols := IF maxParts <= 1 THEN []~ ELSE CopyIndex(For i := seqI Do (~ Local nm := IF i <= Size(knownNames) THEN Slice(knownNames, i) ELSE 'Part ' & i;~ IF nm = 'Scenario' OR nm = 'Folder' THEN nm & ' (part)' ELSE nm));~ LocalIndex Column := [];~ Local fileNum := 0;~ Local fileCnt := Size(allPaths);~ Local maxRow := 0;~ Local dataByFile := FOR file := allPaths DO (~ fileNum := fileNum + 1;~ ShowProgressBar('CSV import', f"Reading {resultName}: file {fileNum} of {fileCnt}...", (fileNum - 0.1)/fileCnt);~ Local parsed := ParseCSV(ReadTextFile(file, showDialog: False), firstLineIsHeader: True);~ IF file = Slice(allPaths, 1) THEN Column := Concat(Concat(['Folder','Scenario'], partCols), parsed.Column);~ Local data := parsed[.Column = Column];~ maxRow := Max([maxRow, Size(data.Row)]);~ Local filePos := PositionInIndex(allPaths, file, allPaths);~ Local key := Slice(keys, filePos);~ data[Column = 'Folder'] := Slice(folderPart, filePos);~ data[Column = 'Scenario'] := key;~ IF Size(partCols) > 0 THEN (~ LocalIndex pieces := SplitText(key, Csv_separator);~ For i := @partCols Do (IF i <= Size(pieces) THEN data[Column = Slice(partCols, i)] := Slice(pieces, i); Null)~ );~ \data~ );~ LocalIndex fileRow := IF maxRow = 0 THEN [] ELSE 1..maxRow;~ Local deref := FOR path := allPaths DO (#(dataByFile[allPaths = path]))[.Row = fileRow, defVal: Null];~ Local flatData := Flatten(deref, allPaths, fileRow, condition: Sum(deref = Null, Column) <> Size(Column));~ LocalIndex Row := CopyIndex(flatData.K);~ flatData[.K = Row]~ )~ ) NodeLocation: 168,375,1 NodeSize: 80,28 Index Csv_results_found Title: Results found Description: Result names that have a .schema file in the folders being read (found with FileSystemListing). Includes results written by other models. Definition: LocalIndex found := [];~ FOR folder := Csv_read_folders DO (~ Csv_folder_refresh;~ LocalIndex f := Try(FileSystemListing(Csv_folder_path(folder), files: True, folders: False), catch: []);~ LocalIndex sc := Subset(TextLength(f) > 7 AND SelectText(f, TextLength(f) - 6, TextLength(f)) = '.schema');~ found := Unique(Concat(found, SelectText(sc, 1, TextLength(sc) - 7)));~ Null~ );~ SortIndex(found) NodeLocation: 168,550,1 NodeSize: 80,28 Index Csv_scenarios Title: Scenarios found Description: File name keys (everything after -) found in the folders being read. Imported results are indexed by this. Definition: LocalIndex found := [];~ FOR folder := Csv_read_folders DO (~ Csv_folder_refresh;~ LocalIndex f := Try(FileSystemListing(Csv_folder_path(folder), files: True, folders: False), catch: []);~ FOR rn := Csv_results_found DO (~ Local prefix := rn & Csv_separator;~ LocalIndex m := Subset((SelectText(f, 1, TextLength(prefix)) = prefix) AND (FindInText('.csv', f) = TextLength(f) - 3));~ found := Unique(Concat(found, SelectText(m, TextLength(prefix) + 1, TextLength(m) - 4)));~ Null~ );~ Null~ );~ SortIndex(found) NodeLocation: 392,375,1 NodeSize: 80,28 Function Csv_add_dims(flat; resultName: Atomic Text) Title: Rebuild dimensions Description: Turns a flat table back into a multi-dimensional array using .schema. Handles both the standard layout and~ value columns (wide). Dimensions: Read from folders (only when more than one folder is read), Scenarios found, then the output's own indexes. Definition: Try((~ Local sch := Csv_read_schema(resultName);~ Local s := #sch;~ LocalIndex hdr := CopyIndex(s.Column);~ Local ids := s[.Row = 1, .Column = hdr];~ LocalIndex dimCol := Subset(IF IsNull(ids) THEN 0 ELSE (ids <> '' AND SelectText(ids, 1, 1) <> '@'));~ LocalIndex wideCol := Subset(IF IsNull(ids) THEN 0 ELSE SelectText(ids, 1, 1) = '@');~ Local dimH := For c := dimCol Do HandleFromIdentifier(ids[hdr = c]);~ Local useFolder := Size(Csv_read_folders) > 1;~ LocalIndex mdDims := Concat(IF useFolder THEN [Handle(Csv_read_folders)] ELSE [], Concat([Handle(Csv_scenarios)], dimH));~ IF Size(wideCol) = 0 THEN (~ Local valName := Slice(flat.Column, Size(flat.Column));~ LocalIndex mdCols := Concat(Concat(IF useFolder THEN ['Folder'] ELSE [], ['Scenario']), Concat(dimCol, [valName]));~ Local tbl := For c := mdCols Do flat[.Column = c];~ MdTable(tbl, flat.Row, mdCols, mdDims, 'First')~ ) ELSE (~ Local w1 := ids[hdr = Slice(wideCol, 1)];~ LocalAlias vi := HandleFromIdentifier(SelectText(w1, 2, TextLength(w1)));~ LocalIndex mdCols := Concat(Concat(IF useFolder THEN ['Folder'] ELSE [], ['Scenario']), Concat(dimCol, ['__value']));~ LocalIndex fc := CopyIndex(flat.Column);~ For e := vi Do (~ Local colName := Csv_label(e);~ Local pos := Sum(For k := @fc Do (IF Csv_label(Slice(fc, k)) = colName THEN k ELSE 0), fc);~ IF pos = 0 THEN Null~ ELSE (~ Local tbl := For c := mdCols Do (IF c = '__value' THEN flat[@.Column = pos] ELSE flat[.Column = c]);~ MdTable(tbl, flat.Row, mdCols, mdDims, 'First')~ )~ )~ )~ ), catch: Null) NodeLocation: 616,375,1 NodeSize: 80,28 Variable Csv_flat_results Title: Flat results (all outputs) Definition: For j := Csv_output Do \Csv_read_flat(Csv_read_folders, Csv_result_name[Csv_output = j]) NodeLocation: 168,462,1 NodeSize: 80,28 Variable Csv_imported_results Title: Imported results (all outputs) Description: Indexed by Outputs to save. Each cell references the imported array for that output. Definition: For j := Csv_output Do (Local fl := #Csv_flat_results[Csv_output = j]; IF Size(Csv_scenarios) = 0 OR Size(fl.Column) <= 1 THEN \Null ELSE \Csv_add_dims(fl, Csv_result_name[Csv_output = j])) NodeLocation: 392,462,1 NodeSize: 80,28 Function Csv_import_result(rname: Atomic Text) Title: Import a result by name Description: Reads -*.csv from the folders being read and rebuilds its dimensions from .schema. Null if nothing is found. Definition: Local fl := Csv_read_flat(Csv_read_folders, rname); IF Size(Csv_scenarios) = 0 OR Size(fl.Column) <= 1 THEN Null ELSE Csv_add_dims(fl, rname) NodeLocation: 840,462,1 NodeSize: 80,28 Function Csv_import(id: Atomic Text) Title: Import an output Description: Returns a saved result as an array, e.g. Csv_import('Generation'). Use an identifier from Outputs to save, or any result~ name listed in Results found (also results written by another model). Indexed by Scenarios found (and Read from folders~ if several), plus the result's own indexes. Definition: IF Sum(Csv_output = id, Csv_output) > 0 THEN #Csv_imported_results[Csv_output = id] ELSE Csv_import_result(id) NodeLocation: 616,462,1 NodeSize: 80,28 Variable Csv_read_result Title: Read-back result Description: The result picked in Result to read, as an array. In your own formulas use Csv_import() instead. Definition: Csv_import(Csv_read_choice) NodeLocation: 392,550,1 NodeSize: 80,28 Close Csv_engine Module Csv_reviewer Title: Reviewer NodeLocation: 120,220,1 NodeSize: 100,30 DiagState: 2,80,40,760,420,17,10 Variable Csv_view_flat_all Title: Flat data (all scenarios) Definition: #Csv_flat_results[Csv_output = Csv_view_output] NodeLocation: 168,50,1 NodeSize: 80,28 Function Csv_pick_scenarios(f) Title: Keep chosen scenarios Description: Rows of a flat table whose Scenario is in "Scenarios to show" (all rows when none are picked). Definition: LocalIndex sel := Csv_view_scenarios;~ IF Size(sel) = 0 THEN f~ ELSE (~ Local keep := Sum(f[.Column = 'Scenario'] = sel, sel) > 0;~ LocalIndex Row := Subset(keep);~ f[.Row = Row]~ ) NodeLocation: 1288,50,1 NodeSize: 80,28 Variable Csv_view_flat Title: Flat data Description: Flat data for the output being reviewed, limited to "Scenarios to show" (all when none are picked). Definition: Csv_pick_scenarios(Csv_view_flat_all) NodeLocation: 392,50,1 NodeSize: 80,28 Variable Csv_review_file Title: Review workbook (full path) Description: Review spreadsheet file as a full path (a plain file name is placed in the results folder). Definition: Local sn := Csv_label(Csv_spreadsheet_name);~ IF FindInText(':', sn) > 0 OR SelectText(sn, 1, 2) = '\\' THEN sn ELSE Csv_results_root & sn NodeLocation: 1288,137,1 NodeSize: 80,28 Index Csv_template_tabs Title: Tabs in template Description: Tabs of your template workbook (Template workbook), or of the review workbook if it already exists and no template is set. Empty when neither exists. Definition: Local src := IF NOT Csv_blank(Csv_label(Csv_spreadsheet_template_file)) THEN Csv_spreadsheet_template ELSE Csv_review_file;~ IF NOT Csv_file_exists(src) THEN []~ ELSE Try((Local wb := SpreadsheetOpen(src, showDialog: 0, backend: Csv_spreadsheet_backend); CopyIndex(SpreadsheetInfo(wb, 'Sheets'))), catch: []) NodeLocation: 1288,225,1 NodeSize: 80,28 Index Csv_template_tab_options Title: Tab choices Definition: Concat(['(result name)'], Csv_template_tabs) NodeLocation: 1288,312,1 NodeSize: 80,28 Function Csv_tab_for(id: Atomic Text) Title: Tab for an output Description: Tab chosen in Tab for each output, or the result name. Definition: Local c := Csv_output_tab[Csv_output = id];~ IF Csv_blank(Csv_label(c)) OR c = '(result name)' THEN Csv_result_name[Csv_output = id] ELSE Csv_label(c) NodeLocation: 1288,400,1 NodeSize: 80,28 Index Csv_view_columns Title: Columns available Definition: Local f := Csv_view_flat;~ LocalIndex c := CopyIndex(f.Column);~ Subset(@c < Size(c)) NodeLocation: 616,50,1 NodeSize: 80,28 Index Csv_sheet_spread_options Title: Spread options Definition: Concat(['(none)'], Csv_view_columns) NodeLocation: 840,50,1 NodeSize: 80,28 Function Csv_sheet_layout(f; spreadCol: Atomic Text; dropList) Title: Spreadsheet layout Description: Turns a flat table (indexes .Row, .Column; last column = values) into the table written to the spreadsheet:~ drops the columns in dropList, and if spreadCol is given, makes one column per value of spreadCol in place of the value column.~ Values are never added up: when spreading, dropped columns still keep rows apart and are removed only at the end. Definition: LocalIndex fc := CopyIndex(f.Column);~ Local valName := Slice(fc, Size(fc));~ LocalIndex dl := IF Size(dropList) = 0 THEN [''] ELSE CopyIndex(dropList);~ LocalIndex keepC := Subset(For k := @fc Do (Sum(dl = Slice(fc, k), dl) = 0 OR Slice(fc, k) = valName OR Slice(fc, k) = spreadCol));~ IF spreadCol = '' OR spreadCol = '(none)' OR Sum(fc = spreadCol, fc) = 0 THEN (~ LocalIndex Column := CopyIndex(keepC);~ f[.Column = Column]~ ) ELSE (~ LocalIndex dimC := Subset(fc <> valName AND fc <> spreadCol);~ LocalIndex dc := Concat(dimC, [spreadCol]);~ LocalIndex mc := Concat(dc, [valName]);~ Local data := f[.Column = mc];~ Local arr := MdTable(data, data.Row, mc, '.' & dc);~ LocalIndex ia := IndexesOf(arr);~ Local dcNorm := TextReplace(dc, '[^A-Za-z0-9]', '_', all: True, re: True);~ Local iaNames := For k := @ia Do (LocalAlias ix := Slice(ia, k); Local idn := TextReplace(TextReplace(Identifier of ix, '^\.', '', re: True), '[^A-Za-z0-9]', '_', all: True, re: True);~ Local p := Sum(IF dcNorm = idn THEN @dc ELSE 0, dc); IF p > 0 THEN Slice(dc, p) ELSE idn);~ Local sPos := Sum(IF iaNames = spreadCol THEN @ia ELSE 0, ia);~ LocalAlias vi := Slice(ia, sPos);~ Local flat2 := MdArrayToTable(arr, valueIndex: vi, omitNull: 1);~ LocalIndex cols := CopyIndex(flat2.Col);~ Local nd := Size(ia) - 1;~ Local names := For k := @cols Do (IF k > nd THEN Csv_label(Slice(cols, k)) ELSE (LocalAlias ix2 := Slice(cols, k);~ Local idn2 := TextReplace(TextReplace(Identifier of ix2, '^\.', '', re: True), '[^A-Za-z0-9]', '_', all: True, re: True);~ Local p2 := Sum(IF dcNorm = idn2 THEN @dc ELSE 0, dc); IF p2 > 0 THEN Slice(dc, p2) ELSE idn2));~ Local keep := For k := @cols Do (k > nd OR Sum(dl = Slice(names, k), dl) = 0);~ LocalIndex pos := Subset(keep);~ LocalIndex Column := CopyIndex(names[cols = pos]);~ Local out := flat2[.Col = pos];~ out[@pos = @Column]~ ) NodeLocation: 840,137,1 NodeSize: 80,28 Variable Csv_sheet_table Title: Spreadsheet preview Description: Exactly what Write review to spreadsheet will write: Flat data minus Leave out columns, spread by Spread across columns. Definition: Csv_sheet_layout(Csv_view_flat, Csv_sheet_spread, Csv_sheet_leave_out) NodeLocation: 1064,50,1 NodeSize: 80,28 Index Csv_aggregation_types Title: Aggregation types Definition: ['Sum','Min','Max','Average','Show all','Percentiles'] NodeLocation: 168,137,1 NodeSize: 80,28 Index Csv_aggregation_percentile Title: Percentiles Definition: [0.05,0.25,0.5,0.75,0.95] NodeLocation: 392,137,1 NodeSize: 80,28 Function Csv_return_percentiles(x: [I]; I: Index; p: Optional = Csv_aggregation_percentile) Title: Return percentiles Definition: GetFract(x, p, I) NodeLocation: 616,137,1 NodeSize: 80,28 Function Csv_aggregate(rdb: [row, col]; row, col, dimCol: Index; method: Atomic Text) Title: Aggregate flat data Definition: Local adjMethod := IF method = 'Show all' THEN 'First'~ ELSE IF method = 'Percentiles' THEN Identifier of Csv_return_percentiles~ ELSE method;~ LocalIndex stdCols := Concat(dimCol, Slice(col, Size(col)));~ LocalIndex cols := IF method = 'Show all' THEN Concat('Slice', stdCols) ELSE CopyIndex(stdCols);~ Local data := IF method = 'Show all'~ THEN (~ LocalIndex excludedCols := #SetDifference(\col, \stdCols);~ Local joinExcluded := JoinText(rdb[col = excludedCols], excludedCols, '|');~ IF cols = 'Slice' THEN joinExcluded ELSE rdb[col = cols]~ )~ ELSE rdb[col = cols];~ MdTable(data, data.Row, cols, '.' & cols, adjMethod) NodeLocation: 168,225,1 NodeSize: 80,28 Variable Csv_view_aggregated Title: Aggregated view Definition: Csv_aggregate(Csv_view_flat, Csv_view_flat.Row, Csv_view_flat.Column, Csv_view_by, Csv_aggregation_method) NodeLocation: 392,225,1 NodeSize: 80,28 Function Csv_col_letter(n: Atomic) Title: Spreadsheet column letter Description: 1 -> A, 26 -> Z, 27 -> AA ... Definition: Local s := '';~ Local k := n;~ While k > 0 Do (~ Local r := Mod(k - 1, 26);~ s := Chr(65 + r) & s;~ k := Floor((k - 1) / 26)~ );~ s NodeLocation: 616,225,1 NodeSize: 80,28 Function Csv_col_number(t: Atomic Text) Title: Spreadsheet column number Description: A -> 1, Z -> 26, AA -> 27 ... Definition: Local u := TextUpperCase(t);~ Local n := 0;~ Local i := 1;~ While i <= TextLength(u) Do (~ n := n * 26 + (Asc(SelectText(u, i, i)) - 64);~ i := i + 1~ );~ n NodeLocation: 840,225,1 NodeSize: 80,28 Function Csv_write_to_spreadsheet(t: [r, c]; r, c: Index; filePath, sheetName, startCell: Atomic Text; keepTab: Atomic) Title: Write a table to a spreadsheet tab Description: Generic helper: writes a 2-D table (rows r, columns c) to tab sheetName of filePath, header row at startCell (e.g. 'A1').~ keepTab = 1: an existing tab is kept and written into (formatting kept; cells outside the new data are untouched).~ keepTab = 0: an existing tab is deleted and recreated. A missing tab is always added.~ If the file does not exist it is copied from Template workbook; if there is no template either, a new workbook is created~ (SpreadsheetOpen('New'), which may not work in every Analytica version - the error message then says what to do).~ Needs Analytica Developer edition or higher; the 'Excel' backend also needs Excel installed. Definition: Local isNew := NOT Csv_file_exists(filePath);~ IF isNew AND Csv_file_exists(Csv_spreadsheet_template) THEN FileSystemCopy(Csv_spreadsheet_template, filePath);~ Local fromScratch := NOT Csv_file_exists(filePath);~ Local wb := IF fromScratch THEN SpreadsheetOpen('New', showDialog: 0, backend: Csv_spreadsheet_backend)~ ELSE SpreadsheetOpen(filePath, showDialog: 0, backend: Csv_spreadsheet_backend);~ Local sh := SelectText(sheetName, 1, 31);~ Local sc := Csv_label(startCell);~ Local sc2 := IF sc = '' THEN 'A1' ELSE sc;~ Local col0 := Csv_col_number(TextReplace(sc2, '[0-9]', '', all: True, re: True));~ Local row0 := ParseNumber(TextReplace(sc2, '[A-Za-z]', '', all: True, re: True));~ Local c1 := Csv_col_letter(col0);~ Local c2 := Csv_col_letter(col0 + Size(c) - 1);~ Local hdrRange := c1 & Csv_label(row0) & ':' & c2 & Csv_label(row0);~ LocalIndex shI := SpreadsheetInfo(wb, 'Sheets');~ Local has := Sum(shI = sh, shI) > 0;~ Local keep := has AND keepTab = 1;~ IF has AND NOT keep THEN SpreadsheetSetRange(wb, 'A1', Null, sheet: '-' & sh);~ SpreadsheetSetRange(wb, hdrRange, c, c, sheet: IF keep THEN sh ELSE '+' & sh);~ IF Size(r) > 0 THEN SpreadsheetSetRange(wb, c1 & Csv_label(row0 + 1) & ':' & c2 & Csv_label(row0 + Size(r)), t, c, r, sheet: sh);~ SpreadsheetSave(wb, filePath);~ IF NOT Csv_file_exists(filePath) THEN Error(f"Could not create {filePath}. No template workbook was found ({Csv_spreadsheet_template}) and this Analytica version could not create a new workbook by itself. Put Blank_workbook.xlsx (it comes with the library) next to your model, or set Template workbook to any existing .xlsx file.");~ filePath NodeLocation: 168,312,1 NodeSize: 80,28 Button Csv_write_view_button Title: Write review to spreadsheet Description: Writes Spreadsheet preview (Flat data minus Leave out columns, optionally spread across columns) to the review workbook, using the spreadsheet settings shown above the button. OnClick: Local t := Csv_sheet_table;~ Local f := Csv_review_file;~ Local fdir := TextReplace(f, '\\[^\\]*$', '', re: True);~ IF NOT Csv_ensure_folder(fdir) THEN Error(f"The folder {fdir} does not exist and could not be created (creating folders needs Analytica Enterprise or higher). Create it in Windows and try again.");~ Local tab := Csv_tab_for(Csv_view_output);~ Local keep := IF Csv_spreadsheet_tab_mode = 'Replace the tab' THEN 0 ELSE 1;~ Csv_write_to_spreadsheet(t, t.Row, t.Column, f, tab, Csv_spreadsheet_start_cell, keep);~ MsgBox(f"Wrote {Size(t.Row)} rows to tab '{tab}' of {f}", 64, 'Write to spreadsheet') NodeLocation: 392,312,1 NodeSize: 80,28 Button Csv_write_all_button Title: Write all outputs to spreadsheet Description: Writes every output in Outputs to save (that has data in the folders being read) to its tab from Tab for each output, using Scenarios to show, Leave out columns, Spread across columns and the other spreadsheet settings. OnClick: Local f := Csv_review_file;~ Local fdir := TextReplace(f, '\\[^\\]*$', '', re: True);~ IF NOT Csv_ensure_folder(fdir) THEN Error(f"The folder {fdir} does not exist and could not be created (creating folders needs Analytica Enterprise or higher). Create it in Windows and try again.");~ Local keep := IF Csv_spreadsheet_tab_mode = 'Replace the tab' THEN 0 ELSE 1;~ Local done := For id := Csv_output Do (~ Local fl0 := #Csv_flat_results[Csv_output = id];~ IF Size(fl0.Column) <= 1 THEN '' ELSE (~ Local t := Csv_sheet_layout(Csv_pick_scenarios(fl0), Csv_sheet_spread, Csv_sheet_leave_out);~ Local tab := Csv_tab_for(id);~ Csv_write_to_spreadsheet(t, t.Row, t.Column, f, tab, Csv_spreadsheet_start_cell, keep);~ f"{id} -> '{tab}' ({Size(t.Row)} rows)"~ )~ );~ MsgBox(f"Wrote to {f}:" & Chr(13) & JoinText(done, Csv_output, Chr(13)), 64, 'Write all outputs') NodeLocation: 616,312,1 NodeSize: 80,28 Close Csv_reviewer Close Csv_library Module Ex_model Title: Example (delete after setup) Description: Stand-in for your own model. Delete this module after embedding the library in your model; nothing in the library depends on it. NodeLocation: 930,230,1 NodeSize: 110,30 NodeColor: 0x00d0f0d0 DiagState: 2,80,40,760,620,17,10 Text Te_ex_about Title: About the example Description: A tiny stand-in for a real model: sales by year, region and product grow at a scenario-dependent rate. Use it to see the whole save / read-back cycle before pointing the library at your own outputs. NodeLocation: 380,50,1 NodeSize: 200,44 NodeColor: 0x00f0f0f0 Index Ex_year Title: Year Definition: 2025..2030 NodeLocation: 168,150,1 NodeSize: 80,28 Index Ex_region Title: Region Definition: ['North','South','East'] NodeLocation: 392,150,1 NodeSize: 80,28 Index Ex_product Title: Product Definition: ['Widgets','Gadgets'] NodeLocation: 616,150,1 NodeSize: 80,28 Index Ex_scenario_list Title: Example scenarios Definition: ['Low','Base','High'] NodeLocation: 168,237,1 NodeSize: 80,28 Variable Ex_scenario Title: Example scenario Description: The example takes its scenario from the library's Scenario label (Low, Base or High). In your own model it is the other way round: point Scenario label at your scenario variable. Definition: Csv_label(Csv_scenario_label) NodeLocation: 392,237,1 NodeSize: 80,28 Constant Ex_growth Title: Growth by scenario Units: /yr Definition: Table(Ex_scenario_list)(0.01,0.03,0.06) NodeLocation: 616,237,1 NodeSize: 80,28 Constant Ex_base_sales Title: Base-year sales Units: units/yr Definition: Table(Ex_region,Ex_product)(100,40,80,60,120,30) NodeLocation: 168,325,1 NodeSize: 80,28 Constant Ex_price Title: Price Units: $/unit Definition: Table(Ex_product)(12.5,30) NodeLocation: 392,325,1 NodeSize: 80,28 Variable Ex_sales Title: Sales Units: units/yr Definition: Ex_base_sales * (1 + Ex_growth[Ex_scenario_list = Ex_scenario]) ^ (Ex_year - 2025) NodeLocation: 168,412,1 NodeSize: 80,28 Variable Ex_revenue Title: Revenue Units: $/yr Definition: Sum(Ex_sales * Ex_price, Ex_product) NodeLocation: 392,412,1 NodeSize: 80,28 Variable Ex_total_revenue Title: Total revenue Units: $/yr Definition: Sum(Ex_revenue, Ex_region) NodeLocation: 616,412,1 NodeSize: 80,28 Button Ex_run_all_scenarios Title: Example: export all 3 scenarios (loop) Description: Loops over the example scenarios, recomputes the model for each and exports it. This is the pattern to copy for batch runs in your own model. OnClick: FOR s := Ex_scenario_list DO (~ Csv_scenario_label := s;~ Csv_export_button~ );~ Csv_scenario_label := 'Base'; NodeLocation: 392,500,1 NodeSize: 110,28 Variable Ex_sales_from_csv Title: Sales read back from CSV Units: units/yr Description: How a downstream model uses saved results: one call, indexed by Scenarios found plus Year, Region, Product. Definition: Csv_import('Ex_sales') NodeLocation: 168,587,1 NodeSize: 80,28 Variable Ex_roundtrip_check Title: Round-trip check (expect 0) Units: units/yr Description: Largest difference between Sales computed now and Sales read back from CSV for the current run (handles the split-by-region feature test). Definition: Local imp := Csv_import('Ex_sales');~ Local keyNow := Csv_file_key;~ Local got := IF Csv_split_index = 'Ex_region'~ THEN (For r := Ex_region Do imp[Csv_scenarios = keyNow & Csv_separator & Csv_clean(r)])~ ELSE imp[Csv_scenarios = keyNow];~ Max(Max(Max(Abs(got - Ex_sales), Ex_year), Ex_region), Ex_product) NodeLocation: 392,587,1 NodeSize: 80,28 Variable Ex_revenue_by_scenario Title: Revenue by scenario (from CSV) Units: $/yr Description: Results for all scenarios side by side, without re-running the model. Definition: Csv_import('Ex_total_revenue') NodeLocation: 616,587,1 NodeSize: 80,28 Close Ex_model Close Scenario_Manager_Library