WEAPApplication API Class

The WEAPApplication class contains top-level properties and methods, including access to all other classes.

Note: in the following examples, a reference to WEAP, as in WEAP.ActiveArea, assumes that there is an object named WEAP of class WEAPApplication. This can be created in VBScript by:

SET WEAP = CreateObject("WEAP.WEAPApplication")

In some cases, the script keeps executing before WEAP is ready.  To prevent any problems, it is best to introduce a delay immediately after starting WEAP:

WHILE not WEAP.ProgramStarted
   WScript.Sleep(1000)   ' Pause 1000 milliseconds.  WScript is the built-in Windows scripting object
WEND

However, this is not necessary when running scripts inside WEAP (e.g. using the Call function in an expression, from the menu (Advanced, Scripting, Run), or from the script editor) because an object named WEAP is automatically added to the internal scripting environment.

WEAPApplication Properties and Methods

Example (using VB script)

ActiveArea: Set or get the active WEAP area (i.e., dataset). Read or write.

WEAP.ActiveArea = "Weaping River Basin"   'Note: This is equivalent to WEAP.Areas("Weaping River Basin").Open

PRINT WEAP.ActiveArea.Name

ActiveScenario: Set or get the active scenario. Read or write.

WEAP.ActiveScenario = "Current Accounts"   ' set it using the scenario's name

WEAP.ActiveScenario = WEAP.Scenarios("Current Accounts")  ' or set it by getting a scenario object

Note: This is equivalent to WEAP.Scenarios("Current Accounts").Activate

PRINT WEAP.ActiveScenario.Name

Areas: Get the collection of all WEAP areas. See WEAPAreas for details. Read only.

WEAP.Areas("Weaping River Basin").Open

PRINT WEAP.Areas(1).Name

AreasDirectory: Gets the full path of the folder in which WEAP areas are stored, typically under My Documents. Read only.

PRINT WEAP.AreasDirectory

AreaSetting(Key, Section): Set or get a text value associated with a key (text).  Value is stored in file area.ini in the area subdirectory.  If Section is not specified, will look in section User.  The area.ini file can be a convenient place for the user to store settings that apply to one area.  WEAP-wide settings can also be saved--see Setting and DeleteSetting.

WEAP.AreaSetting("Custom hydrology model") = "SWAT"

WEAP.AreaSetting("Model directory", "SWAT") = "C:\Program Files\SWAT"

IF WEAP.AreaSetting("Custom hydrology model") = "SWAT" THEN

  ...

END IF

AutoCalc: Set or get the Auto Calculation setting. If AutoCalc is FALSE, WEAP will not calculate any expressions in the Data View. Read or write.

WEAP.AutoCalc = FALSE   ' Turn off automatic calculations

BaseYear: Set or get the first year of the study period. Read or write.

WEAP.BaseYear = 2000

PRINT WEAP.BaseYear

