• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

GMPavanLab / SOAPify / 4629648223

pending completion
4629648223

push

github

GitHub
Adde a new exampled and refined some simple rhings in the documentation (#78)

9 of 14 new or added lines in 2 files covered. (64.29%)

1 existing line in 1 file now uncovered.

828 of 928 relevant lines covered (89.22%)

2.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/SOAPify/cli.py
1
"""submodule containing the command line interfaces of SOAPify"""
2
from argparse import ArgumentParser
×
3

4

5
def getDictFromList(nameAndValues: list) -> dict:
×
6
    """generates a dictionary from a list of couples [name, value]
7

8
    Args:
9
        nameAndValues (list):
10
            the list of couples [name, value]
11

12
    Returns:
13
        dict:
14
            the dictionary, for example {name0:value0, name1:value1}
15
    """
16
    myDict = {}
×
17
    for attr in nameAndValues:
×
18
        myDict[attr[0]] = attr[1]
×
19
    return myDict
×
20

21

22
def createTrajectory():
×
23
    """Creates or overide an hdf5 file containing a given trajectory
24

25
    if you are creating ahdf5 file from a data+dump from a soap simulation
26
    remember to add `-u atom_style "id type x y z"` to the arguments
27

28
    defaults trajChunkSize=1000"""
29
    from MDAnalysis import Universe as mdaUniverse
×
30

31
    from SOAPify.HDF5er import MDA2HDF5
×
32
    from os import path
×
33

34
    parser = ArgumentParser(description=createTrajectory.__doc__)
×
35
    parser.add_argument("topology", help="the topology file")
×
36
    parser.add_argument("hdf5File", help="the file where to putput the trajectory")
×
37
    parser.add_argument(
×
38
        "-t",
39
        "--trajectory",
40
        help="the trajectory file(s)",
41
        metavar="trajectory",
42
        action="append",
43
        default=[],
44
    )
45
    parser.add_argument(
×
46
        "-n",
47
        "--name",
48
        metavar="name",
49
        help="the name of the trajectory to save",
50
    )
51
    parser.add_argument(
×
52
        "--types",
53
        metavar="atomNames",
54
        help="list of the atoms names",
55
        nargs="+",
56
        dest="atomTypes",
57
    )
58
    parser.add_argument(
×
59
        "-a",
60
        "--attribute",
61
        nargs=2,
62
        action="append",
63
        dest="extraAttributes",
64
        metavar=("name", "value"),
65
        help="extra attributes to store in the trajectory, saved as strings",
66
    )
67
    parser.add_argument(
×
68
        "-u",
69
        "--universe-options",
70
        nargs=2,
71
        action="append",
72
        dest="universeOPTs",
73
        metavar=("name", "value"),
74
        help="extra option to pass to the MDA universe, compatible only with string"
75
        " values, use the python script if you need to pass more other settings",
76
    )
77
    parser.add_argument(
×
78
        "-d",
79
        "--dry-run",
80
        action="store_true",
81
        help="just print the output without making any action",
82
    )
83
    args = parser.parse_args()
×
84
    # print(args)
85
    # arguments
86
    trajectoryFiles = args.trajectory
×
87
    filename = args.hdf5File
×
88
    topo = args.topology
×
89
    name = args.name
×
90
    if name is None:
×
91
        name = path.basename(topo)
×
92
        name = name.split(".")[0]
×
93

94
    print(
×
95
        f'from topology "{topo}"',
96
        f'and trajectory "{trajectoryFiles}":',
97
        "and creating a new trajectory in",
98
    )
99

100
    print(f'"{filename}/Trajectories/{name}"')
×
101
    extraAttrs = None
×
102
    if args.extraAttributes:
×
103
        extraAttrs = getDictFromList(args.extraAttributes)
×
104
        print("extra attributes:", extraAttrs)
×
105
    universeOptions = {}
×
106
    if args.universeOPTs:
×
107
        universeOptions = getDictFromList(args.universeOPTs)
×
108

109
    if args.dry_run:
×
110
        exit()
×
111

112
    u = mdaUniverse(topo, *trajectoryFiles, **universeOptions)
×
113
    if args.atomTypes:
×
114
        ntypes = len(args.atomTypes)
×
115
        if len(u.atoms) % ntypes != 0:
×
116
            raise ValueError(
×
117
                f"The number of atom types is not compatible with the number"
118
                f" of atoms:{len(u.atoms)} % {ntypes} = {len(u.atoms) % ntypes}"
119
            )
120
        u.atoms.types = args.atomTypes * (len(u.atoms) // ntypes)
×
121

122
    MDA2HDF5(u, filename, name, trajChunkSize=1000, attrs=extraAttrs)
×
123
    # TODO: implement this:
124
    # from MDAnalysis import transformations
125
    # ref = mdaUniverse(topo, atom_style="id type x y z")
126
    # u.trajectory.add_transformations(transformations.fit_rot_trans(u, ref))
127
    # MDA2HDF5(u, name + "_fitted.hdf5", f"{name}_fitted", trajChunkSize=1000))
128

129

130
def traj2SOAP():
×
131
    """Given an hdf5 file containing trajectories calculates SOAP of the contained trajectories
132

133

134
    default SOAP engine is dscribe"""
135

136
    from SOAPify import saponifyTrajectory
×
137
    from SOAPify.HDF5er import isTrajectoryGroup
×
138
    import h5py
×
139

140
    parser = ArgumentParser(description=traj2SOAP.__doc__)
×
141
    parser.add_argument(
×
142
        "trajFile",
143
        help="the file containing the trajectories",
144
    )
145
    parser.add_argument(
×
146
        "-s",
147
        "--SOAPFile",
148
        help="The file were to save the SOAP fingerprints, if not specified"
149
        ' creates a "SOAP" group in within the trajFile',
150
    )
NEW
151
    parser.add_argument(
×
152
        "-g",
153
        "--group",
154
        default="SOAP",
155
        help="the name of the group where to store the SOAP fingerprints,"
156
        ' if not specified is "SOAP"',
157
        dest="SOAPgroup",
158
    )
159
    parser.add_argument(
×
160
        "-t",
161
        "--trajectory",
162
        default="Trajectories",
163
        help="Specify the group containing the trajectories groups or the"
164
        " trajectory group tha you want to calculate the SOAP fingerprints",
165
    )
166
    parser.add_argument(
×
167
        "-e",
168
        "--engine",
169
        choices=["dscribe", "quippy"],
170
        default="dscribe",
171
        help="the engine used to calculate SOAP",
172
    )
173
    parser.add_argument(
×
174
        "-l",
175
        "--lMax",
176
        type=int,
177
        default=8,
178
        help="the lmax parameter, defaults to 8",
179
    )
180
    parser.add_argument(
×
181
        "-n",
182
        "--nMax",
183
        type=int,
184
        default=8,
185
        help="the nmax parameter, defaults to 8",
186
    )
187
    parser.add_argument(
×
188
        "-r",
189
        "--rCut",
190
        type=float,
191
        default=10.0,
192
        help="the rcut parameter, defaults to 10.0 Å",
193
    )
194
    parser.add_argument(
×
195
        "-j",
196
        "--jobs",
197
        type=int,
198
        default=1,
199
        help="the number of jobs to use, defaults to 1",
200
    )
201
    parser.add_argument(
×
202
        "-d",
203
        "--dry-run",
204
        action="store_true",
205
        help="just print the output without making any action",
206
    )
207
    args = parser.parse_args()
×
208
    # print(args)
209

210
    trajGroupLocation = args.trajectory
×
211

NEW
212
    def worker(
×
213
        group: "h5py.Group|h5py.Dataset", soapFile: h5py.File, SOAPgroup: str = "SOAP"
214
    ):
UNCOV
215
        print(
×
216
            f"\"{group.name}\" is {'' if isTrajectoryGroup(group) else 'not '}a trajectory group"
217
        )
218
        if isTrajectoryGroup(group):
×
219
            if args.dry_run:
×
220
                return
×
221
            saponifyTrajectory(
×
222
                trajContainer=group,
223
                SOAPoutContainer=soapFile.require_group(SOAPgroup),
224
                SOAPOutputChunkDim=1000,
225
                SOAPnJobs=args.jobs,
226
                SOAPrcut=args.rCut,
227
                SOAPnmax=args.nMax,
228
                SOAPlmax=args.lMax,
229
                useSoapFrom=args.engine,
230
            )
231

232
    SOAPFile = args.SOAPFile
×
NEW
233
    SOAPgroup = args.SOAPgroup
×
234
    if args.SOAPFile is None:
×
235
        SOAPFile = args.trajFile
×
236
    with h5py.File(
×
237
        args.trajFile, "r" if SOAPFile != args.trajFile else "a"
238
    ) as workFile, h5py.File(SOAPFile, "a") as SOAPFile:
239
        trajGroup = workFile[trajGroupLocation]
×
240
        if isTrajectoryGroup(trajGroup):
×
NEW
241
            worker(trajGroup, SOAPFile, SOAPgroup)
×
242
        else:
243
            for _, group in trajGroup.items():
×
NEW
244
                worker(group, SOAPFile, SOAPgroup)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc