ArraySplitter 1.3.0__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.
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # @created: 05.06.2011
5
+ # @author: Aleksey Komissarov
6
+ # @contact: ad3002@gmail.com
7
+
8
+ import gzip
9
+
10
+
11
+ def sc_iter_fasta_file(file_name, inmem=False, lower=False):
12
+ """Iter over fasta file."""
13
+
14
+ header = None
15
+ seq = []
16
+ if file_name.endswith(".gz"):
17
+ opener = gzip.open
18
+ decoder = lambda x: x.decode("utf8")
19
+ else:
20
+ opener = open
21
+ decoder = lambda x: x
22
+
23
+ with opener(file_name) as fh:
24
+ if inmem:
25
+ data = [decoder(x) for x in fh.readlines()]
26
+ decoder = lambda x: x
27
+ else:
28
+ data = fh
29
+ for line in data:
30
+ line = decoder(line)
31
+ if line.startswith(">"):
32
+ if seq or header:
33
+ sequence = "".join(seq)
34
+ if lower:
35
+ sequence = sequence.lower()
36
+ yield header, sequence
37
+ header = line.strip()[1:]
38
+ seq = []
39
+ continue
40
+ seq.append(line.strip())
41
+ if seq or header:
42
+ sequence = "".join(seq)
43
+ if lower:
44
+ sequence = sequence.lower()
45
+ yield header, sequence
46
+
47
+
48
+ def sc_iter_arrays_fasta_file(fasta_file):
49
+ """Iter over fasta file and yield sequences."""
50
+ for header, sequence in sc_iter_fasta_file(fasta_file):
51
+ yield sequence
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # @created: 20.02.2024
5
+ # @author: Aleksey Komissarov
6
+ # @contact: ad3002@gmail.com
7
+
8
+ from .tab_file import sc_iter_tab_file
9
+ from ..models.trf_model import TRModel
10
+
11
+
12
+ def sc_iter_arrays_satellome_file(trf_file):
13
+ """Iter over satellome file."""
14
+ for trf_obj in sc_iter_tab_file(trf_file, TRModel):
15
+ yield trf_obj.trf_array
16
+
17
+ def sc_iter_satellome_file(trf_file):
18
+ """Iter over satellome file."""
19
+ for trf_obj in sc_iter_tab_file(trf_file, TRModel):
20
+ yield trf_obj.trf_id, trf_obj.trf_array
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # @created: 05.06.2011
5
+ # @author: Aleksey Komissarov
6
+ # @contact: ad3002@gmail.com
7
+ """
8
+ Classes:
9
+
10
+ - TabDelimitedFileIO(AbstractFileIO)
11
+
12
+ """
13
+ import csv
14
+ import os
15
+ import tempfile
16
+
17
+ from PyExp import AbstractFileIO
18
+
19
+ csv.field_size_limit(1000000000)
20
+
21
+
22
+ class TabDelimitedFileIO(AbstractFileIO):
23
+ """Working with tab delimited file.
24
+
25
+ Public methods:
26
+
27
+ - sort(self, sort_func, reversed=False)
28
+
29
+ Inherited public properties:
30
+
31
+ - data - iterable data, each item is tuple (head, body)
32
+ - N - a number of items in data
33
+
34
+ Overrided public methods:
35
+
36
+ - __init__(self, skip_first=False, format_func=None, delimeter="\\t", skip_startswith=None)
37
+ - write_to_file(self, output_file)
38
+ - read_from_file(self, input_file)
39
+ - read_online(self, input_file) ~> item
40
+
41
+ Inherited public methods:
42
+
43
+ - read_from_db(self, db_cursor)
44
+ - write_to_db(self, db_cursor)
45
+ - read_as_iter(self, source)
46
+ - iterate(self) ~> item of data
47
+ - do(self, cf, args) -> result
48
+ - process(self, cf, args)
49
+ - clear(self)
50
+ - do_with_iter(self, cf, args) -> [result,]
51
+ - process_with_iter(self, cf, args)
52
+
53
+ """
54
+
55
+ def __init__(
56
+ self, skip_first=False, format_func=None, delimeter="\t", skip_startswith="#"
57
+ ):
58
+ """Overrided. Set token velue.
59
+
60
+ Keyword arguments:
61
+
62
+ - skip_first -- skip first line in file
63
+ - format_funcs -- list of functions that format corresponding item in tab delimited line
64
+ - delimeter -- line delimeter
65
+ - skip_startswith -- skip lines starts with this value
66
+ """
67
+ super(TabDelimitedFileIO, self).__init__()
68
+
69
+ self.skip_first = skip_first
70
+ self.format_func = format_func
71
+ self.delimeter = delimeter
72
+ self.skip_startswith = skip_startswith
73
+
74
+ def read_from_file(self, input_file):
75
+ """OVerrided. Read data from tab delimeted input_file."""
76
+ with open(input_file) as fh:
77
+ self._data = fh.readlines()
78
+ if self.skip_first:
79
+ self._data.pop(0)
80
+ if self.skip_startswith:
81
+ self._data = [
82
+ line for line in self._data if not line.startswith(self.skip_startswith)
83
+ ]
84
+ self._data = [self._process_tab_delimeited_line(line) for line in self._data]
85
+
86
+ def read_online(self, input_file):
87
+ """Overrided. Yield items online from data from input_file."""
88
+ with open(input_file) as fh:
89
+ for i, line in enumerate(fh):
90
+ if self.skip_first and i == 0:
91
+ continue
92
+ if self.skip_startswith and line.startswith(self.skip_startswith):
93
+ continue
94
+ yield self._process_tab_delimeited_line(line)
95
+
96
+ def _process_tab_delimeited_line(self, line):
97
+ """Format line with format_func."""
98
+
99
+ line = line.strip().split(self.delimeter)
100
+ if self.format_func:
101
+ assert hasattr(self.format_func, "__call__")
102
+ line = self.format_func(line)
103
+ return line
104
+
105
+ def _all_str(self, line):
106
+ """Convert to string all items in line."""
107
+ return [str(x) for x in line]
108
+
109
+ def write_to_file(self, output_file):
110
+ """Overrided. Write data to tab delimited output_file."""
111
+ self._data = ["\t".join(self._all_str(line)) for line in self._data]
112
+ with open(output_file, "w") as fh:
113
+ fh.writelines(self._data)
114
+
115
+
116
+ def sc_iter_tab_file(
117
+ input_file,
118
+ data_type,
119
+ skip_starts_with="#",
120
+ remove_starts_with=None,
121
+ preprocess_function=None,
122
+ check_function=None,
123
+ ):
124
+ """Iter over tab file, yield an object of given data_type."""
125
+
126
+ temp_file = tempfile.NamedTemporaryFile(delete=False)
127
+ temp_file_name = temp_file.name
128
+
129
+ if remove_starts_with:
130
+ with open(input_file, "r") as fh:
131
+ data = fh.readlines()
132
+ data = [x for x in data if not x.startswith(remove_starts_with)]
133
+ with open(temp_file_name, "w") as fh:
134
+ fh.writelines(data)
135
+ input_file = temp_file_name
136
+ if preprocess_function:
137
+ with open(input_file, "r") as fh:
138
+ data = fh.readlines()
139
+ data = [preprocess_function(x) for x in data]
140
+ with open(temp_file_name, "w") as fh:
141
+ fh.writelines(data)
142
+ input_file = temp_file_name
143
+ if check_function:
144
+ with open(input_file, "r") as fh:
145
+ data = fh.readlines()
146
+ data = [x for x in data if check_function(x)]
147
+ with open(temp_file_name, "w") as fh:
148
+ fh.writelines(data)
149
+ input_file = temp_file_name
150
+ with open(input_file) as fh:
151
+ fields = data_type().dumpable_attributes
152
+ for data in csv.DictReader(
153
+ fh, fieldnames=fields, delimiter="\t", quoting=csv.QUOTE_NONE
154
+ ):
155
+ if skip_starts_with:
156
+ if data[fields[0]].startswith(skip_starts_with):
157
+ continue
158
+ obj = data_type()
159
+ obj.set_with_dict(data)
160
+ yield obj
161
+ if os.path.isfile(temp_file_name):
162
+ os.unlink(temp_file_name)
163
+
164
+
165
+ def sc_iter_simple_tab_file(input_file):
166
+ """Iter tab file, yield a list."""
167
+ with open(input_file) as fh:
168
+ for data in csv.reader(fh, delimiter="\t", quoting=csv.QUOTE_NONE):
169
+ yield data
170
+
171
+
172
+ def sc_read_dictionary(dict_file, value_func=None):
173
+ """Read file of tab-dilimited pairs.
174
+ key\tvalue
175
+ """
176
+ result = {}
177
+ with open(dict_file) as fh:
178
+ for data in csv.reader(fh, delimiter="\t", quoting=csv.QUOTE_NONE):
179
+ if hasattr(value_func, "__call__"):
180
+ data[1] = value_func(data[1])
181
+ result[data[0]] = data[1]
182
+ return result
183
+
184
+
185
+ def sc_write_model_to_tab_file(output_file, objs):
186
+ """Write model obj to tab-delimited file."""
187
+ with open(output_file, "w") as fh:
188
+ for obj in objs:
189
+ fh.write(str(obj))
190
+
191
+
192
+ def sc_read_simple_tab_file(input_file, skip_first=False):
193
+ """Iter tab file, yield a list."""
194
+ result = []
195
+ with open(input_file) as fh:
196
+ if skip_first:
197
+ fh.readline()
198
+ for data in csv.reader(fh, delimiter="\t", quoting=csv.QUOTE_NONE):
199
+ result.append(data)
200
+ return result
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # @created: 05.06.2011
5
+ # @author: Aleksey Komissarov
6
+ # @contact: ad3002@gmail.com
7
+
8
+ """
9
+ Classes:
10
+
11
+ - TRFFileIO(AbstractBlockFileIO)
12
+
13
+ """
14
+
15
+ from .block_file import AbstractBlockFileIO
16
+ from ..models.trf_model import TRModel
17
+
18
+
19
+ class TRFFileIO(AbstractBlockFileIO):
20
+ """Working with raw output from TRF."""
21
+
22
+ def __init__(self):
23
+ """Overridden. Hardcoded start token."""
24
+ token = "Sequence:"
25
+ super(TRFFileIO, self).__init__(token)
26
+
27
+ def iter_parse(self, trf_file, filter=True):
28
+ """Iterate over raw trf data and yield TRFObjs.
29
+
30
+ Args:
31
+ trf_file (str): The path to the TRF file.
32
+ filter (bool, optional): Whether to filter the TRF objects. Defaults to True.
33
+
34
+ Yields:
35
+ TRModel: The parsed TRF object.
36
+
37
+ """
38
+ for ii, (head, body, start, next) in enumerate(self.read_online(trf_file)):
39
+ head = head.replace("\t", " ")
40
+ obj_set = []
41
+ n = body.count("\n")
42
+ for i, line in enumerate(self._gen_data_line(body)):
43
+ trf_obj = TRModel()
44
+ trf_obj.set_raw_trf(head, None, line)
45
+ obj_set.append(trf_obj)
46
+ yield from obj_set
47
+
48
+ def _gen_data_line(self, data):
49
+ """Generate lines of data from the raw TRF data.
50
+
51
+ Args:
52
+ data (str): The raw TRF data.
53
+
54
+ Yields:
55
+ str: A line of data.
56
+
57
+ """
58
+ for line in data.split("\n"):
59
+ line = line.strip()
60
+ if line.startswith("Sequence"):
61
+ continue
62
+ if line.startswith("Parameters"):
63
+ continue
64
+ if not line:
65
+ continue
66
+ yield line
67
+
68
+
69
+ def sc_iter_arrays_trf_file(file_name):
70
+ """Iter over trf file."""
71
+ reader = TRFFileIO()
72
+ for trf_obj in reader.iter_parse(file_name):
73
+ yield trf_obj.trf_array
74
+
75
+ def sc_iter_trf_file(file_name):
76
+ """Iter over trf file."""
77
+ reader = TRFFileIO()
78
+ for trf_obj in reader.iter_parse(file_name):
79
+ yield trf_obj.trf_id, trf_obj.trf_array
File without changes
@@ -0,0 +1,332 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # @created: 14.06.2011
5
+ # @author: Aleksey Komissarov
6
+ # @contact: ad3002@gmail.com
7
+
8
+ import re
9
+
10
+ from PyExp import AbstractModel
11
+
12
+ from ..tools.parsers import (parse_chromosome_name,
13
+ parse_fasta_head,
14
+ trf_parse_head,
15
+ trf_parse_line)
16
+
17
+
18
+ def get_gc(sequence):
19
+ """Count GC content."""
20
+ length = len(sequence)
21
+ if not length:
22
+ return 0
23
+ count_c = sequence.count("c") + sequence.count("C")
24
+ count_g = sequence.count("g") + sequence.count("G")
25
+ gc = float(count_c + count_g) / float(length)
26
+ return float(gc)
27
+
28
+
29
+ def clear_sequence(sequence):
30
+ """Clear sequence (full alphabet):
31
+
32
+ - lower case
33
+ - \s -> ""
34
+ - [^actgn] -> ""
35
+ """
36
+ sequence = sequence.strip().upper()
37
+ sequence = re.sub("\s+", "", sequence)
38
+ return re.sub("[^actgnuwsmkrybdhvACTGNUWSMKRYBDHV\-]", "", sequence)
39
+
40
+
41
+ class TRModel(AbstractModel):
42
+ """Class for tandem repeat wrapping
43
+
44
+ Public properties:
45
+
46
+ Indexes:
47
+
48
+ - id,
49
+ - giid,
50
+ - trf_id,
51
+ - project,
52
+ - trf_gi
53
+
54
+ Coordinates:
55
+
56
+ - trf_l_ind,
57
+ - trf_r_indel
58
+
59
+ TR:
60
+
61
+ - trf_period,
62
+ - trf_n_copy,
63
+ - trf_pmatch,
64
+ - trf_pvar,
65
+ - trf_entropy,
66
+ - trf_array_length,
67
+ - trf_joined,
68
+ - trf_chr
69
+
70
+ Sequence:
71
+
72
+ - trf_consensus,
73
+ - trf_array
74
+
75
+ GC%:
76
+
77
+ - trf_array_gc,
78
+ - trf_consensus_gc
79
+
80
+ Other:
81
+
82
+ - trf_head,
83
+ - trf_params
84
+
85
+ Annotation:
86
+
87
+ - trf_family,
88
+ - trf_subfamily,
89
+ - trf_subsubfamily,
90
+ - trf_hor,
91
+ - trf_n_chrun,
92
+ - trf_n_refgenome,
93
+ - trf_ref_annotation,
94
+ - trf_bands_refgenome,
95
+ - trf_repbase,
96
+ - trf_strand
97
+
98
+ Dumpable attributes:
99
+
100
+ - "project",
101
+ - "id" (int),
102
+ - "trf_id" (int),
103
+ - "trf_type",
104
+ - "trf_family",
105
+ - "trf_family_prob",
106
+ - "trf_l_ind" (int),
107
+ - "trf_r_ind" (int),
108
+ - "trf_period" (int),
109
+ - "trf_n_copy" (float),
110
+ - "trf_pmatch" (float),
111
+ - "trf_pvar" (float),
112
+ - "trf_consensus",
113
+ - "trf_array",
114
+ - "trf_array_gc" (float),
115
+ - "trf_consensus_gc" (float),
116
+ - "trf_gi",
117
+ - "trf_head",
118
+ - "trf_param",
119
+ - "trf_array_length" (int),
120
+ - "trf_chr",
121
+ - "trf_joined" (int),
122
+ - "trf_superfamily",
123
+ - "trf_superfamily_ref",
124
+ - "trf_superfamily_self",
125
+ - "trf_subfamily",
126
+ - "trf_subsubfamily",
127
+ - "trf_family_network",
128
+ - "trf_family_self",
129
+ - "trf_family_ref",
130
+ - "trf_hor" (int),
131
+ - "trf_n_chrun" (int),
132
+ - "trf_ref_annotation",
133
+ - "trf_bands_refgenome",
134
+ - "trf_repbase",
135
+ - "trf_strand",
136
+
137
+ """
138
+
139
+ dumpable_attributes = [
140
+ "project",
141
+ "id",
142
+ "trf_id",
143
+ "trf_type",
144
+ "trf_family",
145
+ "trf_family_prob",
146
+ "trf_l_ind",
147
+ "trf_r_ind",
148
+ "trf_period",
149
+ "trf_n_copy",
150
+ "trf_pmatch",
151
+ "trf_pvar",
152
+ "trf_entropy",
153
+ "trf_consensus",
154
+ "trf_array",
155
+ "trf_array_gc",
156
+ "trf_consensus_gc",
157
+ "trf_gi",
158
+ "trf_head",
159
+ "trf_param",
160
+ "trf_array_length",
161
+ "trf_chr",
162
+ "trf_joined",
163
+ "trf_superfamily",
164
+ "trf_superfamily_ref",
165
+ "trf_superfamily_self",
166
+ "trf_subfamily",
167
+ "trf_subsubfamily",
168
+ "trf_family_network",
169
+ "trf_family_self",
170
+ "trf_family_ref",
171
+ "trf_hor",
172
+ "trf_n_chrun",
173
+ "trf_ref_annotation",
174
+ "trf_bands_refgenome",
175
+ "trf_repbase",
176
+ "trf_strand",
177
+ ]
178
+
179
+ int_attributes = [
180
+ "trf_l_ind",
181
+ "trf_r_ind",
182
+ "trf_period",
183
+ "trf_array_length",
184
+ "trf_joined",
185
+ "trf_hor",
186
+ "trf_n_chrun",
187
+ ]
188
+
189
+ float_attributes = [
190
+ "trf_n_copy",
191
+ "trf_family_prob",
192
+ "trf_entropy",
193
+ "trf_pmatch",
194
+ "trf_pvar",
195
+ "trf_array_gc",
196
+ "trf_consensus_gc",
197
+ ]
198
+
199
+ def set_project_data(self, project):
200
+ """Add project data to self.project."""
201
+ self.project = project
202
+
203
+ def set_raw_trf(self, head, body, line):
204
+ """Init object with data from parsed trf ouput.
205
+
206
+ Parameters:
207
+
208
+ - trf_obj: TRFObj instance
209
+ - head: parsed trf head
210
+ - body: parsed trf body
211
+ - line: parsed trf line
212
+ """
213
+ self.trf_param = 0
214
+ self.trf_head = trf_parse_head(head).strip()
215
+ self.trf_gi = parse_fasta_head(self.trf_head)[0]
216
+ self.trf_chr = parse_chromosome_name(self.trf_head)
217
+
218
+ (
219
+ self.trf_l_ind,
220
+ self.trf_r_ind,
221
+ self.trf_period,
222
+ self.trf_n_copy,
223
+ self.trf_l_cons,
224
+ self.trf_pmatch,
225
+ self.trf_indels,
226
+ self.trf_score,
227
+ self.trf_n_a,
228
+ self.trf_n_c,
229
+ self.trf_n_g,
230
+ self.trf_n_t,
231
+ self.trf_entropy,
232
+ self.trf_consensus,
233
+ self.trf_array,
234
+ ) = trf_parse_line(line)
235
+
236
+ self.trf_pmatch = float(self.trf_pmatch)
237
+ self.trf_pvar = int(100 - float(self.trf_pmatch))
238
+
239
+ try:
240
+ self.trf_l_ind = int(self.trf_l_ind)
241
+ except:
242
+ print("Error:", self)
243
+
244
+ self.trf_r_ind = int(self.trf_r_ind)
245
+ self.trf_period = int(self.trf_period)
246
+ self.trf_n_copy = float(self.trf_n_copy)
247
+
248
+ self.trf_consensus = clear_sequence(self.trf_consensus)
249
+ self.trf_array = clear_sequence(self.trf_array)
250
+
251
+ self.trf_array_gc = get_gc(self.trf_array)
252
+ self.trf_consensus_gc = get_gc(self.trf_consensus)
253
+ self.trf_chr = parse_chromosome_name(self.trf_head)
254
+ self.trf_array_length = len(self.trf_array)
255
+
256
+ def get_header_string(self):
257
+ """Get header string for tsv file."""
258
+ data = "\t".join(self.dumpable_attributes)
259
+ return f"#{data}\n"
260
+
261
+ def get_fasta_repr(self, add_project=False):
262
+ """Get array fasta representation, head - trf_id."""
263
+ if add_project:
264
+ return ">%s_%s\n%s\n" % (self.trf_id, self.project, self.trf_array)
265
+ else:
266
+ return ">%s\n%s\n" % (self.trf_id, self.trf_array)
267
+
268
+ @property
269
+ def fasta(self):
270
+ return self.get_fasta_repr()
271
+
272
+ def get_gff3_string(
273
+ self,
274
+ chromosome=True,
275
+ trs_type="complex_tandem_repeat",
276
+ probability=1000,
277
+ tool="PySatDNA",
278
+ prefix=None,
279
+ properties=None,
280
+ force_header=False,
281
+ ):
282
+ """Return TR in gff format."""
283
+ if chromosome and self.trf_chr and self.trf_chr != "?":
284
+ seqid = self.trf_chr
285
+ elif self.trf_gi and self.trf_gi != "Unknown":
286
+ seqid = self.trf_gi
287
+ else:
288
+ seqid = self.trf_head
289
+ features = []
290
+ if not properties:
291
+ properties = {}
292
+ for name, attr in properties.items():
293
+ features.append("%s=%s" % (name, getattr(self, attr)))
294
+ features = ";".join(features)
295
+ if prefix:
296
+ seqid = prefix + seqid
297
+ if self.trf_l_ind < self.trf_r_ind:
298
+ strand = "+"
299
+ else:
300
+ strand = "-"
301
+ self.trf_l_ind, self.trf_r_ind = self.trf_r_ind, self.trf_l_ind
302
+
303
+ if force_header:
304
+ seqid = self.trf_head
305
+ d = (
306
+ seqid,
307
+ tool,
308
+ trs_type,
309
+ self.trf_l_ind,
310
+ self.trf_r_ind,
311
+ probability,
312
+ strand,
313
+ ".",
314
+ features,
315
+ )
316
+ return "%s\n" % "\t".join(map(str, d))
317
+
318
+ def get_bed_string(self):
319
+ """Return TR in bed format."""
320
+ if self.trf_l_ind < self.trf_r_ind:
321
+ strand = "+"
322
+ else:
323
+ strand = "-"
324
+ self.trf_l_ind, self.trf_r_ind = self.trf_r_ind, self.trf_l_ind
325
+
326
+ seqid = self.trf_head
327
+ d = (
328
+ seqid,
329
+ self.trf_l_ind,
330
+ self.trf_r_ind,
331
+ )
332
+ return "%s\n" % "\t".join(map(str, d))
File without changes