Branch(BranchNameOrID): Get the WEAPBranch object for the specified branch name or ID.  You can use either the full name (e.g., "\Supply and Resources\River\Weaping River\Reservoirs\Central Reservoir") or just the final branch name (e.g., "Central Reservoir").  However, if two branches have the same name, only the first one will be chosen.  ID is the internal unique numeric ID of the branch.  (Each branch in the tree has a unique ID.  It is not displayed in WEAP's normal interface but may be useful when automating WEAP.  See WEAPBranch.ID for more information.)  Read only.

WEAP.Branch("\Demand Sites\South City").Variables("Consumption").Expression = "30"

PRINT WEAP.Branch(176).Name

Branches: Get the collection of all visible branches in the tree. Returns a WEAPBranches object. Read only.

Set xla = CreateObject("Excel.Application")

xla.Visible = true

xla.ScreenUpdating = false

Set xlw = xla.Workbooks.Add

Set xls = xlw.sheets.add

r = 1

FOR EACH B in WEAP.Branches

   FOR EACH V in B.Variables

      IF not V.IsResultVariable THEN

        r = r + 1

        xls.Cells(r, 1).Value = B.FullName

        xls.Cells(r, 2).Value = V.Name

        xls.Cells(r, 3).Value = V.Expression

      END IF

   NEXT

NEXT       

BranchesOfType(BranchTypeOrID): Get the WEAPBranches collection of all branches of the specified type.  Read only.  For a given type, equivalent to each of the type-specific functions: CatchmentInflowNode, Catchments, DemandSites, DiversionNodes, Diversions, FlowRequirements, Gauges, GroundwaterNodes, OtherSupplyNodes, Reservoirs, ReturnFlowLinks, ReturnFlowNodes, RiverReaches, Rivers, RunoffInfiltrationLinks, RunoffInfiltrationNodes, RunOfRiverHydropowerNodes, TransmissionLinks, TributaryNodes, WastewaterTreatmentPlants, WithdrawalNodes.  In addition, there are function to access the subset of reservoir on and off a river: LocalReservoirs and RiverReservoirs.  Note: only includes top-level branches for Demand Sites and Catchments, not their descendants.

Valid branch names and their associated ID's:

 

Type Name

TypeID

Catchment

21

Catchment Inflow Node

23

Demand Site

1

Diversion

15

Diversion Outflow

11

Flow Requirement

9

Groundwater

3

Other Supply

5

Reservoir

4

Return Flow

8

Return Flow Node

17

River

6

River Reach

16

River Withdrawal

10

Run of River Hydro

14

Runoff/Infiltration

22

Streamflow Gauge

20

Transmission Link

7

Tributary Inflow

13

Wastewater Treatment Plant

2

' Turn off all catchments

FOR EACH Br IN WEAP.BranchesOfType("Catchment")  ' same as WEAP.Catchments

  Br.ActiveInCurrentAccounts = FALSE

NEXT

 

' Set all demand sites' monthly variation as constant

FOR EACH Br IN WEAP.DemandSites

  Br.Variable("Monthly Variation").Expression = "100 * (Days / DaysInYear)"

NEXT

 

' Set all river reservoirs' buffer coefficients to 0.8

FOR EACH Br IN WEAP.RiverReservoirs

  Br.Variable("Buffer Coefficient").Expression = 0.8

NEXT

 

' Print the list of all river reaches

FOR EACH Br IN WEAP.RiverReaches

  Print Br.FullName

NEXT

 

' Set North Aquifer's Maximum Withdrawal to 200 Million m^3

WEAP.GroundwaterNodes("North Aquifer").Variable("Maximum Withdrawal").Expression = 200

 

BranchExists(BranchName): Check if a branch exists. Read only.

IF WEAP.BranchExists("\Demand Sites\South City") THEN
  WEAP.Branch("\Demand Sites\South City").Variables("Consumption").Expression = "30"
END IF

BranchVariable(BranchName:VariableName): Get the WEAPVariable object for the specified branch and variable. VariableName can be omitted if BranchName only has one variable (e.g., Key Assumptions branches have one variable). Note: This is equivalent to Branch(BranchName).Variables(VariableName). Read only.

WEAP.BranchVariable("\Demand Sites\South City:Consumption").Expression = "30"

Note: This is equivalent to Branch(BranchName).Variable(VariableName)

WEAP.BranchVariable("\Key Assumptions\Drivers\Population Growth Rate").Expression = 1.5  ' Note: Because Key Assumption and Other Assumption branches do not have variable tabs, you do not need to give a variable name when referencing them.

Calculate(LastYear, LastTimestep, AlwaysCalculate, CalledFromLEAP, NumWorkers): Calculate scenarios.  If optional parameter AlwaysCalculate is False, then only calculate scenarios needing calculation; otherwise, force calculation of all scenarios marked for calculation, even if WEAP thinks the calculations are already up to date. This is useful if you have changed values in an input file that WEAP is reading via ReadFromFile.  If optional parameters LastYear and LastTime are given, only calculate up to that year and timestep.  If linked to LEAP and optional parameter CalculateLEAPIfNecessary is false, do not calculate LEAP, even if it needs calculation.  Optional parameter NumWorkers determines if calculations are done in parallel (on multiple instances of WEAP simultaneously).  If NumWorkers = 1, then do not use parallel calculation.  If NumWorkers > 1, then use that many instances.  (This cannot be larger than the number of CPU cores or logical processors on your computer.)  If NumWorkers = 0, use the previous setting for parallel calculation.  This is the default value if the parameter is not included.

CALL WEAP.Calculate   ' Calculate all scenarios, even if WEAP thinks the calculations are already up to date

CALL WEAP.Calculate(2000, 6)  ' Calculate all scenarios up to the 6th timestep of year 2000

CALL WEAP.Calculate(0, 0, false)   ' Only calculate scenarios that need calculation (for all years and timesteps)

CalculationErrors: Get the number of WEAP calculation errors from the just-run WEAP calculation. Read only.

IF WEAP.CalculationErrors > 0 THEN PRINT WEAP.CalculationErrors, " calculation errors"

CalculationTime: Get the calculation time from the just-run WEAP calculation, in seconds. Read only.

PRINT WEAP.CalculationTime, " seconds to calculate"

CalcTS: Get the timestep being calculated.  Read only.

IF WEAP.CalcYear = WEAP.BaseYear and WEAP.CalcTS = WEAP.NumTimeSteps THEN
' Do something in the last timestep of the Current Accounts
END IF

CalcYear: Get the year being calculated.  Read only.

IF WEAP.CalcYear = WEAP.BaseYear THEN
Initialize
END IF

CalledByBranch: If the script containing this statement was called from an expression using the Call function, this will get the WEAPBranch object for the branch that made the call. Read only.

PRINT WEAP.CalledByBranch.FullName

CalledByScenario: If the script containing this statement was called from an expression using the Call function, this will get the WEAPScenario object for the scenario that made the call. Read only.

PRINT WEAP.CalledByScenario.Name

CalledByTimeStep: If the script containing this statement was called from an expression using the Call function, this will get the timestep number (from 1 to NumTimeSteps) for the timestep that made the call. Read only.

IF WEAP.CalledByTimeStep = 6 THEN

...

CalledByVariable: If the script containing this statement was called from an expression using the Call function, this will get the WEAPVariable object for the variable that made the call. Read only.

PRINT WEAP.CalledByVariable.Name

CalledByYear: If the script containing this statement was called from an expression using the Call function, this will get the year number (between BaseYear and EndYear) for the year that made the call. Read only.

IF WEAP.CalledByYear > WEAP.BaseYear THEN

...

Choose(Title, Options, InitiallySelected, ListSeparator): Ask user to choose one or more items from a list of options.  If the optional parameter InitiallySelected is given, it lists the options that are initially checked.  The return value is the list of options selected.  Multiple items are separated by the character specified by optional parameter ListSeparator (which defaults to comma).

 

SelectedDemandSites = WEAP.Choose("Choose Demand Sites to Process", WEAP.DemandSites.FullNameList)

FOR EACH DS IN Split(SelectedDemandSites, ",")

  ' Process selected demand sites

NEXT

' Note: This is equivalent to FOR EACH DS IN WEAP.DemandSites.Choose("Choose Demand Sites to Process")

CreateLink(TypeNameOrID, Source, Destination, ActiveInBaseYear, Preference): Create a new link on the Schematic between two existing nodes, and return the WEAPBranch object for the new link.  Only TypeNameOrID, Source and Destination are required.  TypeNameOrID is the type name or numerical ID for the type to create -- it must be one of the three link types: "Transmission Link", "Return Flow" and "Runoff/Infiltration".  Source is the WEAPBranch object for the node that the link starts on.  Destination is the WEAPBranch object for the node that the link ends on.  For transmission links only there are two additional (optional) parameters.  Set ActiveInBaseYear to True or False to specify whether the transmission link is active in the Current Accounts or not.  If not specified, it will default to true.  Preference is the numeric supply preference of the transmission link (only applies to Transmission Links).  It will default to 1 if blank.  You can use CreateNode (see below) to create nodes on the Schematic.

' Try the following example in Weaping River Basin

Set NorthCity = WEAP.CreateNode("Demand Site", -70.88, 42, "North City", "North;City", True, 2)

Print NorthCity.FullName & " is located at " & FormatNumber(NorthCity.X, 2) & ", " & FormatNumber(NorthCity.Y, 2)   ' Demand Sites\North City is located at -70.879997253418, 42

Set NewGWLink = WEAP.CreateLink("Transmission Link", WEAP.Branch("North Aquifer"), NorthCity)

Print NewGWLink.FullName & " goes from (" & FormatNumber(NewGWLink.X, 2) & ", " & FormatNumber(NewGWLink.Y, 2) & "), to (" & FormatNumber(NewGWLink.X2, 2) & ", " & FormatNumber(NewGWLink.Y2, 2) & ")"

Set NewWithdrawalNode = WEAP.CreateNode("River Withdrawal", -70.886, 41.97, "Withdrawal for North City")

Set NewRiverLink = WEAP.CreateLink("Transmission Link", NewWithdrawalNode, NorthCity)

Set NewRiverReturnLink = WEAP.CreateLink("Return Flow", NorthCity, NewWithdrawalNode)

CreateNode(TypeNameOrID, X, Y, Name, MapLabel, ActiveInBaseYear, Priority, IsIrrigated, River): Create a new node on the Schematic at the X,Y coordinates, and return the WEAPBranch object for the new node.  Only TypeNameOrID, X, Y and Name are required.  TypeNameOrID is the type name or numerical ID for the type to create, e.g., "Demand Site", "Catchment", "Reservoir", etc.  See WEAPBranch.TypeName for the list of Type Names and IDs.  X, Y are the x, y coordinates of the center of the new node, in the coordinate system of the projection used for the WEAP model.  For example, if it is unprojected WGS84, X is longitude and Y is latitude.  For river nodes, the X, Y coordinates must be on or very close to an existing river line.  Name is the name to give the new node.  The optional MapLabel is the label to use for the Schematic -- leave it blank to have it be the same as Name (except for minor river nodes, which will default to no map label), or specify a single space (" ") to not show any label on the Schematic.  Set ActiveInBaseYear to True or False to specify whether the node is active in the Current Accounts or not.  If not specified, it will default to True.  The optional Priority is the numeric demand priority of the node (only applies to Demand Sites, Catchments, Flow Requirements and Reservoirs).  It will default to 1 if blank (99 for reservoirs).  For catchments, set IsIrrigated to True or False to specify whether the catchment is irrigated.  If not specified, it will default to False.  You can use CreateLink (see above) to create Transmission Links, Return Flow links and Runoff/Infiltration links.  If a River name is given, then the new node will be placed on that river.  Use River = "N/A" to force the node to not be placed on a river, e.g., to make the new reservoir a "Local" reservoir.

' Try the following example in Weaping River Basin

Set NorthCity = WEAP.CreateNode("Demand Site", -70.88, 42, "North City", "North;City", True, 2)

Print NorthCity.FullName & " is located at " & FormatNumber(NorthCity.X, 2) & ", " & FormatNumber(NorthCity.Y, 2)   ' Demand Sites\North City is located at -70.879997253418, 42

Set NewGWLink = WEAP.CreateLink("Transmission Link", WEAP.Branch("North Aquifer"), NorthCity)

Print NewGWLink.FullName & " goes from (" & FormatNumber(NewGWLink.X, 2) & ", " & FormatNumber(NewGWLink.Y, 2) & "), to (" & FormatNumber(NewGWLink.X2, 2) & ", " & FormatNumber(NewGWLink.Y2, 2) & ")"

Set NewWithdrawalNode = WEAP.CreateNode("River Withdrawal", -70.886, 41.97, "Withdrawal for North City")

Set NewRiverLink = WEAP.CreateLink("Transmission Link", NewWithdrawalNode, NorthCity)

Set NewRiverReturnLink = WEAP.CreateLink("Return Flow", NorthCity, NewWithdrawalNode)

Set SouthReservoir = WEAP.CreateNode("Reservoir", -70.88, 42, "South Reservoir", "South;Reservoir", false, 99, "Weaping River")

Set WestReservoir = WEAP.CreateNode("Reservoir", -71.88, 42, "West Reservoir", "West;Reservoir", false, 99, "N/A")

 

CreateRiver(TypeNameOrID, X1, Y1, X2, Y2, Name, MapLabel, ActiveInBaseYear): Create a new river or diversion node on the Schematic, starting at X1,Y1 and ending at X2,Y2, and return the WEAPBranch object for the new river.  All parameters except MapLabel and ActiveInBaseYear are required.  TypeNameOrID is the type name or numerical ID for the type to create, either "River" or "Diversion," or 6 (river) or 15 (diversion).  X1, Y1 and X2, Y2 are the x, y coordinates of first and last points of the river line, in the coordinate system of the projection used for the WEAP model.  For example, if it is unprojected WGS84, X is longitude and Y is latitude.  After the river is created, you can add addition points with WEAPBranch.AddPoint.  Name is the name to give the new river.  The optional MapLabel is the label to use for the Schematic -- leave it blank to have it be the same as Name, or specify a single space (" ") to not show any label on the Schematic.  Set ActiveInBaseYear to True or False to specify whether it is active in the Current Accounts or not -- this only applies to diversions, because rivers are always active.  If not specified, it will default to True.  To connect one river or diversion to another, use WEAPBranch.HeadflowNode or WEAPBranch.TailflowNode.

CALL WEAP.CreateRiver("River", -71, 42, -70.9, 41.8, "Green River", "Green;River")    

CALL WEAP.CreateRiver("Diversion", -70.876, 41.96, -70.88, 41.96, "Yellow Canal", " ", False)    

 

DataExpression(BranchVariableName, InheritIfNecessary): Set or get the data expression for the branch:variable. Because a blank expression will default to the expression from the parent scenario, use FALSE for the optional parameter InheritIfNecessary to prevent inheriting from the scenario.

WEAP.DataExpression("\Demand Sites\South City:Annual Activity Level") = "Growth(3%)"

PRINT WEAP.DataExpression("\Demand Sites\South City:Annual Activity Level")

IF WEAP.DataExpression("\Demand Sites\South City:Annual Activity Level", FALSE) = "" THEN 'check if blank in active scenario
  WEAP.DataExpression("\Demand Sites\South City:Annual Activity Level") = "Growth(3%)"
END IF

DeleteAreaSetting(Key, Section): Delete a text value associated with a key (text) (previously saved by WEAP.AreaSetting), from file area.ini in the area subdirectory.  If Section is not specified, will look in section User.  The area.ini file can be a convenient place for the user to store settings that apply to one area.  WEAP-wide settings can also be saved--see Setting and DeleteSetting.

CALL WEAP.DeleteAreaSetting("Custom hydrology model")

DeleteResults: Delete all results files for the active area.  This might speed up calculations, if the results file contain previously calculated results from many scenarios, but you only want to look at results for one or a few scenarios.

CALL WEAP.DeleteResults

DeleteSetting(Key, Section): Delete a text value associated with a key (text) (previously saved by WEAP.Setting), from file weap.ini in the WEAP main directory.  If Section is not specified, will look in section User.  The weap.ini file can be a convenient place for the user to store settings that apply to all of WEAP.  Area-specific settings can also be saved--see AreaSetting and DeleteAreaSetting.

CALL WEAP.DeleteSetting("PEST directory")

DictionaryVersion: Get the WEAP data dictionary version number. Read only.

PRINT "WEAP data dictionary version "; WEAP.DictionaryVersion

Directory: Get the directory where the WEAP program is located. Read only.

PRINT "WEAP is located in "; WEAP.Directory

DiscountRate: Get or set the area-wide real discount rate (percent).  Can also be set in WEAP from the Main Menu: General, Units, Monetary.  Read or write.

WEAP.DiscountRate = 3     ' Sets real discount rate to 3%

DisplayFile(Filename, ReadOnly): Display text file named Filename.  If optional ReadOnly parameter is TRUE, do not allow editing.

If MsgBox("Report created: " & CHR(13) & ReportFilename & CHR(13) & CHR(13) & "Do you want to view it?", 4 + 32 + 256, "View Report?") = 6 then

  CALL WEAP.DisplayFile(ReportFilename, TRUE)

End If                                   

DownloadFile(URL, Filename, ShowProgress): Download a file from the internet.  Returns TRUE if successful.  Set optional ShowProgress parameter to FALSE to now show download progress dialog.

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       LineNumber = WEAP.SearchFile(Filename, "Date,Snow Water Equivalent (in) Start of Day Values")

       IF LineNumber > 0 THEN

          TheLine = WEAP.ReadLineFromFile(Filename, LineNumber)

          NewLine = "$DateFormat=yyyy-mm-dd" & CHR(13) + CHR(10) + "$Columns=" + TheLine   ' Add DateFormat and Columns directives

          CALL WEAP.ModifyFile(Filename, LineNumber, NewLine)

       END IF

   END IF

END IF

EndYear: Set or get the last year of the study period. Read or write.

WEAP.EndYear = 2020

PRINT WEAP.EndYear

ExportExpressions(NewWorkbook, ExportAllBranches, ExportAllVariables, ExportAllScenarios, ExportBlankExpressions, ExportInheritedExpressions, AutoFilter): Use this option to export to Excel some or all of the data expressions in WEAP. This process will allow you to link your WEAP expressions to Excel values for later import back into WEAP. See ImportExpressions for details of importing. In addition, Excel, with its filtering capabilities, provides a convenient way to view your data.  All parameters are True/False and are optional -- if omitted, all default to True, except for ExportBlankExpressions and ExportInheritedExpressions, which both default to False.  Can only be used in the Data View.  See Export Expressions to Excel for more information.

CALL WEAP.ExportExpressions   ' export expressions for all branches, variables and scenarios to Excel

CALL WEAP.ExportExpressions(True, False, True, False)    ' Export expressions for all variables for the current branch and scenario to Excel

If the filename has the .xls or .xlsx extension, the table will be exported to an Excel file. Otherwise, it will be exported to a CSV file.

ExportGaugeComparisonStatistics(CSVFilename, IncludeTitle, IncludeColTitles, ForceTranspose): Export the table of gauge comparison statistics (e.g., NSE, KGE, PBIAS) to a comma separated value (CSV).  Will switch to Results View if necessary, calculating results as needed.  Only available when a gauge comparison result chart is loaded, e.g., Streamflow Gauge Comparison, Reservoir Storage Gauge Comparison, Snow Gauge Comparison.  Only statistics currently shown are exported (can be changed with WEAP.ResultSetting("Statistic").).  All parameters except CSVFilename are optional and default to True: IncludeTitle, IncludeColTitles, ForceTranspose.  If IncludeTitle = FALSE, do not include a title in the file. If IncludeColumnTitles = FALSE, do not have a row with column titles. If Transpose is FALSE, there will be a row for each statistic; if Transpose is TRUE or not included, there will be a column for each statistic

ExportGaugeComparisonStatistics(ExcelFilename): Export the table of gauge comparison statistics (e.g., NSE, KGE, PBIAS) to an Excel (XLSX) file. Will switch to Results View if necessary, calculating results as needed.  Only available when a gauge comparison result chart is loaded, e.g., Streamflow Gauge Comparison, Reservoir Storage Gauge Comparison, Snow Gauge Comparison.  Only statistics currently shown are exported (can be changed with WEAP.ResultSetting("Statistic").).  

See also WEAP.GaugeComparisonStatistic

WEAP.ResultSetting("Variable") = "Streamflow Gauge Comparison"

FOR EACH SFGauge in WEAP.Gauges

  CALL WEAP.ExportGaugeComparisonStatistics(SFGauge.Name + ".csv")

NEXT

If the filename has the .xls or .xlsx extension, the table will be exported to an Excel file. Otherwise, it will be exported to a CSV file.

ExportResults(CSVFilename, IncludeTitle, IncludeColumnTitles, Transpose, ReadFromFileFormat, LongFormat, IncludeStats, ScaleValues): Save active table (Data View, Results View, Scenario Explorer View) to a comma separated value (CSV) file. If in Schematic View, will switch to Results View, calculating results as needed. All parameters except CSVFilename are optional.  If IncludeTitle = FALSE, do not include a title in the file. If IncludeColumnTitles = FALSE, do not have a row with column titles. If Transpose is TRUE, transpose the rows and columns.  If IncludeStats is TRUE, include rows and columns for totals and any other statistics that are shown, e.g., Min, Max, Std. Dev.  If ScaleValues is TRUE, export values using the current scale (e.g., Million Cubic Meters); if false, without any scale (e.g., Cubic Meters).  If ReadFromFileFormat is TRUE, save in the format expected by the ReadFromFile function (one line per timestep).  If LongFormat is TRUE then save results in a format more suitable to Tableau and other visualization tools, with each result value on a separate line of the CSV file.  This only works in the Results View.  IncludeTitle and IncludeColumnTitles default to TRUE if omitted, whereas Transpose, ReadFromFileFormat, LongFormat, IncludeStats and ScaleValues default to FALSE if omitted.  If LongFormat is TRUE, the values for the other TRUE/FALSE parameters (except ScaleValues) will be ignored.

ExportResults(ExcelFilename): Save active table (Data View, Results View, Scenario Explorer View) to an Excel (XLSX) file. If in Schematic View, will switch to Results View, calculating results as needed. If there are more than 256 columns (e.g., 30 years of monthly results would be 30*12 = 360 columns), the table will be transposed.

Note: ExportResults works in the Data, Results and Scenario Explorer Views.  Precision will depend on value of WEAP.ResultsExportPrecision.

CALL WEAP.ExportResults("C:\Groundwater.csv")

CALL WEAP.ExportResults("C:\Groundwater.csv", FALSE)

CALL WEAP.ExportResults("C:\Groundwater.csv", TRUE, FALSE)

CALL WEAP.ExportResults("C:\Groundwater.csv", TRUE, FALSE, TRUE)

CALL WEAP.ExportResults("C:\Groundwater.csv", TRUE, FALSE, TRUE, TRUE)

CALL WEAP.ExportResults("C:\Groundwater for Tableau.csv", TRUE, FALSE, TRUE, FALSE, TRUE)

CALL WEAP.ExportResults("C:\Groundwater.csv", TRUE, TRUE, FALSE, FALSE, FALSE, TRUE)

CALL WEAP.ExportResults("C:\Groundwater.csv", TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE)

 

CALL WEAP.LoadOverview("Default")

CALL WEAP.ExportResults("C:\Overview.xls")

FileDate(Filename): Get the date the file was last modified.  Returns 1/1/1900 if file does not exist.

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       LineNumber = WEAP.SearchFile(Filename, "Date,Snow Water Equivalent (in) Start of Day Values")

       IF LineNumber > 0 THEN

          TheLine = WEAP.ReadLineFromFile(Filename, LineNumber)

          NewLine = "$DateFormat=yyyy-mm-dd" & CHR(13) + CHR(10) + "$Columns=" + TheLine   ' Add DateFormat and Columns directives

          CALL WEAP.ModifyFile(Filename, LineNumber, NewLine)

       END IF

   END IF

END IF

FileDateTime(Filename): Get the date and time the file was last modified.  Returns 1/1/1900 00:00:00 if file does not exist.

 

Print "StreamflowGauges.csv was last updated on " & WEAP.FileDateTime("StreamflowGauges.csv")

FileExists(Filename): Return True if file exists, False if not.

Filename = WEAP.ActiveAreaDirectory + "ReservoirStorage.csv"

IF NOT WEAP.FileExists(Filename) THEN

  WEAP.ExportResults(Filename)

END IF

Filter: Set or get the Filter for the Schematic and Data Tree.  The Filter can selectively show or hide objects on the Schematic and Data View Tree based on their scenario, type and tags.

WEAP.Filter = "Scenario <> Current Accounts"   ' Only show objects that are not active in Current Accounts

WEAP.Filter = "Type = Demand Site or Type = Wastewater Treatment Plant"    ' only show demand sites and wastewater treatment plants

WEAP.Filter = ""       ' Remove the filter (show everything)

FinalizeInteractiveCalculations(ErrorMesssage): Stops interactive calculations.   If optional parameter ErrorMessage is given, the error message will be shown to user and added to "Messages" tab in Results View.  See InitializeInteractiveCalculations below for information on interactive calculations.

WEAP.FinalizeInteractiveCalculations

 

WEAP.FinalizeInteractiveCalculations("Error reading results from external model")

FirstTimeStep: Deprecated -- use WaterYearStart instead (which can get and set).  Get the index for the first timestep of the water year.

PRINT WEAP.FirstTimeStep    ' if the water year begins in October, this would be 10

WEAP.FirstTimeStep = 3      ' set the water year start to March

Note: FirstTimeStep is equivalent to Timesteps(1).CalendarIndex

GaugeComparisonStatistic(StatisticName): Get the value of a gauge comparison statistic (N, Missing, NSE, KGE, NRMSE, PBIAS, RSR, LogNSE, InvNSE, SqrtNSE, RMSE, MAE, r, r^2).  Must be in Results View with a gauge comparison chart loaded (e.g., Streamflow Gauge Comparison, Reservoir Gauge Comparison, Snow Gauge Comparison).  Any statistic is available, even if it is not currently shown on the chart.  See also WEAP.ExportGaugeComparisonStatistics

WEAP.ResultSetting("Variable") = "Streamflow Gauge Comparison"

FOR EACH SFGauge in WEAP.Gauges

  CALL WEAP.PrintToFile("GaugeStats.csv", WEAP.List(",", SFGauge.Name, WEAP.GaugeComparisonStatistic("N"), WEAP.GaugeComparisonStatistic("NSE"), WEAP.GaugeComparisonStatistic("PBias"), WEAP.GaugeComparisonStatistic("r^2")))

NEXT

ImportExpressions: Import expressions from current Excel worksheet.  Before using this option you must have created and opened a spreadsheet in Excel containing the data you wish to import. This spreadsheet must be strictly formatted with the names of branches, scenarios and variables as the rows of the spreadsheet. The only practical way to create such a spreadsheet is to first use the ExportExpressions API command (main menu: Edit, Export to Excel). Can only be used in the Data View.  See Import Expressions from Excel for more information.

WEAP.ImportExpressions   ' Import expressions from active Excel worksheet

IncludeLeapDays: True if the timestep which includes February 29 will have an extra day in leap years.  Read only.

IF WEAP.IncludeLeapDays Then ...

InitializeInteractiveCalculations: Starts interactive calculations.  Returns True if successful, False if there was a problem.  

Interactive calculations make it possible to calculate a single timestep in WEAP and then perform other tasks in a script before calculating the next timestep, such as transferring WEAP results for the timestep just calculated to another model that is run and results from it are imported back into WEAP.  During the pause between timestep calculations, you may change data expressions; you can change any CSV files that WEAP is reading via the ReadFromFile expression and that new file will be used for subsequent timesteps' calculations; and you can get access to result values that have been calculated in this or a previous timestep, using WEAP.ResultValue.

See also: WEAPApplication.FinalizeInteractiveCalculations, WEAPApplication.IsCalculatingInteractively, WEAPScenario.InitializeInteractiveCalculations, WEAPScenario.CalculateNextTimestep, WEAPScenario.IsCalculatingInteractively and WEAPScenario.FinalizeInteractiveCalculations.

IF WEAP.InitializeInteractiveCalculations THEN

  FOR EACH S IN WEAP.Scenarios

    IF WEAP.Status AND S.ResultsShown AND S.InitializeInteractiveCalculations THEN

      KeepCalculating = TRUE   

      WHILE KeepCalculating

        KeepCalculating = S.CalculateNextTimestep    ' CalculateNextTimestep = FALSE after last timestep in scenario is calculated

        Perform some other tasks...    ' Use WEAP.CalcYear and WEAP.CalcTS to determine which timestep was just calculated

      WEND

      S.FinalizeInteractiveCalculations

    END IF

  NEXT

  IF WEAP.Status THEN

    WEAP.FinalizeInteractiveCalculations

  ELSE

    WEAP.FinalizeInteractiveCalculations "There was an error calculating."    

  END IF

END IF

 

SET S = WEAP.Scenario("Reference")

IF WEAP.InitializeInteractiveCalculations AND S.InitializeInteractiveCalculations THEN

  FOR y = S.FirstYear to S.LastYear

    FOR ts = 1 TO WEAP.NumTimeSteps

      S.CalculateNextTimestep

      Perform some other tasks...

    NEXT

  NEXT

  S.FinalizeInteractiveCalculations

  WEAP.FinalizeInteractiveCalculations

END IF

IsCalculating: True if WEAP is calculating, False if not.  Read Only.

IF WEAP.IsCalculating THEN ...

IsCalculatingInteractively: True if WEAP is calculating interactively, False if not.  See InitializeInteractiveCalculations above for information on interactive calculations.  Read Only.

IF NOT WEAP.IsCalculatingInteractively Then ...

    WEAP.InitializeInteractiveCalculations

List(ListSeparator, Value1, Value2, ...): Get string with list of parameters separated by commas or any other separator character or text.  This can be a convenient method for outputting lines to a CSV file.  Values can be text, number, dates, times or boolean values.  Up to 30 values can be listed.  All value parameters are optional.

Print WEAP.List(",", Date(), Time(), WEAP.ActiveAreaDirectory, WEAP.BaseYear, WEAP.EndYear, WEAP.Scenarios.Count, crWEAP.Branches.Count, WEAP.DemandSites.Count)

LoadFavorite(FavoriteName): Load predefined report format, which had been previously saved as a WEAP "favorite." Will switch to Results View if necessary, calculating results as needed.

CALL WEAP.LoadFavorite("Groundwater Storage")

LoadOverview(OverviewName): Load previously saved WEAP "overview." Will switch to Scenario Explorer View if necessary, calculating results as needed. Tip: Once an overview has been loaded, you may use WEAP.ExportResults to save all the tables to a CSV or Excel file.

CALL WEAP.LoadOverview("Default")

LogCalculationErrors: Set or get value -- if true, log all "calculation" errors and warnings to WEAP.LogFile.  Calculation errors are those that appear on the Messages tab in the Results View.

WEAP.LogCalculationErrors = TRUE

Logfile: Set or get the file to which errors and warnings are logged (only if Verbose is 0, 1 or 2).  Note: these errors and warning are not the same as "calculation" errors -- those that appear on the Messages tab in the Results View.  If you do not set it, it will default to WEAP.AreasDirectory + "WEAP_Errors.txt"

WEAP.Logfile = WEAP.Directory + "Errors.txt"

ModflowCellHead(Scenario, Year, TimeStepNumber, Layer, Row, Column): Get the cell head for a given MODFLOW cell.  Year is the water year and TimeStepNumber is the index from the start of the water year.

PRINT WEAP.ModflowCellHead("Reference", 2020, 6, 1, 7, 7)

ModifyFile(Filename, LineNumber, NewText): Replace specified line number of text file with new text.  Line number 0 means add to beginning of file; use negative LineNumbers to count from end, e.g., -1 is last line, -2 is second from last line.

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

' NOTE: See WEAP.ReplaceInFile for an easier way to do the same thing

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       LineNumber = WEAP.SearchFile(Filename, "Date,Snow Water Equivalent (in) Start of Day Values")

       IF LineNumber > 0 THEN

          TheLine = WEAP.ReadLineFromFile(Filename, LineNumber)

          NewLine = "$DateFormat=yyyy-mm-dd" & CHR(13) + CHR(10) + "$Columns=" + TheLine   ' Add DateFormat and Columns directives

          CALL WEAP.ModifyFile(Filename, LineNumber, NewLine)

       END IF

   END IF

END IF

NumErrors: Get or reset the number of errors this session from using API property and method calls..

IF WEAP.NumErrors > 0 THEN PRINT WEAP.NumErrors; " Errors"

NumTimeSteps: Get the number of time steps in each year (e.g., 12). Read only.

PRINT WEAP.NumTimeSteps

Note: This is equivalent to WEAP.Timesteps.Count

PrevTSCalcTS: Integer: Get the timestep of the previous calculation timestep.  Read only

PRINT WEAP.BranchVariable("\Demand Sites\South City:Supplied").Value(WEAP.PrevTSCalcYear, WEAP.PrevTSCalcTS)

PrevTSCalcYear: Integer: Get the year of the previous calculation timestep.  Read only.

PRINT WEAP.BranchVariable("\Demand Sites\South City:Supplied").Value(WEAP.PrevTSCalcYear, WEAP.PrevTSCalcTS)

Print(Number or text): Prints a number or a text string.  Print statements are sent to the APIPrint.txt file.  This file is automatically monitored and displayed in WEAP's Script Editor. If no parameter is giving, a blank link is printed.

CALL WEAP.Print("The current calculation year is " & WEAP.CalcYear)

PrintToFile(FileName, Number or text, Append): Prints a number or a text string to a named text file.  The value of the optional parameter Append will determine what WEAP will do if the file already exists: if Append is TRUE (or not specified), WEAP will add the number or text to the end of the existing file.  Otherwise, the file will be cleared before writing the number or text to it.

CALL WEAP.PrintToFile("C:\Results.txt", "Results from scenario: " + WEAP.ActiveScenario.Name, TRUE)

CALL WEAP.PrintToFile("C:\AreaCount.txt", WEAP.Areas.Count, FALSE)

ProgramDirectory: Gets the full path of the folder in which WEAP is installed. Read only.

CALL PRINT WEAP.ProgramDirectory

ProgramStarted: Determine if WEAP has finished starting up. Can be used to make sure WEAP is loaded before continuing in the script. Read only.

WEAP = CreateObject("WEAP.WEAPApplication")
WHILE NOT WEAP.ProgramStarted
  ' do nothing
WEND

Quit: Exit WEAP.  If there are any unsaved changes, they will not be saved when WEAP closes.

WEAP.Quit

ReadLineFromFile(Filename, LineNumber): Read specified line from text file, where 1 is first line of file.  Use negative LineNumbers to count from end, e.g., -1 is last line, -2 is second from last line.

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

' NOTE: See WEAP.ReplaceInFile for an easier way to do the same thing

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       LineNumber = WEAP.SearchFile(Filename, "Date,Snow Water Equivalent (in) Start of Day Values")

       IF LineNumber > 0 THEN

          TheLine = WEAP.ReadLineFromFile(Filename, LineNumber)

          NewLine = "$DateFormat=yyyy-mm-dd" & CHR(13) + CHR(10) + "$Columns=" + TheLine   ' Add DateFormat and Columns directives

          CALL WEAP.ModifyFile(Filename, LineNumber, NewLine)

       END IF

   END IF

END IF

Registered: Returns true if WEAP is registered (licensed).  WEAP must be registered in order to save changes to data, or to use the API.  Read only.

IF NOT WEAP.Registered THEN PRINT "Because WEAP is not registered, you cannot use the API"

ReplaceInFile(FileName, SearchText, ReplaceText, ReplaceAll, IgnoreCase): Search a text file for SearchText; if found, replace it with ReplaceText.  Replace all instances in file unless optional parameter ReplaceAll is FALSE.  Ignore case (upper vs. lower case) unless optional IgnoreCase is FALSE.  Return the number of instances found and replaced (zero if none found).

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       SearchText = "Date,Snow Water Equivalent (in) Start of Day Values"

       ReplaceText = "$DateFormat=yyyy-mm-dd" + CHR(13) + CHR(10) + "$Columns=" + SearchText ' Add DateFormat and Columns directives

       NumReplaced = WEAP.ReplaceInFile(Filename, SearchText, ReplaceText, FALSE)

   END IF

END IF

ResultExists(BranchName:VariableName, Year, TimeStepNumber, Scenario): Return TRUE if the result exists for that scenario, year and timestep, FALSE if not.  (For example, River Flood Inflow only exists for catchment branches if there is non-zero flooding inflow in that timestep.)

IF NOT WEAP.ResultExists("\Demand Sites and Catchments\Irrigation District:River Flood Inflow", 2015, 7, "Reference") THEN

  Print "Cannot find river flood inflow result"

END IF

ResultSetting: Make changes to settings for the currently displayed chart or table in the Results View.  The format is:  WEAP.ResultSetting(Attribute) = Value, e.g., WEAP.ResultSetting("XAxis") = "Year".  In the Scenario Explorer view, you can only set the Scenario and Tag attributes.

 

Attribute

Allowed Values

Variable

Result chart to load, e.g., "Water Demand"

XAxis

"Year" or "Scenario" or "Branch" or "Cost" or "Tag"

Legend

"Scenario" or "Branch" or "Cost" or "Pollutant" or "Tag"

Scenario

"All" or any of the scenario names

Year

"All" or "Year" or "Year1,Year2,..." or "Year1-Year2"

Month

"All" or "Month1" or "Month1,Month2,..." or "Month1-Month2"  Can use month name, abbreviation or number, e.g., January, Jan or 1.

Timestep

Same as Month

Branch

Full branch path, e.g., \Demand Sites\South City or \Supply and Resources\Groundwater\West Aquifer

Cost/Benefit Type

"All" or "Benefit" or "Capital Cost" or "Operating Cost"

Cost

Same as Cost/Benefit Type

WQ Constituent

"All" or any of the water quality constituents

Pollutant

Same as WQ Constituent

Statistic

"All" or any of the gauge comparison statistics.  To select multiple statistics, separate by commas.

Layer

MODFLOW Layer

Row

MODFLOW Row

Column

MODFLOW Column

Tag Category

"All" or "Tag Category1"  (cannot select multiple tag categories)

Tag

"All" or "Tag1" or "Tag1,Tag2,..."

Chart Type

"Bar" or "Line" or "Step" or "Area" or "AreaWithLines" or "Pie" or "Surface"

Levels

1, 2, 3, 4 or 5  (levels of branches to display)

Annual Total

True or False (you may also use "Yes" or "No" for any of these)

Monthly Average

True or False

Color Palette

Color palette name (e.g., Rainbow, Victorian, Reds) or a number from 1 to 30

Stacked

True or False

Group

True or False (if True, then filter values shown by size, either largest or smallest.  See below: GroupNum, GroupLargest, GroupSumRemaining)

GroupNum

If Group = True, number of values to show

GroupAllOthers

True or False (if True, then sum all others into "All Others")

GroupLargest

True or False (if True, then show largest values, else show smallest values)

Y=0

True or False

Exceedance

True or False

Log

True or False

Gridlines

True or False

Patterns

True or False

Line Symbols

True or False

Stat

True or False

3D

True or False

WEAP.ResultSetting("Variable") = "Inflows To Area"

WEAP.ResultSetting("Variable") = "Water Demand"

WEAP.ResultSetting("XAxis") = "Scenario"

WEAP.ResultSetting("X-Axis") = "Year"

WEAP.ResultSetting("Legend") = "Scenario"

WEAP.ResultSetting("Legend") = "Branch"

WEAP.ResultSetting("Scenario") = "All"

WEAP.ResultSetting("Scenario") = "Demand Measures"

WEAP.ResultSetting("Scenario") = "Demand Measures, Supply Measures"

WEAP.ResultSetting("Scenario") = WEAP.Scenarios("Demand Measures")

FOR Scen IN WEAP.Scenarios
WEAP.ResultSetting("Scenario") = Scen

WEAP.ResultSetting("Year") = "All"

WEAP.ResultSetting("Year") = 2015

WEAP.ResultSetting("Year") = "2011,2013,2015"

WEAP.ResultSetting("Year") = "2011,2015-2017"

WEAP.ResultSetting("Month") = "All"

WEAP.ResultSetting("Month") = 3

WEAP.ResultSetting("Month") = "5-7,9,12"

WEAP.ResultSetting("Month") = "Aug"

WEAP.ResultSetting("Month") = "Jan-March"

WEAP.ResultSetting("Timestep") = "1-3,7-9"

WEAP.ResultSetting("Branch") = "\Demand Sites\South City"

WEAP.ResultSetting("Branch") = "\Supply and Resources\Groundwater\West Aquifer"

WEAP.ResultSetting("Branch") = "\Demand Sites\South City, Demand Sites\Industry East"   ' set multiple branches, separating branch names by commas

WEAP.ResultSetting("Branch") = "All"

FOR Br IN WEAP.Branches("\Demand Sites").Children
WEAP.ResultSetting("Branch") = Br

WEAP.ResultSetting("Cost") = "All"

WEAP.ResultSetting("Cost/Benefit Type") = "Capital Cost,Operating Cost"

WEAP.ResultSetting("Pollutant") = "All"

WEAP.ResultSetting("WQ Constituent") = "BOD"

WEAP.ResultSetting("Statistic") = "All"

WEAP.ResultSetting("Statistic") = "NSE"

WEAP.ResultSetting("Statistic") = "N,NSE,PBIAS,RMSE,r^2"

WEAP.ResultSetting("Layer") = 2

WEAP.ResultSetting("Row") = 13

WEAP.ResultSetting("Column") = 10

WEAP.ResultSetting("Tag Category") = "All"

WEAP.ResultSetting("Tag Category") = "Location"

WEAP.ResultSetting("Tag") = All"

WEAP.ResultSetting("Tag") = "West"

WEAP.ResultSetting("Tag") = "West,North"

WEAP.ResultSetting("Chart Type") = "Line"

WEAP.ResultSetting("Chart Type") = "Bar"

WEAP.ResultSetting("Chart Type") = "Step"

WEAP.ResultSetting("Chart Type") = "Area"

WEAP.ResultSetting("Chart Type") = "AreaWithLines"

WEAP.ResultSetting("Chart Type") = "Pie"

WEAP.ResultSetting("Levels") = 2

WEAP.ResultSetting("Annual Total") = True

WEAP.ResultSetting("Monthly Average") = "Yes"

WEAP.ResultSetting("Color Palette") = "Rainbow"

WEAP.ResultSetting("Color Palette") = 15

WEAP.ResultSetting("Stacked") = True

WEAP.ResultSetting("Group") = True    ' Turn on grouping (smallest values grouped into "All Other")

WEAP.ResultSetting("GroupNum") = 8    ' Only show 8 largest values, grouping all others into "All Other"

WEAP.ResultSetting("GroupNum") = 4    ' Only show 4 largest values, grouping all others into "All Other"

WEAP.ResultSetting("GroupAllOthers") = False  ' Do not group all others into "All Other"

WEAP.ResultSetting("GroupLargest") = True    ' Only show largest values

WEAP.ResultSetting("GroupLargest") = False   ' Only show smallest values (and never group others into "All Others"), e.g., only show the smallest values for Demand Site Coverage, in order to focus on the worst cases

WEAP.ResultSetting("Y=0") = True

WEAP.ResultSetting("Exceedance") = False

WEAP.ResultSetting("Log") = False

WEAP.ResultSetting("Gridlines") = False

WEAP.ResultSetting("Patterns") = True

WEAP.ResultSetting("Line Symbols") = True

WEAP.ResultSetting("Stat") = False    ' Do not show statistics (min, max, mean, median, standard deviation, root mean square)

WEAP.ResultSetting("3D") = False

ResultsExportPrecision: Set or get the digits of precision (from 1-15, default is 6) to use when exporting result values (WEAP.ResultValue, WEAP.ExportResults).  It will not reduce precision before the decimal point.  E.g., if precision is 5, then 12345678.901 becomes 12345679, 123.456789 becomes 123.46, and 0.123456789 becomes 0.12346.

WEAP.ResultsExportPrecision = 4

ResultValue(BranchName:VariableName[Scale Unit, Dimension = Item], Year, TimeStepNumber, Scenario, Year2, TimeStep2, FunctionType, PercentileValue): Get a single result value or an aggregate result value (e.g., sum or average over time). TimeStepNumber is the index of the timestep, where 1 is the first timestep of the water year, e.g., for June, the TimeStepNumber is 6 (assuming the water year begins in January). The Year and TimeStepNumber parameters are omitted for variables that have a single value for the entire study period (e.g., Demand Site Reliability). Omit Year2 and TimeStepNumber2 to get a single value. Available functions for FunctionType are: Total, Average, Median, Minimum, Maximum, Percentile and CV (coefficient of variation). If FunctionType is omitted, the Total will be calculated. PercentileValue is only used if FunctionType is Percentile. If the Scenario parameter is omitted, the active scenario will be used. Will switch to Results View if necessary, calculating results as needed. Read only.  Precision will depend on value of WEAP.ResultsExportPrecision.

To access MODFLOW cell results, the cell's layer, row and column is given instead of the BranchName: ResultValue(MODFLOWVariableName[layer, row, column], Year, TimeStepNumber, Scenario, Year2, TimeStep2, FunctionType, PercentileValue)

You can specify which scale or unit to report, e.g., Billion Cubic Meters, Acre Feet.  If not specified, the result will be written in the default unit for that unit class:

Unit Class

Default Unit

Area

Square Meter (m^2)

Concentration

Gram/Liter (g/l)

Currency

US Dollar ($)

Energy

Gigajoule (GJ)

Flow

Cubic Meters per Second (CMS)

Length

Meter (m)

Mass

Kilogram (kg)

Power

Kilowatt (kW)

Velocity

Meters/Second (m/s)

Volume

Cubic Meter (m^3)

A few result variables have extra "dimensions," e.g., source, water quality constituent or cost/benefit type.  For these, you can specify the dimension inside the square brackets, after the unit.  If omitted, WEAP will sum up the values across all items, e.g., for costs, it will add Capital Costs, Operating Costs and Benefits.

Note: WEAP.Branch(BranchName).Variables(VariableName).Value(Year, ....) is equivalent to WEAP.ResultValue(BranchName:VariableName, Year, ...), although WEAP.ResultValue lets you choose the scale and unit to report.

PRINT WEAP.ResultValue("\Demand Sites\South City:Reliability") 'Reliability is for the entire study period, so doesn't have a year or time step parameter

PRINT WEAP.ResultValue("\Supply and Resources\River\Weaping River\Reservoirs\Central Reservoir:Storage Volume[Billion Cubic Meter]", 2010, 7)

PRINT WEAP.ResultValue("\Supply and Resources\River\Weaping River\Reservoirs\Central Reservoir:Storage Volume[Million]", 2017, 7, "Reference")

PRINT WEAP.ResultValue("\Demand Sites\West City:Unmet Demand[Cubic Feet]", 2015, 1, "Reference", 2015, WEAP.NumTimeSteps) ' total unmet demand for 2015

PRINT WEAP.ResultValue("\Demand Sites\West City:Unmet Demand", WEAP.BaseYear, 1, "Reference", WEAP.EndYear, WEAP.NumTimeSteps) ' total unmet demand for entire study period

PRINT WEAP.ResultValue("\Demand Sites\West City:Unmet Demand", WEAP.BaseYear, 1, "Reference", WEAP.EndYear, WEAP.NumTimeSteps, "Average") ' average unmet demand for entire study period

PRINT WEAP.ResultValue("\Demand Sites\West City:Unmet Demand", WEAP.BaseYear, 1, "Reference", WEAP.EndYear, WEAP.NumTimeSteps, "Percentile", 90) ' the 90th percentile value for unmet demand for entire study period

PRINT WEAP.ResultValue("Cell Head[1, 57, 30]", 2015, 1, "Reference", 2019, 12, "Minimum") ' The minimum groundwater head elevation of cell layer 1, row 57, column 30 in the period 2015-2019 in scenario Reference, as calculated by a linked MODFLOW model.

PRINT WEAP.ResultValue("\Demand Sites\South City:Pollution Generation[kg, WQ Constituent=BOD]", 2010, 7)  ' BOD generated by South City.

PRINT WEAP.ResultValue("\Supply and Resources\River\Weaping River\Returns\Return Flow from South City:Pollution Loads[kg, Source=South City, WQ Constituent=BOD]", 2010, 7)  ' BOD that flows into the Weaping River return flow node from South City.  (There is also inflow from South City WWTP, but it won't be included.)

