def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hs:o:n:b:e:t:", ["help", "structure=", "output=", "nparal=",
                                                               "binary=", "energy_tol=", "target_forces="])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    workdir = '.'
    structure_file = 'POSCAR'
    output_file = 'pcm_results.json'
    nparal = 2
    energy_tol = 1E-3
    target_forces = 1E-3
    binary = 'vasp'

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-s", "--structure"):
            structure_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-e", "--energy_tol"):
            energy_tol = get_float(arg)
        elif opt in ("-t", "--target_forces"):
            target_forces = get_float(arg)
        elif opt in ("-s", "--structure"):
            structure_file = arg

    structure = pychemia.structure_from_file(structure_file)
    if structure is None:
        print(" ERROR: Invalid structure, no structure could be obtained from '%s'" % structure_file)
        sys.exit(2)

    if structure_file == 'POSCAR':
        os.rename('POSCAR', 'POSCAR_original')

    print("\n PyChemia VASP Relaxator")
    print(" =======================\n")
    print(" VASP binary         : ", binary)
    print(" Energy tolerance    : ", energy_tol)
    print(" Target forces       : ", target_forces)
    print(" MPI number of procs : ", nparal)
    print(" Structure           :\n")
    print(structure)

    wf = open(output_file, 'w')
    data = {'input': {'binary': binary,
                      'energy_tol': energy_tol,
                      'target_forces': target_forces,
                      'nparal': nparal,
                      'structure': structure.to_dict}}
    json.dump(data, wf)
    wf.close()

    # First Round (Relaxing the original structure)
    print('\nFirst Round')
    print('===========')

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(structure, energy_tolerance=energy_tol)
    if os.path.isfile('convergence_encut.json'):
        print('A previous convergence study was found, loading...')
        ce.load()
    if not ce.is_converge:
        ce.run(nparal)
        ce.save()
        ce.plot()
    encut = ce.best_encut

    data['output'] = {'1R_ENCUT': encut}
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(structure, encut=encut, energy_tolerance=energy_tol)
    if os.path.isfile('convergence_kpoints.json'):
        print('A previous convergence study was found, loading...')
        ce.load()
    if not ce.is_converge:
        ce.run(nparal)
        ce.save()
        ce.plot()
    kp = ck.best_kpoints

    data['output'] = {'1R_KPOINTS': list(kp.grid)}
    print(data)
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    os.rename('convergence_encut.json', 'convergence_encut_phase1.json')
    os.rename('convergence_encut.pdf', 'convergence_encut_phase1.pdf')
    os.rename('convergence_kpoints.json', 'convergence_kpoints_phase1.json')
    os.rename('convergence_kpoints.pdf', 'convergence_kpoints_phase1.pdf')

    cleaner()
    print('\nIonic Relaxation')
    print('----------------\n')
    vr = IonRelaxation(structure=structure, encut=encut, kp_grid=kp.grid, workdir=workdir,
                       target_forces=10 * target_forces)
    vr.run(nparal)

    structure = vr.get_final_geometry()
    structure.save_json(workdir + os.sep + 'structure_phase1.json')

    data['output'] = {'1R_structure': structure.to_dict}
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    # Second Round (Symetrize structure and redo convergences)
    st = symmetrize(structure)

    print('\nSecond Round')
    print('============')

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(st, encut=encut, energy_tolerance=energy_tol, recover=True)
    ck.run(nparal)
    ck.save()
    ck.plot()
    kp = ck.best_kpoints

    data['output'] = {'2R_KPOINTS': list(kp.grid)}
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(st, energy_tolerance=energy_tol, kpoints=kp)
    ce.run(nparal)
    ce.save()
    ce.plot()
    encut = ce.best_encut

    data['output'] = {'2R_ENCUT': encut}
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    os.rename('convergence_encut.json', 'convergence_encut_phase2.json')
    os.rename('convergence_encut.pdf', 'convergence_encut_phase2.pdf')
    os.rename('convergence_kpoints.json', 'convergence_kpoints_phase2.json')
    os.rename('convergence_kpoints.pdf', 'convergence_kpoints_phase2.pdf')

    cleaner()
    print('\nIonic Relaxation')
    print('----------------\n')
    vr = IonRelaxation(structure=st, workdir='.', encut=encut, kp_grid=kp.grid, target_forces=target_forces)
    vr.run(nparal)

    structure = vr.get_final_geometry()
    structure.save_json(workdir + os.sep + 'structure_phase2.json')

    data['output'] = {'2R_structure': structure.to_dict}

    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
