def _read_phono3py_fc3(phono3py, symmetrize_fc3r, input_filename, log_level):
    if input_filename is None:
        filename = "fc3.hdf5"
    else:
        filename = "fc3." + input_filename + ".hdf5"
    file_exists(filename, log_level)
    if log_level:
        print('Reading fc3 from "%s".' % filename)

    p2s_map = phono3py.primitive.p2s_map
    try:
        fc3 = read_fc3_from_hdf5(filename=filename, p2s_map=p2s_map)
    except RuntimeError:
        import traceback

        traceback.print_exc()
        if log_level:
            print_error()
        sys.exit(1)
    num_atom = phono3py.supercell.get_number_of_atoms()
    if fc3.shape[1] != num_atom:
        print("Matrix shape of fc3 doesn't agree with supercell size.")
        if log_level:
            print_error()
        sys.exit(1)

    if symmetrize_fc3r:
        set_translational_invariance_fc3(fc3)
        set_permutation_symmetry_fc3(fc3)

    phono3py.fc3 = fc3
def _read_phono3py_fc2(phono3py, symmetrize_fc2, input_filename, log_level):
    if input_filename is None:
        filename = "fc2.hdf5"
    else:
        filename = "fc2." + input_filename + ".hdf5"
    file_exists(filename, log_level)
    if log_level:
        print('Reading fc2 from "%s".' % filename)

    num_atom = phono3py.phonon_supercell.get_number_of_atoms()
    p2s_map = phono3py.phonon_primitive.p2s_map
    try:
        phonon_fc2 = read_fc2_from_hdf5(filename=filename, p2s_map=p2s_map)
    except RuntimeError:
        import traceback

        traceback.print_exc()
        if log_level:
            print_error()
        sys.exit(1)

    if phonon_fc2.shape[1] != num_atom:
        print("Matrix shape of fc2 doesn't agree with supercell size.")
        if log_level:
            print_error()
        sys.exit(1)

    if symmetrize_fc2:
        if phonon_fc2.shape[0] == phonon_fc2.shape[1]:
            symmetrize_force_constants(phonon_fc2)
        else:
            symmetrize_compact_force_constants(phonon_fc2,
                                               phono3py.phonon_primitive)

    phono3py.fc2 = phonon_fc2
Beispiel #3
0
def check_supercell_in_yaml(cell_info, ph3, distance_to_A, log_level):
    """Check consistency between generated cells and cells in yaml."""
    if cell_info["phonopy_yaml"] is not None:
        if distance_to_A is None:
            d2A = 1.0
        else:
            d2A = distance_to_A
        if (cell_info["phonopy_yaml"].supercell is not None
                and ph3.supercell is not None):  # noqa E129
            yaml_cell = cell_info["phonopy_yaml"].supercell.copy()
            yaml_cell.cell = yaml_cell.cell * d2A
            if not cells_isclose(yaml_cell, ph3.supercell):
                if log_level:
                    print("Generated supercell is inconsistent with "
                          'that in "%s".' %
                          cell_info["optional_structure_info"][0])
                    print_error()
                sys.exit(1)
        if (cell_info["phonopy_yaml"].phonon_supercell is not None
                and ph3.phonon_supercell is not None):  # noqa E129
            yaml_cell = cell_info["phonopy_yaml"].phonon_supercell.copy()
            yaml_cell.cell = yaml_cell.cell * d2A
            if not cells_isclose(yaml_cell, ph3.phonon_supercell):
                if log_level:
                    print("Generated phonon supercell is inconsistent with "
                          'that in "%s".' %
                          cell_info["optional_structure_info"][0])
                    print_error()
                sys.exit(1)
Beispiel #4
0
def get_cell_info(settings, cell_filename, log_level):
    """Return calculator interface and crystal structure information."""
    cell_info = collect_cell_info(
        supercell_matrix=settings.supercell_matrix,
        primitive_matrix=settings.primitive_matrix,
        interface_mode=settings.calculator,
        cell_filename=cell_filename,
        chemical_symbols=settings.chemical_symbols,
        phonopy_yaml_cls=Phono3pyYaml,
    )
    if "error_message" in cell_info:
        print_error_message(cell_info["error_message"])
        if log_level > 0:
            print_error()
        sys.exit(1)

    set_magnetic_moments(cell_info, settings, log_level)

    cell_info["phonon_supercell_matrix"] = settings.phonon_supercell_matrix
    ph3py_yaml: Phono3pyYaml = cell_info["phonopy_yaml"]
    if cell_info["phonon_supercell_matrix"] is None and ph3py_yaml:
        ph_smat = ph3py_yaml.phonon_supercell_matrix
        cell_info["phonon_supercell_matrix"] = ph_smat

    return cell_info
def _create_phono3py_phonon_fc2(phono3py, ph3py_yaml, symmetrize_fc2,
                                input_filename, is_compact_fc, fc_calculator,
                                fc_calculator_options, log_level):
    if input_filename is None:
        disp_filename = 'disp_fc2.yaml'
    else:
        disp_filename = 'disp_fc2.' + input_filename + '.yaml'

    _ph3py_yaml = _get_ph3py_yaml(disp_filename, ph3py_yaml)

    try:
        dataset = parse_forces(phono3py,
                               ph3py_yaml=_ph3py_yaml,
                               force_filename="FORCES_FC2",
                               disp_filename=disp_filename,
                               fc_type='phonon_fc2',
                               log_level=log_level)
    except RuntimeError as e:
        if log_level:
            print(str(e))
            print_error()
        sys.exit(1)
    except FileNotFoundError as e:
        file_exists(e.filename, log_level)

    phono3py.phonon_dataset = dataset
    phono3py.produce_fc2(symmetrize_fc2=symmetrize_fc2,
                         is_compact_fc=is_compact_fc,
                         fc_calculator=fc_calculator,
                         fc_calculator_options=fc_calculator_options)
Beispiel #6
0
def get_cell_info(settings, cell_filename, symprec, log_level):
    """calculator interface and crystal structure information"""

    cell_info = collect_cell_info(supercell_matrix=settings.supercell_matrix,
                                  primitive_matrix=settings.primitive_matrix,
                                  interface_mode=settings.calculator,
                                  cell_filename=cell_filename,
                                  chemical_symbols=settings.chemical_symbols,
                                  phonopy_yaml_cls=Phono3pyYaml,
                                  symprec=symprec,
                                  return_dict=True)
    if type(cell_info) is str:
        print_error_message(cell_info)
        if log_level > 0:
            print_error()
        sys.exit(1)

    # cell_info keys
    # ('unitcell', 'supercell_matrix', 'primitive_matrix',
    #  'optional_structure_info', 'interface_mode', 'phonopy_yaml')

    cell_info['phonon_supercell_matrix'] = settings.phonon_supercell_matrix
    ph3py_yaml = cell_info['phonopy_yaml']
    if cell_info['phonon_supercell_matrix'] is None and ph3py_yaml:
        ph_smat = ph3py_yaml.phonon_supercell_matrix
        cell_info['phonon_supercell_matrix'] = ph_smat

    return cell_info
def _create_phono3py_fc3(
    phono3py,
    ph3py_yaml,
    symmetrize_fc3r,
    input_filename,
    is_compact_fc,
    cutoff_pair_distance,
    fc_calculator,
    fc_calculator_options,
    log_level,
):
    """Read or calculate fc3.

    Note
    ----
    cutoff_pair_distance is the parameter to determine each displaced
    supercell is included to the computation of fc3. It is assumed that
    cutoff_pair_distance is stored in the step to create sets of
    displacements and the value is stored n the displacement dataset and
    also as the parameter 'included': True or False for each displacement.
    The parameter cutoff_pair_distance here can be used in the step to
    create fc3 by overwriting original cutoff_pair_distance value only
    when the former value is smaller than the later.

    """
    if input_filename is None:
        disp_filename = "disp_fc3.yaml"
    else:
        disp_filename = "disp_fc3." + input_filename + ".yaml"

    _ph3py_yaml = _get_ph3py_yaml(disp_filename, ph3py_yaml)

    try:
        dataset = parse_forces(
            phono3py,
            ph3py_yaml=_ph3py_yaml,
            cutoff_pair_distance=cutoff_pair_distance,
            force_filename="FORCES_FC3",
            disp_filename=disp_filename,
            fc_type="fc3",
            log_level=log_level,
        )
    except RuntimeError as e:
        # from _parse_forces_type1
        if log_level:
            print(str(e))
            print_error()
        sys.exit(1)
    except FileNotFoundError as e:
        # from _get_type2_dataset
        file_exists(e.filename, log_level)

    phono3py.dataset = dataset
    phono3py.produce_fc3(
        symmetrize_fc3r=symmetrize_fc3r,
        is_compact_fc=is_compact_fc,
        fc_calculator=fc_calculator,
        fc_calculator_options=fc_calculator_options,
    )
Beispiel #8
0
def create_FORCE_SETS_from_FORCES_FCx_then_exit(phonon_smat,
                                                input_filename: Optional[str],
                                                cell_filename: Optional[str],
                                                log_level):
    """Convert FORCES_FC3 or FORCES_FC2 to FORCE_SETS."""
    if cell_filename is not None:
        disp_filename = cell_filename
    elif input_filename is None:
        disp_filename = "phono3py_disp.yaml"
    else:
        disp_filename = f"phono3py_disp.{input_filename}.yaml"
    if phonon_smat is not None:
        forces_filename = "FORCES_FC2"
    else:
        forces_filename = "FORCES_FC3"

    if log_level:
        print(f'Displacement dataset is read from "{disp_filename}".')
        print(f'Forces are read from "{forces_filename}"')

    with open(forces_filename, "r") as f:
        len_first_line = get_length_of_first_line(f)

    if len_first_line == 3:
        file_exists(disp_filename, log_level)
        file_exists(forces_filename, log_level)
        ph3yml = Phono3pyYaml()
        ph3yml.read(disp_filename)
        if phonon_smat is None:
            dataset = copy.deepcopy(ph3yml.dataset)
            smat = ph3yml.supercell_matrix
        else:
            dataset = copy.deepcopy(ph3yml.phonon_dataset)
            smat = ph3yml.phonon_supercell_matrix

        if smat is None or (phonon_smat is not None and
                            (phonon_smat != smat).any()):
            if log_level:
                print("")
                print("Supercell matrix is inconsistent.")
                print(f'Supercell matrix read from "{disp_filename}":')
                print(smat)
                print("Supercell matrix given by --dim-fc2:")
                print(phonon_smat)
                print_error()
            sys.exit(1)

        parse_FORCES_FC2(dataset, filename=forces_filename)
        write_FORCE_SETS(dataset)

        if log_level:
            print("FORCE_SETS has been created.")
            print_end()
    else:
        if log_level:
            print("The file format of %s is already readable by phonopy." %
                  forces_filename)
            print_end()
    sys.exit(0)
Beispiel #9
0
def init_phono3py(settings, cell_info, interface_mode, output_filename,
                  symprec, log_level):
    physical_units = get_default_physical_units(interface_mode)
    distance_to_A = physical_units['distance_to_A']

    # Change unit of lattice parameters to angstrom
    unitcell = cell_info['unitcell'].copy()
    if distance_to_A is not None:
        lattice = unitcell.cell
        lattice *= distance_to_A
        unitcell.cell = lattice

    # updated_settings keys
    # ('grid_points', 'sigmas', 'temperature_points', 'temperatures',
    #  'frequency_factor_to_THz', 'num_frequency_points',
    #  'frequency_step', 'frequency_scale_factor',
    #  'cutoff_frequency')
    updated_settings = get_default_values(settings)

    phono3py = Phono3py(
        unitcell,
        cell_info['supercell_matrix'],
        primitive_matrix=cell_info['primitive_matrix'],
        phonon_supercell_matrix=cell_info['phonon_supercell_matrix'],
        masses=settings.masses,
        mesh=settings.mesh_numbers,
        band_indices=settings.band_indices,
        sigmas=updated_settings['sigmas'],
        sigma_cutoff=settings.sigma_cutoff_width,
        cutoff_frequency=updated_settings['cutoff_frequency'],
        frequency_factor_to_THz=updated_settings['frequency_factor_to_THz'],
        is_symmetry=settings.is_symmetry,
        is_mesh_symmetry=settings.is_mesh_symmetry,
        symmetrize_fc3q=settings.is_symmetrize_fc3_q,
        symprec=symprec,
        calculator=interface_mode,
        log_level=log_level,
        lapack_zheev_uplo=settings.lapack_zheev_uplo)

    check_supercell_in_yaml(cell_info, phono3py, log_level)

    if cell_info['phonopy_yaml'] is not None:
        if (cell_info['phonopy_yaml'].phonon_supercell is not None
                and phono3py.phonon_supercell is not None):
            if not cells_isclose(cell_info['phonopy_yaml'].phonon_supercell,
                                 phono3py.phonon_supercell):
                if log_level:
                    print("Generated phonon supercell is inconsistent with "
                          "that in \"%s\"." %
                          cell_info['optional_structure_info'][0])
                    print_error()
                sys.exit(1)

    return phono3py, updated_settings
Beispiel #10
0
def store_force_constants(phono3py, settings, ph3py_yaml, physical_units,
                          input_filename, output_filename, load_phono3py_yaml,
                          log_level):
    if load_phono3py_yaml:
        if log_level:
            print("-" * 29 + " Force constants " + "-" * 30)

        (fc_calculator,
         fc_calculator_options) = get_fc_calculator_params(settings)

        read_fc = set_dataset_and_force_constants(
            phono3py,
            ph3py_yaml=ph3py_yaml,
            fc_calculator=fc_calculator,
            fc_calculator_options=fc_calculator_options,
            symmetrize_fc=settings.fc_symmetry,
            is_compact_fc=settings.is_compact_fc,
            log_level=log_level)

        if log_level:
            if phono3py.fc3 is None:
                print("fc3 could not be obtained.")
            if phono3py.fc2 is None:
                print("fc2 could not be obtained.")
        if phono3py.fc3 is None or phono3py.fc2 is None:
            print_error()
            sys.exit(1)

        if not read_fc['fc3']:
            write_fc3_to_hdf5(phono3py.fc3,
                              p2s_map=phono3py.primitive.p2s_map,
                              compression=settings.hdf5_compression)
            if log_level:
                print("fc3 was written into \"fc3.hdf5\".")
        if not read_fc['fc2']:
            write_fc2_to_hdf5(phono3py.fc2,
                              p2s_map=phono3py.primitive.p2s_map,
                              physical_unit='eV/angstrom^2',
                              compression=settings.hdf5_compression)
            if log_level:
                print("fc2 was written into \"fc2.hdf5\".")
    else:
        create_phono3py_force_constants(phono3py,
                                        settings,
                                        ph3py_yaml=ph3py_yaml,
                                        input_filename=input_filename,
                                        output_filename=output_filename,
                                        log_level=log_level)
Beispiel #11
0
def run_gruneisen_then_exit(phono3py, settings, output_filename, log_level):
    """Run mode Grueneisen parameter calculation from fc3."""
    if (settings.mesh_numbers is None and settings.band_paths is None
            and settings.qpoints is None):
        print("An option of --mesh, --band, or --qpoints has to be specified.")
        if log_level:
            print_error()
        sys.exit(1)

    if len(phono3py.fc2) != len(phono3py.fc3):
        print("Supercells used for fc2 and fc3 have to be same.")
        if log_level:
            print_error()
        sys.exit(1)

    if settings.band_paths is not None:
        if settings.band_points is None:
            npoints = 51
        else:
            npoints = settings.band_points
        band_paths = settings.band_paths
        bands = get_band_qpoints(band_paths, npoints=npoints)
    else:
        bands = None

    rotations = phono3py.primitive_symmetry.pointgroup_operations
    run_gruneisen_parameters(
        phono3py.fc2,
        phono3py.fc3,
        phono3py.supercell,
        phono3py.primitive,
        bands,
        settings.mesh_numbers,
        rotations,
        settings.qpoints,
        nac_params=phono3py.nac_params,
        nac_q_direction=settings.nac_q_direction,
        ion_clamped=settings.ion_clamped,
        factor=VaspToTHz,
        symprec=phono3py.symmetry.tolerance,
        output_filename=output_filename,
        log_level=log_level,
    )

    if log_level:
        print_end()
    sys.exit(0)
Beispiel #12
0
def init_phph_interaction(phono3py, settings, updated_settings, input_filename,
                          output_filename, log_level):
    ave_pp = settings.constant_averaged_pp_interaction
    phono3py.init_phph_interaction(
        nac_q_direction=settings.nac_q_direction,
        constant_averaged_interaction=ave_pp,
        frequency_scale_factor=updated_settings['frequency_scale_factor'],
        solve_dynamical_matrices=(not settings.read_phonon))

    if log_level > 0:
        dm = phono3py.dynamical_matrix
        if (dm.is_nac() and dm.nac_method == 'gonze'):
            dm.show_Gonze_nac_message()

    if settings.write_phonon:
        freqs, eigvecs, grid_address = phono3py.get_phonon_data()
        filename = write_phonon_to_hdf5(freqs,
                                        eigvecs,
                                        grid_address,
                                        phono3py.mesh_numbers,
                                        compression=settings.hdf5_compression,
                                        filename=output_filename)
        if filename:
            if log_level:
                print("Phonons are written into \"%s\"." % filename)
        else:
            print("Writing phonons failed.")
            if log_level:
                print_error()
            sys.exit(1)

    if settings.read_phonon:
        phonons = read_phonon_from_hdf5(phono3py.mesh_numbers,
                                        filename=input_filename,
                                        verbose=(log_level > 0))
        if phonons is None:
            print("Reading phonons failed.")
            if log_level:
                print_error()
            sys.exit(1)

        try:
            phono3py.set_phonon_data(*phonons)
        except RuntimeError:
            if log_level:
                print_error()
            sys.exit(1)
Beispiel #13
0
def store_force_constants(
    phono3py,
    settings,
    ph3py_yaml,
    input_filename,
    output_filename,
    load_phono3py_yaml,
    log_level,
):
    """Calculate, read, and write force constants."""
    if load_phono3py_yaml:
        if log_level:
            print("-" * 29 + " Force constants " + "-" * 30)

        (fc_calculator,
         fc_calculator_options) = get_fc_calculator_params(settings)

        read_fc = set_dataset_and_force_constants(
            phono3py,
            ph3py_yaml=ph3py_yaml,
            fc_calculator=fc_calculator,
            fc_calculator_options=fc_calculator_options,
            symmetrize_fc=settings.fc_symmetry,
            is_compact_fc=settings.is_compact_fc,
            cutoff_pair_distance=settings.cutoff_pair_distance,
            log_level=log_level,
        )

        if log_level:
            if phono3py.fc3 is None:
                print("fc3 could not be obtained.")
            if phono3py.fc2 is None:
                print("fc2 could not be obtained.")
        if phono3py.fc3 is None or phono3py.fc2 is None:
            print_error()
            sys.exit(1)

        if not read_fc["fc3"]:
            write_fc3_to_hdf5(
                phono3py.fc3,
                p2s_map=phono3py.primitive.p2s_map,
                compression=settings.hdf5_compression,
            )
            if log_level:
                print('fc3 was written into "fc3.hdf5".')
        if not read_fc["fc2"]:
            write_fc2_to_hdf5(
                phono3py.fc2,
                p2s_map=phono3py.primitive.p2s_map,
                physical_unit="eV/angstrom^2",
                compression=settings.hdf5_compression,
            )
            if log_level:
                print('fc2 was written into "fc2.hdf5".')
    else:
        create_phono3py_force_constants(
            phono3py,
            settings,
            ph3py_yaml=ph3py_yaml,
            input_filename=input_filename,
            output_filename=output_filename,
            log_level=log_level,
        )
Beispiel #14
0
def init_phph_interaction(
    phono3py: Phono3py,
    settings,
    updated_settings,
    input_filename,
    output_filename,
    log_level,
):
    """Initialize ph-ph interaction and phonons on grid."""
    if log_level:
        print("Generating grid system ... ", end="", flush=True)
    phono3py.mesh_numbers = settings.mesh_numbers
    bz_grid = phono3py.grid
    if log_level:
        if bz_grid.grid_matrix is None:
            print("[ %d %d %d ]" % tuple(phono3py.mesh_numbers))
        else:
            print("")
            print("Generalized regular grid: [ %d %d %d ]" %
                  tuple(bz_grid.D_diag))
            print("Grid generation matrix:")
            print("  [ %d %d %d ]" % tuple(bz_grid.grid_matrix[0]))
            print("  [ %d %d %d ]" % tuple(bz_grid.grid_matrix[1]))
            print("  [ %d %d %d ]" % tuple(bz_grid.grid_matrix[2]))

        if settings.is_symmetrize_fc3_q:
            print("Permutation symmetry of ph-ph interaction strengths: True")

    ave_pp = settings.constant_averaged_pp_interaction
    phono3py.init_phph_interaction(
        nac_q_direction=settings.nac_q_direction,
        constant_averaged_interaction=ave_pp,
        frequency_scale_factor=updated_settings["frequency_scale_factor"],
        symmetrize_fc3q=settings.is_symmetrize_fc3_q,
        lapack_zheev_uplo=settings.lapack_zheev_uplo,
    )

    if not settings.read_phonon:
        if log_level:
            print("-" * 27 + " Phonon calculations " + "-" * 28)
            dm = phono3py.dynamical_matrix
            if dm.is_nac() and dm.nac_method == "gonze":
                dm.show_nac_message()
            print("Running harmonic phonon calculations...")
            sys.stdout.flush()
        phono3py.run_phonon_solver()

    if settings.write_phonon:
        freqs, eigvecs, grid_address = phono3py.get_phonon_data()
        ir_grid_points, ir_grid_weights, _ = get_ir_grid_points(bz_grid)
        ir_grid_points = np.array(bz_grid.grg2bzg[ir_grid_points],
                                  dtype="int_")
        filename = write_phonon_to_hdf5(
            freqs,
            eigvecs,
            grid_address,
            phono3py.mesh_numbers,
            bz_grid=bz_grid,
            ir_grid_points=ir_grid_points,
            ir_grid_weights=ir_grid_weights,
            compression=settings.hdf5_compression,
            filename=output_filename,
        )
        if filename:
            if log_level:
                print('Phonons are written into "%s".' % filename)
        else:
            print("Writing phonons failed.")
            if log_level:
                print_error()
            sys.exit(1)

    if settings.read_phonon:
        phonons = read_phonon_from_hdf5(phono3py.mesh_numbers,
                                        filename=input_filename,
                                        verbose=(log_level > 0))
        if phonons is None:
            print("Reading phonons failed.")
            if log_level:
                print_error()
            sys.exit(1)

        try:
            phono3py.set_phonon_data(*phonons)
        except RuntimeError:
            if log_level:
                print_error()
            sys.exit(1)
Beispiel #15
0
def main(**argparse_control):
    load_phono3py_yaml = argparse_control.get('load_phono3py_yaml', False)

    args, log_level = start_phono3py(**argparse_control)
    physical_units = get_default_physical_units(get_interface_mode(vars(args)))

    if load_phono3py_yaml:
        input_filename = None
        output_filename = None
    else:
        (input_filename,
         output_filename) = get_input_output_filenames_from_args(args)

    settings, confs, cell_filename = read_phono3py_settings(
        args, argparse_control, log_level)

    if args.force_sets_to_forces_fc2_mode:
        create_FORCES_FC2_from_FORCE_SETS_then_exit(log_level)
    if args.force_sets_mode:
        create_FORCE_SETS_from_FORCES_FCx_then_exit(
            settings.phonon_supercell_matrix, input_filename, log_level)
    if args.write_grid_points:
        run_mode = "write_grid_info"
    elif args.show_num_triplets:
        run_mode = "show_triplets_info"
    else:
        run_mode = None

    # -----------------------------------------------------------------------
    # ----------------- 'args' should not be used below. --------------------
    # -----------------------------------------------------------------------

    ####################################
    # Create FORCES_FC3 and FORCES_FC2 #
    ####################################
    create_FORCES_FC3_and_FORCES_FC2_then_exit(settings, input_filename,
                                               output_filename, log_level)

    ###########################################################
    # Symmetry tolerance. Distance unit depends on interface. #
    ###########################################################
    if settings.symmetry_tolerance is None:
        symprec = 1e-5
    else:
        symprec = settings.symmetry_tolerance

    cell_info = get_cell_info(settings, cell_filename, symprec, log_level)
    unitcell_filename = cell_info['optional_structure_info'][0]
    interface_mode = cell_info['interface_mode']
    # ph3py_yaml = cell_info['phonopy_yaml']

    if run_mode is None:
        run_mode = get_run_mode(settings)

    ######################################################
    # Create supercells with displacements and then exit #
    ######################################################
    if settings.create_displacements:
        phono3py = create_phono3py_supercells(cell_info,
                                              settings,
                                              symprec,
                                              output_filename=output_filename,
                                              interface_mode=interface_mode,
                                              log_level=log_level)

        finalize_phono3py(phono3py,
                          confs,
                          log_level,
                          displacements_mode=True,
                          filename="phono3py_disp.yaml")

    #######################
    # Initialize phono3py #
    #######################
    # updated_settings keys
    # ('grid_points', 'sigmas', 'temperature_points', 'temperatures',
    #  'frequency_factor_to_THz', 'num_frequency_points',
    #  'frequency_step', 'frequency_scale_factor',
    #  'cutoff_frequency')
    phono3py, updated_settings = init_phono3py(settings, cell_info,
                                               interface_mode, output_filename,
                                               symprec, log_level)

    #################################################
    # Show phono3py settings and crystal structures #
    #################################################
    if log_level:
        show_general_settings(settings, run_mode, phono3py, unitcell_filename,
                              input_filename, output_filename)

    if log_level > 1:
        show_phono3py_cells(phono3py, settings)
    else:
        print("Spacegroup: %s" % phono3py.symmetry.get_international_table())
        print("Use -v option to watch primitive cell, unit cell, "
              "and supercell structures.")

    ##################
    # Check settings #
    ##################
    run_modes_with_mesh = ("conductivity-RTA", "conductivity-LBTE",
                           "imag_self_energy", "jdos", "isotope",
                           "write_grid_info", "show_triplets_info")
    run_modes_with_gp = ("imag_self_energy", "jdos", "isotope")
    if phono3py.mesh_numbers is None and run_mode in run_modes_with_mesh:
        print("")
        print("Mesh numbers have to be specified.")
        print("")
        if log_level:
            print_error()
        sys.exit(1)

    if (run_mode in run_modes_with_gp
            and updated_settings['grid_points'] is None):
        print("")
        print("Grid point(s) has to be specified.")
        print("")
        if log_level:
            print_error()
        sys.exit(1)

    #########################################################
    # Write ir-grid points and grid addresses and then exit #
    #########################################################
    if run_mode == "write_grid_info":
        write_grid_points(phono3py.primitive,
                          phono3py.mesh_numbers,
                          mesh_divs=settings.mesh_divisors,
                          band_indices=settings.band_indices,
                          sigmas=updated_settings['sigmas'],
                          temperatures=updated_settings['temperatures'],
                          coarse_mesh_shifts=settings.coarse_mesh_shifts,
                          is_kappa_star=settings.is_kappa_star,
                          is_lbte=(settings.write_collision
                                   or settings.is_lbte),
                          compression=settings.hdf5_compression,
                          symprec=symprec)

        if log_level:
            print_end()
        sys.exit(0)

    ################################################################
    # Show reduced number of triplets at grid points and then exit #
    ################################################################
    if run_mode == "show_triplets_info":
        show_num_triplets(phono3py.primitive,
                          phono3py.mesh_numbers,
                          mesh_divs=settings.mesh_divisors,
                          band_indices=settings.band_indices,
                          grid_points=updated_settings['grid_points'],
                          coarse_mesh_shifts=settings.coarse_mesh_shifts,
                          is_kappa_star=settings.is_kappa_star,
                          symprec=symprec)

        if log_level:
            print_end()
        sys.exit(0)

    ##################################
    # Non-analytical term correction #
    ##################################
    store_nac_params(phono3py,
                     settings,
                     cell_info['phonopy_yaml'],
                     unitcell_filename,
                     log_level,
                     nac_factor=Hartree * Bohr,
                     load_phonopy_yaml=load_phono3py_yaml)

    ###################
    # Force constants #
    ###################
    store_force_constants(phono3py, settings, cell_info['phonopy_yaml'],
                          physical_units, input_filename, output_filename,
                          load_phono3py_yaml, log_level)

    ############################################
    # Phonon Gruneisen parameter and then exit #
    ############################################
    if settings.is_gruneisen:
        run_gruneisen_then_exit(phono3py, settings, output_filename, log_level)

    #################
    # Show settings #
    #################
    if log_level and run_mode is not None:
        show_phono3py_settings(phono3py, settings, updated_settings, log_level)

    ###########################
    # Joint DOS and then exit #
    ###########################
    if run_mode == "jdos":
        run_jdos_then_exit(phono3py, settings, updated_settings,
                           output_filename, log_level)

    ################################################
    # Mass variances for phonon-isotope scattering #
    ################################################
    if settings.is_isotope and settings.mass_variances is None:
        from phonopy.structure.atoms import isotope_data
        symbols = phono3py.phonon_primitive.symbols
        in_database = True
        for s in set(symbols):
            if s not in isotope_data:
                print("%s is not in the list of isotope databese" % s)
                print("(not implemented).")
                print("Use --mass_variances option.")
                in_database = False
        if not in_database:
            if log_level:
                print_end()
            sys.exit(0)

    #########################################
    # Phonon-isotope lifetime and then exit #
    #########################################
    if run_mode == "isotope":
        run_isotope_then_exit(phono3py, settings, updated_settings, log_level)

    ########################################
    # Initialize phonon-phonon interaction #
    ########################################
    if run_mode is not None:
        init_phph_interaction(phono3py, settings, updated_settings,
                              input_filename, output_filename, log_level)

    #######################################################
    # Run imaginary part of self energy of bubble diagram #
    #######################################################
    if run_mode == "imag_self_energy":
        phono3py.run_imag_self_energy(
            updated_settings['grid_points'],
            updated_settings['temperature_points'],
            frequency_step=updated_settings['frequency_step'],
            num_frequency_points=updated_settings['num_frequency_points'],
            scattering_event_class=settings.scattering_event_class,
            write_txt=True,
            write_gamma_detail=settings.write_gamma_detail,
            output_filename=output_filename)

    #####################################################
    # Run frequency shift calculation of bubble diagram #
    #####################################################
    elif run_mode == "real_self_energy":
        phono3py.run_real_self_energy(
            updated_settings['grid_points'],
            updated_settings['temperature_points'],
            frequency_step=updated_settings['frequency_step'],
            num_frequency_points=updated_settings['num_frequency_points'],
            write_txt=True,
            output_filename=output_filename)

    #######################################################
    # Run spectral function calculation of bubble diagram #
    #######################################################
    elif run_mode == "spectral_function":
        phono3py.run_spectral_function(
            updated_settings['grid_points'],
            updated_settings['temperature_points'],
            frequency_step=updated_settings['frequency_step'],
            num_frequency_points=updated_settings['num_frequency_points'],
            num_points_in_batch=updated_settings['num_points_in_batch'],
            write_txt=True,
            write_hdf5=True,
            output_filename=output_filename)

    ####################################
    # Run lattice thermal conductivity #
    ####################################
    elif run_mode == "conductivity-RTA" or run_mode == "conductivity-LBTE":
        phono3py.run_thermal_conductivity(
            is_LBTE=settings.is_lbte,
            temperatures=updated_settings['temperatures'],
            is_isotope=settings.is_isotope,
            mass_variances=settings.mass_variances,
            grid_points=updated_settings['grid_points'],
            boundary_mfp=settings.boundary_mfp,
            solve_collective_phonon=settings.solve_collective_phonon,
            use_ave_pp=settings.use_ave_pp,
            gamma_unit_conversion=settings.gamma_conversion_factor,
            mesh_divisors=settings.mesh_divisors,
            coarse_mesh_shifts=settings.coarse_mesh_shifts,
            is_reducible_collision_matrix=settings.
            is_reducible_collision_matrix,
            is_kappa_star=settings.is_kappa_star,
            gv_delta_q=settings.group_velocity_delta_q,
            is_full_pp=settings.is_full_pp,
            pinv_cutoff=settings.pinv_cutoff,
            pinv_solver=settings.pinv_solver,
            write_gamma=settings.write_gamma,
            read_gamma=settings.read_gamma,
            write_kappa=True,
            is_N_U=settings.is_N_U,
            write_gamma_detail=settings.write_gamma_detail,
            write_collision=settings.write_collision,
            read_collision=settings.read_collision,
            write_pp=settings.write_pp,
            read_pp=settings.read_pp,
            write_LBTE_solution=settings.write_LBTE_solution,
            compression=settings.hdf5_compression,
            input_filename=input_filename,
            output_filename=output_filename)
    else:
        if log_level:
            print("-" * 11 +
                  " None of ph-ph interaction calculation was performed. " +
                  "-" * 11)

    finalize_phono3py(phono3py, confs, log_level)
Beispiel #16
0
def create_FORCES_FC3_and_FORCES_FC2_then_exit(settings, input_filename,
                                               log_level):
    """Create FORCES_FC3 and FORCES_FC2 from files."""
    interface_mode = settings.calculator
    ph3py_yaml = None

    #####################
    # Create FORCES_FC3 #
    #####################
    if settings.create_forces_fc3 or settings.create_forces_fc3_file:
        if input_filename is None:
            disp_fc3_filename = "disp_fc3.yaml"
        else:
            disp_fc3_filename = "disp_fc3." + input_filename + ".yaml"
        disp_filenames = files_exist(["phono3py_disp.yaml", disp_fc3_filename],
                                     log_level,
                                     is_any=True)
        disp_filename = disp_filenames[0]
        if "phono3py_disp.yaml" in disp_filename:
            ph3py_yaml = Phono3pyYaml()
            ph3py_yaml.read(disp_filename)
            if ph3py_yaml.calculator is not None:
                interface_mode = ph3py_yaml.calculator  # overwrite
            disp_dataset = ph3py_yaml.dataset
        else:
            file_exists(disp_filename, log_level)
            disp_dataset = parse_disp_fc3_yaml(filename=disp_filename)

        if log_level:
            print("")
            print('Displacement dataset was read from "%s".' % disp_filename)

        num_atoms = disp_dataset["natom"]
        num_disps = len(disp_dataset["first_atoms"])
        for d1 in disp_dataset["first_atoms"]:
            for d2 in d1["second_atoms"]:
                if "included" not in d2 or d2["included"]:
                    num_disps += 1

        if settings.create_forces_fc3_file:
            file_exists(settings.create_forces_fc3_file, log_level)
            force_filenames = [
                x.strip() for x in open(settings.create_forces_fc3_file)
            ]
        else:
            force_filenames = settings.create_forces_fc3

        for filename in force_filenames:
            file_exists(filename, log_level)

        if log_level > 0:
            print("Number of displacements: %d" % num_disps)
            print("Number of supercell files: %d" % len(force_filenames))

        if not check_number_of_force_files(num_disps, force_filenames,
                                           disp_filename):
            force_sets = []
        else:
            force_sets = get_force_sets(
                interface_mode,
                num_atoms,
                force_filenames,
                verbose=(log_level > 0),
            )

        if settings.subtract_forces:
            force_filename = settings.subtract_forces
            file_exists(force_filename, log_level)
            force_set_zero = get_force_sets(
                interface_mode,
                num_atoms,
                [
                    force_filename,
                ],
                verbose=(log_level > 0),
            )[0]
            for fs in force_sets:
                fs -= force_set_zero

            if log_level > 0:
                print("Forces in '%s' were subtracted from supercell forces." %
                      force_filename)

        if force_sets:
            write_FORCES_FC3(disp_dataset,
                             forces_fc3=force_sets,
                             filename="FORCES_FC3")
            if log_level:
                print("")
                print("%s has been created." % "FORCES_FC3")
                print_end()
            sys.exit(0)
        else:
            if log_level:
                print("")
                print("%s could not be created." % "FORCES_FC3")
                print_error()
            sys.exit(1)

    #####################
    # Create FORCES_FC2 #
    #####################
    if settings.create_forces_fc2:
        if input_filename is None:
            disp_fc2_filename = "disp_fc2.yaml"
        else:
            disp_fc2_filename = "disp_fc2." + input_filename + ".yaml"

        disp_filenames = files_exist(["phono3py_disp.yaml", disp_fc2_filename],
                                     log_level,
                                     is_any=True)
        if "phono3py_disp.yaml" in disp_filenames[0]:
            # ph3py_yaml is not None, phono3py_disp.yaml is already read.
            if ph3py_yaml is None:
                disp_filename = disp_filenames[0]
                ph3py_yaml = Phono3pyYaml()
                ph3py_yaml.read(disp_filename)
                if ph3py_yaml.calculator is not None:
                    interface_mode = ph3py_yaml.calculator  # overwrite
            disp_dataset = ph3py_yaml.phonon_dataset
        else:
            disp_filename = disp_filenames[0]
            file_exists(disp_filename, log_level)
            disp_dataset = parse_disp_fc2_yaml(filename=disp_filename)

        if log_level:
            print('Displacement dataset was read from "%s".' % disp_filename)
        num_atoms = disp_dataset["natom"]
        num_disps = len(disp_dataset["first_atoms"])
        force_filenames = settings.create_forces_fc2
        for filename in force_filenames:
            file_exists(filename, log_level)

        if log_level > 0:
            print("Number of displacements: %d" % num_disps)
            print("Number of supercell files: %d" % len(force_filenames))
        force_sets = get_force_sets(
            interface_mode,
            num_atoms,
            force_filenames,
            verbose=(log_level > 0),
        )

        if settings.subtract_forces:
            force_filename = settings.subtract_forces
            file_exists(force_filename, log_level)
            force_set_zero = get_force_sets(
                interface_mode,
                num_atoms,
                [
                    force_filename,
                ],
                verbose=(log_level > 0),
            )[0]
            for fs in force_sets:
                fs -= force_set_zero

            if log_level > 0:
                print("Forces in '%s' were subtracted from supercell forces." %
                      force_filename)

        if force_sets:
            write_FORCES_FC2(disp_dataset,
                             forces_fc2=force_sets,
                             filename="FORCES_FC2")
            if log_level:
                print("")
                print("%s has been created." % "FORCES_FC2")
                print_end()
            sys.exit(0)
        else:
            if log_level:
                print("")
                print("%s could not be created." % "FORCES_FC2")
                print_error()
            sys.exit(1)
Beispiel #17
0
def create_FORCES_FC3_and_FORCES_FC2_then_exit(settings, input_filename,
                                               output_filename, log_level):
    interface_mode = settings.calculator

    #####################
    # Create FORCES_FC3 #
    #####################
    if settings.create_forces_fc3 or settings.create_forces_fc3_file:
        if input_filename is None:
            disp_fc3_filename = 'disp_fc3.yaml'
        else:
            disp_fc3_filename = 'disp_fc3.' + input_filename + '.yaml'
        ph3py_yaml = None

        disp_filenames = files_exist(['phono3py_disp.yaml', disp_fc3_filename],
                                     log_level,
                                     is_any=True)

        if disp_filenames[0] == 'phono3py_disp.yaml':
            try:
                ph3py_yaml = Phono3pyYaml()
                ph3py_yaml.read('phono3py_disp.yaml')
                if ph3py_yaml.calculator is not None:
                    interface_mode = ph3py_yaml.calculator  # overwrite
                disp_filename = 'phono3py_disp.yaml'
            except KeyError:
                file_exists('disp_fc3.yaml', log_level)
                if log_level > 0:
                    print("\"phono3py_disp.yaml\" was found but wasn't used.")
                disp_filename = disp_fc3_filename
        else:
            disp_filename = disp_filenames[0]

        if ph3py_yaml is None:
            file_exists(disp_filename, log_level)
            disp_dataset = parse_disp_fc3_yaml(filename=disp_filename)
        else:
            disp_dataset = ph3py_yaml.dataset

        if log_level:
            print('')
            print("Displacement dataset was read from \"%s\"." % disp_filename)

        num_atoms = disp_dataset['natom']
        num_disps = len(disp_dataset['first_atoms'])
        for d1 in disp_dataset['first_atoms']:
            for d2 in d1['second_atoms']:
                if 'included' not in d2 or d2['included']:
                    num_disps += 1

        if settings.create_forces_fc3_file:
            file_exists(settings.create_forces_fc3_file, log_level)
            force_filenames = [
                x.strip() for x in open(settings.create_forces_fc3_file)
            ]
        else:
            force_filenames = settings.create_forces_fc3

        for filename in force_filenames:
            file_exists(filename, log_level)

        if log_level > 0:
            print("Number of displacements: %d" % num_disps)
            print("Number of supercell files: %d" % len(force_filenames))

        if not check_number_of_force_files(num_disps, force_filenames,
                                           disp_filename):
            force_sets = []
        else:
            force_sets = get_force_sets(interface_mode,
                                        num_atoms,
                                        num_disps,
                                        force_filenames,
                                        disp_filename=disp_filename,
                                        verbose=(log_level > 0))

        if settings.subtract_forces:
            force_filename = settings.subtract_forces
            file_exists(force_filename, log_level)
            force_set_zero = get_force_sets(interface_mode,
                                            num_atoms,
                                            1, [
                                                force_filename,
                                            ],
                                            verbose=(log_level > 0))[0]
            for fs in force_sets:
                fs -= force_set_zero

            if log_level > 0:
                print(
                    "Forces in \'%s\' were subtracted from supercell forces." %
                    force_filename)

        if force_sets:
            write_FORCES_FC3(disp_dataset, force_sets, filename="FORCES_FC3")
            if log_level:
                print("")
                print("%s has been created." % "FORCES_FC3")
                print_end()
            sys.exit(0)
        else:
            if log_level:
                print("")
                print("%s could not be created." % "FORCES_FC3")
                print_error()
            sys.exit(1)

    #####################
    # Create FORCES_FC2 #
    #####################
    if settings.create_forces_fc2:
        if input_filename is None:
            disp_filename = 'disp_fc2.yaml'
        else:
            disp_filename = 'disp_fc2.' + input_filename + '.yaml'
        file_exists(disp_filename, log_level)
        disp_dataset = parse_disp_fc2_yaml(filename=disp_filename)
        if log_level:
            print("Displacement dataset was read from \"%s\"." % disp_filename)
        num_atoms = disp_dataset['natom']
        num_disps = len(disp_dataset['first_atoms'])
        force_filenames = settings.create_forces_fc2
        for filename in force_filenames:
            file_exists(filename, log_level)

        if log_level > 0:
            print("Number of displacements: %d" % num_disps)
            print("Number of supercell files: %d" % len(force_filenames))
        force_sets = get_force_sets(interface_mode,
                                    num_atoms,
                                    num_disps,
                                    force_filenames,
                                    disp_filename,
                                    verbose=(log_level > 0))

        if settings.subtract_forces:
            force_filename = settings.subtract_forces
            file_exists(force_filename, log_level)
            force_set_zero = get_force_sets(interface_mode,
                                            num_atoms,
                                            1, [
                                                force_filename,
                                            ],
                                            verbose=(log_level > 0))[0]
            for fs in force_sets:
                fs -= force_set_zero

            if log_level > 0:
                print(
                    "Forces in \'%s\' were subtracted from supercell forces." %
                    force_filename)

        if force_sets:
            write_FORCES_FC2(disp_dataset,
                             forces_fc2=force_sets,
                             filename="FORCES_FC2")
            if log_level:
                print("")
                print("%s has been created." % "FORCES_FC2")
                print_end()
            sys.exit(0)
        else:
            if log_level:
                print("")
                print("%s could not be created." % "FORCES_FC2")
                print_error()
            sys.exit(1)