Commit 4b583b8a authored by Marco Govoni's avatar Marco Govoni
Browse files

Merge branch ''Geom_view'' into 'develop'

'geom view'

See merge request west-devel/westpy!3
parents 4571189e 5af30cf3
%% Cell type:code id: tags:
``` python
from westpy import *
def xyz2center(in_xyz,out_xyz,box_length=30):
'''
in_xyz: input xyz file in unit A
out_xyz: output xyz file where coords are centered in simulation box.
box_length: in unit Bohr
'''
from westpy.units import Angstrom
import pandas as pd
BOHR2A = 1.0 / Angstrom
#convert box length 2 A:
box_length *= BOHR2A
#read in_xyz in unit A
dict_atoms = {'element':[], 'x':[], 'y':[], 'z':[]}
with open(in_xyz,'r') as f:
n_atoms=int(f.readline())
f.readline()
for _ in range(n_atoms):
element, x, y, z = f.readline().split()
dict_atoms['element'].append(element.strip())
dict_atoms['x'].append(float(x))
dict_atoms['y'].append(float(y))
dict_atoms['z'].append(float(z))
assert(len(dict_atoms['x']) == n_atoms)
df_atoms_centered=pd.DataFrame(dict_atoms)
# shift in_xyz coords by [box_length/2,box_length/2,box_length/2]
df_atoms_centered[['x','y','z']] -= df_atoms_centered[['x','y','z']].mean(axis=0)
df_atoms_centered[['x','y','z']] += box_length/2.0
# save to out_xyz
xyz=str(len(df_atoms_centered))+'\n\n'
for row in df_atoms_centered.values:
xyz += " ".join([str(e) for e in row]) + '\n'
with open(out_xyz,'w') as f:
f.write(xyz)
```
%%%% Output: stream
The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
_ _ _____ _____ _____
| | | | ___/ ___|_ _|
| | | | |__ \ `--. | |_ __ _ _
| |/\| | __| `--. \ | | '_ \| | | |
\ /\ / |___/\__/ / | | |_) | |_| |
\/ \/\____/\____/ \_/ .__/ \__, |
| | __/ |
|_| |___/
WEST version : 4.1.0
Today : 2020-06-29 22:33:03.328128
%% Cell type:markdown id: tags:
# Geometry.view() Si35H36
%% Cell type:code id: tags:
``` python
#download xyz
url = 'https://journals.aps.org/prx/supplemental/10.1103/PhysRevX.6.041002/si35h36.xyz'
fname = 'si35h36.xyz'
download(url=url, fname='si35h36.xyz')
#center it to fit geom.setCell((box_length,0,0),(0,box_length,0),(0,0,box_length))
box_length = 30 #Bohr
center2box_fname = 'centered_si35h36.xyz'
xyz2center(in_xyz=fname,out_xyz=center2box_fname,box_length=box_length)
#creat geom
geom = Geometry()
geom.setCell((box_length,0,0),(0,box_length,0),(0,0,box_length))
geom.addAtomsFromXYZFile(center2box_fname)
geom.addSpecies( "Si", "http://www.quantum-simulation.org/potentials/sg15_oncv/upf/Si_ONCV_PBE-1.2.upf")
geom.addSpecies( "H", "http://www.quantum-simulation.org/potentials/sg15_oncv/upf/H_ONCV_PBE-1.2.upf")
geom.view()
```
%%%% Output: stream
Downloaded file: si35h36.xyz , from url: https://journals.aps.org/prx/supplemental/10.1103/PhysRevX.6.041002/si35h36.xyz
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
geom.view(style='line')
```
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
geom.view(style='sphere')
```
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
geom.view(ix=2,iy=2,iz=1)
```
%%%% Output: display_data
%% Cell type:markdown id: tags:
# Geometry.view() HBN
%% Cell type:code id: tags:
``` python
from westpy.units import Angstrom
import numpy as np
A2BOHR = Angstrom
```
%% Cell type:code id: tags:
``` python
geom = Geometry()
#define unit cell
#>> ibrav = 4 ,
#>> celldm(1) = 4.695926777902829 ,
#>> celldm(3) = 8.048362859199854 ,
# 4 Hexagonal and Trigonal P celldm(3)=c/a
# v1 = a(1,0,0), v2 = a(-1/2,sqrt(3)/2,0), v3 = a(0,0,c/a)
#https://materialsproject.org/materials/mp-984/
celldm_1 = 2.51242804*A2BOHR #bohr
celldm_3 = 7.70726501/2.0/2.512 #c/a
geom.addSpecies( "B", "http://www.quantum-simulation.org/potentials/sg15_oncv/upf/B_ONCV_PBE-1.2.upf")
geom.addSpecies( "N", "http://www.quantum-simulation.org/potentials/sg15_oncv/upf/N_ONCV_PBE-1.2.upf")
geom.setCell(a1=(1,0,0), a2=(-1/2,np.sqrt(3)/2,0), a3=(0,0,celldm_3), units=celldm_1)
geom.addFracCoordAtom('B', (1.0/3,2.0/3,0.5) )
geom.addFracCoordAtom('N', (2.0/3,1.0/3,0.5) )
```
%% Cell type:code id: tags:
``` python
geom.view(style='stick')
```
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
geom.view(style='line',ix=5,iy=5,iz=2)
```
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
geom.view(style='sphere',ix=2,iy=2,iz=1,width=400,height=400)
```
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
```
......@@ -27,7 +27,8 @@ setup(name='westpy',
'urllib3',
'prompt-toolkit',
'sphinx',
'sphinx_rtd_theme'
'sphinx_rtd_theme',
'py3Dmol'
],
python_requires='>=2.7, >=3.0, !=3.0.*, !=3.1.*, !=3.2.*, <4',
zip_safe=True)
......@@ -150,18 +150,46 @@ class Geometry(object) :
self.atoms.append( Atom(symbol, position, units) )
self.isSet["atoms"] = True
#
def __addAtomsFromXYZLines(self, lines ) :
def addFracCoordAtom(self, symbol, frac_coord):
"""adds a single atom by fractional coords
:param symbol: chemical symbol
:type symbol: string
:param position: position
:type position: 3-dim tuple
:Example:
>>> from westpy import *
>>> geom = Geometry()
>>> geom.addFracCoordAtom( "Si", (0,1/3.0,2/3.0) )
"""
if not self.isSet["cell"]:
print('Set cell first!')
return
import numpy as np
from westpy import Atom, Bohr
M = np.matrix([self.cell['a1'], self.cell['a2'], self.cell['a3']]).tolist()
self.atoms.append(Atom(symbol, tuple(np.array(frac_coord)@M), units=Bohr))
self.isSet["atoms"] = True
def __addAtomsFromXYZLines(self, lines, decode=True ) :
"""Adds atoms from XYZ lines.
:param lines: lines read from XYZ file (only one image)
:type lines: list of string
:param decode:
:type bool:
"""
#
from westpy import Angstrom
natoms = int(lines[0])
for line in lines[2:2+natoms] :
symbol, x, y, z = line.split()[:4]
self.addAtom( symbol.decode("utf-8"), (float(x), float(y), float(z)), units=Angstrom )
if decode:
self.addAtom( symbol.decode("utf-8"), (float(x), float(y), float(z)), units=Angstrom )
else:
self.addAtom( symbol, (float(x), float(y), float(z)), units=Angstrom )
#
def addAtomsFromXYZFile(self, fname ) :
"""Adds atoms from XYZ file (only one image).
......@@ -178,7 +206,7 @@ class Geometry(object) :
#
with open(fname,'r') as file:
lines = file.readlines()
self.__addAtomsFromXYZLines(lines)
self.__addAtomsFromXYZLines(lines, decode=False)
#
def addAtomsFromOnlineXYZ(self, url ) :
"""Adds atoms from XYZ file (only one image) located at url.
......@@ -196,7 +224,7 @@ class Geometry(object) :
import urllib.request
with urllib.request.urlopen(url) as response :
lines = response.readlines()
self.__addAtomsFromXYZLines(lines)
self.__addAtomsFromXYZLines(lines, decode=True)
#
def getNumberOfAtoms(self) :
"""Returns number of atoms.
......@@ -294,3 +322,63 @@ class Geometry(object) :
from westpy import download
for key in self.species.keys() :
download( self.species[key]["url"], fname=self.species[key]["fname"] )
def view(self, style='stick',width=800,height=800, ix=1, iy=1, iz=1, debug=False):
"""Display simulation box geom in Angstrom.
ix, iy, iz is the perodic display to system
style can be line, stick, sphere.
:param style:
:param width:
:param height:
:param ix:
:param iy:
:param iz:
:param debug:
:return:
"""
import py3Dmol
import numpy as np
from westpy.units import Angstrom
BOHR2A = 1.0 / Angstrom
a1 = self.cell["a1"] * BOHR2A
a2 = self.cell["a2"] * BOHR2A
a3 = self.cell["a3"] * BOHR2A
nat = self.getNumberOfAtoms()
times = ix * iy * iz
if times > 1:
nat *= times
#generate xyz data
xyz = str(nat) + '\n\n'
for atom in self.atoms:
if times:
for i in range(ix):
for j in range(iy):
for k in range(iz):
xyz += atom.symbol + " " + " ".join(
map(str, atom.position * BOHR2A + i * a1 + j * a2 + k * a3)) + '\n'
#creat viewer
xyzview = py3Dmol.view(width=width, height=height)
xyzview.addModel(xyz, 'xyz')
if debug:
print(xyz)
xyzview.setStyle({style: {}})
#draw the box
a0 = np.array([0.0, 0.0, 0.0])
from_ = [a0, a1 + a2, a1 + a3, a2 + a3]
to_ = [[a1, a2, a3], [a1, a2, a1 + a2 + a3], [a1, a3, a1 + a2 + a3], [a2, a3, a1 + a2 + a3]]
for frm, li_to in zip(from_, to_):
x0, y0, z0 = frm
for to in li_to:
x1, y1, z1 = to
xyzview.addLine(
{'color': 'blue', 'start': {'x': x0, 'y': y0, 'z': z0}, 'end': {'x': x1, 'y': y1, 'z': z1}});
#show
xyzview.zoomTo()
xyzview.show()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment