Tuesday, October 8, 2013

Compiling MODFLOW with Code::Blocks and gfortran

While I wait for the US government to re-open, I have been working on a book about MODFLOW. One of the problems people can have when something goes wrong with MODFLOW is that it can be difficult to find the source of the problem. Often there is some obscure formatting problem that can be uncovered by running MODFLOW through a debugger. However, many users of MODFLOW don't have a FORTRAN compiler or a debugger and purchasing one is expensive. That is where Code::Blocks can be helpful. It is a free Integrated Development Environment (IDE) for, among other things, gfortran, a free fortran compiler and gdb, a free debugger. I tried it out and it seems to be an excellent program. I wish it were a little smarter about figuring out the best order in which to compile the source code files but that is my only complaint. The following instructions tell how to compile MODFLOW with Code::Blocks. I have also written up a brief description of using the debugger but I haven't included that here.



The first step is to install Code::Blocks and gfortran. Gfortran is included in “MinGW” which is included with the Windows installer for Code::Blocks. For other operating systems, you may need to install Gfortran separately. First go to http://www.codeblocks.org/downloads and click on the link for “Download the binary release.” Then choose the installer for your operating system. There are several different ones available. If you are on Windows, you will need MinGW so choose one of the installers that includes MinGW unless you already have MinGW installed. At the time this was written, the installer that you are most likely to be appropriate is “codeblocks-12.11mingw-setup.exe.” However, by the time you read this, there may be a more recent version.  Once the installer has downloaded, use the installer to install Code::Blocks.
Start Code::Blocks. It will display a dialog box asking whether you want associate C++ files with Code::Blocks. It is up to you how you wish to respond.
Next you will need to configure Code::Blocks to use gfortran.

1.     Select “Settings|Compiler.”
2.     Select the "GNU GCC Compiler", click the "Copy Button."

3.     Enter "GNU GFortran Compiler" as the name of the new compiler.

4.     Select the “Toolchain executables” tab and make sure the compiler’s installation directory is set correctly. Then set “gfortran.exe” as the C compiler, the C++ compiler and the linker for dynamic libs. Then Click OK to close the dialog box. 