PRINT WEAP.ResultValue("\Demand Sites\Agriculture West:Supply Delivered[m^3, Source=West Aquifer]", 2010, 7)  ' Supply delivered to Agriculture West from West Aquifer.

PRINT WEAP.ResultValue("\Demand Sites\Agriculture West:Supply Delivered[m^3]", 2010, 7)  ' Supply delivered to Agriculture West from all sources.

PRINT WEAP.ResultValue("\Demand Sites\South City:Net Benefit[$, Cost/Benefit Type=Operating Cost]", 2010, 7)  ' Operating cost at South City.

SaveArea: Save all changes to current area. NOTE: If you close WEAP without calling SaveArea, the changes will not be saved.

WEAP.SaveArea

SaveAreaAs(NewAreaName): Save area with new name.  The old area will still exist.  Any unsaved changes to current area will be saved in new area, but not in the old area.

CALL WEAP.SaveAreaAs("Weaping River Basin Copy")

 

SaveSchematic(Clipboard, Width): Save schematic to Windows clipboard.
SaveSchematic
(Filename.jpg, Width, ImageQuality): Save schematic to a JPEG (.jpg) graphic file.
SaveSchematic
(Filename.png, Width): Save schematic to a PNG (.png) graphic file.
SaveSchematic
(Filename.kmz, Width, ImageQuality, IsVector, IncludeAreaNotes, IncludeObjectNotes, OpenInGoogleEarth): Save schematic to a Google Earth (kmz) file.  See Export to Google Earth for more information.

Note: The schematic will be saved as it currently appears in the Schematic View.  If you have zoomed in (so that the full area is not visible) or have hidden some WEAP objects (by unchecking them in the upper left legend in the Schematic View), this is what will be saved to the file.  Call WEAP.ZoomSchematic first if you want to zoom out to show the full area boundaries in the saved file.

Filename: The file extension (jpg, png or kmz) determines the type of file saved. 
All parameters after Filename are optional.  If omitted, the default value is used.  The last four parameters only apply to Google Earth export.
Width
: Width (in pixels) of clipboard, jpg, png or raster Google Earth images.  Range: 50 to 5000.  Default: 800.
ImageQuality
: Range from 5 (low quality) to 100 (high quality).  The higher the quality the larger the file.  Default: 80.
IsVector
: If True, will create a Google Earth file with a clickable object for each WEAP object (e.g., Demand Site, Reservoir, River).  If False, will create a Google Earth file with a single raster image (jpg). Width and ImageQuality are used only if IsVector = False.  IncludeObjectNotes is used only if IsVector = True.  Default: True.
IncludeAreaNotes
: If True, include the area note (as edited in Manage Areas, if any).  Default: True.
IncludeObjectNotes
: If True, include the note for each WEAP object (as edited in Notes View).  In Google Earth, the note will be displayed when the object is clicked.  Object notes can contain html formatting codes.  Default: True.
OpenInGoogleEarth
: If True, open Google Earth and load the file after it is created.  Google Earth is free and can be downloaded from http://earth.google.com  Default: False.

