SHEPHARD 0.2.3__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 (108) hide show
  1. shephard/.DS_Store +0 -0
  2. shephard/__init__.py +31 -0
  3. shephard/_version.py +1 -0
  4. shephard/apis/__init__.py +13 -0
  5. shephard/apis/albatross_api.py +211 -0
  6. shephard/apis/fasta.py +432 -0
  7. shephard/apis/metapredict_api.py +373 -0
  8. shephard/apis/uniprot.py +1899 -0
  9. shephard/data/README.md +21 -0
  10. shephard/data/look_and_say.dat +15 -0
  11. shephard/data/test_data/TS1_domains_idr.tsv +21 -0
  12. shephard/data/test_data/TS1_domains_idr_and_others.tsv +22 -0
  13. shephard/data/test_data/TS1_domains_pscore.tsv +2 -0
  14. shephard/data/test_data/TS1_protein_attributes.tsv +2 -0
  15. shephard/data/test_data/TS1_protein_attributes_several.tsv +5 -0
  16. shephard/data/test_data/TS1_sites.tsv +209 -0
  17. shephard/data/test_data/TS1_small_proteins.tsv +3 -0
  18. shephard/data/test_data/TS1_tracks_pscore.tsv +9 -0
  19. shephard/data/test_data/names.txt +9 -0
  20. shephard/data/test_data/seqs.fasta +98 -0
  21. shephard/data/test_data/testset_1.fasta +96 -0
  22. shephard/data/test_data/testset_1.fasta.fai +9 -0
  23. shephard/data/test_data/testset_1_ptms.tsv +3 -0
  24. shephard/data/test_data/ts1_bonus_sites.tsv +5 -0
  25. shephard/data/test_data/ts1_bonus_sites_bad.tsv +6 -0
  26. shephard/data/test_data/ts1_bonus_sites_bad2.tsv +5 -0
  27. shephard/domain.py +600 -0
  28. shephard/exceptions.py +106 -0
  29. shephard/general_utilities.py +169 -0
  30. shephard/interfaces/__init__.py +15 -0
  31. shephard/interfaces/interface_tools.py +350 -0
  32. shephard/interfaces/si_domains.py +750 -0
  33. shephard/interfaces/si_protein_attributes.py +431 -0
  34. shephard/interfaces/si_proteins.py +369 -0
  35. shephard/interfaces/si_sites.py +495 -0
  36. shephard/interfaces/si_tracks.py +828 -0
  37. shephard/protein.py +2409 -0
  38. shephard/proteome.py +1435 -0
  39. shephard/py.typed +0 -0
  40. shephard/sequence_utilities.py +73 -0
  41. shephard/site.py +602 -0
  42. shephard/tests/.ipynb_checkpoints/test_scratchpad-checkpoint.ipynb +33 -0
  43. shephard/tests/__init__.py +13 -0
  44. shephard/tests/conftest.py +110 -0
  45. shephard/tests/example_test_function.py +30 -0
  46. shephard/tests/output_test/all_symbols_test.tsv +2 -0
  47. shephard/tests/output_test/all_values_test.tsv +9 -0
  48. shephard/tests/output_test/all_values_test_from_list.tsv +9 -0
  49. shephard/tests/output_test/out_tracks.tsv +9 -0
  50. shephard/tests/output_test/readme.md +1 -0
  51. shephard/tests/output_test/shephard_track_phosres.tsv +1 -0
  52. shephard/tests/output_test/shephard_track_pscore.tsv +9 -0
  53. shephard/tests/output_test/test_domains.tsv +27 -0
  54. shephard/tests/output_test/test_domains_types.tsv +18 -0
  55. shephard/tests/output_test/test_sites.tsv +773 -0
  56. shephard/tests/output_test/track_phospho_track.tsv +1 -0
  57. shephard/tests/output_test/track_random_vals.tsv +1 -0
  58. shephard/tests/test_DomainInterface.py +33 -0
  59. shephard/tests/test_ProteinAttributesInterface.py +35 -0
  60. shephard/tests/test_ProteinInterface.py +27 -0
  61. shephard/tests/test_SiteInterface.py +36 -0
  62. shephard/tests/test_TrackInterface.py +46 -0
  63. shephard/tests/test_add_remove_annotations.py +115 -0
  64. shephard/tests/test_api_albatross.py +74 -0
  65. shephard/tests/test_api_metapredict.py +206 -0
  66. shephard/tests/test_api_uniprot_annotation.py +1066 -0
  67. shephard/tests/test_api_uniprot_live.py +127 -0
  68. shephard/tests/test_apis_fasta.py +95 -0
  69. shephard/tests/test_attribute_tools.py +77 -0
  70. shephard/tests/test_bugfix_regressions.py +262 -0
  71. shephard/tests/test_bugfix_regressions_0_2_3.py +428 -0
  72. shephard/tests/test_comprehensive_apis.py +155 -0
  73. shephard/tests/test_comprehensive_domain.py +227 -0
  74. shephard/tests/test_comprehensive_interfaces.py +432 -0
  75. shephard/tests/test_comprehensive_protein.py +408 -0
  76. shephard/tests/test_comprehensive_proteome.py +356 -0
  77. shephard/tests/test_comprehensive_site.py +210 -0
  78. shephard/tests/test_comprehensive_tools.py +314 -0
  79. shephard/tests/test_comprehensive_track.py +220 -0
  80. shephard/tests/test_domain_tools.py +258 -0
  81. shephard/tests/test_domains.py +254 -0
  82. shephard/tests/test_interfaces.py +23 -0
  83. shephard/tests/test_protein.py +298 -0
  84. shephard/tests/test_protein_site_functions.py +173 -0
  85. shephard/tests/test_proteome.py +157 -0
  86. shephard/tests/test_scratchpad.ipynb +455 -0
  87. shephard/tests/test_sequence_tools.py +45 -0
  88. shephard/tests/test_shephard.py +18 -0
  89. shephard/tests/test_si_domains.py +191 -0
  90. shephard/tests/test_si_sites.py +153 -0
  91. shephard/tests/test_si_tracks.py +512 -0
  92. shephard/tests/test_sites.py +42 -0
  93. shephard/tests/test_track_tools.py +89 -0
  94. shephard/tests/test_tracks.py +16 -0
  95. shephard/tools/__init__.py +15 -0
  96. shephard/tools/attribute_tools.py +99 -0
  97. shephard/tools/attribute_tools.py~ +94 -0
  98. shephard/tools/domain_tools.py +587 -0
  99. shephard/tools/experimental.py +155 -0
  100. shephard/tools/sequence_tools.py +111 -0
  101. shephard/tools/site_tools.py +118 -0
  102. shephard/tools/track_tools.py +126 -0
  103. shephard/track.py +480 -0
  104. shephard-0.2.3.dist-info/METADATA +131 -0
  105. shephard-0.2.3.dist-info/RECORD +108 -0
  106. shephard-0.2.3.dist-info/WHEEL +5 -0
  107. shephard-0.2.3.dist-info/licenses/LICENSE +57 -0
  108. shephard-0.2.3.dist-info/top_level.txt +1 -0
