Skip to content

Lammps

Tools for reading and writing LAMMPS data files and dumps.

average_log(log_files, freq=1)

Average the log data from multiple files.

Parameters:

Name Type Description Default
log_files list[str]

List of log file names.

required
freq int

Frequency of the data to be read.

1

Returns:

Type Description
tuple[DataFrame, DataFrame]

Data frames containing mean and standard deviation values.

Source code in m2dtools/lmp/tools_lammps.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def average_log(log_files, freq=1):
    """Average the log data from multiple files.

    Parameters
    ----------
    log_files : list[str]
        List of log file names.
    freq : int, default 1
        Frequency of the data to be read.

    Returns
    -------
    tuple[pandas.DataFrame, pandas.DataFrame]
        Data frames containing mean and standard deviation values.
    """
    dfs = []
    for i, log_file in enumerate(log_files):
        log = read_log_lammps(log_file, freq=freq)[-1]
        dfs.append(log)

    # Stack into a 3D array (frames × rows × columns)
    stacked = pd.concat(dfs, keys=range(len(dfs)))  # adds outer index (frame index)

    # Compute mean and std over the first level (i.e., over frames)
    df_mean = stacked.groupby(level=1).mean()
    df_std = stacked.groupby(level=1).std()
    return df_mean, df_std

convert_lmp(file_lmp, file_key, mapping_dict)

Convert LAMMPS data file using the provided mapping dictionary.

Parameters:

Name Type Description Default
file_lmp str

Path to the original LAMMPS data file.

required
file_key str

Path to the key file for atom types.

required
mapping_dict dict

Dictionary containing mapping information for bonds, angles, dihedrals, and masses.

required

Returns:

Name Type Description
lmp object

Converted LAMMPS object.

