molutils 0.3.0__tar.gz → 0.5.0__tar.gz

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 (34) hide show
  1. {molutils-0.3.0 → molutils-0.5.0}/PKG-INFO +2 -2
  2. {molutils-0.3.0 → molutils-0.5.0}/molutils/__init__.py +2 -0
  3. molutils-0.5.0/molutils/_core/count.py +104 -0
  4. molutils-0.5.0/molutils/_core/extract.py +170 -0
  5. {molutils-0.3.0 → molutils-0.5.0}/molutils/_core/list_.py +14 -16
  6. molutils-0.5.0/molutils/_core/remove.py +47 -0
  7. molutils-0.5.0/molutils/_parsers/chain_resid.py +34 -0
  8. {molutils-0.3.0 → molutils-0.5.0}/molutils/_parsers/parser_pdb.py +25 -0
  9. {molutils-0.3.0 → molutils-0.5.0}/molutils/_ui/app_main.py +16 -6
  10. molutils-0.5.0/molutils/_ui/fy_help.fyh +97 -0
  11. molutils-0.5.0/molutils/_ui/fy_rules.fyr +74 -0
  12. molutils-0.5.0/molutils/_version.py +1 -0
  13. {molutils-0.3.0 → molutils-0.5.0}/molutils.egg-info/PKG-INFO +2 -2
  14. {molutils-0.3.0 → molutils-0.5.0}/molutils.egg-info/SOURCES.txt +2 -0
  15. molutils-0.5.0/molutils.egg-info/requires.txt +1 -0
  16. {molutils-0.3.0 → molutils-0.5.0}/setup.py +1 -1
  17. molutils-0.3.0/molutils/_core/count.py +0 -38
  18. molutils-0.3.0/molutils/_core/extract.py +0 -94
  19. molutils-0.3.0/molutils/_ui/fy_help.fyh +0 -49
  20. molutils-0.3.0/molutils/_ui/fy_rules.fyr +0 -32
  21. molutils-0.3.0/molutils/_version.py +0 -1
  22. molutils-0.3.0/molutils.egg-info/requires.txt +0 -1
  23. {molutils-0.3.0 → molutils-0.5.0}/LICENSE.md +0 -0
  24. {molutils-0.3.0 → molutils-0.5.0}/README.md +0 -0
  25. {molutils-0.3.0 → molutils-0.5.0}/molutils/__main__.py +0 -0
  26. {molutils-0.3.0 → molutils-0.5.0}/molutils/_core/__init__.py +0 -0
  27. {molutils-0.3.0 → molutils-0.5.0}/molutils/_parsers/__init__.py +0 -0
  28. {molutils-0.3.0 → molutils-0.5.0}/molutils/_ui/__init__.py +0 -0
  29. {molutils-0.3.0 → molutils-0.5.0}/molutils/_ui/app_subcommand.py +0 -0
  30. {molutils-0.3.0 → molutils-0.5.0}/molutils.egg-info/dependency_links.txt +0 -0
  31. {molutils-0.3.0 → molutils-0.5.0}/molutils.egg-info/entry_points.txt +0 -0
  32. {molutils-0.3.0 → molutils-0.5.0}/molutils.egg-info/top_level.txt +0 -0
  33. {molutils-0.3.0 → molutils-0.5.0}/pyproject.toml +0 -0
  34. {molutils-0.3.0 → molutils-0.5.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: molutils
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: Collection of tools for preprocessing or summarizing details from biomolecular structure files.
5
5
  Home-page: https://github.com/diegobarmor/molutils
6
6
  Author: DiegoBarMor
@@ -12,7 +12,7 @@ Classifier: Operating System :: OS Independent
12
12
  Requires-Python: >=3.10
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE.md
15
- Requires-Dist: freyacli==0.3.2
15
+ Requires-Dist: freyacli==0.4.1
16
16
  Dynamic: author
17
17
  Dynamic: author-email
18
18
  Dynamic: classifier
@@ -1,11 +1,13 @@
1
1
  from ._version import __version__
2
2
 
3
3
  from ._parsers.parser_pdb import ParserPDB
4
+ from ._parsers.chain_resid import ChainResid
4
5
 
5
6
  from ._ui.app_subcommand import AppSubcommand
6
7
 
7
8
  from ._core.list_ import List
8
9
  from ._core.count import Count
9
10
  from ._core.extract import Extract
11
+ from ._core.remove import Remove
10
12
 
11
13
  from ._ui.app_main import AppMain
@@ -0,0 +1,104 @@
1
+ from pathlib import Path
2
+
3
+ import freyacli as fy
4
+ import molutils as mu
5
+
6
+ # //////////////////////////////////////////////////////////////////////////////
7
+ class Count(mu.AppSubcommand):
8
+ # -------------------------------------------------------------------------- UI SECTION
9
+ def run(self):
10
+ command = self.main.subcommands.pop(0)
11
+
12
+ if command == "models" : return self.app_count_models()
13
+ if command == "chains" : return self.app_count_chains()
14
+ if command == "residues": return self.app_count_residues()
15
+ if command == "frames" : return self.app_count_frames()
16
+ if command == "altlocs" : return self.app_count_altlocs()
17
+
18
+ raise ValueError(f"Unknown command: {command}")
19
+
20
+
21
+ # --------------------------------------------------------------------------
22
+ def app_count_models(self):
23
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
24
+ print(mu.Count.models(path_in))
25
+
26
+
27
+ # --------------------------------------------------------------------------
28
+ def app_count_chains(self):
29
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
30
+ print(len(mu.List.chains(path_in, do_sort = False)))
31
+
32
+
33
+ # --------------------------------------------------------------------------
34
+ def app_count_residues(self):
35
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
36
+ print(len(mu.List.residues(path_in, do_sort = False)))
37
+
38
+
39
+ # --------------------------------------------------------------------------
40
+ def app_count_frames(self):
41
+ path_struct = self.main.get_arg_path("path_struct", assertion = fy.PathAssertion.FILE_IN)
42
+ path_traj = self.main.get_arg_path("path_traj",
43
+ assertion = fy.PathAssertion.FILE_IN, allow_none = True
44
+ )
45
+ nframes_valid, nframes_expected = mu.Count.frames(path_struct, path_traj)
46
+ print(f"{nframes_valid}/{nframes_expected}")
47
+
48
+
49
+ # --------------------------------------------------------------------------
50
+ def app_count_altlocs(self):
51
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
52
+ print(mu.Count.altlocs(path_in))
53
+
54
+
55
+ # -------------------------------------------------------------------------- LOGIC SECTION
56
+ @classmethod
57
+ def models(cls, path_pdb: Path) -> int:
58
+ data = path_pdb.read_text()
59
+ return max(1, cls._count_substring('\n'+data, "\nMODEL"))
60
+
61
+
62
+ # --------------------------------------------------------------------------
63
+ @classmethod
64
+ def frames(cls, path_struct: Path, path_traj: Path | None) -> tuple[int, int]:
65
+ import MDAnalysis as mda
66
+ args_traj = [str(path_traj)] if path_traj is not None else []
67
+ u = mda.Universe(str(path_struct), *args_traj)
68
+
69
+ nframes_expected = u.trajectory.n_frames
70
+ nframes_valid = sum(1 for _ in u.trajectory)
71
+ return nframes_valid, nframes_expected
72
+
73
+
74
+ # --------------------------------------------------------------------------
75
+ @classmethod
76
+ def altlocs(cls, path_pdb: Path) -> int:
77
+ atoms: dict[str, str] = {}
78
+ pdb = mu.ParserPDB.from_file(path_pdb)
79
+
80
+ ### [TODO] adapt for extracting first altloc
81
+ for line in pdb.iter_atoms():
82
+ altloc = mu.ParserPDB.get_altloc(line)
83
+ if altloc == " ": continue
84
+
85
+ resid = mu.ChainResid.from_pdb(line).get_dotstr()
86
+ name = mu.ParserPDB.get_atomname(line)
87
+
88
+ key = f"{resid}.{name}"
89
+ if key in atoms: continue
90
+
91
+ atoms[key] = line
92
+
93
+ return len(atoms)
94
+
95
+
96
+ # --------------------------------------------------------------------------
97
+ @staticmethod
98
+ def _count_substring(string: str, substring: str) -> int:
99
+ """Counts the number of occurrences of `substring` in `string`."""
100
+ replaced = string.replace(substring, "")
101
+ return (len(string) - len(replaced)) // len(substring)
102
+
103
+
104
+ # //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,170 @@
1
+ from pathlib import Path
2
+ from collections import defaultdict
3
+
4
+ import freyacli as fy
5
+ import molutils as mu
6
+
7
+ # //////////////////////////////////////////////////////////////////////////////
8
+ class Extract(mu.AppSubcommand):
9
+ # -------------------------------------------------------------------------- UI SECTION
10
+ def run(self):
11
+ command = self.main.subcommands.pop(0)
12
+
13
+ if command == "models" : return self.app_extract_models()
14
+ if command == "chains" : return self.app_extract_chains()
15
+ if command == "residue": return self.app_extract_residue()
16
+ if command == "frames" : return self.app_extract_frames()
17
+
18
+ raise ValueError(f"Unknown command: {command}")
19
+
20
+ # --------------------------------------------------------------------------
21
+ def app_extract_models(self):
22
+ path_in, folder_out = self._io_filein_dirout()
23
+ data_pdb = path_in.read_text()
24
+
25
+ if self.main.get_arg_bool("first_only"):
26
+ _, model = mu.Extract.next_model(data_pdb)
27
+ path_out = folder_out / f"{path_in.stem}.m0.pdb"
28
+ path_out.write_text(model)
29
+ return
30
+
31
+ for i, model in enumerate(mu.Extract.iter_models(data_pdb)):
32
+ path_out = folder_out / f"{path_in.stem}.m{i:03}.pdb"
33
+ path_out.write_text(model)
34
+
35
+
36
+ # --------------------------------------------------------------------------
37
+ def app_extract_chains(self):
38
+ path_in, folder_out = self._io_filein_dirout()
39
+ data_pdb = path_in.read_text()
40
+
41
+ chains = mu.Extract.split_chains(data_pdb)
42
+
43
+ chain_ids = mu.List.chains(path_in, first_only = True) \
44
+ if self.main.get_arg_bool("first_only") else chains.keys()
45
+
46
+ for chain_id in chain_ids:
47
+ path_out = folder_out / f"{path_in.stem}.{chain_id}.pdb"
48
+ path_out.write_text(chains[chain_id])
49
+
50
+
51
+ # --------------------------------------------------------------------------
52
+ def app_extract_residue(self):
53
+ path_in, folder_out = self._io_filein_dirout()
54
+ data_pdb = path_in.read_text()
55
+
56
+ residue_dotstr = self.main.get_arg_str("residue")
57
+ chres = mu.ChainResid.from_dotstr(residue_dotstr)
58
+ extracted = mu.Extract.residue(data_pdb, chres.resid, chres.chain)
59
+
60
+ path_out = folder_out / f"{path_in.stem}.{residue_dotstr}.pdb"
61
+ path_out.write_text(extracted)
62
+
63
+
64
+ # --------------------------------------------------------------------------
65
+ def app_extract_frames(self):
66
+ path_struct, folder_out = self._io_filein_dirout(key_in = "path_struct")
67
+ path_traj = self.main.get_arg_path("path_traj",
68
+ assertion = fy.PathAssertion.FILE_IN, allow_none = True
69
+ )
70
+ frames = self.main.get_arg_int("frames", is_list = True)
71
+ unpack = self.main.get_arg_bool("unpack")
72
+ mu.Extract.frames(path_struct, path_traj, folder_out, frames, unpack)
73
+
74
+
75
+ # -------------------------------------------------------------------------- LOGIC SECTION
76
+ @classmethod
77
+ def next_model(cls, data: str, start: int = 0) -> tuple[int, str]:
78
+ idx_0 = data.find("\nMODEL", start)
79
+ if idx_0 == -1: return -1, data
80
+
81
+ idx_1 = data.find("\nENDMDL", idx_0)
82
+ if idx_1 == -1: return -1, data[idx_0:]
83
+
84
+ idx_1 += len("\nENDMDL")
85
+ return idx_1, data[idx_0:idx_1] + "\nEND"
86
+
87
+
88
+ # --------------------------------------------------------------------------
89
+ @classmethod
90
+ def iter_models(cls, data: str):
91
+ while data:
92
+ idx, model = cls.next_model(data)
93
+ yield model
94
+ if idx == -1: break
95
+ data = data[idx:]
96
+
97
+
98
+ # --------------------------------------------------------------------------
99
+ @classmethod
100
+ def split_chains(cls, data: str) -> dict[str, str]:
101
+ pdb = mu.ParserPDB(data)
102
+ chains = defaultdict(list)
103
+ for line in pdb.iter_atoms():
104
+ chain_id = mu.ParserPDB.get_chainid(line)
105
+ chains[chain_id].append(line)
106
+ return {
107
+ chain_id: mu.ParserPDB.join_lines(lines)
108
+ for chain_id, lines in chains.items()
109
+ }
110
+
111
+
112
+ # --------------------------------------------------------------------------
113
+ @classmethod
114
+ def residue(cls, data: str, resid: str, chain: str = None) -> str:
115
+ pdb = mu.ParserPDB(data)
116
+ gen_residue = (
117
+ line for line in pdb.iter_atoms()
118
+ if mu.ParserPDB.get_resid(line) == resid
119
+ )
120
+ if chain is not None: gen_residue = (
121
+ line for line in gen_residue
122
+ if mu.ParserPDB.get_chainid(line) == chain
123
+ )
124
+ return mu.ParserPDB.join_lines(gen_residue)
125
+
126
+
127
+ # --------------------------------------------------------------------------
128
+ @classmethod
129
+ def frames(cls,
130
+ path_struct: Path, path_traj: Path | None, folder_out: Path,
131
+ frames: list[int] = None, unpack: bool = False
132
+ ) -> None:
133
+ """Note: This method directly saves the specified frames instead of returning them."""
134
+ import MDAnalysis as mda
135
+
136
+ args_traj = [str(path_traj)] if path_traj is not None else []
137
+ u = mda.Universe(str(path_struct), *args_traj)
138
+
139
+ if frames is not None and len(frames) == 1:
140
+ unpack = True
141
+
142
+ if unpack:
143
+ if frames is None: frames = range(u.trajectory.n_frames)
144
+ for frame in frames:
145
+ u.trajectory[frame]
146
+ path_pdb_out = folder_out / f"{path_struct.stem}.{frame:04}.pdb"
147
+ u.atoms.write(str(path_pdb_out))
148
+ return
149
+
150
+ if path_traj is None:
151
+ ### save a struct file separately, useful when the input file
152
+ ### had both the struct and traj data inside (e.g. XYZ)
153
+ path_pdb_out = folder_out / f"{path_struct.stem}.sliced.pdb"
154
+ u.atoms.write(str(path_pdb_out))
155
+
156
+ path_xtc_out = folder_out / f"{path_struct.stem}.sliced.xtc"
157
+ u.atoms.write(str(path_xtc_out), frames = "all" if frames is None else frames)
158
+ return
159
+
160
+
161
+ # --------------------------------------------------------------------------
162
+ def _io_filein_dirout(self, key_in = "path_in") -> tuple[Path, Path]:
163
+ path_in = self.main.get_arg_path(key_in, assertion = fy.PathAssertion.FILE_IN)
164
+ folder_out = self.main.get_arg_path("folder_out",
165
+ default = path_in.parent, assertion = fy.PathAssertion.DIR_OUT
166
+ )
167
+ return path_in, folder_out
168
+
169
+
170
+ # //////////////////////////////////////////////////////////////////////////////
@@ -1,5 +1,6 @@
1
1
  from pathlib import Path
2
2
 
3
+ import freyacli as fy
3
4
  import molutils as mu
4
5
 
5
6
  # //////////////////////////////////////////////////////////////////////////////
@@ -9,45 +10,42 @@ class List(mu.AppSubcommand):
9
10
  command = self.main.subcommands.pop(0)
10
11
 
11
12
  if command == "chains": return self.app_list_chains()
12
- if command == "resids": return self.app_list_resids()
13
+ if command == "residues": return self.app_list_residues()
13
14
 
14
15
  raise ValueError(f"Unknown command: {command}")
15
16
 
16
17
 
17
18
  # --------------------------------------------------------------------------
18
19
  def app_list_chains(self):
19
- path_in = self.main.get_arg_path("path_in")
20
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
20
21
  first_only = self.main.get_arg_bool("first_only")
21
- self.main.assert_file_in(path_in)
22
- print(*mu.List.chains(path_in, first_only))
22
+ print(*mu.List.chains(path_in, first_only = first_only))
23
23
 
24
24
 
25
25
  # --------------------------------------------------------------------------
26
- def app_list_resids(self):
27
- path_in = self.main.get_arg_path("path_in")
28
- self.main.assert_file_in(path_in)
29
- print(*mu.List.resids(path_in))
26
+ def app_list_residues(self):
27
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
28
+ print(*mu.List.residues(path_in))
30
29
 
31
30
 
32
31
  # -------------------------------------------------------------------------- LOGIC SECTION
33
32
  @classmethod
34
- def chains(cls, path_pdb: Path, first_only: bool = False) -> list[str]:
33
+ def chains(cls, path_pdb: Path, do_sort: bool = True, first_only: bool = False) -> list[str]:
35
34
  pdb = mu.ParserPDB.from_file(path_pdb)
36
35
  gen_chain_ids = (mu.ParserPDB.get_chainid(line) for line in pdb.iter_atoms())
37
36
  if first_only: return mu.ParserPDB.safe_next(gen_chain_ids)
38
- return sorted(set(gen_chain_ids))
37
+ if do_sort: return sorted(set(gen_chain_ids))
38
+ return list(set(gen_chain_ids))
39
39
 
40
40
 
41
41
  # --------------------------------------------------------------------------
42
42
  @classmethod
43
- def resids(cls, path_pdb: Path) -> list[str]:
43
+ def residues(cls, path_pdb: Path, do_sort: bool = True) -> list[str]:
44
44
  """Returns list of unique residue identifiers in the format "chainid.resid"."""
45
45
  pdb = mu.ParserPDB.from_file(path_pdb)
46
- gen_resids = (
47
- f"{mu.ParserPDB.get_chainid(line)}.{mu.ParserPDB.get_resid(line)}"
48
- for line in pdb.iter_atoms()
49
- )
50
- return sorted(set(gen_resids))
46
+ gen_residues = (mu.ChainResid.from_pdb(line).get_dotstr() for line in pdb.iter_atoms())
47
+ if do_sort: return sorted(set(gen_residues))
48
+ return list(set(gen_residues))
51
49
 
52
50
 
53
51
  # //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,47 @@
1
+ import freyacli as fy
2
+ import molutils as mu
3
+
4
+ # //////////////////////////////////////////////////////////////////////////////
5
+ class Remove(mu.AppSubcommand):
6
+ # -------------------------------------------------------------------------- UI SECTION
7
+ def run(self):
8
+ command = self.main.subcommands.pop(0)
9
+
10
+ if command == "altlocs" : return self.app_remove_altlocs()
11
+
12
+ raise ValueError(f"Unknown command: {command}")
13
+
14
+
15
+ # --------------------------------------------------------------------------
16
+ def app_remove_altlocs(self):
17
+ path_in = self.main.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
18
+ path_out = self.main.get_arg_path("path_out", assertion = fy.PathAssertion.FILE_OUT)
19
+ out = mu.Remove.altlocs(path_in.read_text())
20
+ path_out.write_text(out)
21
+
22
+
23
+ # --------------------------------------------------------------------------
24
+ @classmethod
25
+ def altlocs(cls, data: str) -> str:
26
+ pdb = mu.ParserPDB(data)
27
+
28
+ out = []
29
+ seen_altlocs = set()
30
+ for line in pdb.iter_atoms():
31
+ altloc = mu.ParserPDB.get_altloc(line)
32
+ if altloc == " ":
33
+ out.append(line)
34
+ continue
35
+
36
+ resid = mu.ChainResid.from_pdb(line).get_dotstr()
37
+ name = mu.ParserPDB.get_atomname(line)
38
+ key = (resid, name)
39
+ if key in seen_altlocs: continue
40
+
41
+ seen_altlocs.add(key)
42
+ out.append(mu.ParserPDB.set_altloc(line, " "))
43
+
44
+ return mu.ParserPDB.join_lines(out)
45
+
46
+
47
+ # //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,34 @@
1
+ import molutils as mu
2
+
3
+ # //////////////////////////////////////////////////////////////////////////////
4
+ class ChainResid:
5
+ def __init__(self, chain: str, resid: str):
6
+ self.chain = chain
7
+ self.resid = resid
8
+
9
+
10
+ # --------------------------------------------------------------------------
11
+ @classmethod
12
+ def from_pdb(cls, line: str) -> "ChainResid":
13
+ """Parses an ATOM/HETATM line (PDB format) and returns a ChainResid instance."""
14
+ return cls(mu.ParserPDB.get_chainid(line), mu.ParserPDB.get_resid(line))
15
+
16
+
17
+ # --------------------------------------------------------------------------
18
+ @classmethod
19
+ def from_dotstr(cls, dotstr: str) -> "ChainResid":
20
+ """Parses a string in the format `chainid.resid`."""
21
+ parts = dotstr.split(".")
22
+ if len(parts) != 2:
23
+ raise ValueError(f"Invalid format for ChainResid: {dotstr}. Expected format: `chainid.resid`.")
24
+ chain, resid = parts
25
+ return cls(chain, resid)
26
+
27
+
28
+ # --------------------------------------------------------------------------
29
+ def get_dotstr(self) -> str:
30
+ """Returns a string in the format `chainid.resid`."""
31
+ return f"{self.chain}.{self.resid}"
32
+
33
+
34
+ # //////////////////////////////////////////////////////////////////////////////
@@ -3,6 +3,9 @@ from pathlib import Path
3
3
  # //////////////////////////////////////////////////////////////////////////////
4
4
  class ParserPDB:
5
5
  LENGTH_RECORD = 80
6
+ IDX0_ATOMNAME = 12
7
+ IDX1_ATOMNAME = 16
8
+ IDX_ALTLOC = 16
6
9
  IDX_CHAIN_ID = 21
7
10
  IDX0_RESID = 22
8
11
  IDX1_RESID = 26
@@ -39,6 +42,13 @@ class ParserPDB:
39
42
  except StopIteration: raise ValueError(f"No ATOM records found in PDB file")
40
43
 
41
44
 
45
+ # --------------------------------------------------------------------------
46
+ @classmethod
47
+ def get_atomname(cls, line: str) -> str:
48
+ try: return line[cls.IDX0_ATOMNAME:cls.IDX1_ATOMNAME].strip()
49
+ except IndexError: raise ValueError(f"Unexpected format of ATOM records in PDB file")
50
+
51
+
42
52
  # --------------------------------------------------------------------------
43
53
  @classmethod
44
54
  def get_chainid(cls, line: str) -> str:
@@ -52,4 +62,19 @@ class ParserPDB:
52
62
  return line[cls.IDX0_RESID:cls.IDX1_RESID].strip()
53
63
 
54
64
 
65
+ # --------------------------------------------------------------------------
66
+ @classmethod
67
+ def get_altloc(cls, line: str) -> str:
68
+ try: return line[cls.IDX_ALTLOC]
69
+ except IndexError: raise ValueError(f"Unexpected format of ATOM records in PDB file")
70
+
71
+
72
+ # --------------------------------------------------------------------------
73
+ @classmethod
74
+ def set_altloc(cls, line: str, altloc: str) -> str:
75
+ if len(altloc) != 1: raise ValueError(f"altloc must be a single character")
76
+ try: return line[:cls.IDX_ALTLOC] + altloc + line[cls.IDX_ALTLOC+1:]
77
+ except IndexError: raise ValueError(f"Unexpected format of ATOM records in PDB file")
78
+
79
+
55
80
  # //////////////////////////////////////////////////////////////////////////////
@@ -1,9 +1,7 @@
1
1
  from pathlib import Path
2
2
 
3
- import molutils as mu
4
-
5
3
  import freyacli as fy
6
-
4
+ import molutils as mu
7
5
 
8
6
  # //////////////////////////////////////////////////////////////////////////////
9
7
  class AppMain(fy.App):
@@ -27,19 +25,31 @@ class AppMain(fy.App):
27
25
  if command == "list" : return mu.List(self).run()
28
26
  if command == "count" : return mu.Count(self).run()
29
27
  if command == "extract": return mu.Extract(self).run()
28
+ if command == "remove" : return mu.Remove(self).run()
30
29
  if command == "select" : return self._run_select()
30
+ if command == "merge" : return self._run_merge()
31
31
  raise ValueError(f"Unknown command: {command}")
32
32
 
33
33
 
34
34
  # --------------------------------------------------------------------------
35
35
  def _run_select(self):
36
36
  query = self.get_arg_str("query")
37
- path_in = self.get_arg_path("path_in")
38
- path_out = self.get_arg_path("path_out")
39
- self.assert_file_in(path_in)
37
+ path_in = self.get_arg_path("path_in", assertion = fy.PathAssertion.FILE_IN)
38
+ path_out = self.get_arg_path("path_out", assertion = fy.PathAssertion.FILE_OUT)
40
39
 
41
40
  import MDAnalysis as mda
42
41
  mda.Universe(path_in).select_atoms(query).write(path_out)
43
42
 
44
43
 
44
+ # --------------------------------------------------------------------------
45
+ def _run_merge(self):
46
+ paths_in = self.get_arg_path("paths_in", assertion = fy.PathAssertion.FILE_IN, is_list = True)
47
+ path_out = self.get_arg_path("path_out", assertion = fy.PathAssertion.FILE_OUT)
48
+ data = mu.ParserPDB.join_lines(
49
+ line for path_in in paths_in
50
+ for line in mu.ParserPDB.from_file(path_in).iter_atoms()
51
+ )
52
+ path_out.write_text(data)
53
+
54
+
45
55
  # //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,97 @@
1
+ !fyh:_ molutils is a collection of tools for preprocessing or summarizing details from biomolecular structure files.
2
+
3
+ @list
4
+ !fyh:_ Lists the unique values for different aspects of biomolecular structures.
5
+ @chains
6
+ !fyh:_ Lists the chains in a PDB file.
7
+ !fyh:path_in Path of a PDB file.
8
+ !fyh:first_only Use this flag for displaying only the first chain of the structure.
9
+ !@
10
+ @residues
11
+ !fyh:_ Lists the residues in a PDB file in the format "chainid.resid".
12
+ !fyh:path_in Path of a PDB file.
13
+ !@
14
+ !@
15
+
16
+ @count
17
+ !fyh:_ Provides counts for different aspects of biomolecular structures.
18
+ @models
19
+ !fyh:_ Counts the number of models in a PDB file.
20
+ !fyh:path_in Path of a PDB file.
21
+ !@
22
+ @chains
23
+ !fyh:_ Counts the number of chains in a PDB file.
24
+ !fyh:path_in Path of a PDB file.
25
+ !@
26
+ @residues
27
+ !fyh:_ Counts the number of residues in a PDB file in the format "chainid.resid".
28
+ !fyh:path_in Path of a PDB file.
29
+ !@
30
+ @frames
31
+ !fyh:_ Counts the number of frames in a trajectory.
32
+ Reports both the expected number of frames (i.e. u.trajectory.n_frames) and the number of actual valid frames.
33
+ These are reported as "valid/expected" and might differ in some formats, like in XYZ.
34
+ Requires MDAnalysis.
35
+ !fyh:path_struct Path of the structure file (e.g. PDB file). Can be anything supported by MDanalysis.
36
+ If the file also contains the trajectory data (e.g. XYZ file), then "path_traj" can be ommitted.
37
+ !fyh:path_traj Path of the trajectory file (e.g. XTC file). Can be anything supported by MDanalysis.
38
+ !@
39
+ @altlocs
40
+ !fyh:_ Counts the number of atoms/heteroatoms in a PDB file that contain alternate locations (altloc).
41
+ Only counts one per atom, disregarding how many alternate locations it has.
42
+ !fyh:path_in Path of a PDB file.
43
+ !@
44
+ !@
45
+
46
+ @extract
47
+ !fyh:_ Extract specific sections of data from biomolecular structures.
48
+ @models
49
+ !fyh:_ Extracts the models in a PDB file into separate files.
50
+ !use:_io_filein_dirout
51
+ !fyh:first_only Use this flag for extracting only the first model of the structure and disregard the rest.
52
+ !@
53
+ @chains
54
+ !fyh:_ Extracts the chains in a PDB file into separate files.
55
+ !use:_io_filein_dirout
56
+ !fyh:first_only Use this flag for extracting only the first chain of the structure and disregard the rest.
57
+ !@
58
+ @residue
59
+ !fyh:_ Extract a specific residue from a PDB file into a separate file.
60
+ !use:_io_filein_dirout
61
+ !fyh:residue Residue to extract, in the format "chainid.resid".
62
+ !@
63
+ @frames
64
+ !fyh:_ Extract specific frames from a PDB file into separate file(s).
65
+ Requires MDAnalysis.
66
+ !fyh:path_struct Path of the structure file (e.g. PDB file). Can be anything supported by MDanalysis.
67
+ If the file also contains the trajectory data (e.g. XYZ file), then "path_traj" can be ommitted.
68
+ In this case, an additional structure file (a copy of the first frame) may be exported for convenience.
69
+ !fyh:path_traj Path of the trajectory file (e.g. XTC file). Can be anything supported by MDanalysis.
70
+ !fyh:folder_out Path of the directory where to place the unpacked structure(s).
71
+ If not provided, the parent directory of the input PDB file will be used.
72
+ !fyh:frames Frame indices to extract. If no frames are specified, all frames are extracted.
73
+ If only 1 frame is specified, the frame is exported to PDB (regardless of the "unpack" flag).
74
+ !fyh:unpack When used, the specified frames will be unpacked into single PDB files.
75
+ Otherwise, the frames are exported into a single XTC file.
76
+ !@
77
+ !@
78
+
79
+ @select
80
+ !fyh:_ Select specific atoms with a custom query (MDAnalysis format) and save them into a file. Requires MDAnalysis.
81
+ !fyh:query Query for selecting the atoms of interest. Must follow MDAnalysis format
82
+ !fyh:path_in Path of the structure file whose atoms will be selected. Can be anything supported by MDanalysis.
83
+ !fyh:path_out Path for the output selected atoms. Can be anything supported by MDanalysis.
84
+ !@
85
+
86
+ @merge
87
+ !fyh:_ Merge structures from multiple PDB files into a single PDB file.
88
+ !fyh:paths_in List of PDB file paths with the input structures to be merged.
89
+ At least one PDB file must be provided.
90
+ !fyh:path_out Path where to save the merged PDB structure.
91
+ !@
92
+
93
+ !def _io_filein_dirout
94
+ !fyh:path_in Path of a PDB file.
95
+ !fyh:folder_out Path of the directory where to place the unpacked structure(s).
96
+ If not provided, the parent directory of the input PDB file will be used.
97
+ !fed
@@ -0,0 +1,74 @@
1
+ @list
2
+ @chains
3
+ path_in[]1.PATH
4
+ ~first_only[f,first-only]
5
+ !@
6
+ @residues
7
+ path_in[]1.PATH
8
+ !@
9
+ !@
10
+
11
+ @count
12
+ @models
13
+ path_in[]1.PATH
14
+ !@
15
+ @chains
16
+ path_in[]1.PATH
17
+ !@
18
+ @residues
19
+ path_in[]1.PATH
20
+ !@
21
+ @frames
22
+ path_struct[]1.PATH
23
+ ~path_traj[]1.PATH
24
+ !@
25
+ @altlocs
26
+ path_in[]1.PATH
27
+ !@
28
+ !@
29
+
30
+ @extract
31
+ @models
32
+ !use:_io_filein_dirout
33
+ ~first_only[f,first-only]
34
+ !@
35
+ @chains
36
+ !use:_io_filein_dirout
37
+ ~first_only[f,first-only]
38
+ !@
39
+ @residue
40
+ path_in[]1.PATH
41
+ residue[]1.STR
42
+ ~folder_out[o,out]1.PATH
43
+ !@
44
+ @frames
45
+ path_struct[]1.PATH
46
+ ~path_traj[]1.PATH
47
+ ~folder_out[o,out]1.PATH
48
+ ~frames[f,frames]1+.INT
49
+ ~unpack[u,unpack]
50
+ !@
51
+ !@
52
+
53
+ @remove
54
+ @altlocs
55
+ path_in[]1.PATH
56
+ path_out[]1.PATH
57
+ !@
58
+ !@
59
+
60
+ @select
61
+ query[]1.STR
62
+ path_in[]1.PATH
63
+ path_out[]1.PATH
64
+ !@
65
+
66
+ @merge
67
+ paths_in[]1+.PATH
68
+ path_out[o,out]1.PATH
69
+ !@
70
+
71
+ !def _io_filein_dirout
72
+ path_in[]1.PATH
73
+ ~folder_out[]1.PATH
74
+ !fed
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: molutils
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: Collection of tools for preprocessing or summarizing details from biomolecular structure files.
5
5
  Home-page: https://github.com/diegobarmor/molutils
6
6
  Author: DiegoBarMor
@@ -12,7 +12,7 @@ Classifier: Operating System :: OS Independent
12
12
  Requires-Python: >=3.10
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE.md
15
- Requires-Dist: freyacli==0.3.2
15
+ Requires-Dist: freyacli==0.4.1
16
16
  Dynamic: author
17
17
  Dynamic: author-email
18
18
  Dynamic: classifier
@@ -15,7 +15,9 @@ molutils/_core/__init__.py
15
15
  molutils/_core/count.py
16
16
  molutils/_core/extract.py
17
17
  molutils/_core/list_.py
18
+ molutils/_core/remove.py
18
19
  molutils/_parsers/__init__.py
20
+ molutils/_parsers/chain_resid.py
19
21
  molutils/_parsers/parser_pdb.py
20
22
  molutils/_ui/__init__.py
21
23
  molutils/_ui/app_main.py
@@ -0,0 +1 @@
1
+ freyacli==0.4.1
@@ -21,7 +21,7 @@ setup(
21
21
  "_ui/fy_rules.fyr", "_ui/fy_help.fyh",
22
22
  ],
23
23
  },
