phbuilder 1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. phbuilder/__init__.py +16 -0
  2. phbuilder/ffield/charmm36-mar2019-cphmd.ff/atomtypes.atp +455 -0
  3. phbuilder/ffield/charmm36-mar2019-cphmd.ff/cmap.itp +1025 -0
  4. phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffbonded.itp +19675 -0
  5. phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffnonbonded.itp +40366 -0
  6. phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.doc +252 -0
  7. phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.itp +26 -0
  8. phbuilder/ffield/charmm36-mar2019-cphmd.ff/gb.itp +49 -0
  9. phbuilder/ffield/charmm36-mar2019-cphmd.ff/ions.itp +98 -0
  10. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.arn +6 -0
  11. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.c.tdb +76 -0
  12. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.hdb +414 -0
  13. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.n.tdb +93 -0
  14. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.r2b +16 -0
  15. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.rtp +123316 -0
  16. phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.vsd +221 -0
  17. phbuilder/ffield/charmm36-mar2019-cphmd.ff/nbfix.itp +101 -0
  18. phbuilder/ffield/charmm36-mar2019-cphmd.ff/old_c36_cmap.itp +486 -0
  19. phbuilder/ffield/charmm36-mar2019-cphmd.ff/popc.itp +1279 -0
  20. phbuilder/ffield/charmm36-mar2019-cphmd.ff/spc.itp +30 -0
  21. phbuilder/ffield/charmm36-mar2019-cphmd.ff/spce.itp +30 -0
  22. phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip3p.itp +49 -0
  23. phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip4p.itp +53 -0
  24. phbuilder/ffield/charmm36-mar2019-cphmd.ff/watermodels.dat +6 -0
  25. phbuilder/ffield/lambdagrouptypes.dat +40 -0
  26. phbuilder/ffield/residuetypes.dat +211 -0
  27. phbuilder/mdp.py +133 -0
  28. phbuilder/parsecmdline.py +228 -0
  29. phbuilder/phbuilder.py +1408 -0
  30. phbuilder/sanitize.py +180 -0
  31. phbuilder/structure.py +333 -0
  32. phbuilder/user.py +142 -0
  33. phbuilder-1.1.dist-info/LICENSE +674 -0
  34. phbuilder-1.1.dist-info/METADATA +609 -0
  35. phbuilder-1.1.dist-info/RECORD +38 -0
  36. phbuilder-1.1.dist-info/WHEEL +5 -0
  37. phbuilder-1.1.dist-info/entry_points.txt +2 -0
  38. phbuilder-1.1.dist-info/top_level.txt +1 -0