CALL SaveSchematic("Clipboard", 1200)

CALL SaveSchematic("C:\Weaping River Basin.jpg")

CALL SaveSchematic("C:\Weaping River Basin.jpg", 1200, 75)

CALL SaveSchematic("C:\Weaping River Basin.png", 2000)

CALL SaveSchematic("C:\Weaping River Basin Vector.kmz")

CALL SaveSchematic("C:\Weaping River Basin Vector.kmz", , , True, False, True, True)

CALL SaveSchematic("C:\Weaping River Basin Raster.kmz", 1200, 85, False, False, , True)

SaveVersion(Comment, IncludeResults): Create a new version of the active area with the given comment. If optional IncludeResults is TRUE, include the results in the version.

CALL WEAP.SaveVersion("Scenario 'Reference' is finished")

CALL WEAP.SaveVersion("Scenario 'Reference' is finished, results included", TRUE)

Scenario: Get the named scenario object.  WEAP.Scenarios can also be used to get access to one named scenario object, but it is somewhat faster to use WEAP.Scenario.

SET S = WEAP.Scenario("Reference")

Note: You can also get this through the Scenarios collection, although it is not quite as fast:  

SET S = WEAP.Scenarios("Reference")

Scenarios: Get the collection of all scenarios in the active area. See WEAPScenarios for details. Read only.

