Why physicists still use Fortran (2015)
moreisdifferent.com
moreisdifferent.com
This is so true. I'm a PhD student in physics using Fortran for pretty much that reason. At the start of my PhD, in response to my supervisor telling me I should learn Fortran to modify our current codebase, I asked if I could rewrite what I'd be working on into C++ first, since I was already familiar with it and wanted to bring future development into a more "modern" language.
His response was "You could do that and it would probably be enough to earn your PhD, since it'll take you at least three years. But I suspect you'll want to work on something else during that time".
He was right. I later learnt one of our "rival groups" attempted the same thing and it took three phd students working full time for a year to rewrite their code from fortran to C++.
In contrast, porting the 30+ year old molecular Dynamics package AMBER to CUDA took about 3 months and probably established me as a CUDA expert. In my opinion its well-maintained Fortran 90 code was far easier to understand and refactor.
While my primary languages today are C++ and CUDA, there is something clean about Fortran when it comes to understanding underlying algorithms. I have a similar opinion about well written C code.
The compression would presumably remove the redundancy of the language itself as a factor (including differences in idiomatic cyclomatic-complexity "depths" of various stdlibs), and also remove any redundancy in the way the test cases were specified. So it'd be down to a measure of how much circumlocution and over-engineering you did in the process of implementing the solution.
I'd worry slightly that code-golf solutions would be rewarded, though. Maybe pass everything through an obfuscator + linter before computing the metric, so that things like identifier lengths and spaces aren't considered.
I constantly run into code where someone takes an obscure corner case in the language, and builds an entire edifice around it.
May I ask how? I don't see ads or any other obvious monetization channels.
GP is not talking about http://rosettacode.org/wiki/Rosetta_Code
The head of information security at the UW calls the PSTN bulletproof secure, but VOIP insecure, then babbles on about how he shares classified info with his buddies casually (happens to be a felony to share said info).
Needless to say, UW's Avaya phone system barebacks the internet, with no regard for using silly security things like TLS or SRTP.
https://sourceforge.net/projects/folderol/
Why write the port in the first place? Because back in the days of yore, I was doing the equivalent of adversarial search to try and design a better potential function for predicting protein tertiary structure. I ultimately arrived at the result that there were too many adversaries to make linear models and single hidden layer neural networks work.
And unfortunately, my postdoctoral advisor at the time didn't consider this publishable research.
OO allows you to make a much worse mess than procedural programming in my experience.
Graduate students need to think in terms of 4-6 years while forward looking professors might want to think in terms of 5-15 years.
A bad advisor wouldn't care what his students wanted, but a good advisor might still have students work on this kind of project as long as they were aware it wasn't going to help them get a tenure track position in the future. If they wanted to go work at a national lab doing HPC work and programing it might have been plenty ok for their career (This is what I am transitioning to now) or if they want to go work for a hedge fund or apple it might also be an okay option.
In the process, they would have understood nearly every approach taken by the group towards producing the results that it does, and I bet that has helped them when they've ended up modifying that same code later for their research. And with fewer supervisor meetings to work out exactly what X, Y and Z part of the code does because they will have worked on it themselves.
I'd say I've easily spent 6 months just spending time getting my head around all the code we work with anyway, so at the very least, I hope that made their following years of research more productive.
However, I guess one drawback is that a lot of the things we currently implement are all written from scratch (for very standard things such as numerical differentiation and parameter optimisation), which has the advantage of having "control" and more understanfing over the code, but less time saving/potentially not as efficient as using pre-existing libraries.
as someone who had contact with that codebase, do you have any insights as to why that is?
Was it the sheer size of the thing? Was it some nuance that Fortran had as an advantage over other languages? was the math just difficult to follow?
Genuine curiousity.
It must surely be generic equipment management, you're not running experiments in physics that are > 30 years old, surely?
> 20,000 lines of code really doesn't seem like that much.
It's not "20k lines of code" but "n lines of code that grew organically over decades to 20k lines" - with the help of probably way more than 100 people who all are not trained as developers. I think it's a safe bet to say the current state only has a faint memory of being a consistent code base.
Once I spent close to a month hunting down a subtle but nasty bug in a number crunching module which was perhaps around 2k LoC. Writing code is very easy. Verifying and validating number crunching code is very hard and very time consuming.
A Ph.D. student or a young researcher might be more interested if a rewrite lets them run experiments using Amazon / CUDA / whatever for a few thousand dollars instead of spending scarce grant money on dedicated hardware.
http://www.nersc.gov/systems/cori/
I completely agree on the domain knowledge statement. It is 100% required more then the CS degree.
I would guess that a C++ codebase written by PhD students, not by seasoned C++ experts, is more complicated and much slower to debug, than a corresponding Fortran codebase.
So especially in the hands of non-experts, Fortran should produce less bugs.
No, I'm not kidding.
I shudder to think what they'd have done with C++. :-)
Function has its side effects. It's use as only once case is really questionable, justified by lack of other means.
I don't know of any studies like this. But there are two aspects to consider. One is what you've pointed out, which is the long-term scientific gains and the productivity of the research group as an entity. But the other aspect is whether those students who rewrote the code into C++ were more or less successful than the students who weren't rewriting code.
Obviously, how you judge success in the latter will be tricky, since there may be differences in the interest of students who rewrote the code and their desired outcome after the PhD (e.g., stay in academia versus go into industry).
I actually rang the recruiter to query why would not be simpler to train your existing staff to use Fortran - the add stayed up for years and years I always wonder if it ever got ported.
I did actually rewrite both IDL and Fortran, but it was always smallish, single-purpose programs or functions.
Note that the SPICE Toolkit[1] is still written in Fortran today, translated to C using f2c, and the C version used as the base for other language support. The Fortran part is unlikely to ever go away, since support for processing past missions is crucially important and all that processing code was written in Fortran. Also, talk about your stable, backward compatible APIs...
That being said, as someone who has integrated CSPICE into several C++ and python projects, the modernization would be a very welcome change. The current arch depends far too much on global state, and none of it is threadsafe.
Good to know Boris is still there! Was Chuck still heading up the team when you left?
> a plan for a complete rewrite in C++
Oh, no! That's a real shame. I'd be all for a rewrite, especially considering their insane test coverage, but that decision worries me.
> That being said, as someone who has integrated CSPICE into several C++ and python projects, the modernization would be a very welcome change.
As someone who worked mostly with CSPICE in C but also with some other non-Fortran toolkits, I agree.
Curious if anyone in your group considered using it?
"At the time, Randy was still stupid enough to be flattered by this attention, when he should have recognized them as bone-chilling words. Three years later, he left the Astronomy Department without a degree, and with nothing to show for his labors except six hundred dollars in his bank account and a staggeringly comprehensive knowledge of UNIX."
– Neal Stephenson, _Cryptonomicon_ (p. 78). HarperCollins.
But it describes two options:
1. "A staggeringly comprehensive knowledge of UNIX", three years of domain-specific education, and a network of people who trust you to--no, who depend on you to be able to get things done with that knowledge
2. A piece of paper just like everyone else in the department.
And while the former might be more difficult to make use of, I think it could be much more valuable in the long run.
>> except six hundred dollars in his bank account >> are ways to get this knowledge.
Edit: are ways 'better' to get this knowledge.1. "A staggeringly comprehensive knowledge of UNIX", three years of domain-specific education, and a network of people who trust you to--no, who depend on you to be able to get things done with that knowledge
2. A piece of paper just like everyone else in the department, three years of domain-specific education, and a network of people who trust you to--no, who depend on you to be able to get things done with that knowledge (and probably a girlfriend)
This might be the case, but he's now like the janitor who unplugs the toilet. His work may be appreciated, and it might be necessary, but it's not respected or well remunerated. I guess he gets a little bit of respect for unplugging more theoretical pipes, but a little respect isn't a PhD.
To paraphrase: "Usually a comprehensive knowledge of UNIX and a girlfriend are mutually exclusive."
So cut-n-paste code. The students are running code that they don't really know what it does, it might not even be correct...it's like StackOverflow in academia.
IMO, Python stands a better chance of breaking the Fortran's lock on physics related computing. Give it a few more years and enough numpy-based libraries might make Python a real competitor. My 2c
Can you clarify why you think Python might be able to do it? For scientific computation with high performance requirements, Python is not competitive with Fortan or C++. For work that continues to happen in Fortran due to "academic inertia", my impression (and vague experience) is that researchers find the convenience of what they're accustomed to (Fortran) to be greater than the convenience of things like rapid prototyping offered by the various Python scientific computing and data analysis libraries. There is a mental overhead is switching, and I think most academics are sort of okay writing code in whatever is familiar and battle-tested if it means they can focus more on the research at hand.
In other words, I'm not saying you're wrong, but I'm not following your reasoning.
Speed is not a huge issue if you're happy to leave your simulation running overnight anyway, or if you have the option to just throw more and more cores at the problem (or in our case, both). The goal is to get your papers published. Code developing/interpreting/debugging time is generally far more serious an obstacle to that goal than simulation speed. I was the only developer there. Everyone else in the group coded on an almost daily basis, but none of them considered themselves programmers, and very few of them actually learn about good programming practices. They're biophysics researchers.
Having not worked in Python much before I was also pretty pleased to find that, having determined that I needed to use Dijkstra's algorithm for path-finding and then working out the smallest Standard Deviation between certain sets of data points, Python came with libraries to do both of those things off the cuff. It's just so easy, I can see why it has a favoured place in this field.
What about those cases that it's the matter between throwing at 1000 core cluster and wether we can have results before next conference in a couple months. That is what really defines the scientific programming -- it's about feasible and infeasible. For other jobs, isn't it just matter of taste?
when I worked for BHR group (a Hydro dynamics research organisation) some times we had emergency projects that had < 24 hour turn around. I recall one where a clinet had had a serious issue at a plant and we ran the simulation and produced a report in a single day
Speed is not nearly as important now as it was 10-15 years ago. A typical scientist's worstation has 20 CPU cores. If I want to use 100 CPUs for a few days, it is trivial and 1000 is easy to get. Thus the fact that Python is slow(er) does not bother me unless I am setting up something major.
What matters though, is the availability of libraries that let me reliably run my experiments. If there is a bug, it must be in my code, not the library -- a "discovery" caused by a software bug is humiliating. This is where Fortran shines and Python is not quite there yet -- the decades of beating on those libraries made them very well understood and trusted.
I am not talking about interactive programs -- a slow browser is annoying. I am talking about scientific computing. This is just my experience, can you provide some counterexamples?
A lot of Numpy is written in FORTRAN.
I wonder if there are any transcoders for Fortran to C++? I wonder if there is even a market for something like that? I've written alpha versions of transcoders for C to Java and Java to Objective-C and I think I could do the same for Fortran to another language but why?
Writing a transcoder first is the right way to do it and it should take you a couple of months to do it, especially if you already have some experience with this kind of stuff. Definitely less than a year for a single person. I would not try to translate the code by hand. It would be a never ending project full of bugs.
Edit: Apparently there are plenty of Fortran to C++ transcoders. Here is just one I found during my google search: http://cci.lbl.gov/fable/
No idea how good they work.
I managed to hack in a step which just dumped the memory of resulting frame to a file, and then we wrote a Python script to read that and produces a PNG.
We combine the PNGs into an animation and show someone else in the department because the supervisor wasn't in that day. "Cool! But, hrmm, those boundary conditions look wrong." Sadly, this was 2/3s into his Masters.
Like much now in Physics, the original code was simply incorrect. This happens all the time, and papers get retracted because of it - well, that's the best case if somebody notices.
At the end of the day, programming languages come with eco-systems, and must be chosen solely as a tool. The problem is not with Fortran, but that often Fortran == outdated development practices and in Physics horrible code hacked on by 10+ people without prior programming experience.
I don't know what can be done about it except hiring programmers to write code, which wouldn't be either easy or cheap
I can see many projects being improved by providing a Python pre-processor that writes out e.g. a binary config file, the hard-code Fortran/C simulation code reads that, and spits out the simulation results, and then having a Python post-processor that does the pretty stuff at the end.
Academically, it seems that pairing CS undergrads with Physics undergrads to do e.g. a molecular dynamics (MD) course would be cool. The Physics behind MD isn't too hard, and given the right parameters the programming part would be manageable. Then again, CS undergrads aren't necessarily great programmers either...
Clean code and tests are overrated. Version control and a big eco-system is underrated. It's like maths, physicists don't understand maths, they just use it like a carpenter uses a nail without understanding metallurgy, or a programmer uses a CPU without understanding solid-state physics. And that's okay.
There are several ways to bind Python and fortran together. E.G http://arogozhnikov.github.io/2015/11/29/using-fortran-from-...
But that doesn't seem the case. The choice seems to be between python and c++/fortran. Does anyone know why?
2. The choice is either "fastest possible" or "I just don't care how long it takes" - for either development or run time. There is usually no middle ground.
3. Tooling - the scientist is most likely using a text editor not an IDE (especially when they start working). Fortran and python are both low enough on boilerplate to not need IDE support.
4. Abstraction level. Scientists in general don't bother care about abstraction level at all. Procedural programing's abstractions are usually more than enough for them (and may actually be the correct level for some numerical work - think cache misses vs. hits).
5. Some areas of science do use Java (check out imagej for example).
Sounds perfectly normal :)
The standard advice here at work for one of our modelling packages is: if it crashes try rotating your input model by one degree and try again. Most of the time that will fix it. If it doesn't fix it try one degree in the other direction.
Is correctness somehow assured provided it doesn't crash? Or is the whole thing just a joke?
I'm sure lots of people do. We're a commercial company selling consultancy service around this software (technically around some inhouse tools built on top of this software), among many other things.
Is correctness somehow assured provided it doesn't crash?
On the whole well tested PDE solvers either crash, give answers that are off by several orders of magnitude, or give a correct answer. (If the answer they give is relevant to what you're trying to model is left as an exercise to the reader)
We're reasonably sure that, if the calculations converge, the solution provided is a correct numeric approximation (within the error bounds given) of the PDEs we're claiming to solve. We also believe that the PDEs we're using provide a reasonable balance between modeling what we claim we're modelling and our computation running in a reasonable amount of time.
From this point of view, rewriting code is an extremely high-risk proposition. As we know, the likelihood of discovering bugs during this process is quite high.
There's a salient lesson here. Clearly, this was a stupid decision for two reasons:
(1) there are many thousands of scientific routines that have had 40-60 years of fine honing and careful debugging and they just work! (For instance, we send voyagers—Voyager, Cassini, etc.—to the end of the solar system and they invariably get there; the Fortran routines that get them there do exactly what they're supposed to do (unlike much of today's poorly written C code)!
(2) Rewriting that already-reliable fully-debugged Fortran code into any other language will almost certainly make it far less reliable, thus it's a no-brainer to stick with the original .F source.
Yes, Fortran is simpler than C [consider it BASIC on steriods] and years ago it had long since evolved well past John Backus's 1954 incarnation of the language into solid workhorse that both physicists and engineers use regularly.
Just because something is old and out of fashion doesn't mean that it's broken or doesn't work well. (Longevity ensures that there's been sufficient time for many hands to make it reliable.)
(Oh, BTW, I'm reminded that decades ago when I was just beginning to learn Fortran using punch cards on an IBM360 mainframe with the WATFOR FORTRAN-IV compiler, that I made four errors in only six lines of code. After dutifully printing ERROR against each offending line, the compiler finished with the message: "YOU NEED TO SEEK ANOTHER CAREER " or words to that effect [yes, it was in uppercase]. Eventually, I got considerably better.)
When you're writing up your proposal for a contract or a grant, the theme should always be that you're "adding capabilities" (which should be well-defined and constrained) to the existing codebase. If you get the money, then you've got carte blanche to rewrite to your heart's content - just don't tell the customer that this is what you're doing. Just make sure that those new capabilities indeed make it into the re-write and that you introduce no regressions in the new code.
I hate how I can't publish easily on modifications I make to our PIC code because it isn't open source; eventually I'm planning to switch to another code (and might implement a needed solver for it) just for the sake of my publications.
But yes, no one sees it this way.
For e-mail, I generally create a new one, and over a year or two, I create new accounts with the new e-mail and gradually move accounts until the old one is seldom used. Similarly here, it may be a bit tricky, and it really depends on how intertwined it all is, but gradually writing new pieces that you're adding in a new language, or using C++ for pieces that you're rewriting. eventually you'll be much closer than trying to do it all at once.
Modern Fortran has many nice features in 2017, but the people that wanted these features moved to C/C++ long before the features became available in Fortran and those that are left using Fortran are usually scientist, not programmers, and so don't care so much about these features. I think it is largely the older generation that says they will never stop using Fortran, in the survey mentioned in the article.
Just to suggest where the field is moving though. NwChem is a large successful electronic structure package using Fortran. Its next gen version NwChemEx that is being designed for exascale will exclusively be written in C++ (https://www.pnnl.gov/science/highlights/highlight.asp?id=441...).
Also just from experience people who work in HPC mostly would rather be writing C/C++, but use Fortran because they have to not because they want to.
In my opinion, Fortran will fall behind as newer hardware, libraries, etc, will drop Fortran support. Also, newer grad students are all much more interested in C/C++/Python. I think this is in part because the newer languages are widely used outside of science and therefore there is much more documentation and tutorials/guides. Not to mention that skills in those languages are transferrable to other areas (data science, machine learning, etc).
As a side note: Wow someone working on the ECP on HN? I'm tangentially related to the project (and just visited PNNL last week)
Really? Seems to me that with very few exceptions (e.g. GPAW which is python/C and nwchemEx which I've never heard about until the parent poster mentioned it), electronic structure is pretty much a Fortran bastion.
(Source: I did a Phd doing mostly electronic structure calculations, graduated ~5 years ago)
New libraries are being written in C/C++, and maybe Python. This includes libraries that should form the foundation of the QM community (matrix/tensor and integral libraries). These are meant to take advantage of newer hardware and libraries which themselves are written in C/C++, and often in a way that is inaccessible from Fortran.
The old Fortran code will be around for a long time, but I don't know of any large-scale, serious efforts to develop new packages or major new functionality that are starting with Fortran.
(I'm not totally against Fortran - I just spend a week devloping in it. But I still much prefer C++ and Python)
My background is in QM, so I guess that's my bias showing through :)
Somewhere under http://www.archer.ac.uk, there's a summary of the time used by various codes on that UK "Tier 1" system.
I'm afraid you need a 10-, or preferably 20-, year perspective, not a week.
About C compatiblity: Many C libraries use pointers in their interfaces. Interoperability is indeed defined by the Fortran 2003 standard, which I have used several times to wrap existing C libraries. However, much of the existing code is F90 only (some even F77...), and a vast majority of Fortran developers in the field are not familiar with even modules and other F90 features, let alone iso_c_binding in 2003.
Also, newer libraries tend to be C++ as well, which is more difficult (or at least more awkward) to wrap.
Finally the fact that groups like Facebook and google are writing their machine learning code in C++ shows that 1 they find it useful and 2 plenty performant. This kinda became a response to the comment above yours sorry.
If you don't feel like it, feel free to ignore.
On the parallel front MPQC has been around a long time and is C++.
So why is NWChem being re-written in C++, and what relationship does that have to exascale? Richard O'Keefe said 10 years ago ago "Why not start by rewriting the Fortran code _in_ Fortran? Fortran 90 is a very pleasant language." (NWChem is just in Fortran77 as far as I remember.)
I work in HPC, though I don't write numerical code these days, but I'd definitely prefer to write it in Fortran than C, and I'm not clever enough to use C++. I'd also much rather maintain typical scientific Fortran.
So my first programming class ever was a Numerical Analysis class taught at FIT, and to be honest, this was my first exposure to a "real" editor (vi on a PDP11 in this case)..up to then it was all MS-BASIC with that wonky line editor and, of course, goto-s and line numbers.
At the end of the first class (8am ugh), the instructor announced that anyone looking to get extra credit and perhaps skip having to come to early class, to talk to him after class. Of course that sounded good to me, so I went to see him and he said "ok...if you can write me a bowling league manager in 10 weeks you will get an A and not have to ever come to class."
Ok...hell yes in fact! This sounded a ton more interesting then sitting around a silly class talking about programming. He gave me a spec sheet and away I went to lab to begin my struggles with vi and FORTRAN.
I wasn't easy, but holy shit did i learn a lot...more then I ever could have just doing the exercises in floating-point rounding error and non-linear simulations (I ended up doing that later as well) that were "taught" in class.
I can still remember FORTRAN (77 I believe) has the a very strict formatting scheme where the column had to match the keyword in order of the program to compile or something stringent like that. But mostly, coming from BASIC, it was a breath of fresh air.
I ended with completing the program with extra bells and whistles...sorting, multiple leagues and other things...and the instructor was duly impressed.
I got my A and never woke up before 8am again.
Hurray for attendance-optional JCs! :D
Most of it transferred to an UC and then the fun began:
- caching http/1.0 forking select() proxy server as the third project in a networking class, circa 2002
- Java subset to MIPS assembly compiler
- Reimplement most of the OpenGL pipeline in C++, quaternions and write a trapezoid (scanline to scanline) engine (on which a triangle engine could be built). Oh and then model the interior of the building.
- Pipelined, microcoded, simple branch-predicting processor. Bonus points for smallest microcode and fewest microcycles. (I Huffman mapped the histogram of the sample assembly programs’ executed instructions to the user-defined binary macro ISA (students had to write the assembler too), and then used progressive decoding in the microcode (43 micro ops long microprogram IIRC). Blew the doors off the extra credit in that class.)
Another issue is computational people think C++ is about OOP, ffs, what a way to sell C++ short and ignore the more significant tool C++ brings to the table: generic programming. Whenever I talk to my computational colleagues, they talk about "C++ and OOP" as if they are two peas in a pod; what if I told you you didn't need to use inheritance to leverage the best of what C++ offers (what if I told you you didn't need inheritance to even leverage OOP!?). Templates have the potential to be a powerhouse for performance in codes I feel, just no one in the computational side has leveraged them because they quite simply don't understand it.
The same sort of thing is true for cs people and their critique of Fortran usage, but I'll leave scathing comments on one of those stories that are shared here.
What do you base this on?
It should instead be compared with how long it took to engineer and build the system or program in a particular paradigm and the qualitative engineering aspects of a particular platform. FP may be amazing for certain areas, but a difficulty in basing a large-scale project or business on it would be hampered by the small supply of developers who can comfortably program in it.
Regarding more important performance issues like low level control of memory layout and avoiding pointless copying and indirection, C++ and Fortran are both at the most effective end of the spectrum, while typical functional languages lie between "don't even think about it, by design" and "it might be OK but only a fool would put a project at the mercy of what optimizations a relatively unproven compiler opts to do".
This doesn't actually make Python an alternative to Fortran, though -- what it's saying is that no one writes the performant code in Python.
https://calhounpress.net/blogs/blog/78070918-wet-streets-cau...
There was a library written in Fortran called CERNLIB which included a broad variety of miscellaneous numerical algorithm implementations (e.g. minimization, integration, special functions, random number generation) [1]. I couldn't tell you exactly when the library was first released, but my best guess would be the early 80s. It can't possibly be later than 1986 when PAW was initally released [2]. The field has since transitioned from the Fortran based PAW to the C++ based ROOT since then, but many high energy collaborations still rely on CERNLIB for their own analysis frameworks (keep in mind that many of these experiments had been in planning and development stages for over a decade before they actually turned on).
The thing about this that I find interesting is that compiling CERNLIB has become a lost art and that this fact has had far reaching consequences. The last available binaries were compiled with GCC 4.3 in 2006 and packages are only available for Scientific Linux 4 [3]. This crucial dependency has led to collaborations using extremely outdated Linux distributions and GCC versions in their computing facilities. The majority of analysis code is written in C++, but not even C++11 additions can be used because everything is frozen on GCC 4.3. Nobody can even run the analysis environment on their local machines without resorting to the use of virtual machines running SL4. It was really a nightmare to deal with.
[1] - https://en.wikipedia.org/wiki/CERN_Program_Library
[2] - https://en.wikipedia.org/wiki/Physics_Analysis_Workstation
(1) Each compiler gave different results: compilation errors, code that goes in an infinite loop.
I've heard an anecdote of HEP analysis code that was written by a team in C++ and wasn't ready for impending data collection on LHC. Someone apparently rescued the situation by turning up with a working Fortran system he'd written on his own. I don't know details other than which university group the report originated from; I'd be interested to know more about it.
The bigger experiments at CERN use C++14 and python quite a lot. There's still a bit of wrapped FORTRAN code kicking around, and we definitely use rather old school distributions, but I haven't seen anything as bad your anecdote.
Why would IO be slow in any language? What does the language have to do besides buffering and system calls?
> In Fortran, variables are usually passed by reference, not by value. Under the hood the Fortran compiler automatically optimizes the passing so as to be most efficient.
Aren't arrays implicitly passed by reference in C also?
I believe many Fortran implementations default to unbuffered io.
Which is probably easy enough to change.
But I think that's really the core issue. Physicists don't want to learn more about programming languages. They want whatever mostly works out of the box and has local documentation and expertise specific to their problem domain.
>Aren't arrays implicitly passed by reference in C also?
He covers that. C passes arrays by reference, but the individual elements aren't contiguous. He says Fortran passes an optimized reference.
That seems to be the context from his example:
for(i = 0; i < nrows; i++){
array[i] = malloc(ncolumns * sizeof(double));
}
I suppose the counterpoint is that he's doing it wrong. But again, maybe physicists just don't want a tool with that much flexibility. arr(m, x, y)
Not quite as nice, but not too bad. double *a = malloc(sizeof(double)*nx*ny*nz);
int id;
for(int k = 0; k < nz; k++) {
for(int j = 0; j < ny; j++) {
for(int i = 0; < i < nx; i++) {
id = k*nx*ny + j*nx + i;
a[id] = /* some mathematical operation */
}
}
}
You can do it in other ways (arrays of pointes, etc), but I think this is probably the simplest conceptually, and the memory is contiguous.Sure, C could make multi-dimensional array handling nicer, but I have macros that basically do his A[x,y,z] for me, admittedly a bit more verbosely.
Many of his points about Fortran are true, but almost all his statements about C are false. Or nearly so, yes, copying an array of floats requires calling a function, memcpy, and not just using an equals sign, but that ain't rough and falls into his idea of "what actually happens ‘under the hood’ inside a computer". And others are easily handled by adopting things like the MKL (want to take the sin of everything in an array, see https://software.intel.com/en-us/mkl-developer-reference-c-t... )
That being said, I usually just use python and surf on other people’s hard work!
Oh, and the author is wrong on many of the specific details. For instance, MPI is available to many languages, including python.
I read this whole discussion with interest, and I think this is the most compact and insightful statement here. Thinking about it this way makes the situation very clear.
Everybody is used to cringing when they hear "legacy code," and that's justifiable for several good reasons. Note that "not wanting to learn an unfamiliar language" isn't one of them. And "not having, or not being willing to use/cultivate, the skill set of reading someone else's code" isn't one of them either.
But there is obviously a lot of bad code out there. And that's the thing, there are only two kinds of code: good code and bad code. And by extension there is bad legacy code and there is good legacy code. Don't assume legacy code is always bad code. If something has been used successfully for 40 years, do yourself a favor and try to have the humility to assume people implemented it well, found all the bugs, know what they're doing, and/or generally are rational-thinking adults who make good choices... instead of the usual naïve assumption that everybody's an idiot but I'm going to change all that! No, you're going to duplicate a lot of effort, and possibly (depending on the faithfulness of your reading of the code) reintroduce some of the same bugs that were dealt with years ago.
But if you try to refactor the code to, say support other feature or optimise it, you might get into nastiness that is beyond comprehension, and you cannot count on that the code is coherent or correct.
This is my experience for maintaining a legacy base that has been many years in production. It's just a pile of frozen code that nobody has properly refactored probably out of fear for breaking something. This way you end up with unreadable layers and weird technology-specific hacks that were carefully made just work, probably not understanding what the existing code actually did but cargo-culting and resulting with massive amount of code that does little.
I think this is fairly recent that C/C++ wins. I don’t know how recent exactly, but I remember a colloquium not too long ago by a compiler researcher who said that cross-compiling to Fortran and then optimizing almost always produced faster code than the C/C++ compiler could. Fortran is apparently easier to optimize.
If a specific function is important enough it will be hand optimized in a way that the language doesn't really matter. Sometimes that means calling MKL, or using Cuda, or writing your own assembly.
Which is the main reason why ANSI C++ members are not keen in having restrict in C++.
Amen. A one-character mistake might take a week to find as it exhibits only subtly wrong behavior (e.g. wrong grid convergence rate, overly noisy boundary condition, odd symmetry breaking beyond IEEE floating point). During that week no science happens.
Originally, Fortran had manual memory management, as per the times. Thankfully, the language progressed.
Overall, the evolution of languages from assembly/raw instructional to procedural ones needed early languages like Fortran on which other higher-level languages, tools and OSes could be later built/bootstrapped.
Why haven't we moved to something else? It works, it is time-tested, and the original author continues to maintain it.
(P.S. I'd like to compile it with the gfortran tools, in order to preserve the library for the future. Is there any documentation for simple conversions from Microsoft's implementation of the language to the more-traditional spec?)
What's the plan when they retire?
That's not a piece of software I'd want to tie my code to.
Answering my own question: It doesn't appear to be.
https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprogra...
Immense amount of effort was put in performance, correctness, feature set, and numerical stability of such widely used libraries. Replacing the without a very good reason is hardly feasible.
The point I am trying to make is that Numpy is unlikely to still be using the exact same code that was written in the 1970's unless its performance isn't critical. It is making the same function calls but the actual code will look pretty different.
Basically I refused to touch this thing, using a library which makes the code unreadable is going to be a bug magnet. I would be surprised if I was the only one having this reaction to 1960s coding convention surfacing in modern code.
So selling new licenses should be a good enough reason.
https://www.nag.co.uk/numeric/DT/nagdotnet_dtw02/html/conten...
We use the algorithm published by Clenshaw [1]_ and referenced by
Abramowitz and Stegun [2]_, for which the function domain is ...
.. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in
*National Physical Laboratory Mathematical Tables*, vol. 5, London:
Her Majesty's Stationery Office, 1962.
.. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical
Functions*, 10th printing, New York: Dover, 1964, pp. 379.
http://www.math.sfu.ca/~cbm/aands/page_379.htm
Quoting numpy/core/src/npymath/npy_math_complex.c.src: /* Algorithm 312, CACM vol 10, Oct 1967. */
if (a >= 0) {
t = npy_sqrt@c@((a + npy_hypot@c@(a, b)) * 0.5@c@);
result = npy_cpack@c@(t, b / (2 * t));
}https://www.scipy.org/scipylib/faq.html#how-can-scipy-be-fas...
"Actually, the time-critical loops are usually implemented in C or Fortran. "
My understanding is that the code modernization and co-design efforts that are a part of the Exascale initiative are changing this.
The predominant issue is that physics codes are typically written by PhD candidates, often with little to no programming experience. The projects can span 3-5 years and continue existing in the physics ecosystem for decades. Good programming practices are seldom employed, and the codes become these massive patchwork ships, leaking everywhere with holes plugged by spaghetti code.
The issue is not that the students aren't smart enough to learn good programming practices, it's that the advisers are not patient enough to wait for documentation, unit tests and so forth. They view good practices as wasted time, after all it's "physics not computer science".
Unfortunately, the path of least resistance is actually to adopt unit tests, write code documentation and generally employ industry programming practices, it's just that this path has a barrier to entry and the benefits are not immediately apparent to older academics who have fallen out of the loop.
The end result is quite sad; students with advanced programming skills are chronically under appreciated in the field. Professors will happily bring them on board as post docs to develop their simulations, but they balk at giving them jobs based on their computational skill set. It is thus no surprise why the computational talent leaves physics and takes careers in the private sector where the union of math skills and programming is in high demand.
real, dimension(:,:), allocatable :: name_of_array
allocate(name_of_array(xdim, ydim))
Into something that looks like auto *my_matrix = new MathArray<double, 10, 10>();
The code the author showed demonstrates a lack of understanding of C and C++. Even if you restrict it to C your matrix code should look something like this typedef struct {
size_t rows, cols;
void values[];
} mat;
inline mat *matrix_make(size_t rows, size_t cols, size_t value_size) {
mat *m = malloc(sizeof(size_t) + sizeof(size_t) + (rows * cols * value_size));
m->rows = rows;
m->cols = cols;
memset(m->values , 0, rows * cols * value_size);
return m;
}
While that code may be complicated the physicists only need to see.... mat *matrix = matrix_make(10, 10, sizeof(double));
And if you'd really like you can hide the sizeof via a macro... #define MATRIX_MAKE(r, c, type) matrix_make(r, c, sizeof(type))
For me "real, dimension(:,:), allocatable :: " is much more complicated than "matrix_make"Many of the issues people see in the speed difference between Fortran and C code will likely be based on their misunderstanding of how Fortran actually does their data layout and a misunderstanding of how the computer hardware (and what you're describing to C) to do. This "Double array" that was defined would never be allowed in production code. The amount you'd be hitting the OS for even small allocations is crazy.
The arguments for Fortran, as far as I'm concerned, are:
1. We already know it
2. We're not going to get grant money to rewrite a library
3. We've built a bunch of computer clusters and have to justify what we spent (rather than buying 2 GPUs for your workstation)
4. We've all spent a lot of time learning how to use MPI that we're never getting back.An additional reason I've heard (I don't personally use Fortran) for keeping Fortran around is that it's straightforward to convert Matlab prototype code into Fortran
> Into something that looks like > > auto *my_matrix = new MathArray<double, 10, 10>();
The dimensions here are a template parameter. They must be known at compile time. Also, if you go this route and you want to write a function that, say, adds two matrices, you get one copy of that function in your binary for every matrix size that occurs in your program. You also can't naturally interoperate with someone else's matrix code unless that someone else specifically wrote against your MathArray template class.
> And if you'd really like you can hide the sizeof via a macro... > > #define MATRIX_MAKE(r, c, type) matrix_make(r, c, sizeof(type)) > > For me "real, dimension(:,:), allocatable :: " is much more complicated than "matrix_make"
It looks uglier, but it's language syntax rather than custom code. Whoever is reading your code doesn't have to unpack a macro and then look into a function to figure out what you're doing. (And as a bonus, the Fortran user can index the matrix without mentioning that it's a 'double' matrix when he's indexing.)
> Many of the issues people see in the speed difference between Fortran and C code will likely be based on their misunderstanding of how Fortran actually does their data layout and a misunderstanding of how the computer hardware (and what you're describing to C) to do. This "Double array" that was defined would never be allowed in production code. The amount you'd be hitting the OS for even small allocations is crazy.
Which many issues are you thinking about? Idiomatic Fortran has an inherent advantage over idiomatic C in that better aliasing information is available to the compiler.
> auto *my_matrix = new MathArray<double, 10, 10>();
In Fortran, one can choose the matrix size at runtime, though.But otherwise, great. Now if you just add slicing so that if we, say
allocate(name_of_array(-1:5, 1:3))
and then say fill in the matrix by 1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
then name_or_array(0:4:2,2:3)
should return 9 11 13
16 18 20
and then we're talking. (Slicing should of course also work in higher dimensions than 2.) auto *my_matrix = new MathArray<double, 10, 10>();
Into auto *my_matrix = new MathArray<double>(10, 10);
Most programs don't need dynamically sized arrays (rows and columns) and as such it makes sense to also provide a template Row and Column width. By doing this you can likely implement matrix multiplication and addition as a constexpr (with some effort) and thus get.... 1. Compile time matrix evaluation
2. Vectorized multiplication/addition of matrices
3. Pipline-efficient codeThat said, Fortran really is dying. Scientific code is much larger nowadays with more functionality and scientists want to do everything in one language. C++ and Python are taking over.
1) Some stuff is already written in Fortran so they don't want to rewrite that. I dig it.
2) It's fast (except C sometimes) but easier to write than c. Like 100x faster than python.
I'm not sure about number two. With the gpu processing revolution wouldn't a python/TensorFlow stack be faster than Fortran? Am I missing something?
I remember talking to someone who had worked heavily on atmospheric weather predictors recently and her description of the program was: we divide the space into tiny little cubes and then run some differential physics equations to predict what will happen next. My basic questions to her:
1) From a computational perspective this seems very GPU friendly.
2) Why not use a convolutional neural network? If you use the same data for training you will probably wind up with a more accurate prediction than a theoretically based physics system.
Her reaction was basically that she hadn't heard of these things before so my impression is in fact that the physics community is just behind and they will catch up when they are ready.
Hope I'm not missing something here.
As for general purpose GPU programming, some parts physics are GPU friendly put not all of them.
https://developer.nvidia.com/cuda-fortran
And no, neural networks aren't suitable for discrete problems.
Training a neural network to map "current state of atmosphere" to "state of atmosphere in the future" is definitely possible to do with a neural network, and sounds like a good idea to me.
I would be extremely surprised if you could get similar or better predictions for the same amount of computation from an off the shelf CNN than from a carefully tuned physical model. (I would love to see counterexamples). Even then I would question how well it extrapolates; you generally have a very good idea of where your physics simulation will break down.
I think your friend is right; the physics community can't afford to throw away as much code as the tech community. I wouldn't spend years building a simulation in tensorflow because it will likely be obsolete before I finished (leading to the same problems as FORTRAN but increasing the amount of dependencies).
In any case, if it works well enough it's not going to be rewritten.
Eventually ML will become part of physics simulations, but I don't think there will be easy wins in these well developed areas.
From what I see from googling, cyclone tracks forecasting by neural network is definitely an active area of research, but apparently they aren’t practical yet. The lady you talked to were probably working on some chaotic systems like this.
I suspect it’s the lack of standardization that’s really the issue.
I'm not sure which feature you're referring to, because while GCC has -fbounds-check, that's for the GNU Compiler Collection and only for frontends that support it (to wit, Fortran and Java). I don't know of any runtime bounds checking that ever made it into vanilla. Clang and GCC both have some limited array bounds checking, but it's static, and there are plenty of issues it won't catch. People maintained third party patches for a long time, but these are obsolete now. Perhaps you're thinking of ASAN/-fstack-protector-*?
Just because it's not as "cool" as the language your currently using is not a reason to change and never will be.
Don't get me wrong, this is probably an opinion I would defend if it were exclusively related to programmers being "too lazy to learn a new language", but this is a different learning purpose.
Lets say I wanted to write a web blog server. One language has "import blog; blog.run()" and I am up and running instantly. Another language makes me install a blog library and some other side stuff, and choose a webserver. The point is it isn't just built right in. Which language is better for writing web blog software? The answer is, you have literally no idea from what I just told you. My analysis is insanely superficial and meaningless. Presumably, if I am going to spend hundreds or thousands of hours in some coding environment, what is 'built in with no effort' matters somewhat on hour 0, but virtually not at all by hour 200. Professional scientists presumably spend thousands of hours on this stuff, it's really not too much to ask that they become somewhat competent with the tools they are using.
just a case in point: what do you think is easier to use, standards conformant and is more typesafe:
a) a typedef that gives you "__restrict const * const double"
b) declaring inputs as "real(8), intent(in)"
This and the linked news piece [1] from MIT News sound pretty weird to me. The OP article probably takes the bit about "researchers at MIT" developing Julia from the MIT News page, so that's the real source of the issue - the MIT News pages seems to have been written with weird biases, making it sound like a primarily MIT project that other people have just tacked a few things on to. And then there's:
> A few years ago, when an HPC startup Edelman was involved in [...] was acquired by Microsoft, he launched a new project with three others.
That to me sounds like an implication that Edelman was the one to initiate the project and take in the others. They seem to be writing from the usual academic bias of "the senior faculty gets the credit even if the actual work is done by the PhD/graduate students". Edelman was Bezanson's thesis advisor and a crucial part of Julia's history, but this article seems to be downplaying the role of the other core contributors and the open source community.
I had assumed university news, at least in such technical topics, would be more reliable and less inherently biased, learned something new today.
[1] http://news.mit.edu/2014/high-performance-computing-programm...
It’s done mostly for historical tradition reasons, and it costs nontrivial time and money to switch.
If we know the software libraries won't change (blas, lapack) then what chips can we build to make them run even faster?
The idea is to take current COBOL and FORTRAN code and compile it down to IL similar to .NET's CIL, in the .NET world once code is brought down to CIL it can be read back in VB.NET, C#, C++.NET
Essentially bring it down to some sort of lossless IL to convert to another language. It should be possible to do this given we have the source code. In certain cases where source code doesn't match the binary (happens over years due to monkey patching the binaries etc...) then we'll have to take an approach a few folks at IBM are talking with recompilation and reoptimization of existing old binaries for COBOL. [1]
Don't throw away that debugged and battle-hardened code, change the IL and the final compile target, if possible re-interpret the IL into a newer language if its not lossy.
[1]http://www.ibm.com/common/ssi/cgi-bin/ssialias?infotype=AN&s...
https://www.microfocus.com/products/visual-cobol/
"Compile COBOL applications directly to Microsoft intermediate language for deployment within Microsoft .NET... Compile COBOL applications to Java byte code for deployment within the Java Virtual Machine"
I've actually seen this idea suggested, at least as part of a bake-off between design ideas. There's a certain amount of sense to it.
¹https://arstechnica.com/science/2014/05/scientific-computing...
I brought up a possible rewrite, and one of the greybeards told me that they had looked at that in the past, but the govt V&V process on any rewritten algorithms would have been so onerous that they eventually dropped the idea.
The last guy who actually understood that old code retired about a year after I started there and then things started to get... interesting.
As an aside, for 'new' code, I'm actually ok with the science folks dumping a pile of matlab script on me so I can rewrite it in Python, Java, etc. (rather than letting scientists write production code, which I'll have to rewrite later anyway).
I've done some programming for cognitive psychology experiments, fMRI analysis etc, and although I didn't like the often proprietary systems used (E-Prime, Presentation etc), I could see it would have required hefty investments of very scarce time to switch to something 'better'. The vast bulk of the software was written by non-programmer grad students, for whom the tech was a very 3rd order issue: they just needed their experiments up and running. This was generally done by finding a close-enough prior experiment, and tweaking it in a hurry, often with limited understanding of how the system worked. There was in most cases no possibility of paying programmers to do the work.
If you are using the GNU compilers (and the appropriate compiler flags with gcc), there isn't much difference in performance --- and there shouldn't be.
There are a few FORTRAN-only compilers out there; I'd be curious to see how well they do.
No language is truely superior to all others, the question is always context and the conditions and constrictions it puts on the developer.
For physicists Fortran or C are the best choices. Even Go uses a garbage collector which brakes it for large HPC scenarios. VM based languages are completely useless. Their low speed is already a nuisance for simple common tasks, never mind problems that already take days or weeks to execute when they are properly optimised. If you think Java, Ruby or any such language could be used, look at benchmarks. You will find CPU time of 1.5-2.5x and memory at least 5-7x the amount needed by the same problem executed by a program written in C.
My industry is rewriting its FORTRAN base in C++ and a lot of physicists are switching to Python + Numpy for all but the most intensive tasks. I see FORTRAN being only used in legacy systems within the next 5-10 years.
Though there are many using Python + Numpy R still have a larger piece of user base in scientific and mathematical spaces.
Whats your usecase?
It seems it is faster for some, but a lot slower in others:
https://benchmarksgame.alioth.debian.org/u64q/compare.php?la...
spectral-norm
1.99s Fortran Intel
1.99s C++ g++
URL provided @quickben"However, the two benchmarks where Fortran wins (n-body simulation and calculation of spectra) are the most physics-y. The results vary somewhat depending on whether one compares a single core or quad core machine with Fortran lagging a bit more behind C++ on the quad core."
Though I don't see how the single core version is measured. As far as I can tell, the spectra calculations are always using 4 CPUs while the n-body is always using 1 CPU.
Back-then a second set of measurements were shown with the programs forced to run on one-core, using set-affinity.
Basically, Rust could be excellent at this in the future, but right now, is merely okay.
2) noone wants to spend 1$ to rewrite it in any other language.
-> enjoy fortran