phbuilder/sanitize.py ADDED
@@ -0,0 +1,180 @@
1
+ import sys
2
+ import os
3
+
4
+ class Sanitize:
5
+ """Class for sanitizing user input of various types."""
6
+
7
+ def __init__(self, var, name: str = '', v: bool = True, exit: bool = True) -> None:
8
+ """Initialize Sanitize object.
9
+
10
+ Args:
11
+ var (Any): variable under consideration.
12
+ name (str, optional): Additional description of variable (for user message).
13
+ v (bool, optional): verbose. Defaults to True.
14
+ exit (bool, optional): exit python upon encountering an error. Defaults to True.
15
+ """
16
+
17
+ self.var = var
18
+ self.__name = name
19
+ self.__verbose = v
20
+ self.__exit = exit
21
+ self.__good = True
22
+
23
+ def __error(self, msg: str) -> None:
24
+ """Handles the error message program logic. Sets exitcode to 1 when executed.
25
+
26
+ Args:
27
+ msg (str): Information on the error.
28
+ """
29
+
30
+ pre = 'phbuilder : SANITIZE - ' # Pre-string for error messages.
31
+
32
+ if self.__verbose:
33
+
34
+ if self.__name:
35
+ if type(self.var) == str:
36
+ print(f'{pre}[\'{self.var}\'] specified for [{self.__name}] {msg}.')
37
+ else:
38
+ print(f'{pre}[{self.var}] specified for [{self.__name}] {msg}.')
39
+
40
+ else:
41
+ if type(self.var) == str:
42
+ print(f'{pre}[\'{self.var}\'] {msg}.')
43
+ else:
44
+ print(f'{pre}[{self.var}] {msg}.')
45
+
46
+ self.__good = False
47
+
48
+ def __endbehavior(self):
49
+ # if exit=True and we've had an error, exit python.
50
+ if self.__exit and not self.__good:
51
+ sys.exit(1)
52
+ # if exit=False and we've had an error, return None.
53
+ elif not self.__good:
54
+ return None
55
+ # If exit=False and we haven't had an error we're good.
56
+ else:
57
+ return self.var
58
+
59
+ def num(self, Type=None, Range: list = [], signed: bool = False):
60
+ """Sanitize numerical types (int, float, bool).
61
+
62
+ Args:
63
+ Type (Any, optional): (list of) acceptable type(s). Defaults to None.
64
+ Range (list, optional): acceptable interval. Defaults to [].
65
+ signed (bool, optional): Signed or unsigned. Defaults to False.
66
+
67
+ Returns:
68
+ int: exitcode.
69
+ """
70
+
71
+ # If Type was user-specified in any way, turn it into a list.
72
+ if Type is not None and type(Type) != list:
73
+ Type = [Type]
74
+
75
+ # First of all, if you use this function var should be an int, float, bool.
76
+ if type(self.var) not in [int, float, bool]:
77
+ self.__error(f'not a number (should be in {[int, float, bool]})')
78
+
79
+ else:
80
+ # Second, if Type was user-specified in any way, check for match.
81
+ if Type is not None and type(self.var) not in Type:
82
+ self.__error(f'should be of type {Type} (found {type(self.var)})')
83
+
84
+ # Check range.
85
+ if len(Range) and (self.var < Range[0] or self.var > Range[1]):
86
+ self.__error(f'outside of acceptable interval {Range}')
87
+
88
+ # Check signed versus unsigned.
89
+ if signed and self.var < 0:
90
+ self.__error('cannot be negative')
91
+
92
+ return self.__endbehavior()
93
+
94
+ def string(self, Range: list = [], upper: bool = False, lower: bool = False, ws: bool = True):
95
+ """sanitize strings (str).
96
+
97
+ Args:
98
+ Range (list, optional): acceptable string length. Defaults to [].
99
+ upper (bool, optional): all uppercase. Defaults to False.
100
+ lower (bool, optional): all lowercase. Defaults to False.
101
+ ws (bool, optional): accept whitespace. Defaults to True.
102
+
103
+ Returns:
104
+ int: exitcode.
105
+ """
106
+ # Confirm whether var is a string.
107
+ if type(self.var) != str:
108
+ self.__error(f'should be of type {str}')
109
+
110
+ # Check range.
111
+ if len(Range) and (len(self.var) < Range[0] or len(self.var) > Range[1]):
112
+ self.__error(f'outside of acceptable length {Range}')
113
+
114
+ if upper and not self.var.isupper():
115
+ self.__error('should be all uppercase')
116
+
117
+ if lower and not self.var.islower():
118
+ self.__error('should be all lowercase')
119
+
120
+ if (not ws) and (self.var.count(' ') > 0):
121
+ self.__error('cannot contain whitespace')
122
+
123
+ return self.__endbehavior()
124
+
125
+ def path(self, ext: str = '', out: bool = False, abs: bool = False):
126
+ """Sanitize file paths (str).
127
+
128
+ Args:
129
+ ext (str, optional): acceptable extension(s). Defaults to ''.
130
+ out (bool, optional): path meant for creation/output? Defaults to False.
131
+ abs (bool, optional): absolute path required. Defaults to False.
132
+
133
+ Returns:
134
+ int: exitcode.
135
+ """
136
+ # Only strings can represent file paths.
137
+ if type(self.var) != str:
138
+ self.__error(f'should be of type {str}')
139
+ return int(not self.__good)
140
+
141
+ # File paths cannot be empty strings.
142
+ if self.var == '':
143
+ self.__error('cannot be empty')
144
+
145
+ # File paths cannot be directories.
146
+ elif os.path.isdir(self.var):
147
+ self.__error('is a directory')
148
+
149
+ # (input) file path should correspond to an existing file.
150
+ elif not os.path.exists(self.var) and not out:
151
+ self.__error('corresponding file does not exist')
152
+
153
+ # (output) file DIRECTORY should already exist:
154
+ if out and not os.path.isdir(os.path.split(os.path.abspath(self.var))[0]):
155
+ self.__error('directory for output does not exist')
156
+
157
+ # Check extension.
158
+ if ext:
159
+ tail = os.path.split(self.var)[1]
160
+
161
+ if type(ext) != list:
162
+ ext = [ext]
163
+
164
+ if tail.count(' ') != 0:
165
+ self.__error('cannot contain whitespace')
166
+
167
+ if (tail.count('.') == 0) or (tail.count('.') > 1) or (tail[-1] == '.'):
168
+ self.__error(f'ambiguous extension (should be {ext})')
169
+
170
+ elif tail.index('.') == 0:
171
+ self.__error('cannot be just an extension')
172
+
173
+ elif tail[tail.index('.'):] not in ext:
174
+ self.__error(f'should have extension {ext}')
175
+
176
+ # Check absolute file path.
177
+ if abs and not os.path.isabs(self.var):
178
+ self.__error('should be an absolute file path')
179
+
180
+ return self.__endbehavior()
phbuilder/structure.py ADDED
@@ -0,0 +1,333 @@
1
+ import os
2
+ from .user import User
3
+
4
+
5
+ class Residue:
6
+ """Stores the structural (pdb, gro) information for one residue."""
7
+
8
+ def __init__(self, atoms: list, resname: str, chain: str, resid: int, x: list, y: list, z: list):
9
+ """Initialize Residue object.
10
+
11
+ Args:
12
+ atoms (list): residue atom names.
13
+ resname (str): residue name.
14
+ chain (str): chain identifier.
15
+ resid (int): residue id.
16
+ x (list): residue atom x-coordinates.
17
+ y (list): residue atom y-coordinates.
18
+ z (list): residue atom z-coordinates.
19
+ """
20
+ self.d_atoms = atoms
21
+ self.d_resname = resname
22
+ self.d_chain = chain
23
+ self.d_resid = resid
24
+ self.d_x = x
25
+ self.d_y = y
26
+ self.d_z = z
27
+ self.d_init = '' # Holds the initial lambda value (for record).
28
+
29
+
30
+ class Crystal:
31
+ """Stores the information pertaining the periodic box.
32
+ """
33
+
34
+ def __init__(self, a: float, b: float, c: float, alpha: float, beta: float, gamma: float, space: str, Z: int):
35
+ """Initialize Crystal object.
36
+
37
+ Args:
38
+ a (float): a (Angstroms).
39
+ b (float): b (Angstroms).
40
+ c (float): b (Angstroms).
41
+ alpha (float): alpha (degrees).
42
+ beta (float): beta (degrees).
43
+ gamma (float): gamma (degrees).
44
+ space (str): space group.
45
+ Z (int): z-value.
46
+ """
47
+ self.d_a = a
48
+ self.d_b = b
49
+ self.d_c = c
50
+ self.d_alpha = alpha
51
+ self.d_beta = beta
52
+ self.d_gamma = gamma
53
+ self.d_space = space
54
+ self.d_Z = Z
55
+
56
+
57
+ class Structure:
58
+ """Parses and stores the information in a structure (pdb, gro) file.
59
+ Is also able to write (internal) information to either .pdb or .gro format."""
60
+
61
+ def __init__(self, name: str, verbosity: int):
62
+ """Initialize structure object.
63
+
64
+ Args:
65
+ name (str): structure (.pdb/.gro) file name.
66
+ verbosity (int): verbosity.
67
+ """
68
+ self.__user = User(verbosity, logFileName='builder.log')
69
+ self.read(name)
70
+
71
+ def read(self, name: str):
72
+ """Read structure (.pdb/.gro) file into internal data.
73
+
74
+ Args:
75
+ name (str): input structure file name.
76
+ """
77
+ extension = os.path.splitext(name)[1]
78
+
79
+ if extension == ".pdb":
80
+ self.__read_pdb(name)
81
+ self.__read_record()
82
+
83
+ if extension == ".gro":
84
+ self.__read_gro(name)
85
+ self.__read_record()
86
+
87
+ def write(self, name: str):
88
+ """Write internal data to a structure (.pdb/.gro) file.
89
+
90
+ Args:
91
+ name (str): output structure file name.
92
+ """
93
+ extension = os.path.splitext(name)[1]
94
+
95
+ if extension == ".pdb":
96
+ self.__write_pdb(name)
97
+ self.__write_record()
98
+
99
+ if extension == ".gro":
100
+ self.__write_gro(name)
101
+ self.__write_record()
102
+
103
+ def __read_pdb(self, name: str):
104
+ """Load a .pdb file into d_residues.
105
+
106
+ Args:
107
+ name (str): file name.
108
+ """
109
+ self.__user.verbose(f"Reading structure from {name}...")
110
+
111
+ with open(name) as file:
112
+
113
+ atomLines = []
114
+
115
+ for line in file.readlines():
116
+
117
+ # Get title.
118
+ if (line[0:6] == "TITLE "):
119
+ self.d_title = line[7:80].strip()
120
+
121
+ # Get periodic box information (if any).
122
+ elif (line[0:6] == "CRYST1"):
123
+ self.d_box = Crystal(float(line[6:15]), float(line[15:24]), float(line[24:33]), float(line[33:40]), float(line[40:47]), float(line[47:54]), line[55:66], int(line[66:70]))
124
+
125
+ # Get the ATOM lines.
126
+ elif (line[0:6] == "ATOM "):
127
+ atomLines.append(line)
128
+
129
+ # Only import the first MODEL...
130
+ elif (line[0:6] == "ENDMDL"):
131
+ break
132
+
133
+ # Loop through the atomLines and create a list of Residue objects.
134
+
135
+ residues = []
136
+ atoms = []
137
+ x = []
138
+ y = []
139
+ z = []
140
+ lastLine = False
141
+
142
+ for idx in range(0, len(atomLines)):
143
+
144
+ atoms.append(atomLines[idx][12:16].strip())
145
+ x.append(float(atomLines[idx][30:38]))
146
+ y.append(float(atomLines[idx][38:46]))
147
+ z.append(float(atomLines[idx][46:54]))
148
+
149
+ try:
150
+ currentResID = int(atomLines[idx][22:27])
151
+ nextResID = int(atomLines[idx + 1][22:27])
152
+ except IndexError:
153
+ lastLine = True
154
+
155
+ if (currentResID != nextResID or lastLine):
156
+
157
+ currentResName = atomLines[idx][17:21].strip()
158
+ currentChain = atomLines[idx][21:22]
159
+
160
+ # Create the Residue object.
161
+ residues.append(Residue(atoms, currentResName, currentChain, currentResID, x, y, z))
162
+
163
+ # Reset.
164
+ atoms = []
165
+ x = []
166
+ y = []
167
+ z = []
168
+
169
+ # Add the list of Residues to universe.
170
+ self.d_residues = residues
171
+
172
+ def __write_pdb(self, name: str):
173
+ """Write a .pdb file from d_residues.
174
+
175
+ Args:
176
+ name (str): file name.
177
+ """
178
+ self.__user.verbose(f"Writing structure to {name}...")
179
+
180
+ with open(name, 'w') as file:
181
+ if hasattr(self, 'd_title'):
182
+ file.write(f"TITLE {self.d_title}\n")
183
+
184
+ if hasattr(self, 'd_box'):
185
+ cryst = self.d_box
186
+ file.write("CRYST1{:>9.3f}{:>9.3f}{:>9.3f}{:>7.2f}{:>7.2f}{:>7.2f} {:11s}{:>4d}\n".format(cryst.d_a, cryst.d_b, cryst.d_c, cryst.d_alpha, cryst.d_beta, cryst.d_gamma, cryst.d_space, cryst.d_Z))
187
+
188
+ file.write(f"MODEL {1:8d}\n")
189
+
190
+ atomNumber = 1
191
+ for residue in self.d_residues:
192
+ for idx in range(0, len(residue.d_atoms)):
193
+
194
+ atom = residue.d_atoms[idx]
195
+ if len(atom) == 3:
196
+ atom = ' ' + atom
197
+
198
+ file.write("{:6s}{:5d} {:^4s}{:1s}{:4s}{:1s}{:4d}{:1s} {:8.3f}{:8.3f}{:8.3f}\n".format('ATOM', atomNumber % 100000, atom, '', residue.d_resname, residue.d_chain, residue.d_resid % 10000, '', residue.d_x[idx], residue.d_y[idx], residue.d_z[idx]))
199
+ atomNumber += 1
200
+
201
+ file.write("TER\nENDMDL\n")
202
+
203
+ def __read_gro(self, name: str):
204
+ """Load a .gro file into d_residues.
205
+
206
+ Args:
207
+ name (str): file name.
208
+ """
209
+ self.__user.verbose(f"Reading structure from {name}...")
210
+
211
+ atomLines = open(name).read().splitlines()
212
+
213
+ # Loop through the atomLines and create a list of Residue objects.
214
+
215
+ residues = []
216
+ atoms = []
217
+ x = []
218
+ y = []
219
+ z = []
220
+
221
+ for idx in range(0, len(atomLines)):
222
+
223
+ # Title.
224
+ if (idx == 0):
225
+ self.d_title = atomLines[idx]
226
+ continue
227
+
228
+ # Number of atoms.
229
+ if (idx == 1):
230
+ continue
231
+
232
+ # Periodic box information.
233
+ if (idx == len(atomLines) - 1):
234
+ self.d_box = Crystal(10 * float(atomLines[idx][0:10]), 10 * float(atomLines[idx][10:20]), 10 * float(atomLines[idx][20:30]), 90, 90, 90, "P 1", 1)
235
+ continue
236
+
237
+ atoms.append(atomLines[idx][11:15].strip())
238
+ x.append(10 * float(atomLines[idx][20:28]))
239
+ y.append(10 * float(atomLines[idx][28:36]))
240
+ z.append(10 * float(atomLines[idx][36:44]))
241
+
242
+ if (idx != len(atomLines) - 2):
243
+ currentResID = int(atomLines[idx][0:5])
244
+ nextResID = int(atomLines[idx + 1][0:5])
245
+
246
+ if (currentResID != nextResID or idx == len(atomLines) - 2):
247
+ currentResName = atomLines[idx][5:10].strip()
248
+
249
+ # Create the Residue object.
250
+ residues.append(Residue(atoms, currentResName, ' ', currentResID, x, y, z))
251
+
252
+ # Reset.
253
+ atoms = []
254
+ x = []
255
+ y = []
256
+ z = []
257
+
258
+ # Add the list of Residues to universe.
259
+ self.d_residues = residues
260
+
261
+ def __write_gro(self, name: str):
262
+ """Write a .gro file from d_residues.
263
+
264
+ Args:
265
+ name (str): file name.
266
+ """
267
+ self.__user.verbose(f"Writing structure to {name}...")
268
+
269
+ with open(name, 'w') as file:
270
+ # Title.
271
+ if hasattr(self, 'd_title'):
272
+ file.write(f"{self.d_title.strip()}\n")
273
+ else:
274
+ file.write("Dummy Title\n")
275
+
276
+ # Total number of atoms.
277
+ total = 0
278
+ for residue in self.d_residues:
279
+ for _ in residue.d_atoms:
280
+ total += 1
281
+ file.write(f"{total:>5d}\n")
282
+
283
+ # Atoms.
284
+ total = 1
285
+ for residue in self.d_residues:
286
+ for idx in range(0, len(residue.d_atoms)):
287
+ file.write("{:>5d}{:5s}{:>5s}{:>5d}{:>8.3f}{:>8.3f}{:>8.3f}\n".format(
288
+ residue.d_resid, residue.d_resname, residue.d_atoms[idx],
289
+ total % 100000, residue.d_x[idx] / 10, residue.d_y[idx] / 10, residue.d_z[idx] / 10))
290
+ total += 1
291
+
292
+ # Periodic box.
293
+ if hasattr(self, 'd_box'):
294
+ cryst = self.d_box
295
+ file.write(f"{cryst.d_a / 10:>10.5f}{cryst.d_b / 10:>10.5f}{cryst.d_c / 10:>10.5f}\n")
296
+ else:
297
+ file.write(f"{0.0:>10.5f}{0.0:>10.5f}{0.0:>10.5f}\n")
298
+
299
+ def __read_record(self):
300
+ """Reads the record of initial lambda values (phrecord.dat) if it exists.
301
+ Will set any inits found in phrecord.dat to the corresponding residue in d_residues.
302
+ """
303
+
304
+ if os.path.isfile('phrecord.dat'):
305
+ self.__user.verbose('Found existing record of initial lambda values (phrecord.dat)...')
306
+ # Split file by lines.
307
+ idx = 0
308
+ for line in open('phrecord.dat').read().splitlines():
309
+ resname = line[0:4].strip()
310
+ resid = int(line[5:9])
311
+ chain = line[10:11]
312
+ init = line[12:14].strip()
313
+
314
+ if (init != ""):
315
+ # Set the init value found in phrecord.dat in corresponding residue object.
316
+ self.d_residues[idx].d_init = init
317
+ # User update.
318
+ self.__user.verbose("Matched {}-{} in chain {} with record entry for {}-{} in chain {} (init = {})".format(
319
+ self.d_residues[idx].d_resname, self.d_residues[idx].d_resid, self.d_residues[idx].d_chain,
320
+ resname, resid, chain, init))
321
+
322
+ idx += 1
323
+ else:
324
+ self.__user.update("Did not find existing record of initial lambda values (phrecord.dat)...")
325
+
326
+ def __write_record(self):
327
+ """Write a record of initial lambda values to phrecord.dat
328
+ """
329
+ self.__user.verbose('Writing initial lambda record to phrecord.dat...')
330
+
331
+ with open('phrecord.dat', 'w+') as file:
332
+ for residue in self.d_residues:
333
+ file.write("{:4s} {:4d} {:1s} {:2s}\n".format(residue.d_resname, residue.d_resid % 10000, residue.d_chain, residue.d_init))
phbuilder/user.py ADDED
@@ -0,0 +1,142 @@
1
+ import sys
2
+
3
+ class User:
4
+ """Provides and formats user updates, warnings, and errors.
5
+ """
6
+
7
+ def __init__(self, verbosity: int, logFileName='', maxLineLength=90):
8
+ """Initialize User object.
9
+
10
+ Args:
11
+ verbosity (int): verbosity value. 0 = supress all, 1 = only warnings and errors, 2 = regular, 3 = verbose.
12
+ maxLineLength (int): maximum length of sentence before a newline (does not consider length of preMessage etc).
13
+ """
14
+
15
+ self.verbosity = verbosity
16
+ self.logFileName = logFileName
17
+ self.maxLineLength = maxLineLength
18
+
19
+ def doPrint(self, message: str):
20
+ """Handle printing internals.
21
+
22
+ Args:
23
+ message (str): message to be printen/logged.
24
+ """
25
+
26
+ if self.logFileName:
27
+ with open(self.logFileName, 'a+') as logfile:
28
+ print(message, file=logfile)
29
+
30
+ print(message)
31
+
32
+ def base(self, message: str, preMessage: str = ''):
33
+ """Base method for handeling user messages.
34
+
35
+ Args:
36
+ message (str): message.
37
+ preMessage (str, optional): pre-message. Defaults to ''.
38
+ """
39
+
40
+ # If we input a dictionary of list as a message, print and return.
41
+ if isinstance(message, list) or isinstance(message, dict):
42
+ self.doPrint(message)
43
+ return
44
+
45
+ firstLineWritten = False
46
+ charCount = 0
47
+ currentLine = ''
48
+
49
+ for word in message.split(' '):
50
+
51
+ charCount += len(word) + 1
52
+
53
+ if charCount < self.maxLineLength:
54
+ currentLine += word + ' '
55
+ else:
56
+ self.doPrint(f"phbuilder : {preMessage}{currentLine}")
57
+ firstLineWritten = True
58
+ charCount = len(word) + 1
59
+ currentLine = word + ' '
60
+
61
+ # This we add so that not every subsequent line has preMessage,
62
+ # but it is aligned nonetheless.
63
+ if firstLineWritten and preMessage != '':
64
+ preMessage = ' '.ljust(len(preMessage))
65
+
66
+ self.doPrint(f"phbuilder : {preMessage}{currentLine.lstrip()}") # Flush.
67
+
68
+ def verbose(self, message: str):
69
+ """Print message when verbosity is high.
70
+
71
+ Args:
72
+ message (str): message.
73
+ """
74
+
75
+ if self.verbosity > 2:
76
+ self.base(message)
77
+
78
+ def update(self, message: str):
79
+ """Print default message.
80
+
81
+ Args:
82
+ message (str): message.
83
+ """
84
+
85
+ if self.verbosity > 1:
86
+ self.base(message)
87
+
88
+ def warning(self, message: str):
89
+ """Print warning message.
90
+
91
+ Args:
92
+ message (str): message.
93
+ """
94
+
95
+ if self.verbosity > 0:
96
+ self.doPrint('phbuilder : ')
97
+ self.base(message, preMessage='WARNING - ')
98
+ self.doPrint('phbuilder : ')
99
+
100
+ def error(self, message: str):
101
+ """Print error message and sys.exit() the program.
102
+
103
+ Args:
104
+ message (str): message.
105
+ """
106
+
107
+ if self.verbosity > 0:
108
+ self.doPrint('phbuilder : ')
109
+ self.base(message, preMessage='ERROR - ')
110
+ self.doPrint('phbuilder : ')
111
+
112
+ sys.exit()
113
+
114
+ def inputOptionHandler(self, message: str, options: list) -> int:
115
+ """Handles user input.
116
+
117
+ Args:
118
+ message (str): message.
119
+ options (list): list of strings describing the options. Starts counting from 0.
120
+
121
+ Returns:
122
+ int: number corresponding to the option selected by the user.
123
+ """
124
+
125
+ valids = []
126
+ msgstring = "phbuilder : {}:".format(message)
127
+
128
+ # Loop through the options list and create string for display
129
+ for idx in range(0, len(options)):
130
+ msgstring += "\nphbuilder : {}. {}".format(idx, options[idx])
131
+ valids.append(str(idx))
132
+
133
+ while True:
134
+ self.doPrint(msgstring)
135
+ val = input("phbuilder : Type a number: ")
136
+
137
+ if val in valids:
138
+ self.doPrint(f"phbuilder : selected {val}")
139
+ self.doPrint('')
140
+ return int(val)
141
+
142
+ self.doPrint("phbuilder : {} is not a valid option, please try again:\n".format(val))