Sometimes, the arrow key in python shell does not act like usually. Pressing arrow key does not gives history(previous line) but gives characters. This can be fixed by installing "gnureadline" package.
2024년 11월 13일 수요일
2024년 11월 10일 일요일
Binary file problem with intel fortran (ifort) and gfortran (GNU fortran)
I found that reading a binary file created with the same source file but compiled by ifort and gfortan give different results. By searching internet, I found that the way binary file is written in ifort is not the same sa gfortran. Thus, to make the same code gives the same results, one have to use open binary files with ACCESS='stream', FORM='unformatted'.
- Non-standard: open(unit=20,file=fname,form='binary')
- Standard: open(unit=20,file=fname,form='unformatted',access='stream',status='replace')
But, this seems to be not the full story.
I need to check the correct way to convert following gfortran code to ifort code.
open(pin_file_id, file=trim(pin_file), status='unknown',form='unformatted', &
access='direct',action='write',recl=nsize,iostat=ios)
* After testing, following seems to be equivalent to the above one.
open(pin_file_id, file=trim(pin_file), status='unknown',form='BINARY', &
access='direct',action='write',recl=nsize,iostat=ios)
* According to ChatGPT, ifort and gfortran interpret differently the recl= argument in open statement. In gfortran, 'recl' is interpreted as length of bytes. In ifort, 'recl' is interpreted as length of 4 bytes. Thus, to get the same results, if "recl= nsize" in gfortran , "recl= nsize/4" in ifort have to be used. Or/And(?) one have to use compile option in "ifort -assume byterecl .
This also imply that the "recl" in gfortran must be a multiple of 4.
* But, modifying the source code depending on the compiler or machine is not desirable. access='stream' option without 'recl=' parameter will behave similarily in both ifort and gfortran. keep form='unformatted'. status='replace' create a new file if it does not exist, or replace it if it exist. Thus, it may be better than status='unknown' to ensure freshfile in each run. (Or default status='unknown' may be okay??)
But, to access specific data, one have to use 'pos=' parameter which should be counted in whole file. For example, if data is stored as 'real(8), integer(4), real(4)', to read these
read(file_id, pos=1) real_value
read(file_id, pos=9) int_value
read(file_id, pos=13) real4_value
In other words, 'pos' specify the starting byte position, and type of variable specify the length of the data to read.
2024년 10월 29일 화요일
Gradient of eigenvalue eigenvector of Matrix
Matrix 의 eigenvalue 와 eigen vector 는 다음과 같은 관계가 있다.
$A u = v u$.
여기서, eigenvalue와 eigenvector 를 일종의 matrix A에 대한 함수로 생각하고($v(A)$ and $u(A)$.) , 미분 Gradient 을 정의할 수 있다고 볼 수 있다.
문제는 이러한 미분을 일반적인 Matrix 에 대해서는 정확하게 정의하기가 어렵다는 것이다. 다만, real symmetric matrix인 경우에는 다음과 같은 정의를 할 수 있다. matrix $A_0$ 에 대해서 eigenvalue, eigenvector가 $v_0$, $u_0$라고 하자. 그러면 매우 작은 Matrix변화에 대해
$ d v = u_0^T (d A) u_0 $ 또는 $ dv/d(A_{ij}) = (u_0)_i (u_0)_j$.
$ d u = ( v_0 I - A_0) ( d A) u_0$ 또는 $ (d u)_i = ( v_0 I - A_0)_{ij} ( d A)_{jk} (u_0)_k$
와 같이 정의할 수 있다고 한다. (real symmetric matrix임에 유의.)
REF: https://www.janmagnus.nl/papers/JRM011.pdf
즉, matrix $A_0$ 가 matrix $A_0 + d A$ 로 변할 때, eigen value와 eigen vector는
$ v_0 -> v_0 + d v $,
$ u_0 -> u_0 + d u$
로 계산할 수 있다는 것이다. 하지만, 논문을 자세히 읽어보진 않았지만 아마도 degeneracy 가 없어야 한다는 조건이 붙을 것 같다.
2024년 10월 20일 일요일
Baldur's Gate 2 hex edit
How To hex edit Baludur's gate save file.
(1) Open Baldur.gam file in the save folder.
(2) money: convert gold in hex number. Edit by searching in reverse order.( For example,2000 -> 07D0. Search "D0 07").
(3) Character status: convert status in hex number. serach in order of
"STR STRMOD INT WIS DEX CON CHA". (STRMOD is for STR=18 case.)
어나더에덴
https://m.cafe.naver.com/ca-fe/web/cafes/29617015/articles/247442?tc=cafe_member_profile
2024년 9월 10일 화요일
Caution for the copying of python list or dictionary ( '=' is not what you think!)
I found there is a surprising behavior of '=' in python!!
a = np.array([1,2,3]);b=a;b[0]=0;print(a,b)
[0 2 3] [0 2 3]
* When one use '=' in python , it usually mean to copy the values of the right hand side variable to the left hand side variable, i.e. assignment.
* However, in python, if the variable is a list or dictionary, '=' has different meaning.
The operation depends on the variable.
(1) If it is a default simple data type like, it creates different copy.
b=a : a and b are unrelated except they have the same values.
(2) If it is a compound object like list, dictionary, or complex object,
'=' means assign alternative name.
b=a : a and b directs the same adress and shares the values.
In other words, a and b are linked.
Thus, any change in a or b affacts the other.
To avoid this, one can copy the compound object. However, there is two different copies.
(1) Shallow copies : if the object is just a list or shallow, one can use
b = a[:] or b = a.copy()
This creates a shallow copy of a and changes in a or b does not affect the other
if the object is shallow(only one index).
However, if it is more complex object like list of lists, in fact they share memory.
Any change in deeper level of a or b affects the other.
(2) Deep copies : to make a completely decoupled copy of compound object.
one have to make a deep copy using 'copy' module.
import copy
b = copy.deepcopy(a)
REF: https://medium.com/@thawsitt/assignment-vs-shallow-copy-vs-deep-copy-in-python-f70c2f0ebd86
자주 틀리거나 헷갈리는 맞춤법 구분
(1) 되다/돼다 :
'되'와 '돼'가 들어가는 부분을 '하'와 '해'로 바꾸어 본다. 쓰지 않는 말이되더라도 둘중에 어느쪽이 더 자연스럽게 들리는지를 생각해보면 된다. (예를 들어, 앞의 글에서 '한다' 와 '핸다'를 비교하면 '한다'가 자연스럽기 때문에 '된다'를 쓰면 된다.)
(2) 결재/결제 :
'재판'이라고 할때의 '재'와 경제라고 할 때의 '제'를 떠올리면 된다. '결재'는 '재판'이라고 할때 처럼 일종의 판단을 하는 것이고, '결제'는 경제 활동의 일종이므로 '제'를 쓴다.
(3) 깨닫게, 깨닳게, 깨달케 :
"깨달음"의 동사는 "깨닫다" 이다. ("깨닳다", "깨달다" 라는 단어는 없음.) 단지, "ㄷ" 받침이 불규칙적으로 변하여 "ㅇ" 앞에서 "ㄹ" 로 발음되는 것이다. (때문에 "깨달음", "깨달아" 는 맞는 맞춤법) 따라서, "깨닫게"를 제외하곤 전부 틀린 맞춤법이다.
2024년 6월 12일 수요일
numerical calculation of confluent hypergeometric function
It is known that numerical computation of confluent hypergeometric function with large argument is challenging.
I found a strange behavior of scipy special function hyp1f1.
For example, scipy.sepcial.hyp1f1(-40.5,0.5,64.0) gives
-1.1979592767053608e+16 in Linux
and 65755449963894.45 in Windows.
Compared the result with the independent fortran code
written by Shanjie Zhang, Jianming Jin,
it is consistent with -1.1979592767053608e+16.
(The fortran code gives the same result in both OS.)
How can I understand this? Scipy version difference?
2024년 6월 2일 일요일
네이처 논문 신문기사
https://v.daum.net/v/20240516000111666
- 디지털타임스: 전하 반지름 정밀하게 계산... 원자핵 숨겨진 비밀 엿본다 https://www.dt.co.kr/contents.html?article_no=2024051502109931731004&ref
- 이데일리: IBS 포함 국제연구팀, 원자핵 비밀 엿볼 새 핵이론 개발 https://www.edaily.co.kr/news/read?newsId=01102086638889576&mediaCodeNo=257&OutLnkChk=Y
- 동아사이언스: 원자핵 비밀 엿볼 새로운 핵이론, 국제공동연구로 개발 https://www.dongascience.com/news.php?idx=65420
- 매일경제: 韓 연구팀 “원자핵 비밀 엿볼 새 이론 국제공동연구로 개발” https://www.mk.co.kr/news/it/11016370
- 헤럴드경제: 韓 포함 국제연구진 “원자핵 비밀 풀 방법 찾았다”…‘네이처’ 게재 https://news.heraldcorp.com/view.php?ud=20240515050221
- 뉴스웍스: IBS, 무거운 핵 질량‧전하반지름 계산…'네이처'에 실려 https://www.newsworks.co.kr/news/articleView.html?idxno=752875
- 전자신문: IBS, 국제공동연구로 원자핵 비밀 엿볼 새 핵이론 개발…희귀동위원소 연구 활용 기대 https://www.etnews.com/20240515000049
- BBS: 원자핵 비밀 엿볼 새로운 핵이론, 국제공동연구로 개발 https://news.bbsi.co.kr/news/articleView.html?idxno=3156020
- 조선비즈: 전 세계 핵물리학자 모여 만든 계산법…만물의 근원 원자핵 밝힌다 https://biz.chosun.com/science-chosun/science/2024/05/16/665SFMP5F5GFFOETEIGGWHTZZI/?utm
- 충청뉴스: IBS 참여 국제공동연구팀, ‘파동함수 맞춤’ 방법론 개발 https://www.ccnnews.co.kr/news/articleView.html?idxno=334690
- 충남일보: IBS 참여 국제공동연구팀, ‘파동함수 맞춤’ 방법론 개발 https://www.chungnamilbo.co.kr/news/articleView.html?idxno=771019
- 내일신문: 원자핵 비밀 엿볼 새로운 핵이론 개발 https://www.naeil.com/news/read/510487?
2024년 5월 22일 수요일
thought on the "Random close packing of binary hard spheres predicts the stability of atomic nuclei"
There was an interesting article in arxiv. https://arxiv.org/abs/2405.11268
Apparently , it claims that the mean ratio between proton and neutron in stable nuclei can be explained by the Random close packing of two hard spheres with different size.
According to the article, Z/N ~ 0.75 gives maximal packing/maximul number density for protons(r~ 0.84 fm) and neutrons(r~ 1fm) without any adjustable parameters. This is roughly the same as the slope of stable line in nuclear chart.
This is interesting. However, is it really correct approach? The estimation does not involves any Coulomb repulsion or interaction between nucleons. (It may corresponds to the very hard repulsive core and very attractive interaction so that the maimal packing gives minimum energy.)
As far as I can understand, the ratio between total volume and the sum of volumes of hard spheres is estimated as $\phi ~ 0.661 ~ 1/8 (sum of volumes of hard spheres)/(total volume)$. Using $r_p~0.84$fm , $r_n~1$fm and maximal packing condition $Z/N~0.75$, one would get the number density of inifinite nuclear matter as ~ 1.5 nucleons/fm^3. This seems to be not right. Right? (Or should one remove 1/8? in that case, it will be about 0.19 nucleons/fm^3 roughly correct value.) I am not sure whether it is a correct estimation...
2024년 5월 21일 화요일
How to add codebox in Blogger post
This is from https://www.techyleaf.in/add-code-box-in-blogger-post/ .
Step 1: copy and paste the following into the HTML of the post.
<pre style="background: rgb(238, 238, 238); border-bottom-color: initial; border-bottom-style: initial; border-image: initial; border-left-color: initial; border-left-style: initial; border-radius: 10px; border-right-color: initial; border-right-style: initial; border-top-color: rgb(221, 221, 221); border-top-style: solid; border-width: 5px 0px 0px; color: #444444; font-family: "Courier New", Courier, monospace; font-stretch: inherit; font-variant-east-asian: inherit; font-variant-numeric: inherit; line-height: inherit; margin-bottom: 1.5em; margin-top: 0px; overflow-wrap: normal; overflow: auto; padding: 12px; vertical-align: baseline;"><span style="font-size: 13px;">Replace the text with codes</span></pre><p>Start write the next paragraph here </p>
Step 2: Copy/Edit in the Compose View of the post
This adds codebox. However, it is rather cumbersome. Better method?
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 yourparty 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 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)