FOR EACH s IN WEAP.Scenarios
  PRINT WEAP.ResultValue("\Demand Sites\South City:Reliability", , , s.Name)
NEXT

ScreenRefresh: Call ScreenRefresh to update the schematic when ScreenUpdating = FALSE

CALL WEAP.ScreenRefresh

ScreenUpdating: Turn on or off updates to the screen in the Schematic or Data View.  Useful when using CreateNode and CreateLink to build a large WEAP model, or changing many data expressions at once -- it will be much faster if you set ScreenUpdating = FALSE before calling CreateNode and CreateLink.  ScreenUpdating will automatically be set to TRUE when opening an area.

WEAP.ScreenUpdating = FALSE

WEAP.ScreenUpdating = TRUE

 

SearchFile(Filename, SearchText, IgnoreCase): Search a text file for specified text.  Does not need to match entire line -- partial match is OK.  Return the line number where the text first occurred, or 0 if not found.  Ignore case (upper vs. lower case) unless optional IgnoreCase is FALSE.

' Download latest SNOTEL file for site 531 and add $DateFormat and $Columns=" to the line with the column names

' NOTE: See WEAP.ReplaceInFile for an easier way to do the same thing

URL = "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/" + "daily/531:CO:SNTL%7Cid=%22%22%7Cname/POR_BEGIN,POR_END/WTEQ::value,PREC::value," + "TMAX::value,TMIN::value,TAVG::value,PRCP::value"

