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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# -*- coding: utf-8 -*-

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)
            #win32pipe.WaitNamedPipe(_pipe_out, 1000) 
            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:
                #win32file.SetFilePointer(_pipe_out,0,win32file.FILE_BEGIN)
                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")
                #os.close(_pipe_out)
                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":
        #flush previous result
        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"]): #TODO:add NWChem
        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"]): #TODO:add NWChem
        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")