Exemple #2
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hi:p:", ["help", "ip=", "port="])
    except getopt.GetoptError:
        print('Wrong parsing of options')
        usage(argv[0])
        sys.exit(2)

    # Default Values
    port = None
    ip = None

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-p", "--port"):
            port = get_int(arg)
        elif opt in ("-i", "--ip"):
            ip = arg

    if ip is None:
        ip = socket.gethostbyname(socket.gethostname())

    print('PyChemia Client connecting to server on : ', ip)

    workdir = None
    entry_id = None
    while True:
        if port is not None:
            try:
                workdir, entry_id = inquirer(ip, port)
            except TimedOutExc as e:
                print("INQUIRER took too long: %s", e.message)
        else:
            lt = time.localtime()
            random.seed(lt.tm_yday * 24 + lt.tm_hour)
            rndport = random.randint(10000, 20000)
            print('PyChemia Client using port : ', rndport)
            try:
                workdir, entry_id = inquirer(ip, rndport)
            except TimedOutExc as e:
                print("Error({0}): {1}".format(e, e.message))

        print('We got the workdir: ', workdir)
        print('The entry_id is : ', entry_id)

        if workdir is not None and entry_id is not None:
            if entry_id == '':
                print('No entries to execute, taking a nap')
                time.sleep(15)
            else:
                break
        else:
            'Inquierer failed to get data, retry...'

    executor(workdir)

    if port is not None:
        finisher(entry_id, ip, port)
    else:
        lt = time.localtime()
        random.seed(lt.tm_yday * 24 + lt.tm_hour)
        rndport = random.randint(10000, 20000)
        print('PyChemia Client using port : ', rndport)

        try:
            finisher(entry_id, ip, rndport)
        except TimedOutExc as e:
            print("Error({0}): {1}".format(e, e.message))
