Controlling HEC-RAS Using MATLAB PDF
Controlling HEC-RAS Using MATLAB PDF
Abstract
The U.S. Army Corps of Engineers Hydrologic Engineering Centers River Anal-
ysis System (HEC-RAS) is a widely used software application for performing
one-dimensional and two-dimensional steady and unsteady flow river hydraulics
calculations, sediment transport-mobile bed modeling, and water quality anal-
ysis. Users of HEC-RAS have often unique applications including the coupling
with other software to perform system analysis such as optimization of flooding
structures and multi-objective reservoir operation under uncertainty. One state-
of-the-art environment for integrating software is MATLAB, which integrates
computation, visualization, and programming in an easy-to-use environment.
This paper presents a set of MATLAB scripts to write input files, read output
files, make plots, execute parallel computations, and perform fully-automated
functions of HEC-RAS. Examples of procedures are presented throughout the
paper and they are illustrated using a river-reservoir network that involves ten
inline structures (e.g., dams) with operation of gates at each of these dams.
Keywords: HEC-RAS, HECRASController, MATLAB, Model integration,
Numerical modeling, Optimization
1. Introduction
HEC-RAS is a widely used software application that can perform one and
two-dimensional hydraulic calculations for a full network of natural and con-
Corresponding author
Email address: [email protected] (Arturo S. Leon)
50 2. HEC-RAS Controller
This section presents a very brief discussion on the USACE HECRASCon-
troller. We will only focus on few functions of the HECRASController that are
2
very useful. For an in-depth discussion of all functions available in the USACE
HECRASController, the reader is referred to Goodell (2014). The reader is
55 referred to Script 1 for this discussion.
The script line containing actxserver will create a new, invisible copy of
HEC-RAS. The text RAS500.HECRASCONTROLLER is used for HEC-
RAS version 5.0 and RAS41.HECRASCONTROLLER for version 4.1.
The function P roject_Open(ras_f ile) will open a RAS file, where ras_f ile
60 is a string.
The function Compute_HideComputationW indow hides the HEC-RAS
computation window, which is useful when performing parallel computa-
tions or serial batch computations. The function Compute_ShowComputationW indow
shows the computation window for each HEC-RAS computation.
65 The function Compute_CurrentP lan runs HEC-RAS for current plan.
The function P roject_Save saves the HEC-RAS project
The function OutputDSS_GetStageF low is intended for extracting water
surface stage and flow discharge at selected cross-sections.
As described in Goodell (2014), the most common HEC-RAS input text files
are:
1. Geometry file: .g##
3
2. Steady flow file: .f##
95 3. Unsteady flow file: .u##
There are other input files such as Plan file (.p##), Project file (.prj), and
others. The manipulation of the input files are very similar so due to space
limitations we will show four examples for the geometry and unsteady flow input
files.
100 The first example will find and printout the title name of the geometry file.
The reader is referred to Script 2 for this example. In this script, the filename
will have the extension .g##. Script 2 reads the file line by line. Whenever
the script finds the character = , it will split the text in two (left and right
of =). Then the script checks if the left of the text is the same as the string
105 Geom Title. If it is, it will extract and printout the right of the text, which
will be the title name of the geometry file.
The second example updates water stage elevations and flow discharges at
125 multiple cross-sections that will be used as the initial conditions for an unsteady
flow simulation. This example corresponds to an optimization of reservoir op-
eration in a ten-reservoir system. The reader is referred to Script 3 for this
example. In this script, the filename to use will have the extension .u##.
Script 3 first reads data of current tailwater and forebay elevation for the
130 ten dams. Then the script reads the current inflows and outflows of the ten
reservoirs, which are stored for later use. Following, the unsteady input file needs
to be updated with the corresponding initial water stages and flow discharges.
To perform this task, first the original unsteady file is copied to a temporal
file (24XSN EW _temp.u01). Then using as baseline the temporal unsteady
135 file, the original unsteady file (24XSN EW.u01) is rewritten with the current
water stages and flow discharges. To start to replace the initial conditions, it is
necessary to find the key variable Use Restart= 0 in the temporal file that is
being read. Once this string is found, it should be printed out in the file and
then the initial flows and stages are also printed out in the original file being
140 rewritten. The initial flow should contain the string Initial Flow Loc= at the
4
most left part of the text line. This string should be followed by the river, reach,
station and the initial flow discharge at this river station. The initial water stage
should contain the string Initial RRR Elev= at the most left part of the text
line. This string should be followed by the river, reach, station and the initial
145 water stage at this river station. After this data is written in the original file,
we should continue reading the temporal file without writing anything until the
string Boundary Location= is found. The latter will avoid errors in the input
file due to data size incompatibility between the old (temporal file) and the new
(being rewritten) input files.
Script 3. Script to update water stage elevations and flow discharges at multiple cross-
sections that will be used as the initial conditions for an unsteady flow simulation
150
1 %Initial conditions: Update initial water stages and outflows
2 file_current_TW = [home_dir '\InitCond\CurrentTW.txt'];
3 Data_curr_TW = dlmread(file_current_TW);
4 file_current_FB = [home_dir '\InitCond\CurrentFB.txt'];
155 5 Data_curr_FB = dlmread(file_current_FB);
6 file_current_inflow = [home_dir '\InitCond\CurrentInflows.txt'];
7 Data_curr_inflows = dlmread(file_current_inflow);
8 file_current_outflow = [home_dir '\InitCond\CurrentOutflows.txt'];
9 Data_curr_outflows = dlmread(file_current_outflow);
160 10 for j=1:Number_dams;
11 k = Order_Conv(j);
12 m = 2*j;
13 XS_stage(m-1) = Data_curr_FB(k);
14 XS_stage(m) = Data_curr_TW(k);
165 15 XS_flow(m-1) = 1000*Data_curr_inflows(k);%to concvert to cfs
16 XS_flow(m) = 1000*Data_curr_outflows(k);
17 end
18 filenameinput = [home_dir '\RAS_folders\24XS-Col\24XSNEW_temp.u01'];
19 filenameoutput = [home_dir '\RAS_folders\24XS-Col\24XSNEW.u01'];
170 20 copyfile(filenameoutput,filenameinput);
21 %filenameinput %Input file is the temporal file
22 %filenameoutput %Output file is the initial file
23 fid = fopen (filenameinput, 'rt'); %Open file for reading
24 fout = fopen (filenameoutput, 'wt'); %Open file for writing
175 25 while ~feof(fid)
26 strTextLine = fgetl(fid); %To read one additional line
27 if strfind(strTextLine,'Use Restart= 0');
28 fprintf(fout,'%s\n',strTextLine);
29 for j=1:Number_dams; %Initial_flows
180 30 m = 2*j;
31 str1 = 'Initial Flow Loc=';
32 str2 = num2str(XS_flow(m-1));
33 strTextLine2 = strcat(str1,XS_IC(m-1),str2);
34 fprintf(fout,'%s\n',strTextLine2{1});
185 35 str2 = num2str(XS_flow(m));
36 strTextLine2 = strcat(str1,XS_IC(m),str2);
37 fprintf(fout,'%s\n',strTextLine2{1});
38 end
39 for j=1:Number_dams; %Initial water stages
190 40 m = 2*j;
41 str1 = 'Initial RRR Elev=';
42 str2 = num2str(XS_stage(m-1));
5
43 strTextLine2 = strcat(str1,XS_IC(m-1),str2);
44 fprintf(fout,'%s\n',strTextLine2{1});
195 45 str2 = num2str(XS_stage(m));
46 strTextLine2 = strcat(str1,XS_IC(m),str2);
47 fprintf(fout,'%s\n',strTextLine2{1});
48 end
49 else
200 50 fprintf(fout,'%s\n',strTextLine);
51 end
52 end
53 fclose (fid); %Close the text file
205
54 fclose (fout); %Close the text file
The third example updates the inflow hydrographs (two) and pre-scheduled
gate outflows at ten inline structures (i.e, dams). The pre-scheduled outflows are
generated by an optimization routine (Genetic Algorithm) with a pre-specified
population.
210 In a genetic algorithm, a population of candidate solutions (called individ-
uals) to an optimization problem is evolved toward better solutions. The evo-
lution usually starts from a population of randomly generated individuals, and
is an iterative process, with the population in each iteration called a genera-
tion. In each generation, the fitness of every individual in the population is
215 evaluated; the fitness is usually the value of the objective function in the op-
timization problem being solved. The more fit individuals are stochastically
selected from the current population, and each individuals genome is modi-
fied (recombined and randomly mutated) to form a new generation. The new
generation of candidate solutions is then used in the next iteration of the algo-
220 rithm. Commonly, the algorithm terminates when either a maximum number of
generations has been produced, or a satisfactory fitness level has been reached
for the population. For more details about the genetic algorithm and its ap-
plication to reservoir operation the reader is referred to Wardlaw and Sharif
(1999), Leon and Kanashiro (2010), Leon et al. (2014),Lerma et al. (2015),
225 Yang et al. (2015), and Chen et al. (2016). Due to space limitations, a code of a
genetic algorithm is not presented herein. However, there are various codes avail-
able in the literature (e.g., https://www.idealsoftware.com/opensource/
genetic-algorithm.html and http://gaul.sourceforge.net/).
The update of dam outflows is done at each generation for each population
230 of the optimization. It is worth mentioning that in an optimization-simulation
framework, the initial conditions (second example) need to be updated only at
the beginning of the optimization. The reader is referred to Scripts 4 and 5 for
the third example. In this example, the file to update will have the extension
.u##.
235 This example has two parts. In the first part, the data (inflow hydrographs
and outflows) to be written in the unsteady file is prepared. The HEC-RAS
unsteady input file (.u##) is formatted in such a way that the data points
for inflow hydrographs and outflows at inline structures can have a maximum
of 10 data points per line. Script 4 prepares the lines of data to be written in
240 the unsteady file. This script first calculates the number of lines of data for
6
the inflow hydrographs (N Lines_inf low) and the outflows (N Lines_Out)
based on the number of data points. For instance, if the simulation period
is 4 days with gate outflows specified every hour, the number of data points
for the outflows would be 97 that includes the initial condition (t = 0). In
245 this case, the number of lines of data for the outflows (N Lines_Out) would
be 10. Next, the script calculates the number of data points for the last line of
the inflow hydrographs (last_line_inf ) and the outflows (last_line_dam).
The reason for the latter is because not always the number of data points of
the last line is 10. Then, the data for inflow hydrographs is split in two, one
250 for all the lines except the last one (Inf low_array_main) and the last line
(Inf low_array_last_line). Likewise, the data for the dam outflows are split
into (Outf low_array_main) and (Outf low_array_last_line).
Once the data has been prepared, Script 4 will call Script 5 for each popu-
lation of the optimization. To start to replace the data, it is necessary to find
255 key variables in the temporal unsteady file that is being read. These variables
are Flow Hydrograph= for the inflow hydrographs and Rule Table= for the
dam outflows. In a similar way to the second example, after the data has been
written in the original file, we should continue reading the temporal file without
writing anything until the strings DSS Path= and Rule Operation= have
260 been found for the inflow hydrographs and dam outflows, respectively. The lat-
ter will avoid errors in the input file due to data size incompatibility between
the old (temporal file) and the new (being rewritten) input files.
Script 4. Script to prepare the data lines for the inflow hydrographs and gate outflows to be
written in the unsteady file of HEC-RAS
1 NLines_inflow = fix((Inflow_points-0.1)/10) + 1;
265 2 last_line_inf = Inflow_points-10*(NLines_inflow-1);%last line infl
3 NLines_Out = fix((Outflow_points-0.1)/10) + 1;
4 last_line_dam = Outflow_points-10*(NLines_Out-1); %last line outfl
5 pos_data = 10*(NLines_inflow-1);
6 for j=1:Number_Inflow_hydrog;
270 7 arrayflow1 = Data_Inflow_hydrog(1:pos_data,j:j)';
8 Inflow_array_main(:,:,j) = reshape(arrayflow1, 10, [])';
9 arrayflow2 = Data_Inflow_hydrog(pos_data+1:Inflow_points,j:j);
10 Inflow_array_last_line(1,:,j) = arrayflow2'; %Transpose
11 end
275 12
13 %Adding initial outflows
14 Data_outflow_current = Data_curr_outflows';
15 for i=1:Pop_Opt;
16 temp_int1 = 10*(i-1)+1;
280 17 temp_int2 = 10*(i);
18 temp_array1 = Data_optimization_flows(1:Outflow_points-1, ...
19 temp_int1:temp_int2);
20 temp_array2 = [Data_outflow_current; temp_array1];
21 temp_array2 = 1000*temp_array2; %to convert to cfs
285 22 pos_data = 10*(NLines_Out-1);
23 for j = 1:Number_dams;
24 k = Order_Conv(j);
25 temp_array3 = temp_array2(1:pos_data,k:k)';
7
26 Outflow_array_main(:,:,j) = reshape(temp_array3, 10, [])';
290 27 temp_array4 = temp_array2(pos_data+1:Outflow_points,k:k);
28 Outflow_array_last_line(1,:,j) = temp_array4'; %Transpose
29 end
30 ChangeInlineStruct_Data(ras_inp{i},ras_out{i},NLines_Out, ...
31 Outflow_array_main,Outflow_array_last_line,NLines_inflow, ...
295 32 Inflow_array_main,Inflow_array_last_line);
33 end
8
46 fprintf(fout,'%s\n',A1string);
345 47 else
48 fprintf(fout,'%s\n',strTextLine);
49 end
50 end
51 fclose (fid); %Close the text file
350 52 fclose (fout); %Close the text file
This section presents examples to extract water surface stages and flow dis-
charges, plotting and to perform parallel HEC-RAS computations. There are
355 functions available in the HECRASController for extracting water surface stages
and flow discharges, and their plotting, so these tasks are straight forward. The
reader is referred to Script 6 for extracting water surface stages and flow dis-
charges and Script 7 for plotting water surface stage and flow discharge at a given
river station. The HECRASController function OutputDSS_GetStageF low
360 allows to extract stage and flow hydrographs at a given river station. The
HECRASController subroutine P lotStageF low allows to plot the stage and
flow hydrograph at a given river station. An example of this plot is shown in
Figure 1.
10
Following we present the script to perform parallel HEC-RAS computations.
390 The reader is referred to Script 8 for this example. The script first creates
a special job on a pool of workers, and connects the MATLAB client to the
parallel pool. This is done using the parpool function of MATLAB. Then, the
scripts defines an array of handles (h {j}) with a number equal to the number
of HEC-RAS computations. Next, the parf or function of MATLAB is used
395 for the parallel computations. Finally, the system taskkill command is used
to close all open HEC-RAS projects. A snapshot of simultaneous HEC-RAS
computations is shown in Figure 2.
5. Conclusions
This paper presents a set of MATLAB scripts to write input files, read output
files, and perform fully-automated functions of HEC-RAS. Examples of various
425 programming procedures are presented throughout the paper and they are illus-
trated using a river-reservoir network that involves ten inline structures (e.g.,
dams) with operation of gates at each of these dams. The procedures includes
reading and writing HEC-RAS input files, extracting output variables, plotting
and parallel computing. In addition, this paper presents a brief introduction to
430 the USACE HECRASController.
Acknowledgments
The first author gratefully acknowledges the financial support of the Bon-
neville Power Administration of the U.S. Department of Energy under award
11
Figure 2. A snapshot of simultaneous HEC-RAS computations
number TIP#258.
435 References
Chen, D., Leon, A.S., Gibson, N.L., Hosseini, P., 2016. Dimension reduction
of decision variables for multireservoir operation: A spectral optimization
model. Water Resources Research 52, 3651.
Goodell, C., 2014. Breaking the HEC-RAS Code. First ed., h2ls, Portland,
440 Oregon.
Leon, A.S., Kanashiro, E., Valverde, R., Sridhar, V., 2014. Dynamic frame-
work for intelligent control of river flooding: Case study. Journal of Water
Resources Planning and Management 140, 258268. doi:10.1061/(ASCE)WR.
1943-5452.0000260.
455 Lerma, N., Paredes-Arquiola, J., Andreu, J., Solera, A., Sechi, G.M., 2015.
Assessment of evolutionary algorithms for optimal operating rules design in
12
real water resource systems. Environmental Modelling & Software 69, 425
436.
Mathworks, 2015. MATLAB version 8.6.0.267246 (R2015b). The Mathworks,
460 Inc. Natick, Massachusetts.
Wardlaw, R., Sharif, M., 1999. Evaluation of genetic algorithms for optimal
reservoir system operation. Journal of Water Resources Planning and Man-
agement 125, 2533.
Yang, T., Gao, X., Sellars, S.L., Sorooshian, S., 2015. Improving the multi-
465 objective evolutionary optimization algorithm for hydropower reservoir oper-
ations in the california orovillethermalito complex. Environmental
Modelling & Software 69, 262 279.
13