Source code in m2dtools/lmp/tools_lammps.py
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def convert_lmp(file_lmp, file_key, mapping_dict):
    """
    Convert LAMMPS data file using the provided mapping dictionary.

    Parameters
    ----------
    file_lmp : str
        Path to the original LAMMPS data file.
    file_key : str
        Path to the key file for atom types.
    mapping_dict : dict
        Dictionary containing mapping information for bonds, angles, dihedrals, and masses.

    Returns
    -------
    lmp: object
        Converted LAMMPS object.
    """

    lmp_react1 = read_lammps_full(file_lmp)
    tmp = pd.read_table(file_key,
                        header=None, sep='\s+', skiprows=31, nrows=lmp_react1.natoms)

    mapping = np.zeros([lmp_react1.natoms, 2])
    mapping[:, 0] = np.arange(lmp_react1.natoms)+1
    # modify the types given by Ligpargen

    for i, type in enumerate(mapping_dict['unique_type']):
        mapping[tmp.iloc[:, 3] == type, 1] = i+1

    # natom_types_new = len(mapping_dict['mass_new'])
    atom_info_new = lmp_react1.atom_info.copy()
    atom_info_new[:, 2] = mapping[:, 1]

    ### bonds ####
    bond_info_new = lmp_react1.bond_info.copy()
    for i in range(lmp_react1.natoms):
        bond_info_new[lmp_react1.bond_info[:, 2] == i+1, 2] = mapping[i, 1]
        bond_info_new[lmp_react1.bond_info[:, 3] == i+1, 3] = mapping[i, 1]

    for i in range(len(bond_info_new)):
        if bond_info_new[i, 2] > bond_info_new[i, 3]:
            tmp = bond_info_new[i, 3]
            bond_info_new[i, 3] = bond_info_new[i, 2]
            bond_info_new[i, 2] = tmp

    for i in range(len(bond_info_new)):
        bond_info_new[i, 1] = 0
        for j in range(len(mapping_dict['mapping_bonds'])):
            if ((bond_info_new[i, 2] == mapping_dict['mapping_bonds'][j, 0]) and (bond_info_new[i, 3] == mapping_dict['mapping_bonds'][j, 1])):
                bond_info_new[i, 2] = lmp_react1.bond_info[i, 2]
                bond_info_new[i, 3] = lmp_react1.bond_info[i, 3]
                bond_info_new[i, 1] = j+1
    print(np.sum(bond_info_new[:, 1] == 0))

    # nangle_types_new = len(mapping_dict['angle_coeff_new'])
    ### angles ####
    angle_info_new = lmp_react1.angle_info.copy()
    for i in range(lmp_react1.natoms):
        angle_info_new[lmp_react1.angle_info[:, 2] == i+1, 2] = mapping[i, 1]
        angle_info_new[lmp_react1.angle_info[:, 3] == i+1, 3] = mapping[i, 1]
        angle_info_new[lmp_react1.angle_info[:, 4] == i+1, 4] = mapping[i, 1]

    for i in range(len(angle_info_new)):
        if angle_info_new[i, 2] > angle_info_new[i, 4]:
            tmp = angle_info_new[i, 4]
            angle_info_new[i, 4] = angle_info_new[i, 2]
            angle_info_new[i, 2] = tmp

    for i in range(len(angle_info_new)):
        angle_info_new[i, 1] = 0
        match = 0
        for j in range(len(mapping_dict['mapping_angles'])):
            if (angle_info_new[i, 3] == mapping_dict['mapping_angles'][j, 1]) and ((angle_info_new[i, 2] == mapping_dict['mapping_angles'][j, 0]) and (angle_info_new[i, 4] == mapping_dict['mapping_angles'][j, 2])):
                angle_info_new[i, 2] = lmp_react1.angle_info[i, 2]
                angle_info_new[i, 3] = lmp_react1.angle_info[i, 3]
                angle_info_new[i, 4] = lmp_react1.angle_info[i, 4]
                angle_info_new[i, 1] = j+1
                match += 1
        if match == 0:
            print(angle_info_new[i])
    print(np.sum(angle_info_new[:, 1] == 0))
    ### dihedrals ####
    dihedral_info_new = lmp_react1.dihedral_info.copy()
    for i in range(lmp_react1.natoms):
        dihedral_info_new[lmp_react1.dihedral_info[:, 2] == i+1, 2] = mapping[i, 1]
        dihedral_info_new[lmp_react1.dihedral_info[:, 3] == i+1, 3] = mapping[i, 1]
        dihedral_info_new[lmp_react1.dihedral_info[:, 4] == i+1, 4] = mapping[i, 1]
        dihedral_info_new[lmp_react1.dihedral_info[:, 5] == i+1, 5] = mapping[i, 1]

    for i in range(len(dihedral_info_new)):
        dihedral_info_new[i, 1] = 0
        match = 0
        for j in range(len(mapping_dict['mapping_dihedrals'])):
            if ((dihedral_info_new[i, 2] == mapping_dict['mapping_dihedrals'][j, 0]) and (dihedral_info_new[i, 3] == mapping_dict['mapping_dihedrals'][j, 1]) and (dihedral_info_new[i, 4] == mapping_dict['mapping_dihedrals'][j, 2]) and (dihedral_info_new[i, 5] == mapping_dict['mapping_dihedrals'][j, 3])) or ((dihedral_info_new[i, 2] == mapping_dict['mapping_dihedrals'][j, 3]) and (dihedral_info_new[i, 3] == mapping_dict['mapping_dihedrals'][j, 2]) and (dihedral_info_new[i, 4] == mapping_dict['mapping_dihedrals'][j, 1]) and (dihedral_info_new[i, 5] == mapping_dict['mapping_dihedrals'][j, 0])):
                dihedral_info_new[i, 2] = lmp_react1.dihedral_info[i, 2]
                dihedral_info_new[i, 3] = lmp_react1.dihedral_info[i, 3]
                dihedral_info_new[i, 4] = lmp_react1.dihedral_info[i, 4]
                dihedral_info_new[i, 5] = lmp_react1.dihedral_info[i, 5]
                dihedral_info_new[i, 1] = j+1
                match += 1
        if match == 0:
            dihedral_info_new[i, 2] = lmp_react1.dihedral_info[i, 2]
            dihedral_info_new[i, 3] = lmp_react1.dihedral_info[i, 3]
            dihedral_info_new[i, 4] = lmp_react1.dihedral_info[i, 4]
            dihedral_info_new[i, 5] = lmp_react1.dihedral_info[i, 5]
            dihedral_info_new[i, 1] = mapping_dict['dihedral_coeff_new'][np.sum(
                mapping_dict['dihedral_coeff_new'][:, 1:], axis=1) == 0, 0][0]
            print(dihedral_info_new[i])

    dihedral_info_new = np.delete(dihedral_info_new, np.squeeze(
        np.argwhere(dihedral_info_new[:, 1] == 0)), 0)
    ndihedrals = len(dihedral_info_new)
    dihedral_info_new[:, 0] = np.arange(1, ndihedrals+1)

    print(np.sum(dihedral_info_new[:, 1] == 0))

    nimproper_types_new = len(mapping_dict['improper_coeff_new'])
    ### impropers ####
    impropers_info_new = lmp_react1.improper_info.copy()
    for i in range(lmp_react1.natoms):
        impropers_info_new[lmp_react1.improper_info[:, 2] == i+1, 2] = mapping[i, 1]
        impropers_info_new[lmp_react1.improper_info[:, 3] == i+1, 3] = mapping[i, 1]
        impropers_info_new[lmp_react1.improper_info[:, 4] == i+1, 4] = mapping[i, 1]
        impropers_info_new[lmp_react1.improper_info[:, 5] == i+1, 5] = mapping[i, 1]

    for i in range(len(impropers_info_new)):
        impropers_info_new[i, 1] = 0
        match = 0
        for j in range(len(mapping_dict['mapping_impropers'])):
            if (impropers_info_new[i, 2] == mapping_dict['mapping_impropers'][j, 0]) and np.all(np.sort(impropers_info_new[i, 3:]) == np.sort(mapping_dict['mapping_impropers'][j, 1:])):
                impropers_info_new[i, 2] = lmp_react1.improper_info[i, 2]
                impropers_info_new[i, 3] = lmp_react1.improper_info[i, 3]
                impropers_info_new[i, 4] = lmp_react1.improper_info[i, 4]
                impropers_info_new[i, 5] = lmp_react1.improper_info[i, 5]
                impropers_info_new[i, 1] = j+1
                match += 1
        if match == 0:
            impropers_info_new[i, 2] = lmp_react1.improper_info[i, 2]
            impropers_info_new[i, 3] = lmp_react1.improper_info[i, 3]
            impropers_info_new[i, 4] = lmp_react1.improper_info[i, 4]
            impropers_info_new[i, 5] = lmp_react1.improper_info[i, 5]
            impropers_info_new[i, 1] = mapping_dict['improper_coeff_new'][mapping_dict['improper_coeff_new'][:, 1] == 0, 0][0]
            print(impropers_info_new[i])

    print(np.sum(impropers_info_new[:, 1] == 0))

    lmp_react_new = lammps(natoms=lmp_react1.natoms,
                           natom_types=len(mapping_dict['mass_new']),
                           nbonds=lmp_react1.nbonds,
                           nbond_types=len(mapping_dict['bond_coeff_new']),
                           nangles=lmp_react1.nangles,
                           nangle_types=len(mapping_dict['angle_coeff_new']),
                           ndihedrals=lmp_react1.ndihedrals,
                           ndihedral_types=len(mapping_dict['dihedral_coeff_new']),
                           nimpropers=lmp_react1.nimpropers,
                           nimproper_types=len(mapping_dict['improper_coeff_new']),
                           mass=mapping_dict['mass_new'],
                           x=lmp_react1.x,
                           y=lmp_react1.y,
                           z=lmp_react1.z,
                           pair_coeff=mapping_dict['pair_coeff_new'],
                           bond_coeff=mapping_dict['bond_coeff_new'],
                           angle_coeff=mapping_dict['angle_coeff_new'],
                           dihedral_coeff=mapping_dict['dihedral_coeff_new'],
                           improper_coeff=mapping_dict['improper_coeff_new'],
                           atom_info=atom_info_new,
                           bond_info=bond_info_new,
                           angle_info=angle_info_new,
                           dihedral_info=dihedral_info_new,
                           improper_info=impropers_info_new)
    return lmp_react_new