Exemple #3
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hs:o:n:b:e:", ["help", "structure=", "output=", "nparal=",
                                                             "binary=", "energy_tol="])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    structure_file = 'POSCAR'
    output_file = 'static_calculation.json'
    nparal = 2
    energy_tol = 1E-3
    binary = 'vasp'

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-s", "--structure"):
            structure_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-e", "--energy_tol"):
            energy_tol = get_float(arg)
        elif opt in ("-s", "--structure"):
            structure_file = get_int(arg)

    structure = pychemia.structure_from_file(structure_file)
    if structure is None:
        print(" ERROR: Invalid structure, no structure could be obtained from '%s'" % structure_file)
        sys.exit(2)

    if structure_file == 'POSCAR':
        os.rename('POSCAR', 'POSCAR_original')

    print("\n PyChemia VASP Static")
    print(" =======================\n")
    print(" Executable          : ", binary)
    print(" Energy tolerance    : ", energy_tol)
    print(" MPI number of procs : ", nparal)
    print(" Structure           :\n")
    print(structure)
    data = {}

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(structure, energy_tolerance=energy_tol, binary=binary)
    ce.run(nparal)
    ce.save()
    ce.plot()
    encut = ce.best_encut

    cvg = json.load(open('task.json'))
    data['Convergece Cut-off'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(structure, encut=encut, energy_tolerance=energy_tol, binary=binary)
    ck.run(nparal)
    ck.save()
    ck.plot()
    kp = ck.best_kpoints

    cvg = json.load(open('task.json'))
    data['Convergece KPoints'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()

    job = StaticCalculation(structure, encut=encut, kpoints=kp, binary=binary)
    job.run(nparal)
    job.save()
    cvg = json.load(open('task.json'))
    data['Static'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hs:o:i:f:d:n:b:e:x:t:", ["help", "structure=", "output=", "ini_factor=",
                                                                       "fin_factor=", "delta_factor", "nparal=",
                                                                       "binary=", "energy_tol=", "expansion=",
                                                                       "target_forces"])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    structure_file = 'POSCAR'
    delta_factor = 0.01
    ini_factor = 0.01
    fin_factor = 0.1
    output_file = 'IdealStrength.json'
    nparal = 2
    energy_tol = 1E-3
    target_forces = 1E-3
    binary = 'vasp'
    expansion = 111

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-s", "--structure"):
            structure_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-i", "--ini_factor"):
            ini_factor = get_float(arg)
        elif opt in ("-f", "--fin_factor"):
            fin_factor = get_float(arg)
        elif opt in ("-d", "--delta_factor"):
            delta_factor = get_float(arg)
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-e", "--energy_tol"):
            energy_tol = get_float(arg)
        elif opt in ("-t", "--target_forces"):
            target_forces = get_float(arg)
        elif opt in ("-x", "--expansion"):
            expansion = get_int(arg)
        elif opt in ("-s", "--structure"):
            structure_file = get_int(arg)

    expansion = [int(expansion / 100), int(expansion / 10) % 10, expansion % 10]
    if len(expansion) == 0:
        print(" ERROR: ini_factor, fin_factor and delta_factor are not creating a finite range of values")
        sys.exit(2)

    structure = pychemia.structure_from_file(structure_file)
    if structure is None:
        print(" ERROR: Invalid structure, no structure could be obtained from '%s'" % structure_file)
        sys.exit(2)

    if structure_file == 'POSCAR':
        os.rename('POSCAR', 'POSCAR_original')

    print("\n PyChemia Ideal Strenght")
    print(" =======================\n")
    print(" Scaling factors     : ", str(np.arange(ini_factor, fin_factor + 0.9 * delta_factor, delta_factor)))
    print(" Executable          : ", binary)
    print(" Energy tolerance    : ", energy_tol)
    print(" Target forces       : ", target_forces)
    print(" Expansion directions: ", str(expansion))
    print(" MPI number of procs : ", nparal)
    print(" Structure           :\n")
    print(structure)

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(structure, energy_tolerance=energy_tol, binary=binary)
    if os.path.isfile('convergence_encut.json'):
        print('A previous convergence study was found, loading...')
        ce.load()
    if not ce.is_converge:
        ce.run(nparal)
        ce.save()
        ce.plot()
    encut = ce.best_encut
    print('ENCUT: ', encut)

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(structure, workdir='.', binary=binary, encut=encut,
                               energy_tolerance=energy_tol, recover=True)
    if os.path.isfile('convergence_kpoints.json'):
        print('A previous convergence study was found, loading...')
        ck.load()
    if not ck.is_converge:
        ck.run(nparal)
        ck.save()
        ck.plot()
    kp = ck.best_kpoints
    kp_density = kp.get_density_of_kpoints(structure.lattice)
    print('KPOINT GRID', kp.grid)

    strenght = IdealStrength(structure, ini_factor, fin_factor, delta_factor, kp, kp_density, expansion, encut,
                             nparal, binary, target_forces, output_file)

    strenght.run(nparal)
    strenght.save()

    cleaner()
def main(argv):
    try:
        opts, args = getopt.getopt(
            argv[1:], "hi:o:n:b:p:",
            ["help", "input=", "output=", "nparal=", "binary=", 'pseudo='])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    workdir = '.'
    inpu_file = 'abinit.in'
    output_file = 'pcm_results.json'
    nparal = 2
    binary = 'abinit'
    pseudo = 'FHI_LDA'

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-i", "--input"):
            inpu_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-p", "--pseudo"):
            pseudo = arg

    structure = pychemia.code.abinit.AbinitInput(inpu_file).get_structure()
    if structure is None:
        print(" ERROR: Invalid structure, no structure could be obtained")
        sys.exit(2)

    print("\n PyChemia ABINIT Job")
    print(" =======================\n")
    print(" MPI number of procs : ", nparal)
    print(" ABINIT binary       : ", binary)
    print(" ABINIT input_file   : ", inpu_file)
    print(" ABINIT pseudo       : ", pseudo)
    print(" Structure           :\n")
    print(structure)

    wf = open(output_file, 'w')
    data = {
        'input': {
            'binary': binary,
            'nparal': nparal,
            'structure': structure.to_dict
        },
        'complete': False,
    }
    json.dump(data, wf, sort_keys=True)
    wf.close()

    cleaner()

    aj = pychemia.code.abinit.AbinitJob()
    aj.initialize(workdir=workdir,
                  input_file='abinit.in',
                  psp_kind=pseudo.split('_')[0],
                  psp_exchange=pseudo.split('_')[1])
    aj.set_inputs()

    if os.path.exists('abinit.out'):
        os.remove('abinit.out')

    aj.run(use_mpi=True, omp_max_threads=2, mpi_num_procs=nparal)
    time.sleep(5)
    ao = pychemia.code.abinit.AbinitOutput('abinit.out')
    old_niter = 0
    while aj.runner.returncode is None:
        aj.runner.poll()
        ao.reload()
        energetics = ao.get_energetics()
        if energetics is not None:
            if len(energetics['iter']) > old_niter:
                print(
                    "ITER %4d  ETOT= %15.8f deltaE(h)= %9.2E residm= %9.2E nres2= %9.2E"
                    % (energetics['iter'][-1], energetics['etot'][-1],
                       energetics['deltaEh'][-1], energetics['residm'][-1],
                       energetics['nres2'][-1]))
                old_niter = len(energetics['iter'])
        time.sleep(60)

    ao.reload()
    energetics = ao.get_energetics()
    occupation_matrix = ao.get_occupation_matrix()
    output = {'energetics': energetics}
    if occupation_matrix is not None:
        output['occupation_matrix'] = occupation_matrix
    if os.path.isfile('abinit-o_OUT.nc'):
        nco = pychemia.code.abinit.netcdf2dict('abinit-o_OUT.nc')
        output['variables'] = nco
    data['output'] = output

    data['complete'] = True

    wf = open(output_file, 'w')
    json.dump(data, wf, sort_keys=True)
    wf.close()

    cleaner()
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hs:o:n:b:e:", [
            "help", "structure=", "output=", "nparal=", "binary=",
            "energy_tol="
        ])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    structure_file = 'POSCAR'
    output_file = 'static_calculation.json'
    nparal = 2
    energy_tol = 1E-3
    binary = 'vasp'

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-s", "--structure"):
            structure_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-e", "--energy_tol"):
            energy_tol = get_float(arg)
        elif opt in ("-s", "--structure"):
            structure_file = get_int(arg)

    structure = pychemia.structure_from_file(structure_file)
    if structure is None:
        print(
            " ERROR: Invalid structure, no structure could be obtained from '%s'"
            % structure_file)
        sys.exit(2)

    if structure_file == 'POSCAR':
        os.rename('POSCAR', 'POSCAR_original')

    print("\n PyChemia VASP Static")
    print(" =======================\n")
    print(" Executable          : ", binary)
    print(" Energy tolerance    : ", energy_tol)
    print(" MPI number of procs : ", nparal)
    print(" Structure           :\n")
    print(structure)
    data = {}

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(structure,
                                 energy_tolerance=energy_tol,
                                 binary=binary)
    ce.run(nparal)
    ce.save()
    ce.plot()
    encut = ce.best_encut

    cvg = json.load(open('task.json'))
    data['Convergece Cut-off'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(structure,
                               encut=encut,
                               energy_tolerance=energy_tol,
                               binary=binary)
    ck.run(nparal)
    ck.save()
    ck.plot()
    kp = ck.best_kpoints

    cvg = json.load(open('task.json'))
    data['Convergece KPoints'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()

    job = StaticCalculation(structure, encut=encut, kpoints=kp, binary=binary)
    job.run(nparal)
    job.save()
    cvg = json.load(open('task.json'))
    data['Static'] = cvg
    wf = open(output_file, 'w')
    json.dump(data, wf)
    wf.close()

    cleaner()
Exemple #7
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hd:p:i:w:", ["help", "dbsettings_file=", "port=", "ip=", 'workdir='])
    except getopt.GetoptError:
        print('Error with options')
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    workdir = None
    dbsettings_file = None
    port = None
    ip = None

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-w", "--workdir"):
            workdir = arg
        elif opt in ("-d", "--dbsettings_file"):
            dbsettings_file = arg
        elif opt in ("-p", "--port"):
            port = get_int(arg)
        elif opt in ("-i", "--ip"):
            ip = arg

    if workdir is None:
        print('Missing workdir')
        usage(argv[0])
        sys.exit()
    if not os.path.isdir(workdir):
        os.mkdir(workdir)

    print('dbsettings_file:', dbsettings_file)
    if dbsettings_file is None or not os.path.exists(dbsettings_file):
        print('Missing dbsettings')
        usage(argv[0])
        sys.exit()
    else:
        dbsettings = json.load(open(dbsettings_file))

    if ip is None:
        ip = socket.gethostbyname(socket.gethostname())

    print('PyChemia Server binded to IP: ', ip)

    pcq = get_database(dbsettings)
    print('Connected with database, number of entries: ', pcq.db.pychemia_entries.count())

    if port is not None:
        print('Using port : %s' % port)
        p = multiprocessing.Process(target=listener, args=(dbsettings, ip, port, workdir))
        p.start()
    else:
        old_port = 0
        p = None
        while True:
            lt = time.localtime()
            random.seed(lt.tm_yday * 24 + lt.tm_hour)
            port = random.randint(10000, 20000)
            if port != old_port:
                if p is not None and p.is_alive():
                    print('Terminating listener on port : %s' % old_port)
                    p.terminate()
                print('Using port : %s' % port)
                p = multiprocessing.Process(target=listener, args=(dbsettings, ip, port, workdir))
                p.start()
                old_port = port
            time.sleep(300)
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hs:o:i:f:d:n:b:e:x:t:", [
            "help", "structure=", "output=", "ini_factor=", "fin_factor=",
            "delta_factor", "nparal=", "binary=", "energy_tol=", "expansion=",
            "target_forces"
        ])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    structure_file = 'POSCAR'
    delta_factor = 0.01
    ini_factor = 0.01
    fin_factor = 0.1
    output_file = 'IdealStrength.json'
    nparal = 2
    energy_tol = 1E-3
    target_forces = 1E-3
    binary = 'vasp'
    expansion = 111

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-s", "--structure"):
            structure_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-i", "--ini_factor"):
            ini_factor = get_float(arg)
        elif opt in ("-f", "--fin_factor"):
            fin_factor = get_float(arg)
        elif opt in ("-d", "--delta_factor"):
            delta_factor = get_float(arg)
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-e", "--energy_tol"):
            energy_tol = get_float(arg)
        elif opt in ("-t", "--target_forces"):
            target_forces = get_float(arg)
        elif opt in ("-x", "--expansion"):
            expansion = get_int(arg)
        elif opt in ("-s", "--structure"):
            structure_file = get_int(arg)

    expansion = [
        int(expansion / 100),
        int(expansion / 10) % 10, expansion % 10
    ]
    if len(expansion) == 0:
        print(
            " ERROR: ini_factor, fin_factor and delta_factor are not creating a finite range of values"
        )
        sys.exit(2)

    structure = pychemia.structure_from_file(structure_file)
    if structure is None:
        print(
            " ERROR: Invalid structure, no structure could be obtained from '%s'"
            % structure_file)
        sys.exit(2)

    if structure_file == 'POSCAR':
        os.rename('POSCAR', 'POSCAR_original')

    print("\n PyChemia Ideal Strenght")
    print(" =======================\n")
    print(
        " Scaling factors     : ",
        str(
            np.arange(ini_factor, fin_factor + 0.9 * delta_factor,
                      delta_factor)))
    print(" Executable          : ", binary)
    print(" Energy tolerance    : ", energy_tol)
    print(" Target forces       : ", target_forces)
    print(" Expansion directions: ", str(expansion))
    print(" MPI number of procs : ", nparal)
    print(" Structure           :\n")
    print(structure)

    cleaner()
    print('\nConvergence of Cut-off Energy')
    print('-----------------------------\n')
    ce = ConvergenceCutOffEnergy(structure,
                                 energy_tolerance=energy_tol,
                                 binary=binary)
    if os.path.isfile('convergence_encut.json'):
        print('A previous convergence study was found, loading...')
        ce.load()
    if not ce.is_converge:
        ce.run(nparal)
        ce.save()
        ce.plot()
    encut = ce.best_encut
    print('ENCUT: ', encut)

    cleaner()
    print('\nConvergence of K-Point Grid')
    print('---------------------------\n')
    ck = ConvergenceKPointGrid(structure,
                               workdir='.',
                               binary=binary,
                               encut=encut,
                               energy_tolerance=energy_tol,
                               recover=True)
    if os.path.isfile('convergence_kpoints.json'):
        print('A previous convergence study was found, loading...')
        ck.load()
    if not ck.is_converge:
        ck.run(nparal)
        ck.save()
        ck.plot()
    kp = ck.best_kpoints
    kp_density = kp.get_density_of_kpoints(structure.lattice)
    print('KPOINT GRID', kp.grid)

    strenght = IdealStrength(structure, ini_factor, fin_factor, delta_factor,
                             kp, kp_density, expansion, encut, nparal, binary,
                             target_forces, output_file)

    strenght.run(nparal)
    strenght.save()

    cleaner()