Filename = WEAP.ActiveAreaDirectory + "Data\SNOTEL\Hoosier Pass (531).csv"

IF WEAP.FileDate(Filename) <> Date() then     ' only download if haven't already downloaded today

    IF WEAP.DownloadFile(URL, Filename) THEN

       LineNumber = WEAP.SearchFile(Filename, "Date,Snow Water Equivalent (in) Start of Day Values")

       IF LineNumber > 0 THEN

          TheLine = WEAP.ReadLineFromFile(Filename, LineNumber)

          NewLine = "$DateFormat=yyyy-mm-dd" & CHR(13) + CHR(10) + "$Columns=" + TheLine   ' Add DateFormat and Columns directives

          CALL WEAP.ModifyFile(Filename, LineNumber, NewLine)

       END IF

   END IF

END IF

Setting(Key, Section): Set or get a text value associated with a key (text).  Value is stored in file weap.ini in the WEAP main directory.  If Section is not specified, will look in section User.  The weap.ini file can be a convenient place for the user to store settings that apply to all of WEAP.  Area-specific settings can also be saved -- see AreaSetting and DeleteAreaSetting.

WEAP.Setting("Custom hydrology model") = "SWAT"

WEAP.Setting("Model directory", "SWAT") = "C:\Program Files\SWAT"