distance_pbc(coord1, coord2, box)

Compute pairwise distances under periodic boundary conditions.

Parameters:

Name Type Description Default
coord1 ndarray

Array of shape (N, 3) with coordinates for N atoms.

required
coord2 ndarray

Array of shape (M, 3) with coordinates for M atoms.

required
box ndarray

(3, 3) matrix whose rows are the box vectors.

required

Returns:

Type Description
ndarray

Distance matrix of shape (N, M) between coord1 and coord2.

Source code in m2dtools/lmp/tools_lammps.py
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
def distance_pbc(coord1, coord2, box):
    """Compute pairwise distances under periodic boundary conditions.

    Parameters
    ----------
    coord1 : numpy.ndarray
        Array of shape ``(N, 3)`` with coordinates for ``N`` atoms.
    coord2 : numpy.ndarray
        Array of shape ``(M, 3)`` with coordinates for ``M`` atoms.
    box : numpy.ndarray
        ``(3, 3)`` matrix whose rows are the box vectors.

    Returns
    -------
    numpy.ndarray
        Distance matrix of shape ``(N, M)`` between ``coord1`` and ``coord2``.
    """
    # Expand coord1 and coord2 to (N, 1, 3) and (1, M, 3) respectively to broadcast subtraction
    delta = coord1[:, np.newaxis, :] - coord2[np.newaxis, :, :]

    # Compute box inversions and apply periodic boundary conditions
    delta -= np.round(delta @ np.linalg.inv(box)) @ box

    # Compute the Euclidean distance
    dist_matrix = np.linalg.norm(delta, axis=-1)

    return dist_matrix

dump2str(save_file, dump_file, sample_file, idx)

Convert selected dump frames to a LAMMPS data structure file.

Parameters:

Name Type Description Default
save_file str

Destination for the generated structure file.

required
dump_file str

Path to the dump custom trajectory.

required
sample_file str

Reference LAMMPS data file used for topology and masses.

required
idx int or list[int]

Frame index or indices to convert.

required

