2024년 5월 21일 화요일

using binary file read/write between fortran and python

Reference: post in stackoverflow. 

Problem: Let us suppose the fortran program stores integer*4, real*8, complex*16 type of data as a binary files. How one can read the binary files in python? 


(1) In Fortran : store data as a binary file   

   In this example, an real array 'fn' with dimension(100,100) is stored in a file. 

   Because the double precision real number is 8 byte, writing 'fn' corresponds to writing 8*100*100= 80000 bytes. When writing binary file ('direct' access), one have to specify a length of data and position to write the data. 'rec_array' is a length of data and 'rec' in write command tells where the 'rec_array' length have to be written in a file. For example, rec = 3 corresponds to the position after 2*80000 bytes.  

program binary_out
implicit none
integer :: i,j,t,rec_array
double precision, dimension(100,100) :: fn
double precision, parameter :: p=2*3.1415929

INQUIRE(IOLENGTH=rec_array) fn
write(*,*) 'rec_array=',rec_array ! 100*100*8 byte
open(unit=10,file='temp.dat',status='unknown', &
     form='unformatted',access='direct',recl=rec_array)
fn=0
write(10,rec=1) fn
do t=1,3
  do i=1,100 ! filling all fn(i,j)
    do j=1,100
      fn(i,j)=sin(i*p*t/100)*cos(j*p*t/100)
    enddo
  enddo
  write(10,rec=t+1) fn ! t-th rec_array size
enddo
! rec=1-4 fn
! Thus total size of file is 80000*4 bytes
close(10)
end program binary_out

Note: Writing to disk is actually done when the buffer is full or when the file is closed. 

        To write in real-time, one have to use "flush(10)" 


(2) In python, one can open/read the file as a binary. One have to specify the type/size of the data to read (using 'np.fromfile') and position to start reading the data(using 'f.seek') . (Note that one cannot read the same position twice. One have to specify the starting position for each reading.)   


#!/usr/bin/env python
import scipy
import glob
import numpy as np
import matplotlib.pyplot as plt
import os, sys
from pylab import *

# binary file is written as (8byte real)*(100*100 elements)*(4 cycles)
def readslice(inputfilename,field,nx,ny,timeslice):
   f = open(inputfilename,'rb') # open as binary
   f.seek(8*timeslice*nx*ny) # find starting byte position for reading
   field = np.fromfile(f,dtype='float64',count=nx*ny) # 8byte = 64 bit
   field = np.reshape(field,(nx,ny))
   f.close()
   return field

a=np.dtype('d')
a=readslice('temp.dat',a,100,100,1)
print(a[0])
im=plt.imshow(a)
plt.show()

In other words, the binary file have to be write/read by specifying the starting position of the data and length and type of the data. ( Since binary is a collection of '0' and '1', same binary can be read in different ways depending on the length and format.) 

It is important to know the exact type/order of the data to read/write. 


Note: In case of multi-dimensional array from fortran, reshaping could be different from original one because of the convention difference. To have the same indexing, one can use '"order='F' " in the np.reshape. For example, fortran wrote a array 'f(1:Nx,1:Ny,1:Nz)' to get the same array in python 'f(0:Nx-1,0:Ny-1,0:Nz-1)', use 

a = np.fromfile(f,dtype='float64',count=Nx*Ny*Nz)
a = np.reshape(a,(Nx,Ny,Nz),order='F')

In case of c, order='C'

2024년 3월 17일 일요일

디스가이아2 PSP

 # 주의해야하는 숨겨진 캐릭터 조건(기회가 제한된 것)

에트나는 chapter 9 후

Kurtis - Enter the Land of Carnage. 

Axel - Enter the Land of Carnage.

Fubuki - Beat the story stage in Zenon's Castle where he is an ally. 

Mid-Boss - Have at least 20 hours of play time, have at least one character
with 400+ mana, and you must not have gotten Etna yet. There will be a bill
called "I want to see the ending!" Pass it and beat the stage that appears.
Doing so will lead to an ending (and a new song) so make sure you do 
everything you want to do in the currecnt cycle first. On the new game, pass
the same bill again. After it's passed, do not go to the Mid-Boss stage again,
but instead have Adell enter a Dark Assembly. An option called "Allow moi to
join" appears. Pass it and we're done.

Pink ,Actress,Main Hero B - Beat Axel Mode and enter the Land of Carnage. Axel must be in your
party before you can proceed. Then have Adell attend a Dark Assembly and
there should be a bill from her. Pass it and she joins, but only in the Land 
of Carnage!

Prism Red - Defeat the optional "Hero Show Event" map that shows up after
losing to Laharl in Shinra Tower. Next use 5 Prism Ranger Cell Phones.
Have Adell enter a dark assembly as a Senator and there should be a bill 
called "Be My Friend" by a Prism Ranger. 