IF WEAP.Setting("Custom hydrology model") = "SWAT" THEN

  ...

END IF

SoftwareVersion: Get the WEAP version number. Read only.

PRINT "WEAP version: "; WEAP.SoftwareVersion

Status: Determine whether the previous property or method call was successful, returning a logical value of TRUE or FALSE. Read only.

IF WEAP.Status = FALSE THEN EXIT FOR

Tags: Get the collection of all tags. Returns a WEAPTags object. Read only.

FOR EACH Tag IN WEAP.Tags
PRINT Tag.Name & ", " & Tag.Category.Name

NEXT

TempDirectory: Get the full path of the WEAP temp directory, e.g., C:\Users\Jack\Documents\WEAP Areas\_Temp. Read only.

Filename = WEAP.TempDirectory + "GW_Storage.csv"

CALL WEAP.ExportResults(Filename, TRUE, TRUE) ' Export to CSV

TimeStepName(TimeStepNumber): Get the name of a time step (e.g., "May" or "Oct 15"). Read only.

PRINT WEAP.TimeStepName(12)

Note: This is equivalent to WEAP.Timesteps(12).Name

UpdateCatchmentClimate(ForceUpdate): Check if climate data (on WEAP website) that catchment delineation uses has been updated since last processed for this WEAP area.  If so, download and process for catchments and return True; otherwise, return False.  If optional parameter ForceUpdate is True, then download and process climate data regardless of whether WEAP thinks they need updating or not.

IF WEAP.UpdateCatchmentClimate THEN

   WEAP.Calculate(0, 0, True)   ' Force calculation

END IF

IF WEAP.UpdateCatchmentClimate(True) THEN    ' Force update

   WEAP.Calculate(0, 0, True)   ' Force calculation

END IF

UserID: Set or get the 3-letter User ID (the user's initials).

WEAP.UserID = "JGS"

UserName: Get the current user's full name.

PRINT WEAP.UserName    

Verbose: Set or get level of information and interaction, from 0-4. 0 = display no messages; 1 = display errors only; 2 = ask questions; 3 = show warnings; 4 = show all messages. The default level is 1.

WEAP.Verbose = 0

WEAP.Verbose = 2

Versions: Get the collection of versions for the active area. See WEAPVersions for details. Read only.

WEAP.Versions("Finished Reference Scenario").Revert

FOR Each Version in WEAP.Versions

   PRINT Version.Name

END IF

View: Set or get the active view (one of "Schematic", "Data", "Results", "ResultsNoCalculation", "Scenario Explorer" or "Notes").  When switching to the Results or Scenario Explorer views, WEAP will automatically run calculations if necessary.  If set view to ResultsNoCalculation, WEAP will go to the Results View without running calculations.

WEAP.View = "Data"

WEAP.View = "Results"

IF WEAP.View <> "Results" THEN do something

Visible: Show or hide WEAP

WEAP.Visible = TRUE

WEAP.Visible = FALSE

WaterYearStart: Set or get the index for the first timestep of the water year.

PRINT WEAP.WaterYearStart    ' if the water year begins in October, this would be 10

WEAP.WaterYearStart = 3      ' set the water year start to March

Note: WaterYearStart is equivalent to Timesteps(1).CalendarIndex

WorkingDirectory: Gets the full path of the WEAP working directory. Read only.

PRINT WEAP.WorkingDirectory

YearTimeStepName(Year, TimeStepNumber): Get the name of a year and time step (e.g., "May 2010" or "Oct 15 2011"). Read only.

PRINT WEAP.YearTimeStepName(2010, 12)

ZoomLevel: Set or get the zoom level of the map in the Schematic View.  ZoomLevel = 1 corresponds to the full area extent; ZoomLevel = 2 is zoomed in by a factor of two, such that the width and height shown are half of the full area extent.

PRINT WEAP.ZoomLevel

WEAP.ZoomLevel = 8    ' Zoom in by a factor of 8

WEAP.ZoomLevel = 1    ' Zoom out to the area boundaries

ZoomSchematic: Zoom out on the Schematic so that it shows the full area boundaries.

WEAP.ZoomSchematic