Returns:

Type Description
None

The converted structure is written to save_file.

Source code in m2dtools/lmp/tools_lammps.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
def dump2str(save_file: str,
             dump_file: str,
             sample_file: str,
             idx: int or list):
    """Convert selected dump frames to a LAMMPS data structure file.

    Parameters
    ----------
    save_file : str
        Destination for the generated structure file.
    dump_file : str
        Path to the ``dump custom`` trajectory.
    sample_file : str
        Reference LAMMPS data file used for topology and masses.
    idx : int or list[int]
        Frame index or indices to convert.

    Returns
    -------
    None
        The converted structure is written to ``save_file``.
    """
    lmp = read_lammps_full(sample_file)
    lmp.atom_info = lmp.atom_info[np.argsort(lmp.atom_info[:, 0])]
    frame_list, t_list, L_list = read_lammps_dump_custom(dump_file)
    lmp_new = copy.copy(lmp)

    if type(idx) == int:
        idx = [idx]
    for id in idx:
        lmp_new.x = L_list[id][0]
        lmp_new.y = L_list[id][1]
        lmp_new.z = L_list[id][2]

        coors = frame_list[id].loc[:, ['x', 'y', 'z']].values
        lmp_new.atom_info[:, 4:7] = coors
        write_lammps_full(save_file + f'{id}', lmp_new)

read_lammps_dump_custom(dump_file, interval=1)

Read a LAMMPS dump custom trajectory.

Parameters:

Name Type Description Default
dump_file str

Path to the dump file produced by LAMMPS.

required
interval int

Step interval between stored frames.

1

Returns:

Type Description
tuple[list[ndarray], list[int], list[ndarray]]

Parsed coordinate frames, timesteps and box bounds for each frame.

Source code in m2dtools/lmp/tools_lammps.py
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
def read_lammps_dump_custom(dump_file, interval=1):
    """Read a LAMMPS ``dump custom`` trajectory.

    Parameters
    ----------
    dump_file : str
        Path to the dump file produced by LAMMPS.
    interval : int, default 1
        Step interval between stored frames.

    Returns
    -------
    tuple[list[numpy.ndarray], list[int], list[numpy.ndarray]]
        Parsed coordinate frames, timesteps and box bounds for each frame.
    """
    t_list = []
    frame = []
    L_list = []
    frame_count = 0

    with open(dump_file, 'r') as f:
        for line in f:
            if line.startswith('ITEM: TIMESTEP'):
                frame_count += 1
                timestep = int(next(f).split()[0])

                # Only process and store the frame if frame_count is a multiple of the interval
                if frame_count % interval == 0:
                    t_list.append(timestep)
                    store_frame = True
                else:
                    store_frame = False

            if line.startswith('ITEM: NUMBER OF ATOMS') and store_frame:
                natoms = int(next(f).split()[0])

            if line.startswith('ITEM: BOX') and store_frame:
                lx = [float(x) for x in next(f).split()[:2]]
                ly = [float(x) for x in next(f).split()[:2]]
                lz = [float(x) for x in next(f).split()[:2]]
                L_list.append([lx, ly, lz])

            if line.startswith('ITEM: ATOMS') and store_frame:
                columns = line.split()[2:]
                data = []
                for i in range(natoms):
                    line_data = []
                    raw_fields = [x for x in next(f).split() if x.strip()]
                    for x in raw_fields[:len(columns)]:
                        try:
                            line_data.append(float(x))
                        except ValueError:
                            line_data.append(str(x))
                    data.append(line_data)
                    # data.append([float(x) for x in next(f).split()])
                df = pd.DataFrame(data, columns=columns)
                df_sorted = df.sort_values(by=['id'])
                frame.append(df_sorted)

    return frame, t_list, L_list

read_log_lammps(logfile, freq=1)

Read a LAMMPS log file into per-block data frames.

Parameters:

Name Type Description Default
logfile str

Path to log.lammps.

required
freq int

Sampling frequency for the returned data.

1

Returns:

Type Description
list[DataFrame]

Thermodynamic blocks parsed from the log file.

Source code in m2dtools/lmp/tools_lammps.py
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
def read_log_lammps(logfile, freq=1):
    """Read a LAMMPS log file into per-block data frames.

    Parameters
    ----------
    logfile : str
        Path to ``log.lammps``.
    freq : int, default 1
        Sampling frequency for the returned data.

    Returns
    -------
    list[pandas.DataFrame]
        Thermodynamic blocks parsed from the log file.
    """
    f = open(logfile, 'r')
    L = f.readlines()
    f.close()
    l1_list, l2_list = [], []
    for i in range(len(L)):
        if ('Step' in L[i]) and ('Temp' in L[i]):
            l1_list.append(i)
        if 'Loop time' in L[i]:
            l2_list.append(i)
    if len(l2_list) == 0:
        l2_list.append(len(L)-1)
    # print(l1_list, l2_list)
    data_list = []
    for i, l1 in enumerate(l1_list):
        l2 = l2_list[i]
        data = np.array(L[l1+1].split())
        for i in range(l1+1, l2, freq):
            data = np.vstack((data, L[i].split()))
        data = pd.DataFrame(data, dtype='float64', columns=L[l1].split())
        data_list.append(data)
    return data_list