def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hi:o:n:b:p:", ["help", "input=", "output=", "nparal=", "binary=",
                                                             'pseudo='])
    except getopt.GetoptError:
        usage(argv[0])
        sys.exit(2)

    if len(opts) == 0:
        usage(argv[0])
        sys.exit(2)

    # Default Values
    workdir = '.'
    inpu_file = 'abinit.in'
    output_file = 'pcm_results.json'
    nparal = 2
    binary = 'abinit'
    pseudo = 'FHI_LDA'

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage(argv[0])
            sys.exit()
        elif opt in ("-i", "--input"):
            inpu_file = arg
        elif opt in ("-o", "--output"):
            output_file = arg
        elif opt in ("-n", "--nparal"):
            nparal = get_int(arg)
        elif opt in ("-b", "--binary"):
            binary = arg
        elif opt in ("-p", "--pseudo"):
            pseudo = arg

    structure = pychemia.code.abinit.AbinitInput(inpu_file).get_structure()
    if structure is None:
        print(" ERROR: Invalid structure, no structure could be obtained")
        sys.exit(2)

    print("\n PyChemia ABINIT Job")
    print(" =======================\n")
    print(" MPI number of procs : ", nparal)
    print(" ABINIT binary       : ", binary)
    print(" ABINIT input_file   : ", inpu_file)
    print(" ABINIT pseudo       : ", pseudo)
    print(" Structure           :\n")
    print(structure)

    wf = open(output_file, 'w')
    data = {'input': {'binary': binary, 'nparal': nparal, 'structure': structure.to_dict}, 'complete': False, }
    json.dump(data, wf, sort_keys=True)
    wf.close()

    cleaner()

    aj = pychemia.code.abinit.AbinitJob()
    aj.initialize(workdir=workdir, input_file='abinit.in',
                  psp_kind=pseudo.split('_')[0],
                  psp_exchange=pseudo.split('_')[1])
    aj.set_inputs()

    if os.path.exists('abinit.out'):
        os.remove('abinit.out')

    aj.run(use_mpi=True, omp_max_threads=2, mpi_num_procs=nparal)
    time.sleep(5)
    ao = pychemia.code.abinit.AbinitOutput('abinit.out')
    old_niter = 0
    while aj.runner.returncode is None:
        aj.runner.poll()
        ao.reload()
        energetics = ao.get_energetics()
        if energetics is not None:
            if len(energetics['iter']) > old_niter:
                print("ITER %4d  ETOT= %15.8f deltaE(h)= %9.2E residm= %9.2E nres2= %9.2E" % (energetics['iter'][-1],
                                                                                              energetics['etot'][-1],
                                                                                              energetics['deltaEh'][-1],
                                                                                              energetics['residm'][-1],
                                                                                              energetics['nres2'][-1]))
                old_niter = len(energetics['iter'])
        time.sleep(60)

    ao.reload()
    energetics = ao.get_energetics()
    occupation_matrix = ao.get_occupation_matrix()
    output = {'energetics': energetics}
    if occupation_matrix is not None:
        output['occupation_matrix'] = occupation_matrix
    if os.path.isfile('abinit-o_OUT.nc'):
        nco = pychemia.code.abinit.netcdf2dict('abinit-o_OUT.nc')
        output['variables'] = nco
    data['output'] = output

    data['complete'] = True

    wf = open(output_file, 'w')
    json.dump(data, wf, sort_keys=True)
    wf.close()

    cleaner()