24
- install_requires=["freyacli==0.3.2"],
24
+ install_requires=["freyacli==0.4.1"],
25
25
  entry_points={
26
26
  "console_scripts": [
27
27
  "molutils=molutils.__main__:main",
@@ -1,38 +0,0 @@
1
- from pathlib import Path
2
-
3
- import molutils as mu
4
-
5
- # //////////////////////////////////////////////////////////////////////////////
6
- class Count(mu.AppSubcommand):
7
- # -------------------------------------------------------------------------- UI SECTION
8
- def run(self):
9
- command = self.main.subcommands.pop(0)
10
-
11
- if command == "models": return self.app_count_models()
12
-
13
- raise ValueError(f"Unknown command: {command}")
14
-
15
-
16
- # --------------------------------------------------------------------------
17
- def app_count_models(self):
18
- path_in = self.main.get_arg_path("path_in")
19
- self.main.assert_file_in(path_in)
20
- print(mu.Count.models(path_in))
21
-
22
-
23
- # -------------------------------------------------------------------------- LOGIC SECTION
24
- @classmethod
25
- def models(cls, path_pdb: Path) -> int:
26
- data = path_pdb.read_text()
27
- return max(1, cls._count_substring('\n'+data, "\nMODEL"))
28
-
29
-
30
- # --------------------------------------------------------------------------
31
- @staticmethod
32
- def _count_substring(string: str, substring: str) -> int:
33
- """Counts the number of occurrences of `substring` in `string`."""
34
- replaced = string.replace(substring, "")
35
- return (len(string) - len(replaced)) // len(substring)
36
-
37
-
38
- # //////////////////////////////////////////////////////////////////////////////
@@ -1,94 +0,0 @@
1
- from collections import defaultdict
2
-
3
- import molutils as mu
4
-
5
- # //////////////////////////////////////////////////////////////////////////////
6
- class Extract(mu.AppSubcommand):
7
- # -------------------------------------------------------------------------- UI SECTION
8
- def run(self):
9
- command = self.subcommands.pop(0)
10
-
11
- if command == "models": return self.app_extract_models()
12
- if command == "chains": return self.app_extract_chains()
13
-
14
- raise ValueError(f"Unknown command: {command}")
15
-
16
- # --------------------------------------------------------------------------
17
- def app_extract_models(self):
18
- path_in = self.main.get_arg_path("path_in")
19
- self.main.assert_file_in(path_in)
20
-
21
- folder_out = self.main.get_arg_path("folder_out", default = path_in.parent)
22
- self.main.assert_dir_out(folder_out)
23
-
24
- data_pdb = path_in.read_text()
25
-
26
- if self.main.get_arg_bool("first_only"):
27
- _, model = mu.Extract.next_model(data_pdb)
28
- path_out = folder_out / f"{path_in.stem}.m0.pdb"
29
- path_out.write_text(model)
30
- return
31
-
32
- for i, model in enumerate(mu.Extract.iter_models(data_pdb)):
33
- path_out = folder_out / f"{path_in.stem}.m{i:03}.pdb"
34
- path_out.write_text(model)
35
-
36
-
37
- # --------------------------------------------------------------------------
38
- def app_extract_chains(self):
39
- path_in = self.main.get_arg_path("path_in")
40
- self.main.assert_file_in(path_in)
41
-
42
- folder_out = self.main.get_arg_path("folder_out", default = path_in.parent)
43
- self.main.assert_dir_out(folder_out)
44
-
45
- data_pdb = path_in.read_text()
46
-
47
- chains = mu.Extract.split_chains(data_pdb)
48
-
49
- chain_ids = mu.List.chains(path_in, first_only = True) \
50
- if self.main.get_arg_bool("first_only") else chains.keys()
51
-
52
- for chain_id in chain_ids:
53
- path_out = folder_out / f"{path_in.stem}.{chain_id}.pdb"
54
- path_out.write_text(chains[chain_id])
55
-
56
-
57
- # -------------------------------------------------------------------------- LOGIC SECTION
58
- @classmethod
59
- def next_model(cls, data: str, start: int = 0) -> tuple[int, str]:
60
- idx_0 = data.find("\nMODEL", start)
61
- if idx_0 == -1: return -1, data
62
-
63
- idx_1 = data.find("\nENDMDL", idx_0)
64
- if idx_1 == -1: return -1, data[idx_0:]
65
-
66
- idx_1 += len("\nENDMDL")
67
- return idx_1, data[idx_0:idx_1] + "\nEND"
68
-
69
-
70
- # --------------------------------------------------------------------------
71
- @classmethod
72
- def iter_models(cls, data: str):
73
- while data:
74
- idx, model = cls.next_model(data)
75
- yield model
76
- if idx == -1: break
77
- data = data[idx:]
78
-
79
-
80
- # --------------------------------------------------------------------------
81
- @classmethod
82
- def split_chains(cls, data: str) -> dict[str, str]:
83
- pdb = mu.ParserPDB(data)
84
- chains = defaultdict(list)
85
- for line in pdb.iter_atoms():
86
- chain_id = mu.ParserPDB.get_chainid(line)
87
- chains[chain_id].append(line)
88
- return {
89
- chain_id: mu.ParserPDB.join_lines(lines)
90
- for chain_id, lines in chains.items()
91
- }
92
-
93
-
94
- # //////////////////////////////////////////////////////////////////////////////
@@ -1,49 +0,0 @@
1
- !fyh:_ molutils is a collection of tools for preprocessing or summarizing details from biomolecular structure files.
2
-
3
- @list
4
- !fyh:_ Lists the unique values for different aspects of biomolecular structures.
5
- @chains
6
- !fyh:_ Lists the chains in a PDB file.
7
- !fyh:path_in Path of a PDB file.
8
- !fyh:first_only Use this flag for displaying only the first chain of the structure.
9
- !@
10
- @resids
11
- !fyh:_ Lists the residue identifiers in a PDB file in the format "chainid.resid".
12
- !fyh:path_in Path of a PDB file.
13
- !@
14
- !@
15
-
16
- @count
17
- !fyh:_ Provides counts for different aspects of biomolecular structures.
18
- @models
19
- !fyh:_ Counts the number of models in a PDB file.
20
- !fyh:path_in Path of a PDB file.
21
- !@
22
- !@
23
-
24
- @extract
25
- !fyh:_ Extract specific sections of data from biomolecular structures.
26
- @models
27
- !fyh:_ Extracts the models in a PDB file into separate files.
28
- !use:_extract
29
- !fyh:first_only Use this flag for extracting only the first model of the structure and disregard the rest.
30
- !@
31
- @chains
32
- !fyh:_ Extracts the chains in a PDB file into separate files.
33
- !use:_extract
34
- !fyh:first_only Use this flag for extracting only the first chain of the structure and disregard the rest.
35
- !@
36
- !@
37
-
38
- @select
39
- !fyh:_ Select specific atoms with a custom query (MDAnalysis format) and save them into a file. Requires MDAnalysis.
40
- !fyh:query Query for selecting the atoms of interest. Must follow MDAnalysis format
41
- !fyh:path_in Path of the structure file whose atoms will be selected. Can be anything supported by MDanalysis.
42
- !fyh:path_out Path for the output selected atoms. Can be anything supported by MDanalysis.
43
- !@
44
-
45
- !def _extract
46
- !fyh:path_in Path of a PDB file.
47
- !fyh:folder_out Path of the directory where to place the unpacked structures.
48
- If not provided, the parent directory of the input PDB file will be used.
49
- !fed
@@ -1,32 +0,0 @@
1
- @list
2
- @chains
3
- path_in[]1.PATH
4
- ~first_only[f,first-only]
5
- !@
6
- @resids
7
- path_in[]1.PATH
8
- !@
9
- !@
10
-
11
- @count
12
- @models
13
- path_in[]1.PATH
14
- !@
15
- !@
16
-
17
- @extract
18
- @models !use:_extract !@
19
- @chains !use:_extract !@
20
- !@
21
-
22
- @select
23
- query[]1.STR
24
- path_in[]1.PATH
25
- path_out[]1.PATH
26
- !@
27
-
28
- !def _extract
29
- path_in[]1.PATH
30
- ~folder_out[]1.PATH
31
- ~first_only[f,first-only]
32
- !fed
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"
@@ -1 +0,0 @@
1
- freyacli==0.3.2
File without changes
File without changes
File without changes
File without changes
File without changes