If you have not already done so, download MODFLOW-2005 from the USGS web site (http://water.usgs.gov/nrp/gwsoftware/modflow2005/modflow2005.html‎). MODFLOW-2005 comes in a zip file that you will need to unzip. The directory to which it is normally unzipped is “C:\WRDAPP.” (WRDAPP stands for Water Resources Division Application.) On of the subdirectories include in the zip file is named “src.” It contains the source code for MODFLOW-2005. There are two subdirectories of the src directory that contain the source code for two other programs that are distributed with MODFLOW-2005. We won’t deal with those other programs.
Here are step-by-step instructions on compiling MODFLOW-2005.

1.     In Code::Blocks, select “File|New|Project” or click the “Create new project” link.

2.     Select “Fortran Application” and click the Go button.


3.     A new “wizard” dialog box will appear. If you have never used Code::Blocks before, the first page of the dialog box does nothing so just click the “Next” button.

4.     On the next page, specify a project title and a folder for MODFLOW-2005 and click the “Next” button. In this example, we will use “MF2005” as the name of the project. Code::Blocks will create a subfolder in that directory to contain the source code for the project. In this case, the folder is “C:\MF2005.”
 

5.     On the next page, be sure to set the compiler to the gfortran compiler and click the “Finish” button.


6.     At this point, the workspace will contain one file named “main.f95” under “Fortran Sources” that was automatically generated by Code::Blocks. That file isn’t needed because we already have all of the source code for MODFLOW. Click on it to select it. Then right-click and select “Remove file from project” from the pop-up menu. You may also delete the file from your computer using Windows Explorer.

7.     Copy all the source code files into the folder for the project (C:\MF2005).

8.     Right-click on “MF2005” and select “Add files…” from the pop-up menu.

9.     Select all the files in the folder for the project except MF2005.cbp, nogmg.txt, and openspec.inc. That should be all the files with the extension “.f”, “.f90”, “.c”, or “.h”.  (MF2005.cbp is the Code::Blocks project file. Nogmg.txt is used to replace gmg.f if MODFLOW is being compiled without the GMG package. Openspec.inc is part of the source code that will be “included” in several different source code files.)

10.  Code::Blocks will display a dialog box asking to which targets the files should belong. The default is that the files should belong to both the debug and release targets which is what we want so just click OK.



11.  Select Project|Build Options and select the “Compiler Settings” tab. Under that select the “defines” tab. Enter _UF on that tab.





12.  Switch to the Linker settings tab and click the “Add” button under “Link libraries”. Select the file libgfortran.a which you may find at C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.7.1\. When it asks if you want to “Keep this as a relative path?”, click the Yes button. Click the Add button two more times and select libgcc.a and libquadmath.a too.


13.  Because of dependencies among the various source code files in MODFLOW, the order in which they are compiled is important with gfortran. (With other compilers, it may not be necessary to specify a compile order.) The order in which the files are compiled can be controlled using the “priority weight” for each file. The default priority weight is 50. We will need to specify smaller priority weights for some files in order to control the order in which the files are compiled. The table below gives the priority weights that will be assigned. To assign a priority weight, expand “Fortran Sources” and right click on one of the files. From the pop-up menu, select “Properties”. In the dialog box, select the “Build” tab and use the slider to set the priority weight.


File name
Priority Weight
gwf2bas7.f
20
gwf2bcf7.f
25
gwf2huf7.f
22
gwf2ibs7.f
25
gwf2lak7.f
27
gwf2lpf7.f
22
gwf2str7.f
27
gwf2sub7.f
30
gwfsfrmodule.f
21
gwfuzfmodule.f
22
pcg7.f
30
pcgn2.f90
33
pcgn_solve2.f90
30
sip7.f
27

14.  Open Openspec.inc in a text editor such as Notepad. Openspec.inc has some Fortran code that used in opening binary files. What we want to do is to compile MODFLOW in such a way that a binary file is a “unstructured non-formatted” file so that programs that aren’t compiled with gfortran will be able to read them. With gfortran we need to change Openspec.inc slightly so that the binary files are unstructured non-formatted files.

15.  In FORTRAN, if the first character of a line is a “C”, that line is considered a comment and is ignored by the compiler. Note that most of the lines in openspec.inc are comments. There are only four lines that are not comments. The first one declares three variables named ACCESS,FORM, and ACTION. The other three lines each set one of those variables. If you look at the comments, for FORM, and ACTION, there are two versions of the lines that set those variables. For each of them, one version of the line is marked with a C as the first character and so is ignored by the compiler. The other one isn’t marked with a C as the first character and so is used by the compiler. In the version of MODFLOW with which I am working, the version of the line for ACTION is the “Standard FORTRAN” version. Leave it alone. The active version of the line for FORM is “Non-standard Fortran”. We will need to change that to the “Standard FORTRAN” version. Delete the “C” at the beginning of the line
C      DATA FORM/'UNFORMATTED'/
and insert a “C” at the beginning of the line
      DATA FORM/'BINARY'/

16.  Now both FORM and ACCESS are using Standard FORTRAN. We need to make two more changes. Locate the line where ACCESS is specified. It reads
      DATA ACCESS/'SEQUENTIAL'/
Insert a “C” at the beginning of that line so that it is ignored by the compiler. Then insert the following lines
C
c    Non-standard Fortran that causes code compiled by gfortran
C    on personal computers to use unstructured non-formatted
C    files.  This may make it possible for the non-formatted files used
C    by MODFLOW to be used with programs that are compiled by other
C    compilers.
C
      DATA ACCESS/'STREAM'/

17.  Select “Build|Build.”

Wednesday, October 2, 2013

Should we do anything about climate change?



A few weeks ago, my brother posted on my Facebook page “Any thought oh you global warming people” with a link to a Wall Street Journal opinion piece by Matt Ridley entitled “Dialing Back the Alarm on Climate Change” (http://online.wsj.com/article/SB10001424127887324549004579067532485712464.html?mod=iPhone). I, rather flippantly replied “You can ask again when the report that the reporter reportedly reports on is published.” The report in question was the fifth assessment report by the Intergovernmental Panel on Climate Change (IPCC). A draft report is now available online (http://www.ipcc.ch/report/ar5/wg1/#.UksXud0hG8A) so now that I have some extra time on my hand due to the US government shutdown I thought I would take a stab at replying to my brother’s question. At over 2200 pages, the report is a rather daunting document and I won’t pretend I have read it all. (On the other hand, the Ridley didn’t claim he had read the whole thing either.) In addition to the full report, there is a 36 page “Summary for Policymakers”.
The main points Ridley makes are that (1) the estimates of the amount of climate change in the new report are less than in the previous report, (2) that in the next 70 years, the effects of climate change may be beneficial, and (3) the estimates in the latest report may still be too high.
What strikes me when comparing Ridley’s article with the “Summary for Policymakers” is how different the emphasis is in the “Summary for Policymakers” from what Ridley presents. Ridley emphasizes the differences in the estimates of "equilibrium climate sensitivity" and "transient climate response" between the most recent report and the previous one. While these are technical measures of climate change, they don’t really tell you that much without some context. Overall, it seems to me that Ridley is cherry-picking; he is emphasizing minor differences that don’t really mean much and ignoring the main message.
So what is the main message? Well here are some of the most strongly highlighted messages from the “Summary for Policymakers.” (I have only picked a few because I don’t have space for all of them.)

Warming of the climate system is unequivocal, and since the 1950s, many of the observed changes are unprecedented over decades to millennia. The atmosphere and ocean have warmed, the amounts of snow and ice have diminished, sea level has risen, and the concentrations of greenhouse gases have increased.
Each of the last three decades has been successively warmer at the Earth’s surface than any preceding decade since 1850… In the Northern Hemisphere, 1983–2012 was likely the warmest 30-year period of the last 1400 years (medium confidence).
The atmospheric concentrations of carbon dioxide (CO2), methane, and nitrous oxide have increased to levels unprecedented in at least the last 800,000 years. CO2 concentrations have increased by 40% since pre-industrial times, primarily from fossil fuel emissions and secondarily from net land use change emissions. The ocean has absorbed about 30% of the emitted anthropogenic carbon dioxide, causing ocean acidification.
Human influence has been detected in warming of the atmosphere and the ocean, in changes in the global water cycle, in reductions in snow and ice, in global mean sea level rise, and in changes in some climate extremes… This evidence for human influence has grown since AR4. It is extremely likely that human influence has been the dominant cause of the observed warming since the mid-20th century.
Continued emissions of greenhouse gases will cause further warming and changes in all components of the climate system. Limiting climate change will require substantial and sustained reductions of greenhouse gas emissions.
Changes in the global water cycle in response to the warming over the 21st century will not be uniform. The contrast in precipitation between wet and dry regions and between wet and dry seasons will increase, although there may be regional exceptions.
Cumulative emissions of CO2 largely determine global mean surface warming by the late 21st century and beyond... Most aspects of climate change will persist for many centuries even if emissions of CO2 are stopped. This represents a substantial multi-century climate change commitment created by past, present and future emissions of CO2.

Another difference I note is that Ridley expects the climate change to be beneficial. He states that climate change “would extend the range of farming further north, improve crop yields, [and] slightly increase rainfall (especially in arid areas).” Warming would indeed extend the range of farming further north but I am not clear where he gets the idea that it would increase rainfall in arid areas. The Summary for Policymakers states that “the contrast in precipitation between wet and dry regions … will increase.” That directly contradicts Ridley. A lot of our agriculture is in areas that don’t get all that much rainfall. If they get less, they will be able to grow less. Thus the idea that a warmer climate would mean more food is speculation on Ridley’s part. It is not something that is backed up by science. It seems to me that a more likely scenario is that agricultural productivity would increase in Canada and Russia due to warmer temperatures but would decrease in the United States and China due to less rainfall. However, this is speculation on my part. It is not backed up by any more science than Ridley’s speculation. I am reminded of a quote from Mark Twain that ends “There is something fascinating about science. One gets such wholesale returns of conjecture out of such a trifling investment of fact.” (For the full quote, see http://todayinsci.com/T/Twain_Mark/TwainMark-Quotations.htm.) Anybody can speculate. Backing up those speculations with science is a lot more difficult. That’s why you end up with reports that are over 2200 pages long.
Finally, Ridley emphasizes possible benefits in the next 70 years but ignores what happens after that. In my opinion this is cherry picking again but with the added fault that it is based more on speculation than science.

Thus, I find Ridley’s article unconvincing. To me, it doesn’t seem like an unbiased treatment of the evidence. On the other hand, should I blindly accept the conclusions of a big long report that I haven’t read and which I might not understand if I did read? I think a lot of us are in that position these days not only about this issue but about a lot of things. How do we judge whether something is true if we don’t really understand it?
A few years ago, I was a juror in a civil trial. One thing the judge told us in our instructions seems relevant here. He told us that in making our decision we did not have to ignore our life experiences. We could use our life experiences, for example, in judging the credibility of the witnesses.
A key part of the issue of climate change is the predictions that various models make regarding future climate. Now while, I don’t know much about climate models in particular, I do know a bit about models in general – their strengths, their weaknesses, what they are good for, and how they can go wrong. I work with groundwater models all the time and I think some of what I know about groundwater models is applicable to models in general including climate models. Thus, while I do not have the background to fully judge the validity of the climate models, I do have some knowledge that is applicable and I can use that to make a judgment.
First of all, why use a model at all. My colleague, Ken Belitz, had a good explanation for that. He said (and I’m paraphrasing) “We model what we can not measure. If we could measure everything we would not need to model.” If we knew, really knew, what the future climate was going to be, we would not need climate models. We don’t know what the future climate will be. However, we still need to make decisions now that depend on what we expect for the future. We make such decisions about weather all the time. Are we going to take an umbrella with us today? If we expect it to rain we will. How do we judge whether it will rain or not? We look at a weather report and see what it predicts. When I was growing up, there were lots of jokes about weathermen and how bad their predictions were. It’s been a long time since I’ve heard one of those. That’s because these days, weather predictions are usually pretty good. If you check the weather report in the morning and it says it is going to rain that day, then it is very likely that it will, indeed, rain. Those weather reports are based on computer models and today those computer models are pretty good. I don’t understand the details of those weather models but their track record gives me confidence in them. So one lesson I take from this is that computer models can be useful.
I think computer models can be harmful too. We have a recent example of that too. One of the causes of the recession that began in 2008 was the large numbers of credit default swaps that had been sold. The companies, such as AIG, that sold them used computer models to estimate the risk associated with them. Those models were flawed. As I understand it, the basic fault was that they assumed that the risk of someone defaulting on an obligation was independent of the risk of someone else defaulting. For example, if the owner of the house next door defaults on their mortgage, that doesn’t mean I will default on my mortgage too. (This is almost certainly a simplification of the actual situation.) Unfortunately, for them (and us) that wasn’t correct. For example, if a big company closes a big factory in a small town, a lot of people in the town will be out of a job and a lot of them might default on their mortgages. Basically two of the seven deadly sins were big players here: greed and pride. The people who created and used the financial models were too confident about how well they understood the financial system and in order to get as much money as they could, the took unwarranted risks.
So what about climate models? Personally, I don’t think they are nearly as good as the weather models but I doubt they are as bad as the financial models turned out to be. Climate models don’t have the sort of track record that weather models have. Every day we get a new weather report and we can compare that report to the weather that actually occurs. We can’t do that with climate models. Climate models make predictions over much longer time scales and the predictions they make are harder to compare to reality.
First of all, it is hard to measure the climate. We can’t go outside and measure the average temperature. We can only measure the temperature at that time we make the measurement. We have to make lots of measurements to get an average temperature.
Second, the long time scales involved in climate models means that we haven’t had the opportunity to compare the models to reality to the same degree that we have with weather models. That means if there are important errors in the models, we might not yet have had a chance to see them.
Twenty years ago, I was of the opinion that global warming was likely but unproven. (I also thought that global warming was sufficiently likely and serious that we should try to do something about it.) The reason I thought global warming was unproven was because of a conflict in the data. The ground-based measurements indicated that the temperatures were increasing but the satellite data showed no such trend. It wasn’t clear which was correct. The ground-based data might have been affected by local effects. One hundred years ago, a weather station that is now in an urban area might have been in a rural area because a city grew up around it. It is well known that cities are heat islands. They have warmer temperatures that the surrounding rural areas because people heat up their houses in winter and they build black roads that absorb heat in summer and probably because of other reasons that I don’t know about. Such effects could have introduced a bias into the ground-based data. You could try to eliminate it by only using readings from weather stations that were not affected in this way but you would have to be careful in how you did it.
It turned out that it was the satellite data that were wrong or at least wrongly interpreted.
Measuring temperatures of the earth from space is a bit more complicated than measuring it on the ground. You don’t measure temperature directly. Instead you measure something else like infrared light and convert that to a temperature reading. One of the things that wasn’t adequately understood at first was that the distance from the earth to the satellite affects the temperature reading. That wouldn’t matter much if the satellite’s orbit never changed. Unfortunately, the orbits do change. Friction with the upper parts of the earth’s atmosphere causes the orbits to decay and eventually, the satellite crashes to the ground, burns up in the atmosphere, or is boosted into a higher orbit. Because the satellites were getting closer and closer to the Earth, their temperature measurements got progressively worse. Once this effect was understood, it was possible to correct for it. When the corrections were made, the ground-based and satellite-based temperatures both showed a warming trend.
The problem with the satellite temperature measurements was a problem with the computer model used to convert what the satellite actually measured to a temperature reading. The model did not include an important process (change in the satellite orbit) in its calculations and hence gave an incorrect result.
With groundwater models, there have been similar problems. In the textbook, Applied Groundwater Model, by Mary P. Anderson and William W. Woessner, the authors discuss a study in which the predictions made by four groundwater models were compared with what actually happened several years later. In all four cases, the model predictions were wrong. The reasons why they were wrong varied and I don’t remember exactly what they were. In at least one case, the model had failed to include an important process. If I remember correctly, another one was wrong because they had to guess how much people would attempt to pump out of the aquifer and that estimate was wrong. In any case, one lesson from that study was that with predictions over long time scales there is a lot more opportunity for the predictions to go awry and one of the ways they can go wrong is by failing to include an important process. Another lesson is that some things that are important inputs for the model (the pumping rate) may themselves need to be predicted and that predicting them may be difficult or impossible. In the context of climate change, the timing and magnitude of volcanic eruptions is a similar sort of input. By injecting sulfates and other chemicals into the atmosphere, volcanos can affect climate but nobody can predict a volcanic eruption long enough in advance to be useful for climate modeling. The climate modelers are certainly aware of the possibility of errors due to important processes being misrepresented because one section of the IPCC report specifically addresses the known limitations of the models in representing certain processes (page 9-60).
While the possibility of errors in the models may mean that the predictions of the models are imprecise or even wrong, that is not a valid reason to believe that climate change is not occurring. Climate change is not a model prediction; it is an observation. What the models are good for is for giving us some understanding, however imperfect, of why climate change is happening and the direction of climate change.
If the climate models are imperfect, does that mean we don’t know enough to make decisions that involve climate change now? I believe we can make such decisions based on things that we do know.
1.     We know that elevated levels of carbon dioxide can lead to warmer temperatures. We know that, for among other reasons, because that’s why Venus has such a high surface temperature. Venus is hotter than Mercury even though Mercury is closer to the sun.
2.     We know that the levels of carbon dioxide in the Earth’s atmosphere are increasing. We know that because we have measured it.
3.     From geologic measurements, such as measurements of carbon dioxide from Antarctic ice cores, we know that the levels of carbon dioxide in the Earth’s atmosphere are higher now than they have been for a very long time. According to the Summary for Policymakers, it has been at least 800,000 since carbon dioxide levels were this high. For context, the earliest fossil record of modern humans is from about 200,000 years ago.
4.     From the fossil record, we know that during most of Earth’s history, glaciers covering entire continents (such as Antarctica) have been uncommon and that consequently sea levels have been higher than they are now.
5.     We know that glaciers are glaciers have retreated worldwide because we have measured the retreat.
6.     We have a good estimate of the rate at which ice is being lost because we can measure the change using satellite data.
7.     We have measured the rate at which sea level is rising and most of that rise can be explained by glacial melting.
From the above, we can make a decision about whether or not we can expect sea level to rise in the future. We can expect it to rise in the future. If our infrastructure, such as subways in New York City, is vulnerable to such a sea level rise, we need to decide whether we should do something to protect that infrastructure. It is important to note that our infrastructure doesn’t need to be below sea level to be vulnerable to sea level rise. To be vulnerable, a structure just needs to be below the highest likely storm surge. When sea level rises, the elevation of that storm surge rises too.
1.     We know that in many regions, the timing of snowmelt is important for water supply. This is particularly true in the western United States.
2.     With rising temperatures, we can expect the timing of snowmelt to change.
From the above, we can make a decision about whether we need to plan for a change in the water supply in regions where snowmelt is important for water supply. We do need to make such plans.
The biggest thing we need to make a decision about is whether or not we need to reduce or limit carbon dioxide emissions from the burning of fossil fuels. There are big risks to it. If we choose to limit carbon dioxide emissions, we risk wasting a lot of money, time, and effort on something that we may not need. If choose not to limit carbon dioxide emissions, we risk changing the climate in ways that we don’t understand and with effects that we do not anticipate. Furthermore, no matter what decision we make, we will probably never know the full outcome of our decision. (Our descendants might know but we probably will not.) I think we have enough information to make a decision about this.
1.     We know that the climate has been changing in the sorts of ways that the climate models predict.
2.     We understand why the climate is changing though we may not be able to predict the extent or rate of change as well as we would like.
3.     Carbon dioxide in the atmosphere has been increasing and has increased to levels unprecedented in human existence.
4.     The increase in carbon dioxide in the atmosphere is a major cause of climate change.
5.     The increase in carbon dioxide in the atmosphere is due to the burning of fossil fuels.
6.     We can not easily reverse climate change.
In my opinion, the prudent thing to do would be to limit carbon dioxide emissions because the consequences of failing to do so are too severe.