Mr. Champloo - You must have beaten Axel Mode, have at least one unit with 
9999+ mana, and have at least 50 hours of play time. There will be a bill

Raspberyl - Defeat her special map "This is Taboo Love".  You will need 30 Dark World maps cleared and have beaten
Mr. Champloo 

Mao - Defeat his special map "Final Departure". 
You will need to have beaten Mr. Champloo and have access to the
Land of Carnage 

Flonne - Pass a bill to fight Laharl after losing to him in story mode. The stage must be beaten in Holt Village for it to count.


Laharl - Dark Assembly and look
for the proposal "Summon Laharl". 

Priere - You must not have recruited Etna yet, and have at least one character
with a 66+ Felony stamp and at least one character with 100+ mana. A bill
"Unleash the Fallen Maiden" 

Marjoly - Have at least one character with a 99 Felony stamp and at least one 
character with 1500+ mana. A bill "Break the Mysterious Seal" should appear. 

Zetta - Beat at least 10 Dark World maps and have at least one character with
3000+ mana. A new bill called "Meet the Strongest Overlord" should appear. 

Asagi (monster) - at least
one character with a 33+ displayed felony, at least one character with 100+ 
mana and be on a new cycle. There should be a bill to "Fight a Hero from 
Another Game". 

Asagi (human) - Raise monster Asagi to level 2000+.  a bill from her that says "Make me human". Do note that when she transforms, her equipment stays on her
monster form, and vice versa, and can only be recovered by transforming again.

Gordon - Defeat the second Defender of Earth map. The map is accessed by using
6 Defender of Earth cell phones and beating the first Defender of Earth stage.

2024년 3월 11일 월요일

Feynmann Hellmann theorem, Virial theorem

Feynmann Hellmann theorem, Virial theorem 이 무슨 내용이었는지 자꾸 잊어버려서 여기에 정리함. 

(1) Feynmann Hellmann theorem : 간단하게 요약하면 Hamiltonian 이 parameter dependent인 경우

으로 쓸 수 있다는 것이다. 간단해 보이지만, 완전히 trivial 하지는 않은 것은 , 오른쪽에 wave function에 대한 미분이 없다는 것이다. 좀 더 자세한 것은 위키피디아에 이미 잘 정리되어 있다. https://en.wikipedia.org/wiki/Hellmann%E2%80%93Feynman_theorem 


(2) Virial theorem: bound state 에 대한 variational approximation |Psi> to H = T +V는 

다음과 같은 relation을 만족한다. 

Virial 이란 단어는 라틴어 vis ( "force", "energy") 에서 왔다. 

왜 Virial theorem이 중요한가? 위키피디아에 따르면 

The significance of the virial theorem is that it allows the average total kinetic energy to be calculated even for very complicated systems that defy an exact solution, such as those considered in statistical mechanics; this average total kinetic energy is related to the temperature of the system by the equipartition theorem. However, the virial theorem does not depend on the notion of temperature and holds even for systems that are not in thermal equilibrium.

2024년 2월 13일 화요일

Error estimation of fitting parameters

 https://stackoverflow.com/questions/40187517/getting-covariance-matrix-of-fitted-parameters-from-scipy-optimize-least-squares

2024년 2월 5일 월요일

PyQt5 adding FigureCanvas in designer

(1) Put a layout in a designer. rename it as convenient

(2) Click Right Mouse Button and change it into a Widget. 

(3) After that, one can put Canvas Widget into the layout. 

2024년 1월 31일 수요일

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized

It is suspected that this error comes from the multiple library confilcts which have libiomp5.dll files. 

One solution is to delete  libiomp5md.dll (and other libiomp5 related files)

in anaconda3/Library/bin . (anaconda3 is located in hidden "ProgramData" folder.) 

It is not clear whether this is the best solution, but it works. 


(Update) The above symptom first appeared while using PyTorch , Matplotlib, and Scipy. 

However, after above procedure, 

there are many occasions that the kernel stops and restart. Python became very unstable.

To avoid this problem, it may be better to use separate environment when installing pytorch. 

2024년 1월 24일 수요일

Wolfram Engine Jupyter 매쓰매티카

(1) get Free Wolfram engine : https://www.wolfram.com/engine/

(2) get Wolfram language for Jupyter

https://github.com/WolframResearch/WolframLanguageForJupyter

    unzip the file at permanant folder and do not delete it.  

(3) Follow steps in the page 

    - install Wolfram engine and run "wolframscript" at command line  

    - download Wolfram language for Jupyer and run "configure-jupyter.wls add" in powershell. (not command prompt)