|
|
|
|
| import os, threading, time, sys
|
| if os.name == "nt":
|
| import win32pipe, win32file
|
| if sys.version_info[0] < 3:
|
| import codecs
|
|
|
| _pipe_out = None
|
| _pipe_out_result = None
|
| _nanolabo_dir = None
|
| _debug = False
|
| _echo = False
|
|
|
| def write_pipe_in(input):
|
| """Write input string to pipe nanolaboIn"""
|
| if _echo or _debug: print(input)
|
|
|
| if sys.version_info[0] < 3:
|
| open2 = codecs.open
|
| else:
|
| open2 = open
|
|
|
| for i in range(30):
|
| try:
|
| if os.name == "nt":
|
| handle = open2(r'\\.\pipe\nanolaboIn', 'w', buffering=1, encoding='utf-8')
|
| elif os.name == "posix" and os.path.exists('/tmp/nanolaboIn'):
|
| handle = open2('/tmp/nanolaboIn', 'w', buffering=1, encoding='utf-8')
|
| break
|
| except IOError as e:
|
| if e.errno == 2:
|
| time.sleep(0.1)
|
| continue
|
| else:
|
| print("I/O error({0}): {1}".format(e.errno, e.strerror))
|
| raise e
|
| else:
|
| print("error: failed to open pipe nanolaboIn")
|
|
|
| try:
|
| if sys.version_info[0] < 3 and type(input) is str:
|
| handle.write(unicode(input, sys.stdin.encoding))
|
| else:
|
| handle.write(input)
|
| handle.flush()
|
| handle.close()
|
| except IOError as e:
|
| print("I/O error({0}): {1}".format(e.errno, e.strerror))
|
| raise e
|
| except Exception as e:
|
| print("error: failed to write to pipe nanolaboIn")
|
| raise e
|
|
|
| def _create_pipe_out():
|
| global _pipe_out
|
| global _debug
|
| if _pipe_out is not None:
|
| if _debug: print("use existing pipe nanolaboOut")
|
| if os.name == "nt":
|
| win32pipe.DisconnectNamedPipe(_pipe_out)
|
| win32pipe.ConnectNamedPipe(_pipe_out, None)
|
| return
|
|
|
| try:
|
| if os.name == "nt":
|
| _pipe_out = win32pipe.CreateNamedPipe(
|
| r'\\.\pipe\nanolaboOut',
|
| win32pipe.PIPE_ACCESS_INBOUND,
|
| win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_WAIT,
|
| 1, 4096, 4096,
|
| 100,
|
| None)
|
|
|
| if _debug: print("created pipe nanolaboOut")
|
| win32pipe.ConnectNamedPipe(_pipe_out, None)
|
|
|
| elif os.name == "posix":
|
| pipe_path = "/tmp/nanolaboOut"
|
| if not os.path.exists(pipe_path):
|
| os.mkfifo(pipe_path)
|
| if _debug: print("created pipe nanolaboOut")
|
| _pipe_out = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)
|
| if _debug: print("opened pipe nanolaboOut")
|
|
|
| except:
|
| print("error: failed to create pipe nanolaboOut")
|
|
|
| return
|
|
|
| def _read_pipe_out():
|
| global _pipe_out
|
| global _pipe_out_result
|
| global _debug
|
| if os.name == "nt":
|
| for i in range(30):
|
| try:
|
|
|
| status, result = win32file.ReadFile(_pipe_out, 4096)
|
| break
|
| except IOError as e:
|
| if e.errno == 2:
|
| time.sleep(0.1)
|
| continue
|
| else:
|
| print("I/O error({0}): {1}".format(e.errno, e.strerror))
|
| raise e
|
| else:
|
| print("error: failed to read pipe nanolaboOut")
|
| return
|
|
|
| if _debug: print(status)
|
| _pipe_out_result = result.decode("utf-8")
|
| return
|
| elif os.name == "posix":
|
| for i in range(30):
|
| try:
|
| result = os.read(_pipe_out, 4096)
|
| except OSError as err:
|
| if err.errno == 11:
|
| time.sleep(0.1)
|
| continue
|
| else:
|
| raise err
|
| if len(result) != 0:
|
| _pipe_out_result = result.decode("utf-8")
|
|
|
| break
|
| time.sleep(0.1)
|
| return
|
| else:
|
| return
|
|
|
| def query_pipe(input):
|
| """Write input string to pipe nanolaboIn and read output string from pipe nanolaboOut"""
|
| global _pipe_out
|
| global _pipe_out_result
|
| global _debug
|
| if os.name == "nt" and _pipe_out is not None:
|
| _pipe_out.close()
|
| _pipe_out = None
|
| thread_out = threading.Thread(target = _create_pipe_out)
|
| thread_out.setDaemon(True)
|
| if _debug: print("start nanolaboOut thread")
|
| thread_out.start()
|
|
|
| if _debug: sys.stdout.write("waiting for pipe nanolaboOut created ... ")
|
| for i in range(30):
|
| if _pipe_out is not None:
|
| break
|
| time.sleep(0.1)
|
| if _debug: sys.stdout.write("\rwaiting for pipe nanolaboOut created ... {0}/30".format(i))
|
| else:
|
| print("")
|
| print("error: failed to create pipe nanolaboOut")
|
| return None
|
| if _debug: print("")
|
|
|
| if os.name == "posix":
|
|
|
| os.read(_pipe_out, 4096)
|
|
|
| if _debug: print("input: " + input)
|
| write_pipe_in(input)
|
| if _debug: print("wrote to nanolaboIn")
|
| _pipe_out_result = None
|
| thread_read = threading.Thread(target = _read_pipe_out)
|
| thread_read.setDaemon(True)
|
| if _debug: print("start read thread")
|
| thread_read.start()
|
| if _debug: sys.stdout.write("waiting for read ...")
|
| for i in range(30):
|
| if _pipe_out_result is not None:
|
| break
|
| time.sleep(0.1)
|
| if _debug: sys.stdout.write("\rwaiting for read ... {0}/30".format(i))
|
| else:
|
| print("")
|
| print("failed to read pipe nanolaboOut")
|
| return None
|
| if _debug: print("")
|
|
|
| if _debug: print("read from nanolaboOut")
|
| return _pipe_out_result
|
|
|
| def _get_nanolabo_dir():
|
| global _nanolabo_dir
|
| if _nanolabo_dir is None:
|
| _nanolabo_dir = query_pipe("#projectsPath")
|
| return _nanolabo_dir
|
|
|
| def _get_full_path(path):
|
| if _debug: print("get_full_path " + path)
|
| if os.path.isdir(path):
|
| return os.path.abspath(path)
|
| else:
|
| path2 = _get_nanolabo_dir()
|
| if path2 is None:
|
| return None
|
| path2 += "/" + path
|
| if os.path.isdir(path2):
|
| return os.path.abspath(path2)
|
| else:
|
| print("error: path not exist")
|
| return None
|
|
|
| def open_project(path):
|
| """Open a project."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| query_pipe("#openProject " + path2)
|
|
|
| def close_project(path):
|
| """Close a project."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| query_pipe("#closeProject " + path2)
|
|
|
| def save_project(path, dst_path=""):
|
| """Save a project.
|
| If dst_path is specified, the project is saved as another project.
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| dst_path2 = ""
|
| if dst_path == "":
|
| dst_path2 = path2
|
| else:
|
| if os.path.isabs(dst_path):
|
| dst_path2 = dst_path
|
| else:
|
| dst_path2 = os.path.abspath(_get_nanolabo_dir() + "/" + dst_path)
|
| if sys.version_info[0] < 3:
|
| dst_path2 = dst_path2.encode()
|
| if os.path.exists(dst_path2):
|
| print("error: destination path already exists")
|
| print(dst_path2)
|
| return
|
| if dst_path2 is None:
|
| print("error: invalid destination path")
|
| return
|
| query_pipe("#saveProject " + path2 + " " + dst_path2)
|
|
|
| def mode_project(path, mode):
|
| """Change calculator of a project."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| if mode not in set(["QuantumESPRESSO", "LAMMPS"]):
|
| print("error: invalid calculation mode")
|
| return
|
| query_pipe("#modeProject " + path2 + " " + mode)
|
|
|
| def run_project(path, jobType="", host="", queue=""):
|
| """Run a project.
|
| jobType: "SCF"(default), "OPTIMIZ", "MD", "DOS", "BAND", "TDDFT", "Phonon", "PhDisp", "NEB", "LAMMPS".
|
| host: "localhost"(default), or SSH/Lambda server host name (need settings be done within NanoLabo GUI beforehand).
|
| queue: specify in case you use SSH/Lambda server.
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| if jobType not in set(["", "SCF", "OPTIMIZ", "MD", "DOS", "BAND", "TDDFT", "Phonon", "PhDisp", "NEB", "LAMMPS"]):
|
| print("error: invalid job type")
|
| return
|
| if host != "" and host.lower() != "localhost" and queue == "":
|
| print("error: queue name cannot be empty to run on SSH/Lambda server.")
|
| return
|
| query_pipe("#runProject " + path2 + " " + jobType + " " + host + " " + queue)
|
|
|
| def create_project(file_path, project_path=""):
|
| """Create new project from atomic structure file.
|
| The project is saved to project_path if specified, or to the default projects directory otherwise.
|
| """
|
| if not os.path.isfile(file_path):
|
| print("error: invalid file path")
|
| return
|
| file_path2 = os.path.abspath(file_path)
|
| project_path2 = ""
|
| if project_path != "":
|
| if os.path.isabs(project_path):
|
| project_path2 = project_path
|
| else:
|
| project_path2 = os.path.abspath(_get_nanolabo_dir() + "/" + project_path)
|
| if sys.version_info[0] < 3:
|
| project_path2 = project_path2.encode()
|
| query_pipe("#createProject " + file_path2 + " " + project_path2)
|
|
|
| def clear_all_atoms(path):
|
| """Clear all atoms in a project."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| query_pipe("#clearAllAtoms " + path2)
|
|
|
| def set_all_atoms(path, atomsFile):
|
| """Set geometry info of a project from file.
|
| Geometry info already in the project will be overwritten.
|
| The file format contains lattice vectors, number of atoms,
|
| and coordinates of atoms in this order, as follows:
|
|
|
| -------------------------
|
| 3.09200995 0.00000000 0.00000000 # ax ay az
|
| -1.54600497 2.67775791 0.00000000 # bx by bz
|
| 0.00000000 0.00000000 5.07335137 # cx cy cz
|
| 4 # number of atoms
|
| Si -0.000002 1.785172 2.534588 1 1 1 # name x y z FIXED_X FIXED_Y FIXED_Z
|
| Si 1.546002 0.892585 5.071262 0 0 0 # 0:fixed, 1:mobile
|
| C -0.000002 1.785172 4.441264 0 0 0
|
| C 1.546002 0.892585 1.904590 0 0 0
|
| -------------------------
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| if not os.path.isfile(atomsFile):
|
| print("error: invalid atomsFile")
|
| return
|
| atomsFile2 = os.path.abspath(atomsFile)
|
| query_pipe("#setAllAtoms " + path2 + " " + atomsFile2)
|
|
|
| def get_lattice(path):
|
| """Get lattice vectors of a project"""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| strlat = query_pipe("#getLattice " + path2)
|
| if strlat is None:
|
| return None
|
| strlat2 = strlat.split()
|
| if len(strlat2) != 9:
|
| return None
|
| lat = [float(x) for x in strlat2]
|
| return [lat[0:3], lat[3:6], lat[6:9]]
|
|
|
| def set_lattice(path, lattice):
|
| """Set lattice vectors of a project.
|
| lattice: 2D list of size 3*3
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return
|
| if [len(v) for v in lattice] != [3, 3, 3]:
|
| print("error: lattice must be 2D list of size 3x3")
|
| return
|
| strlat = " ".join([" ".join([str(x) for x in v]) for v in lattice])
|
| query_pipe("#setLattice " + path2 + " " + strlat)
|
|
|
| def num_atoms(path):
|
| """Get number of atoms in a project."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#numAtoms " + path2)
|
| return int(result) if result is not None else None
|
|
|
| def add_atom(path, name, x, y, z):
|
| """Add an atom to a project.
|
| name: element symbol of the atom to be added
|
| In case you have coordinates as a list, you can unpack it when calling the function:
|
| >>> coords = [0.0, 0.0, 0.0]
|
| >>> add_atom(path, name, *coords)
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe("#addAtom " + path2 + " " + name + " " + str(x) + " " + str(y) + " " + str(z))
|
|
|
| def remove_atom(path, index):
|
| """Remove an atom in a project. The index starts at 0."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe("#removeAtom " + path2 + " " + str(index))
|
|
|
| def get_atom_name(path, index):
|
| """Get name (element symbol) of an atom in a project. The index starts at 0."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| return query_pipe("#getAtomName " + path2 + " " + str(index))
|
|
|
| def get_atom_xyz(path, index):
|
| """Get coordinates of an atom in a project as a list. The index starts at 0.
|
| Returns 2D list: [[x, y, z], [FIXED_X, FIXED_Y, FIXED_Z]], 0:fixed, 1:mobile.
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#getAtomXYZ " + path2 + " " + str(index))
|
| if result is None:
|
| return None
|
| coord = result.split()
|
| if len(coord) != 6:
|
| return None
|
| return [[float(x) for x in coord[0:3]], [int(x) for x in coord[3:6]]]
|
|
|
| def set_atom_name(path, index, name):
|
| """Change an atom in a project. The index starts at 0.
|
| name: element symbol of the atom
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe("#setAtomName " + path2 + " " + str(index) + " " + name)
|
|
|
| def set_atom_xyz(path, index, x, y, z, xfix=1, yfix=1, zfix=1):
|
| """Set coordinates of an atom in a project. The index starts at 0.
|
| In case you have coordinates as a list, you can unpack it when calling the function:
|
| >>> coords = [0.0, 0.0, 0.0]
|
| >>> set_atom_xyz(path, name, *coords)
|
| You can also set if the atom is fixed. 0:fixed, 1:mobile (default).
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe(" ".join(["#setAtomXYZ", path2] + [str(x) for x in [index, x, y, z, xfix, yfix, zfix]]))
|
|
|
| def qe_get_kpoints(path):
|
| """Get number of K points for SCF calculation of a project.
|
| Returns 2D list: [[nk1, nk2, nk3], [sk1, sk2, sk3]]
|
| sk's specify whether to apply offset. Please refer to QE manual (K_POINTS automatic) for detail.
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#qeGetKPoints " + path2)
|
| if result is None:
|
| return None
|
| kpoints = result.split()
|
| if len(kpoints) != 6:
|
| return None
|
| return [[int(x) for x in kpoints[0:3]], [int(x) for x in kpoints[3:6]]]
|
|
|
| def qe_set_kpoints(path, nk1, nk2, nk3, sk1, sk2, sk3):
|
| """Set number of K points for SCF calculation of a project.
|
| nk's: number of K points, sk's: whether to apply offset
|
| Please refer to QE manual (K_POINTS automatic) for detail.
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe(" ".join(["#qeSetKPoints", path2] + [str(x) for x in [nk1, nk2, nk3, sk1, sk2, sk3]]))
|
|
|
| def qe_get_mass(path, name):
|
| """Get atomic mass currently set for an element.
|
| name: element symbol
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#qeGetMass " + path2 + " " + name)
|
| return float(result) if result is not None else None
|
|
|
| def qe_set_mass(path, name, mass):
|
| """Set atomic mass for an element.
|
| name: element symbol
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe("#qeSetMass " + path2 + " " + name + " " + str(mass))
|
|
|
| def qe_get_pseudo(path, name):
|
| """Get pseudo potential file name currently set for an element.
|
| name: element symbol
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| return query_pipe("#qeGetPseudo " + path2 + " " + name)
|
|
|
| def qe_set_pseudo(path, name, pseudo):
|
| """Set pseudo potential file name for an element.
|
| name: element symbol
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| query_pipe("#qeSetPseudo " + path2 + " " + name + " " + pseudo)
|
|
|
| def qe_get_total_energy(path):
|
| """Get total energy calculated by Quantum ESPRESSO
|
| Returns list: [isConverged, total energy]
|
| 1:converged, 0:not converged
|
| """
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#qeGetTotalEnergy " + path2)
|
| if result is None:
|
| return None
|
| result2 = result.split()
|
| if len(result2) != 2:
|
| return None
|
| conv, te = result2
|
| return [int(conv), float(te)]
|
|
|
| def qe_get_geometry(path):
|
| """Export optimized geometry info to file and returns if the optimization is converged."""
|
| path2 = _get_full_path(path)
|
| if path2 is None:
|
| print("error: invalid project path")
|
| return None
|
| result = query_pipe("#qeGetGeometry " + path2)
|
| if result is None:
|
| return None
|
| return result.startswith("1") |