read_table_pot(file_name, key_words)

Read a LAMMPS table potential block.

Parameters:

Name Type Description Default
file_name str

Path to the table potential file.

required
key_words str

Keyword marking the start of the desired table section.

required

Returns:

Type Description
tuple[list[float], list[float], list[float]]

Radial positions, potential energies and forces from the table.

Source code in m2dtools/lmp/tools_lammps.py
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
def read_table_pot(file_name, key_words):
    """Read a LAMMPS table potential block.

    Parameters
    ----------
    file_name : str
        Path to the table potential file.
    key_words : str
        Keyword marking the start of the desired table section.

    Returns
    -------
    tuple[list[float], list[float], list[float]]
        Radial positions, potential energies and forces from the table.
    """
    r = []
    e_pot = []
    f_pot = []
    with open(file_name, 'r') as f:
        while True:
            line = f.readline()
            if key_words in line:
                meta_info = f.readline()
                f.readline()
                for i in range(int(meta_info.split()[1])):
                    line = f.readline()
                    data = line.split()
                    r.append(float(data[1]))
                    e_pot.append(float(data[2]))
                    f_pot.append(float(data[3]))
                break
    r = np.array(r)
    e_pot = np.array(e_pot)
    f_pot = np.array(f_pot)
    return r, e_pot, f_pot

wrap_mol(save_file, input_file)

Wrap molecules into the primary box while preserving connectivity.

Parameters:

Name Type Description Default
save_file str

Base path for the wrapped output file.

required
input_file str

LAMMPS data file containing molecule ids and coordinates.

required

Returns:

Type Description
None

The wrapped structure is written with the save_file prefix.

Source code in m2dtools/lmp/tools_lammps.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
def wrap_mol(save_file: str,
             input_file: str):
    """Wrap molecules into the primary box while preserving connectivity.

    Parameters
    ----------
    save_file : str
        Base path for the wrapped output file.
    input_file : str
        LAMMPS data file containing molecule ids and coordinates.

    Returns
    -------
    None
        The wrapped structure is written with the ``save_file`` prefix.
    """

    lmp = read_lammps_full(input_file)
    lmp.atom_info = lmp.atom_info[np.argsort(lmp.atom_info[:, 0])]
    lmp_new = copy.copy(lmp)
    box_size = lmp.x[1] - lmp.x[0]  # assume cubic for now

    mol_id = lmp.atom_info[:, 1]
    mol_list = np.unique(mol_id)

    for mol in mol_list:
        idx = np.argwhere(mol_id == mol).flatten()
        coors = lmp.atom_info[idx, 4:7]
        rcoors = coors - coors[0]
        rcoors = rcoors - np.round(rcoors/box_size)*box_size
        coors = coors[0] + rcoors
        lmp_new.atom_info[idx, 4:7] = coors

    write_lammps_full(save_file, lmp_new)

write_lammps(file_name, lmp_tmp, mode='full')

Write a LAMMPS data file from an in-memory structure.

Parameters:

Name Type Description Default
file_name str

Path to the output LAMMPS data file.

required
lmp_tmp lammps

LAMMPS object containing box bounds, atom data, masses and optional potential coefficients.

required
mode (full, atomic)

Atom style used when writing the Atoms section.

"full"

Returns:

Type Description
None

The data file is written to file_name.

Source code in m2dtools/lmp/tools_lammps.py
 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
def write_lammps(file_name, lmp_tmp, mode='full'):
    """Write a LAMMPS data file from an in-memory structure.

    Parameters
    ----------
    file_name : str
        Path to the output LAMMPS data file.
    lmp_tmp : lammps
        LAMMPS object containing box bounds, atom data, masses and optional
        potential coefficients.
    mode : {"full", "atomic"}, default "full"
        Atom style used when writing the ``Atoms`` section.

    Returns
    -------
    None
        The data file is written to ``file_name``.
    """
    with open('{}'.format(file_name), 'w') as f:
        f.write('Generated by ZYMD\n\n')

        f.write('{} atoms\n'.format(lmp_tmp.natoms))
        f.write('{} atom types\n'.format(lmp_tmp.natom_types))
        f.write('{} bonds\n'.format(lmp_tmp.nbonds))
        f.write('{} bond types\n'.format(lmp_tmp.nbond_types))
        f.write('{} angles\n'.format(lmp_tmp.nangles))
        f.write('{} angle types\n'.format(lmp_tmp.nangle_types))
        f.write('{} dihedrals\n'.format(lmp_tmp.ndihedrals))
        f.write('{} dihedral types\n'.format(lmp_tmp.ndihedral_types))
        f.write('{} impropers\n'.format(lmp_tmp.nimpropers))
        f.write('{} improper types\n'.format(lmp_tmp.nimproper_types))
        f.write('\n')

        f.write('{0:.16f} {1:.16f} xlo xhi\n'.format(lmp_tmp.x[0], lmp_tmp.x[1]))
        f.write('{0:.16f} {1:.16f} ylo yhi\n'.format(lmp_tmp.y[0], lmp_tmp.y[1]))
        f.write('{0:.16f} {1:.16f} zlo zhi\n'.format(lmp_tmp.z[0], lmp_tmp.z[1]))
        f.write('\n')

        f.write('Masses\n\n')
        for i in range(len(lmp_tmp.mass)):
            if lmp_tmp.mass.shape[1] == 3:
                f.write('{0:d} {1:.3f} # {2:s}\n'.format(
                    int(float(lmp_tmp.mass[i, 0])), float(lmp_tmp.mass[i, 1]), lmp_tmp.mass[i, 2]))
            elif lmp_tmp.mass.shape[1] == 2:
                f.write('{0:d} {1:.3f}\n'.format(
                    int(float(lmp_tmp.mass[i, 0])), float(lmp_tmp.mass[i, 1])))
        f.write('\n')

        if hasattr(lmp_tmp, 'pair_coeff') and not (lmp_tmp.pair_coeff is None):
            f.write('Pair Coeffs\n\n')
            for i in range(len(lmp_tmp.pair_coeff)):
                f.write('{0:d} {1:f} {2:f}\n'.format(
                    int(lmp_tmp.pair_coeff[i, 0]), lmp_tmp.pair_coeff[i, 1], lmp_tmp.pair_coeff[i, 2]))
            f.write('\n')

        if hasattr(lmp_tmp, 'bond_coeff') and not (lmp_tmp.bond_coeff is None):
            f.write('Bond Coeffs\n\n')
            for i in range(len(lmp_tmp.bond_coeff)):
                f.write('{0:d} {1:f} {2:f}\n'.format(
                    int(lmp_tmp.bond_coeff[i, 0]), lmp_tmp.bond_coeff[i, 1], lmp_tmp.bond_coeff[i, 2]))
            f.write('\n')

        if hasattr(lmp_tmp, 'angle_coeff') and not (lmp_tmp.angle_coeff is None):
            f.write('Angle Coeffs\n\n')
            for i in range(len(lmp_tmp.angle_coeff)):
                f.write('{0:d} {1:f} {2:f}\n'.format(
                    int(lmp_tmp.angle_coeff[i, 0]), lmp_tmp.angle_coeff[i, 1], lmp_tmp.angle_coeff[i, 2]))
            f.write('\n')

        if hasattr(lmp_tmp, 'dihedral_coeff') and not (lmp_tmp.dihedral_coeff is None):
            f.write('Dihedral Coeffs\n\n')
            for i in range(len(lmp_tmp.dihedral_coeff)):
                f.write('{0:d} {1:f} {2:f} {3:f} {4:f}\n'.format(int(lmp_tmp.dihedral_coeff[i, 0]), lmp_tmp.dihedral_coeff[i, 1], lmp_tmp.dihedral_coeff[i, 2],
                                                                 lmp_tmp.dihedral_coeff[i, 3], lmp_tmp.dihedral_coeff[i, 4]))
            f.write('\n')

        if hasattr(lmp_tmp, 'improper_coeff') and not (lmp_tmp.improper_coeff is None):
            f.write('Improper Coeffs\n\n')
            for i in range(len(lmp_tmp.improper_coeff)):
                f.write('{0:d} {1:f} {2:d} {3:d}\n'.format(int(lmp_tmp.improper_coeff[i, 0]), lmp_tmp.improper_coeff[i, 1], int(lmp_tmp.improper_coeff[i, 2]),
                                                           int(lmp_tmp.improper_coeff[i, 3])))
            f.write('\n')

        # f.write('Atoms\n\n')
        # for i in range(len(lmp_tmp.atom_info)):
        #     if lmp_tmp.atom_info.shape[1] > 7:
        #         f.write('{0:d} {1:d} {2:d} {3:f} {4:f} {5:f} {6:f} {8:d} {7:d} {9:d}\n'.format(int(lmp_tmp.atom_info[i, 0]), int(lmp_tmp.atom_info[i, 1]), int(lmp_tmp.atom_info[i, 2]),
        #            lmp_tmp.atom_info[i, 3], lmp_tmp.atom_info[i, 4], lmp_tmp.atom_info[i, 5], lmp_tmp.atom_info[i, 6], int(lmp_tmp.atom_info[i, 7]), int(lmp_tmp.atom_info[i, 8]), int(lmp_tmp.atom_info[i, 9])))
        #     else:
        #         f.write('{0:d} {1:d} {2:d} {3:f} {4:f} {5:f} {6:f}\n'.format(int(lmp_tmp.atom_info[i, 0]), int(lmp_tmp.atom_info[i, 1]), int(lmp_tmp.atom_info[i, 2]),
        #              lmp_tmp.atom_info[i, 3], lmp_tmp.atom_info[i, 4], lmp_tmp.atom_info[i, 5], lmp_tmp.atom_info[i, 6]))
        # f.write('\n')

        f.write('Atoms\n\n')
        lmp_tmp.atom_info = lmp_tmp.atom_info.astype(object)
        lmp_tmp.atom_info[:, 0] = lmp_tmp.atom_info[:, 0].astype(int)
        lmp_tmp.atom_info[:, 1] = lmp_tmp.atom_info[:, 1].astype(int)
        if mode=='full':
            lmp_tmp.atom_info[:, 2] = lmp_tmp.atom_info[:, 2].astype(int)
        for row in lmp_tmp.atom_info:
            line = []
            for val in row:
                if isinstance(val, float) or (isinstance(val, np.float64) or isinstance(val, np.float32)):
                    line.append(f'{val:.6f}')
                else:
                    line.append(f'{int(val)}')
            f.write(' '.join(line) + '\n')
        f.write('\n')

        if hasattr(lmp_tmp, 'velocity_info') and not (lmp_tmp.velocity_info is None):
            f.write('Velocities \n\n')
            for i in range(len(lmp_tmp.velocity_info)):
                f.write('{0:d} {1:f} {2:f} {3:f}\n'.format(int(
                    lmp_tmp.velocity_info[i, 0]), lmp_tmp.velocity_info[i, 1], lmp_tmp.velocity_info[i, 2], lmp_tmp.velocity_info[i, 3]))
            f.write('\n')

        if hasattr(lmp_tmp, 'bond_info') and not (lmp_tmp.bond_info is None) and not (lmp_tmp.nbonds == 0):
            f.write('Bonds\n\n')
            for i in range(len(lmp_tmp.bond_info)):
                f.write('{0:d} {1:d} {2:d} {3:d}\n'.format(int(lmp_tmp.bond_info[i, 0]), int(
                    lmp_tmp.bond_info[i, 1]), int(lmp_tmp.bond_info[i, 2]), int(lmp_tmp.bond_info[i, 3])))
            f.write('\n')

        if hasattr(lmp_tmp, 'angle_info') and not (lmp_tmp.angle_info is None) and not (lmp_tmp.nangles == 0):
            f.write('Angles\n\n')
            for i in range(len(lmp_tmp.angle_info)):
                f.write('{0:d} {1:d} {2:d} {3:d} {4:d}\n'.format(int(lmp_tmp.angle_info[i, 0]), int(lmp_tmp.angle_info[i, 1]), int(lmp_tmp.angle_info[i, 2]),
                                                                 int(lmp_tmp.angle_info[i, 3]), int(lmp_tmp.angle_info[i, 4])))
            f.write('\n')

        if hasattr(lmp_tmp, 'dihedral_info') and not (lmp_tmp.dihedral_info is None) and not (lmp_tmp.ndihedrals == 0):
            f.write('Dihedrals\n\n')
            for i in range(len(lmp_tmp.dihedral_info)):
                f.write('{0:d} {1:d} {2:d} {3:d} {4:d} {5:d}\n'.format(int(lmp_tmp.dihedral_info[i, 0]), int(lmp_tmp.dihedral_info[i, 1]), int(lmp_tmp.dihedral_info[i, 2]),
                                                                       int(lmp_tmp.dihedral_info[i, 3]), int(lmp_tmp.dihedral_info[i, 4]), int(lmp_tmp.dihedral_info[i, 5])))
            f.write('\n')

        if hasattr(lmp_tmp, 'improper_info') and not (lmp_tmp.improper_info is None) and not (lmp_tmp.nimpropers == 0):
            f.write('Impropers\n\n')
            for i in range(len(lmp_tmp.improper_info)):
                f.write('{0:d} {1:d} {2:d} {3:d} {4:d} {5:d}\n'.format(int(lmp_tmp.improper_info[i, 0]), int(lmp_tmp.improper_info[i, 1]), int(lmp_tmp.improper_info[i, 2]),
                                                                       int(lmp_tmp.improper_info[i, 3]), int(lmp_tmp.improper_info[i, 4]), int(lmp_tmp.improper_info[i, 5])))
            f.write('\n')

write_lammps_atomic(file_name, lmp_tmp)

Write an atomic-style LAMMPS data file.

Parameters:

Name Type Description Default
file_name str

Destination path for the data file.

required
lmp_tmp lammps

LAMMPS object containing atomic coordinates and masses.

required

Returns:

Type Description
None

The data file is written to file_name.

Source code in m2dtools/lmp/tools_lammps.py
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
def write_lammps_atomic(file_name, lmp_tmp):
    """Write an atomic-style LAMMPS data file.

    Parameters
    ----------
    file_name : str
        Destination path for the data file.
    lmp_tmp : lammps
        LAMMPS object containing atomic coordinates and masses.

    Returns
    -------
    None
        The data file is written to ``file_name``.
    """
    with open('{}'.format(file_name), 'w') as f:
        f.write('Generated by ZY code\n\n')

        f.write('{} atoms\n'.format(lmp_tmp.natoms))
        f.write('{} atom types\n'.format(lmp_tmp.natom_types))
        f.write('\n')

        f.write('{0:.16f} {1:.16f} xlo xhi\n'.format(lmp_tmp.x[0], lmp_tmp.x[1]))
        f.write('{0:.16f} {1:.16f} ylo yhi\n'.format(lmp_tmp.y[0], lmp_tmp.y[1]))
        f.write('{0:.16f} {1:.16f} zlo zhi\n'.format(lmp_tmp.z[0], lmp_tmp.z[1]))
        f.write('\n')

        f.write('Masses\n\n')
        for i in range(len(lmp_tmp.mass)):
            if lmp_tmp.mass.shape[1] == 3:
                f.write('{0:d} {1:.3f} # {2:s}\n'.format(
                    int(float(lmp_tmp.mass[i, 0])), float(lmp_tmp.mass[i, 1]), lmp_tmp.mass[i, 2]))
            elif lmp_tmp.mass.shape[1] == 2:
                f.write('{0:d} {1:.3f}\n'.format(
                    int(float(lmp_tmp.mass[i, 0])), float(lmp_tmp.mass[i, 1])))
        f.write('\n')

        f.write('Atoms # full\n\n')
        for i in range(len(lmp_tmp.atom_info)):
            if lmp_tmp.atom_info.shape[1] > 7:
                f.write('{0:d} {1:d} {2:f} {3:f} {4:f}\n'.format(int(lmp_tmp.atom_info[i, 0]), int(lmp_tmp.atom_info[i, 2]), lmp_tmp.atom_info[i, 4], lmp_tmp.atom_info[i, 5], lmp_tmp.atom_info[i, 6]))
        f.write('\n')

write_lammps_dump_custom(file_name, frame, t_list, L_list)

Write dump custom data from in-memory frames.

Parameters:

Name Type Description Default
file_name str

Output path for the dump file.

required
frame list[DataFrame]

Per-frame atom data sorted by id.

required
t_list list[int]

Timesteps corresponding to each frame.

required
L_list list[ndarray]

Box bounds for each frame as (3, 2) arrays.

required

Returns:

Type Description
None

The combined dump is written to file_name.

Source code in m2dtools/lmp/tools_lammps.py
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
def write_lammps_dump_custom(file_name, frame, t_list, L_list):
    """Write ``dump custom`` data from in-memory frames.

    Parameters
    ----------
    file_name : str
        Output path for the dump file.
    frame : list[pandas.DataFrame]
        Per-frame atom data sorted by id.
    t_list : list[int]
        Timesteps corresponding to each frame.
    L_list : list[numpy.ndarray]
        Box bounds for each frame as ``(3, 2)`` arrays.

    Returns
    -------
    None
        The combined dump is written to ``file_name``.
    """
    f = open('{}'.format(file_name), 'w')
    for it in range(len(t_list)):
        f.write('ITEM: TIMESTEP\n')
        f.write('{}\n'.format(t_list[it]))
        f.write('ITEM: NUMBER OF ATOMS\n')
        f.write('{}\n'.format(len(frame[it])))
        f.write('ITEM: BOX BOUNDS pp pp pp\n')
        for i in range(3):
            f.write('{} {}\n'.format(L_list[it][i][0], L_list[it][i][1]))
        f.write('ITEM: ATOMS ')
        for col in frame[it].columns:
            f.write('{} '.format(col))
        f.write('\n')
        for i in range(len(frame[it])):
            f.write('{} '.format(int(frame[it].iloc[i, 0])))
            for j in range(1, len(frame[it].columns)):
                # if integer, write as int, otherwise as float
                if isinstance(frame[it].iloc[i, j], int):
                    f.write('{0:d} '.format(int(frame[it].iloc[i, j])))
                else:
                    f.write('{0:.6f} '.format(frame[it].iloc[i, j]))
            f.write('\n')
    f.close()