현대 시대의 포트란 배우기
저는 최근에 많은 양의 과학적 계산 집약적 인 FORTRAN 코드를 유지하기 위해 왔습니다. Google과 두 권의 입문 레벨 책에도 불구하고 40 년 된 언어의 모든 뉘앙스를 다루는 데 어려움을 겪고 있습니다. 이 코드는 "성능 향상 개선"으로 가득 차 있습니다. 사람이 어떤 가이드 또는에 대한 실질적인 조언이 있습니까 드 CS (101) 수준에 -optimizing FORTRAN을? FORTRAN 코드 최적화가 어떻게 작동하는지 아는 사람이 있습니까? FORTRAN 77/90 코드베이스를 인수하는 Java / C ++ /. NET 개발자에게 발생하지 않을 수있는 일반적인 FORTRAN 'gotchas'가 있습니까?
프로그래머가 과거에했던 일에 대해 "느낌"을 가져야합니다. 내가 작업하는 대부분의 코드는 나보다 오래되었고 부모님이 고등학교에 다니셨을 때 "새로운"컴퓨터에서 실행되었습니다.
내가 다루는 일반적인 FORTRAN-isms는 가독성을 떨어 뜨립니다.
- 공통 블록
- 암시 적 변수
- 공유 CONTINUE 문이있는 두 개 또는 세 개의 DO 루프
- DO 루프 대신 GOTO
- 산술 IF 문
- 계산 된 GOTO
- 일부 공통 블록에서 등가 REAL / INTEGER / other
이를 해결하기위한 전략에는 다음이 포함됩니다.
- 얻을 Spag / plusFORT을 , 가치가 돈, 그것은 자동으로 많이 해결하고 버그 무료 (TM)
- 가능하면 Fortran 90으로 이동하고, 자유 형식 Fortran 77로 이동하지 않으면
- 각 서브 루틴에 IMPLICIT NONE을 추가 한 다음 모든 컴파일 오류를 수정하고 시간이 많이 걸리지 만 궁극적으로 필요한 경우 일부 프로그램이 자동으로이를 수행 할 수 있습니다 (또는 스크립트를 작성할 수 있음).
- 모든 COMMON 블록을 MODULE, 낮은 매달려있는 과일로 이동
- 산술 IF 문을 IF..ELSEIF..ELSE 블록으로 변환
- 계산 된 GOTO를 SELECT CASE 블록으로 변환
모든 DO 루프를 최신 F90 구문으로 변환
myloop: do ii = 1, nloops ! do something enddo myloop
동등한 공통 블록 멤버를 모듈에 할당 된 ALLOCATABLE 메모리로 변환하거나 Hollerith가 REAL에 저장되는 경우 해당 문자 루틴으로 변환합니다.
가독성 작업을 수행하는 방법에 대해 더 구체적인 질문이 있으면 조언을 드릴 수 있습니다. 40 년에 걸쳐 작성된 몇 십만 줄의 Fortran 코드베이스를 가지고 있으며 어떤 방식 으로든 책임을 져야합니다. 그래서 여러분이 발견 할 수있는 "문제"를 발견했을 것입니다.
레거시 포트란 비누 상자
나는 꽤 오랫동안 레거시 Fortran 코드 기반을 유지 / 개선하는 데 도움을 줬고 대부분의 경우 sixlettervariables 가 돈에 있다고 생각 했습니다 . 하지만 그 조언은 기술적 인 경향이 있습니다. 더 어려운 행은 "우수 사례"를 구현하는 것입니다.
- 필요한 코딩 스타일 및 코딩 지침을 설정합니다.
- 코드베이스에 제출 된 모든 항목에 대해 코드 검토 (코더 이상의 것!)를 요구합니다. (버전 제어는이 프로세스와 연결되어야합니다.)
- 단위 테스트 빌드 및 실행을 시작하십시오. 벤치 마크 또는 회귀 테스트도 마찬가지입니다.
요즘은 당연한 일처럼 들릴지 모르지만 과도하게 일반화 될 위험이 있지만 대부분의 포트란 코드 상점은 확고한 문화를 가지고 있으며 일부는 "소프트웨어 엔지니어링"이라는 용어가 존재하기 전에 시작했으며 시간이 지남에 따라 지배하게 될 것이라고 주장합니다. "지금 완료"입니다. (이것은 Fortran 상점에만 국한되지 않습니다.)
Gotchas 수용
하지만 이미 존재하는 끔찍한 오래된 레거시 코드베이스로 무엇을해야할까요? 나는 다시 작성에 Spolsky 조엘에 동의 하지 않습니다 . 그러나 내 생각에 sixlettervariables 는 허용 가능한 예외를 가리 킵니다. 소프트웨어 도구를 사용하여 더 나은 Fortran 구조로 전환합니다. 코드 분석기 ( FORCHECK ) 및 코드 재 작성기 ( plusFORT ) 는 많은 것을 포착 / 수정할 수 있습니다 . 손으로해야하는 경우 긴급한 이유가 있는지 확인하십시오. (저는 소프트웨어 버그 수정에서 나온 소프트웨어 버그의 수에 대한 언급이 있었으면 좋겠습니다. 겸손합니다. 그런 통계가 Expert C Programming 에 있다고 생각 합니다.)
아마도 Fortran gotchas 게임에서 승리하는 가장 좋은 공격은 최고의 방어력을 갖는 것입니다. 언어를 상당히 잘 아는 것입니다. 이를 위해 ... 책을 추천합니다!
포트란 데드 트리 라이브러리
나는 수년 동안 "QA nag"로서 약간의 성공을 거두었지만 교육은 때때로 우연히 효과가 있으며 가장 영향력있는 것 중 하나는 누군가가 가지고있는 참고서라는 것을 발견했습니다. 나는 사랑하고 적극 추천합니다
과학자 및 엔지니어를위한 Fortran 90/95 , Stephen J. Chapman
이 책은 사용해서는 안되는 구조를 구체적으로 식별하고 더 나은 대안을 제공한다는 점에서 Fortran 77 과도 잘 어울립니다. 그러나 실제로는 교과서이며 Fortran 95의 핵심을 정말로 알고 싶을 때 증기가 떨어질 수 있습니다.
Fortran 90/95 Explained , by Michael Metcalf & John K. Reid
Fortran 95에 대한 참조 (원문)로. 가장 명쾌한 글은 아니지만 새로운 Fortran 95 기능을 최대한 활용하고 싶을 때 베일이 해제됩니다.
Fortran 77에서 Fortran 90으로 이동하는 문제에 초점을 맞춰
Fortran 90으로 마이그레이션 , Jim Kerrigan
그러나 책은 이제 절판되었습니다. (저는 O'Reilly의 Safari 사용을 이해하지 못합니다 . 왜 절판 된 책을 모두 사용할 수 없습니까?)
마지막으로, 훌륭한, 멋진 클래식,에 후계자에 관한 소프트웨어 도구 , 나는 지명
Michael Kupferschmid의 클래식 포트란
이 책은 "오직"Fortran 77으로 무엇을 할 수 있는지 보여줄뿐만 아니라 발생하는 더 미묘한 문제에 대해서도 설명합니다 (예 : EXTERNAL 선언을 사용해야하거나 사용해서는 안 됨). 이 책은 "Software Tools"와 똑같은 공간을 정확히 다루지는 않지만 "fun"이라고 태그를 붙인 세 개의 Fortran 프로그래밍 책 중 두 권입니다 .... ( 여기 세 번째입니다 ).
거의 모든 Fortran 컴파일러에 적용되는 기타 조언
- IMPLICIT NONE 동작을 적용하는 컴파일러 옵션이 있으며,이를 사용하여 먼저 IMPLICIT NONE 선언으로 수정하지 않고 문제 루틴을 식별 할 수 있습니다. 이 조언은 레거시 루틴에 삽입 된 IMPLICIT NONE 명령으로 인해 처음 빌드 폭탄이 터지기 전까지는 의미가 없어 보입니다. (뭐? 코드 리뷰에서이 문제를 파악하지 못했습니까? ;-)
- Fortran 77 코드를 디버깅 할 때 유용 할 수있는 배열 경계 검사를위한 컴파일러 옵션이 있습니다.
- Fortran 90 컴파일러는 거의 모든 Fortran 77 코드와 더 오래된 Fortran 코드를 컴파일 할 수 있어야합니다. Fortran 90 컴파일러에서보고 옵션을 켜고이를 통해 레거시 코드를 실행하면 구문 검사를 제대로 시작할 수 있습니다. 일부 상용 Fortran 77 컴파일러는 실제로 Fortran 77 모드에서 실행되는 Fortran 90 컴파일러이므로 보유한 빌드 스크립트에 대해 상대적으로 간단한 옵션이 될 수 있습니다.
There's something in the original question that I would caution about. You say the code is rife with "performance enhancing improvements". Since Fortran problems are generally of a scientific and mathematical nature, do not assume these performance tricks are there to improve the compilation. It's probably not about the language. In Fortran, the solution is seldom about efficiency of the code itself but of the underlying mathematics to solve the end problem. The tricks may make the compilation slower, may even make the logic appear messy, but the intent is to make the solution faster. Unless you know exactly what it is doing and why, leave it alone.
Even simple refactoring, like changing dumb looking variable names can be a big pitfall. Historically standard mathematical equations in a given field of science will have used a particular shorthand since the days of Maxwell. So to see an array named B(:) in electromagnetics tells all Emag engineers exactly what is being solved for. Change that at your peril. Moral, get to know the standard nomenclature of the science before renaming too.
As someone with experience in both FORTRAN (77 flavor although it has been a while since I used it seriously) and C/C++ the item to watch out for that immediately jumps to mind are arrays. FORTRAN arrays start with an index of 1 instead of 0 as they do in C/C++/Java. Also, memory arrangement is reversed. So incrementing the first index gives you sequential memory locations.
My wife still uses FORTRAN regularly and has some C++ code she needs to work with now that I'm about to start helping her with. As issues come up during her conversion I'll try to point them out. Maybe they will help.
I have used Fortran starting with the '66 version since 1967 (on an IBM 7090 with 32k words of memory). I then used PL/1 for some time, but later went back to Fortran 95 because it is ideally suited for the matrix/complex-number problems we have. I would like to add to the considerations that much of the convoluted structure of old codes is simply due to the small amount of memory available, forcing such thing like reusing a few lines of code via computed or assigned GOTO
s. Another problem is optimization by defining auxiliary variables for every repeated subexpression - compilers simply did not optimize for that. In addition, it was not allowed to write DO i=1,n+1
; you had to write n1=n+1
; DO i=1,n1
. In consequence old codes are overwhelmed with superfluous variables. When I rewrote a code in Fortran 95, only 10% of the variables survived. If you want to make the code more legible, I highly recommend looking for variables that can easily be eliminated.
Another thing I might mention is that for many years complex arithmetic and multidimensional arrays were highly inefficient. That is why you often find code rewritten to do complex calculations using only real variables, and matrices addressed with a single linear index.
Well, in one sense, you're lucky, 'cause Fortran doesn't have much in the way of subtle flow-of-control constructs or inheritance or the like. On the other, it's got some truly amazing gotchas, like the arithmetically-calculated branch-to-numeric-label stuff, the implicitly-typed variables which don't require declaration, the lack of true keywords.
I don't know about the "performance enhancing improvements". I'd guess most of them are probably ineffective, as a couple of decades of compiler technology have made most hinting unnecessary. Unfortunately, you'll probably have to leave things the way they are, unless you're planning to do a massive rewrite.
Anyway, the core scientific calculation code should be fairly readable. Any programming language using infix arithmetic would be good preparation for reading Fortran's arithmetic and assignment code.
Could you explain what you have to do in maintaining the code? Do you really have to modify the code? If you can get away by modifying just the interface to that code instead of the code itself, that would be the best.
The inherent problem when dealing with a large scientific code (not just FORTRAN) is that the underlying mathematics and the implementation are both complex. Almost by default, the implementation has to include code optimization, in order to run within reasonable time frame. This is compounded by the fact that a lot of code in this field is created by scientists / engineers that are expert in their field, but not in software development. Let's just say that "easy to understand" is not the first priority to them (I was one of them, still learning to be a better software developer).
Due to the nature of the problem, I don't think a general question and answer is enough to be helpful. I suggest you post a series of specific questions with code snippet attached. Perhaps starting with the one that gives you the most headache?
I loved FORTRAN, I used to teach and code in it. Just wanted to throw that in. Haven't touched it in years.
I started out in COBOL, when I moved to FORTRAN I felt I was freed. Everything is relative, yeah? I'd second what has been said above - recognise that this is a PROCEDURAL language - no subtelties - so take it as you see it.
Probably frustrate you to start with.
I started on Fortran IV (WATFIV) on punch cards, and my early working years were VS FORTRAN v1 (IBM, Fortran 77 level). Lots of good advice in this thread.
I would add that you have to distinguish between things done to get the beast to run at all, versus things that "optimize" the code, versus things that are more readable and maintainable. I can remember dealing with VAX overlays in trying to get DOE simulation code to run on IBM with virtual memory (they had to be removed and the whole thing turned into one address space).
I would certainly start by carefully restructuring FORTRAN IV control structures to at least FORTRAN 77 level, with proper indentation and commenting. Try to get rid of primitive control structures like ASSIGN and COMPUTED GOTO and arithmetic IF, and of course, as many GOTOs as you can (using IF-THEN-ELSE-ENDIF). Definitely use IMPLICIT NONE in every routine, to force you to properly declare all variables (you wouldn't believe how many bugs I caught in other people's code -- typos in variable names). Watch out for "premature optimizations" that you're better off letting the compiler handle by itself.
If this code is to continue to live and be maintainable, you owe it to yourself and your successors to make it readable and understandable. Just be certain of what you are doing as you change the code! FORTRAN has lots of peculiar constructs that can easily trip up someone coming from the C side of the programming world. Remember than FORTRAN dates back to the mid-late '50s, when there was no such thing as a science of language and compiler design, just ad hoc hacking together of something (sorry, Dr. B!).
Here's another one that has bit me from time to time. When you are working on FORTRAN code make sure you skip all six initial columns. Every once and a while, I'll only get the code indented five spaces and nothing works. At first glance everything seems okay and then I finally realize that all the lines are starting in column 6 instead of column 7.
For anyone not familiar with FORTRAN, the first 5 columns are for line numbers (=labels), the 6th column is for a continuation character in case you have a line longer than 80 characters (just put something here and the compiler knows that this line is actually part of the one before it) and code always starts in column 7.
참고URL : https://stackoverflow.com/questions/31672/learning-fortran-in-the-modern-era
'program tip' 카테고리의 다른 글
빈 파일을 읽을 때 "Pickle-EOFError : Ran out of input"이 발생하는 이유는 무엇입니까? (0) | 2020.10.26 |
---|---|
키 값 쌍 데이터 구조를위한 최상의 구현? (0) | 2020.10.26 |
C ++의 클래스 이니셜 라이저에서 const 배열 초기화 (0) | 2020.10.26 |
Facebook 좋아요 버튼-수 숨기기? (0) | 2020.10.26 |
$ location을 사용하여 AngularJS의 새 페이지로 리디렉션 (0) | 2020.10.26 |