shephard/.DS_Store ADDED
Binary file
shephard/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """
2
+ SHEPHARD:
3
+ Sequence-based Hierarchical and Extendable Platform for High-throughput Analysis of Region of Disorder
4
+
5
+ Authors: Garrett M. Ginell & Alex S. Holehouse
6
+ Contact: (g.ginell@wustl.edu)
7
+
8
+ Holehouse Lab - Washington University in St. Louis
9
+ """
10
+ import os
11
+ from shephard.proteome import Proteome
12
+
13
+
14
+ # Generate _version.py if missing and in the Read the Docs environment
15
+ if os.getenv("READTHEDOCS") == "True" and not os.path.isfile('../shephard/_version.py'):
16
+ import versioningit
17
+ __version__ = versioningit.get_version('../')
18
+ else:
19
+ from ._version import __version__
20
+
21
+ def get_version():
22
+ return __version__
23
+
24
+ _ROOT = os.path.abspath(os.path.dirname(__file__))
25
+ def get_data(path):
26
+ """
27
+ This function
28
+ """
29
+ return os.path.join(_ROOT, 'data', path)
30
+
31
+
shephard/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.3"
@@ -0,0 +1,13 @@
1
+ """
2
+ SHEPHARD:
3
+ Sequence-based Hierarchical and Extendable Platform for High-throughput Analysis of Region of Disorder
4
+
5
+ Authors: Garrett M. Ginell & Alex S. Holehouse
6
+ Contact: (g.ginell@wustl.edu)
7
+
8
+ Holehouse Lab - Washington University in St. Louis
9
+ """
10
+
11
+ from . import uniprot
12
+ from . import fasta
13
+ from . import metapredict_api
@@ -0,0 +1,211 @@
1
+ ##
2
+ ## API into ALBATROSS
3
+ ##
4
+ ## For all APIS we do do not make hard dependencies, safe informative
5
+ ## import checking should be done.
6
+ ##
7
+
8
+
9
+ from shephard.exceptions import APIException
10
+
11
+ ## Check sparrow (the package in which ALBATROSS is implemented) is installed.
12
+ ## Note that a missing sparrow is only reported when one of the functions here
13
+ ## is actually called, so importing this module is always safe.
14
+ try:
15
+ from sparrow.predictors.batch_predict import batch_predict
16
+
17
+ except ModuleNotFoundError:
18
+ batch_predict = None
19
+
20
+
21
+ ## ------------------------------------------------------------------------
22
+ ##
23
+ def _check_sparrow():
24
+ """
25
+ Internal function that ensures sparrow is installed. Called at the top of
26
+ every public function in this module.
27
+
28
+ Returns
29
+ -----------------
30
+ None
31
+ No return type, but raises an APIException if sparrow is missing.
32
+
33
+ """
34
+
35
+ if batch_predict is None:
36
+ raise APIException('Unable to import sparrow (the package where ALBATROSS is implemented).\nTo use ALBATROSS, make sure sparrow is installed. This can be done as follows:\n\npip install git+https://git@github.com/idptools/sparrow.git')
37
+
38
+
39
+ ## ------------------------------------------------------------------------
40
+ ##
41
+ def annotate_proteome_with_dimensions(proteome,
42
+ rg_name = 'rg',
43
+ re_name = 're',
44
+ gpuid=00,
45
+ show_progress_bar=True,
46
+ batch_mode=None,
47
+ safe=True):
48
+ """
49
+ Function that annotates a proteome with it's predicted radius
50
+ of gyration (rg) and end-to-end distance (re) for every protein.
51
+
52
+ By default, rg and re are added as attributes to each Protein, with
53
+ the names 'rg' and 're' respectively. However, this can be changed
54
+ by setting the `rg_name` and `re_name` parameters.
55
+
56
+ Dimension prediction uses the batch mode in sparrow, which
57
+ leverages parallel predictions automatically on GPUs or CPUs.
58
+ However, if a specific device is requested, this can be passed via
59
+ the `gpuid` parameter.
60
+
61
+ Parameters
62
+ -----------------
63
+ proteome : shephard.proteome.Proteome
64
+ Proteome object to be annotated.
65
+
66
+ rg_name : str
67
+ Name of the rg attribute added to each Protein.
68
+
69
+ re_name : str
70
+ Name of the re attribute added to each Protein.
71
+
72
+ gpuid : int
73
+ Identifier for the GPU being requested. Note that if
74
+ this is left unset the code will use the first GPU available
75
+ and if none is available will default back to CPU; in
76
+ general, it is recommended not to try and set this unless
77
+ there's a specific reason why a specific GPU should be
78
+ used. Default = 0.
79
+
80
+ show_progress_bar : bool
81
+ Flag which, if set to True, means a progress bar is printed as
82
+ predictions are made, while if False no progress bar is printed.
83
+ Default = True
84
+
85
+ batch_mode : None
86
+ Deprecated and ignored - sparrow always uses batch mode here. Retained
87
+ so existing code that passes this keyword continues to work.
88
+
89
+ safe : bool
90
+ Flag which, if set to False, means the function overwrites
91
+ existing tracks and domains if present. If True, overwriting
92
+ will trigger an exception.
93
+ Default = True.
94
+
95
+ Returns
96
+ -----------------
97
+ None
98
+ No return type, but the Protein objects in the Proteome
99
+ will be annotated with per-residue disorder Tracks.
100
+
101
+ """
102
+
103
+ _check_sparrow()
104
+
105
+ uid2seq = {}
106
+ for p in proteome:
107
+ uid2seq[p.unique_ID] = p.sequence
108
+
109
+ # batch predict dimensions for all proteins
110
+ rg = batch_predict(uid2seq, network='scaled_rg', gpuid=gpuid, show_progress_bar=show_progress_bar)
111
+ re = batch_predict(uid2seq, network='scaled_re', gpuid=gpuid, show_progress_bar=show_progress_bar)
112
+
113
+ # add as an attribute to the proteins
114
+ for k in rg:
115
+ proteome.protein(k).add_attribute(rg_name, rg[k][1], safe=safe)
116
+
117
+ for k in re:
118
+ proteome.protein(k).add_attribute(re_name, re[k][1], safe=safe)
119
+
120
+
121
+
122
+ ## ------------------------------------------------------------------------
123
+ ##
124
+ def annotate_domains_with_dimensions(proteome,
125
+ domain_type,
126
+ rg_name = 'rg',
127
+ re_name = 're',
128
+ gpuid=00,
129
+ show_progress_bar=True,
130
+ batch_mode=None,
131
+ safe=True):
132
+ """
133
+ Function that annotates every domain matching the domain_name in
134
+ a proteome with it's predicted radius of gyration (rg) and end-to-end
135
+ distance (re).
136
+
137
+ By default, rg and re are added as attributes to each Domain, with
138
+ the names 'rg' and 're' respectively. However, this can be changed
139
+ by setting the `rg_name` and `re_name` parameters.
140
+
141
+ Dimension prediction uses the batch mode in sparrow, which
142
+ leverages parallel predictions automatically on GPUs or CPUs.
143
+ However, if a specific device is requested, this can be passed via
144
+ the `gpuid` parameter.
145
+
146
+ Parameters
147
+ -----------------
148
+ proteome : shephard.proteome.Proteome
149
+ Proteome object to be annotated.
150
+
151
+ domain_type : str
152
+ Type of the domain to be annotated.
153
+
154
+ rg_name : str
155
+ Name of the rg attribute added to each Protein.
156
+
157
+ re_name : str
158
+ Name of the re attribute added to each Protein.
159
+
160
+ gpuid : int
161
+ Identifier for the GPU being requested. Note that if
162
+ this is left unset the code will use the first GPU available
163
+ and if none is available will default back to CPU; in
164
+ general, it is recommended not to try and set this unless
165
+ there's a specific reason why a specific GPU should be
166
+ used. Default = 0.
167
+
168
+ show_progress_bar : bool
169
+ Flag which, if set to True, means a progress bar is printed as
170
+ predictions are made, while if False no progress bar is printed.
171
+ Default = True
172
+
173
+ batch_mode : None
174
+ Deprecated and ignored - sparrow always uses batch mode here. Retained
175
+ so existing code that passes this keyword continues to work.
176
+
177
+ safe : bool
178
+ Flag which, if set to False, means the function overwrites
179
+ existing tracks and domains if present. If True, overwriting
180
+ will trigger an exception.
181
+ Default = True.
182
+
183
+ Returns
184
+ -----------------
185
+ None
186
+ No return type, but the Protein objects in the Proteome
187
+ will be annotated with per-residue disorder Tracks.
188
+
189
+ """
190
+
191
+ _check_sparrow()
192
+
193
+ # build the dictionary of keys to sequences. Note we key on the position of the
194
+ # domain in the list rather than on unique_ID + domain_name; domain names are
195
+ # unique within a protein, but concatenating the two is ambiguous if a unique_ID
196
+ # itself contains an underscore
197
+ target_domains = [d for d in proteome.domains if d.domain_type == domain_type]
198
+
199
+ uid2seq = {}
200
+ for idx, d in enumerate(target_domains):
201
+ uid2seq[str(idx)] = d.sequence
202
+
203
+ # batch predict dimensions for all domains
204
+ rg = batch_predict(uid2seq, network='scaled_rg', gpuid=gpuid, show_progress_bar=show_progress_bar)
205
+ re = batch_predict(uid2seq, network='scaled_re', gpuid=gpuid, show_progress_bar=show_progress_bar)
206
+
207
+ for idx, d in enumerate(target_domains):
208
+ d.add_attribute(rg_name, rg[str(idx)][1], safe=safe)
209
+ d.add_attribute(re_name, re[str(idx)][1], safe=safe)
210
+
211
+
shephard/apis/fasta.py ADDED
@@ -0,0 +1,432 @@
1
+ """
2
+ SHEPHARD:
3
+ Sequence-based Hierarchical and Extendable Platform for High-throughput Analysis of Region of Disorder
4
+
5
+ Authors: Garrett M. Ginell & Alex S. Holehouse
6
+ Contact: (g.ginell@wustl.edu)
7
+
8
+ Holehouse Lab - Washington University in St. Louis
9
+ """
10
+
11
+ import protfasta
12
+ from shephard.proteome import Proteome
13
+ from shephard.exceptions import APIException
14
+
15
+ SHEPHARD_ATTRIBUTE_SPLITTER='SHPRD_ATTRIBUTES='
16
+
17
+ ## ------------------------------------------------------------------------
18
+ ##
19
+ def fasta_to_proteome(filename,
20
+ proteome=None,
21
+ build_unique_ID=None,
22
+ build_attributes=None,
23
+ use_header_as_unique_ID=False,
24
+ force_overwrite=False,
25
+ invalid_sequence_action='fail'):
26
+ """
27
+ Stand alone function that allows the user to build a Proteome from a
28
+ standard FASTA file, or add sequences in a FASTA file to an existing
29
+ Proteome.
30
+
31
+ This function can be used to read additional sequences into an existing
32
+ Proteome object, or create a new Proteome object from a FASTA file.
33
+ In addition, some control over how invalid sequences should be dealt
34
+ with are defined by the invalid_sequence_action flag.
35
+
36
+ The input filename must be a FASTA file without duplicate headers. If
37
+ the file has duplicate headers and these have to be further processed
38
+ we suggest using the protfasta (https://protfasta.readthedocs.io/)
39
+ package to parse through the FASTA file first creating a santizied
40
+ input FASTA.
41
+
42
+ The FASTA file is parsed into a set of proteins, each of which has (1)
43
+ a unique ID, (2) a name, (3) a sequence, and (4) optionally, a
44
+ dictionary of attributes.
45
+
46
+ The protein name is defined as the full FASTA header, and the
47
+ sequence based on the FASTA record sequence. Sequence validation is
48
+ also provided at the point of file-parsing. The unique ID and
49
+ attributes are discused below.
50
+
51
+ Each protein in a Proteome must have a unique_ID associated with it.
52
+ There are three ways a FASTA file can be used to generate a unique ID:
53
+
54
+ 1. By using the FASTA header as a unique ID, although this fails
55
+ if there are non-unique FASTA headers.
56
+
57
+ 2. By parsing the FASTA header, to extract out a unique ID. For
58
+ example, FASTA files generated by other databases often include
59
+ unique identifiers in a structured way, which could be extracted
60
+ in a consistent manner for every FASTA record.
61
+
62
+ 3. By incrementing an automatically unique ID, removing any
63
+ dependence on the FASTA header itself.
64
+
65
+ These options can be selected using the flags provided in the function
66
+ signature. Note that if both using the FASTA header directly and parsing
67
+ the FASTA header are selected an exception will be raised as only one
68
+ of these two can be requested simultaneously.
69
+
70
+ By default, a numerically unique value is used. Note that if your are
71
+ reading FASTA files generated by UniProt, we recommend the api.uniprot
72
+ functions instead of the more generic api.fasta functions.
73
+
74
+ To build protein attributes, this can in principle be parsed out of the
75
+ FASTA header by providing a build_attributes() function. However, we
76
+ would in general suggest that the better way to do this would be annotate
77
+ a Proteome with attribibutes and the same those using the associated
78
+ interfaces.si_protein_attributes functionality.
79
+
80
+
81
+ Parameters
82
+ ------------
83
+
84
+ filename : string
85
+ Name of the FASTA file we're going to parse in.
86
+
87
+ proteome : Proteome (default = None)
88
+ If a Proteome object is provided the FASTA file will be read and
89
+ added to the existing proteome, whereas if set to None a new
90
+ Proteome will be generated.
91
+
92
+ build_unique_ID : funct (default = None)
93
+ This parameter allows a user-defined function that is used to
94
+ convert the FASTA header to a (hopefully) unique string. This can
95
+ be useful if the FASTA header is well structured and includes
96
+ a specific, useful unique ID that can be used as the unique_ID.
97
+
98
+ Specifically, the build_unique_ID function should take in the
99
+ a str (a FASTA header) and return a string which will be used
100
+ as a unique ID.
101
+
102
+ build_attributes : funct (default = None)
103
+ This parameter allows a user-defined function that allows
104
+ meta-information from the FASTA header to be converted into
105
+ protein attributes. Specifically, build_attributes should be a
106
+ function which takes in the FASTA header as a string and returns
107
+ a dictionary where key:value pairs are assigned as protein attributes.
108
+ This can be useful if the FASTA header is well-structured.
109
+
110
+ use_header_as_unique_ID : bool (default = False)
111
+ If this flag is set to true, it means the unique_ID is set to the FASTA
112
+ file header. If non-unique headers are found this will trigger an
113
+ exception.
114
+
115
+ force_overwrite : bool (default = False)
116
+ If this flag is set to true and we encounter a unique_ID that is
117
+ already in the proteome the newer value overwrites the older one.
118
+ This is mostly useful if you are adding in a file with known
119
+ duplicate entries OR combining multiple FASTA files where you know
120
+ there's some duplications. Important - if we're building unique IDs
121
+ based on numerical record indices then EVERY FASTA entry will be given
122
+ a unique_ID (meaning force_overwrite is irrelevant in this case).
123
+
124
+ invalid_sequence_action : str (default = 'fail')
125
+ Selector which defines the behaviour if a sequence with a non-
126
+ standard amino acid is encountered. Valid options and their meaning
127
+ are listed below:
128
+
129
+ * ``ignore`` - invalid sequences are completely ignored.
130
+
131
+ * ``fail`` - invalid sequence cause parsing to fail and throw an exception.
132
+
133
+ * ``remove`` - invalid sequences are removed.
134
+
135
+ * ``convert`` - invalid residues are converted to valid residues.
136
+
137
+ * ``convert-ignore`` - invalid sequences are converted to valid sequences and any remaining invalid residues are ignored.
138
+
139
+
140
+ Returns
141
+ --------
142
+ Proteome
143
+ Returns an initialized Proteome object
144
+
145
+ """
146
+
147
+ # parameter sanity checking
148
+ if use_header_as_unique_ID is True and build_unique_ID is not None:
149
+ raise APIException('Cannot simultaneously set use_header_as_unique_ID = True and build_unique_ID to not None')
150
+
151
+ # read in the fasta file using protfasta
152
+ fasta_dictionary = protfasta.read_fasta(filename, invalid_sequence_action=invalid_sequence_action)
153
+
154
+ # extract the keys (FASTA headers) and initialize the record_index (internal
155
+ # numbering used for construction. Also initialize the proteom_dict, which is
156
+ # a dictionary of protein entries we passed to Proteome.
157
+ record_index = 0
158
+
159
+ # IF we're adding to a new proteome this bit of code sets the record_index to the largest new integer
160
+ # such that we can add multiple proteomes in succession and we'll get a proteome where there are numerically
161
+ # contigous unique_IDs. Note we only do this if we'll be using the record_index
162
+ if proteome is not None and build_unique_ID is None and use_header_as_unique_ID is False:
163
+ numeric_record_ids = []
164
+ for uid in proteome.proteins:
165
+ try:
166
+ numeric_record_ids.append(int(uid))
167
+ except ValueError:
168
+ pass
169
+ if len(numeric_record_ids) > 0:
170
+ record_index = max(numeric_record_ids)+1
171
+
172
+ # initialize the empty list
173
+ proteome_list = []
174
+
175
+ # for each entry
176
+ for k in fasta_dictionary:
177
+
178
+ # create a key-value pair where
179
+ # key = the unique record_index (this is only used for internal structure
180
+ # within this function to assure we never overwrite in this dictionary
181
+ #
182
+ # value = a four-position list where the positions reflect the following
183
+ # [0] = amino acid sequence
184
+ # [1] = name (this can be anything)
185
+ # [2] = unique_ID - this should be a unique identifier that can be used
186
+ # to cross-reference this entry to other data. If extrat_unique_ID
187
+ # is passed we try to use this
188
+ # [3] = attribute dictionary (we set this to None)
189
+
190
+
191
+ # get unique_ID
192
+ if build_unique_ID:
193
+ unique_ID = build_unique_ID(k)
194
+ elif use_header_as_unique_ID is True:
195
+ unique_ID = k
196
+ else:
197
+ unique_ID = str(record_index)
198
+
199
+ # build an attributes dictionary using the user-provided custom function
200
+ if build_attributes:
201
+ attributes = build_attributes(k)
202
+ else:
203
+ attributes = {}
204
+
205
+ # now create an input dictionary orbject
206
+ newdict = {}
207
+ newdict['sequence'] = str(fasta_dictionary[k])
208
+ newdict['name'] = k
209
+ newdict['unique_ID'] = unique_ID
210
+ newdict['attributes'] = attributes
211
+
212
+ proteome_list.append(newdict)
213
+
214
+ record_index = record_index + 1
215
+
216
+ # finally if a proteome was provided then
217
+ if proteome is not None:
218
+ proteome.add_proteins(proteome_list, force_overwrite=force_overwrite)
219
+ return proteome
220
+ else:
221
+ # no proteome provided so build a new proteome and return it
222
+ return Proteome(proteome_list, force_overwrite=force_overwrite)
223
+
224
+
225
+
226
+ ## ------------------------------------------------------------------------
227
+ ##
228
+ def shephard_fasta_to_proteome(filename,
229
+ proteome = None,
230
+ force_overwrite=False,
231
+ invalid_sequence_action='fail'):
232
+
233
+ """
234
+ Stand alone function that allows the user to build a proteome
235
+ from a FASTA file generated by SHEPHARD (using the proteome_to_fasta()
236
+ function. When SHEPHARD generates a FASTA file it uses a general
237
+ convention for encoding the unique ID, protein name, and attributes.
238
+
239
+ Specifically, the FASTA header has the form
240
+
241
+ >SHPRD|<UNIQUE_ID>|<PROTEIN_NAME|SHPRD_ATTRIBUTES=<ATTRIBUTE_NAME>=<ATTRIBUTE_VALUE>\t
242
+
243
+ Where an arbitrary number of name/value attribute paris can be encoded
244
+ separated by a tab character.
245
+
246
+ WARNING: The support for protein attributes in FASTA files is included
247
+ mainly for easy sharing of FASTA files that are usable outside of
248
+ SHEPHARD. We recommend using interfaces.si_protein_attributes functions
249
+ for dealing with Protein attributes.
250
+
251
+
252
+ Parameters
253
+ ------------
254
+
255
+ filename : str
256
+ Name of the FASTA file we're going to parse in.
257
+
258
+ proteome : Proteome (default = None)
259
+ If a Proteome object is provided the FASTA file will be read and
260
+ added to the existing proteome, whereas if set to None a new
261
+ Proteome will be generated.
262
+
263
+ force_overwrite : bool (default = False)
264
+ If this flag is set to true and we encounter a unique_ID that is
265
+ already in the proteome the newer value overwrites the older one.
266
+ This is mostly useful if you are adding in a file with known
267
+ duplicate entries OR combining multiple FASTA files where you know
268
+ there's some duplications. Important - if we're building unique IDs
269
+ based on numerical record indices then EVERY FASTA entry will be given
270
+ a unique_ID (meaning force_overwrite is irrelevant in this case).
271
+
272
+ invalid_sequence_action : str (default = 'fail')
273
+ Selector which defines the behaviour if a sequence with a non-
274
+ standard amino acid is encountered. Valid options and their meaning
275
+ are listed below:
276
+
277
+ * ``ignore`` - invalid sequences are completely ignored.
278
+
279
+ * ``fail`` - invalid sequence cause parsing to fail and throw an exception.
280
+
281
+ * ``remove`` - invalid sequences are removed.
282
+
283
+ * ``convert`` - invalid residues are converted to valid residues.
284
+
285
+ * ``convert-ignore`` - invalid sequences are converted to valid sequences and any remaining invalid residues are ignored.
286
+
287
+
288
+ Returns
289
+ --------
290
+ Proteome Object
291
+ Returns an initialized Proteome object
292
+
293
+ """
294
+
295
+ # read in the fasta file using protfasta
296
+ fasta_dictionary = protfasta.read_fasta(filename, invalid_sequence_action=invalid_sequence_action)
297
+
298
+ # initialize the empty list
299
+ proteome_list = []
300
+
301
+ # for each entry
302
+ for k in fasta_dictionary:
303
+
304
+ # because we know what the header format will be we can be definitive about extracting the relevant information
305
+ fasta_split = k.split('|')
306
+
307
+ # ENSURE EVERY single line is a valid
308
+ if fasta_split[0] != "SHPRD":
309
+ raise APIException(f'Trying to parse a FASTA file that is expected to be SHEPHARD generated but formatting does not comply [on entry {k} in file {filename}]')
310
+
311
+ # extract out
312
+ try:
313
+ # get the unique ID
314
+ unique_ID = fasta_split[1]
315
+
316
+ # then take everything after the unique_ID
317
+ tmp = "|".join(fasta_split[2:])
318
+ attributes_string = tmp.split(SHEPHARD_ATTRIBUTE_SPLITTER)
319
+
320
+ # note the rstrip() - the writer separates the name from the attribute
321
+ # block with a space, and without stripping it the name picks up a
322
+ # trailing space every time it round-trips through a FASTA file
323
+ name = attributes_string[0].rstrip()
324
+ except IndexError:
325
+ raise APIException(f'Trying to parse a FASTA file that is expected to be SHEPHARD generated but formatting does not comply [on entry {k} in file {filename}]')
326
+
327
+ attributes_dict = {}
328
+
329
+ if len(attributes_string) > 1:
330
+ attributes_string_s = attributes_string[1].split('\t')
331
+
332
+ for a in attributes_string_s:
333
+
334
+ # the writer emits a leading tab after SHPRD_ATTRIBUTES=
335
+ # so skip empty tokens rather than creating a spurious
336
+ # '' : '' attribute
337
+ a = a.strip()
338
+ if a == '':
339
+ continue
340
+
341
+ # partition on the first '=' so attribute values that
342
+ # themselves contain '=' are preserved, and the value is
343
+ # the value (not a duplicate of the key)
344
+ local_k, _, local_v = a.partition('=')
345
+ attributes_dict[local_k.strip()] = local_v.strip()
346
+
347
+ # now create an protein dictionary object and populate!
348
+ newdict = {}
349
+ newdict['sequence'] = str(fasta_dictionary[k])
350
+ newdict['name'] = name
351
+ newdict['unique_ID'] = unique_ID
352
+ newdict['attributes'] = attributes_dict
353
+
354
+ proteome_list.append(newdict)
355
+
356
+ # finally if a proteome was provided then
357
+ if proteome is not None:
358
+ proteome.add_proteins(proteome_list, force_overwrite=force_overwrite)
359
+ return proteome
360
+ else:
361
+ # no proteome provided so build a new proteome and return it
362
+ return Proteome(proteome_list, force_overwrite=force_overwrite)
363
+
364
+
365
+ ## ------------------------------------------------------------------------
366
+ ##
367
+ def proteome_to_fasta(filename, proteome, include_attributes_in_header=False):
368
+ """
369
+ Stand alone function that allows the user to write a SHEPHARD-specific
370
+ FASTA file from a Proteome object.
371
+
372
+ WARNING: The support for protein attributes in FASTA files is included
373
+ mainly for easy sharing of FASTA files that are usable outside of
374
+ SHEPHARD. We recommend using interfaces.si_protein_attributes functions
375
+ for dealing with Protein attributes.
376
+
377
+ Parameters
378
+ ------------
379
+ filename : str
380
+ Name of the FASTA file we're going to write to. We will automatically
381
+ overwrite a file if it's there, so be careful! Note that no extension
382
+ is added in part because FASTA files can be .f/.fa/.fasta.
383
+ Recommended a .fasta file extension.
384
+
385
+ proteome : Proteome
386
+ The proteome object that will be written to disk
387
+
388
+ include_attributes_in_header : bool (default = False)
389
+ Flag which if set to true means each Protein's attributes will be
390
+ included in the FASTA header. We generally do not recommend this
391
+ other than times when sharing annotated FASTA files outside of a
392
+ SHEPHARD ecosystem would be useful.
393
+
394
+ Returns
395
+ -----------
396
+ None
397
+ No return object but a new file will be written
398
+
399
+ """
400
+
401
+ # build output list with or without the unique_ID
402
+ outlist = []
403
+ for protein in proteome:
404
+
405
+ # this is where we define the FASTA header...
406
+ fasta_header = f"SHPRD|{protein.unique_ID}|{protein.name}"
407
+
408
+ # this is where we append the FASTA header with attributes
409
+ if include_attributes_in_header:
410
+
411
+ fasta_header = fasta_header + " " + SHEPHARD_ATTRIBUTE_SPLITTER
412
+
413
+ for k in protein.attributes:
414
+
415
+ # these lines ensure there are no tabs in the attribute names of
416
+ # values before we append them to the header file, ensuring that
417
+ # IF we want to read the fasta header info back in to attributes
418
+ # we can be confident that hidden tabs in the variables won't
419
+ # mess things up!
420
+ k_fixed = str(k).replace('\t', ' ' )
421
+ i = protein.attribute(k)
422
+ i_fixed = str(i).replace('\t', ' ')
423
+
424
+ fasta_header = fasta_header + '\t' + f"{k_fixed}={i_fixed}"
425
+
426
+ outlist.append([fasta_header, protein.sequence])
427
+
428
+ # use the protfasta library to write the file to disk
429
+ protfasta.write_fasta(outlist, filename, linelength=80)
430
+
431
+
432
+