-
Notifications
You must be signed in to change notification settings - Fork 45
Hw4 bobkov #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Hw4 bobkov #8
Changes from all commits
299cd03
e5cae11
8e0ed9b
3eede33
1bf4f43
f025570
6917d98
ad7bf5b
843eb68
fa17b0d
d2b0584
b7a67dc
441b615
6574d2c
1e2fd63
968a091
fea73ed
4ef3eac
80be85d
5f2770d
c54a7ae
627721b
fec205a
26f6b8b
61eed0b
5891196
4a80750
6b78362
b0f927d
da10f7b
612dceb
4cda1c1
1aa6619
763eb0d
d91ccdd
fb74369
a15a4c3
a730b35
3a6fbc8
859fead
1e5c186
12fc927
84d8b4b
28f2075
fdd87f5
f0cb458
b683dd9
04de74f
ce992ed
06ff93d
b6bd43c
0f37939
4b820d7
af86f0d
d40e3e9
5f83179
ab3d60c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,120 @@ | ||||||
# protein_tools.py | ||||||
> *Discription how the protein_tools.py works:* | ||||||
This program contains the function `protein_tool`. The `protein_tool` function takes as input an arbitrary number of arguments in the form of amino acid (aa)/protein sequences of type *str*, as well as the name for the procedure to be performed. After this, the function performs the specified action on all provided sequences. Carefully read the rules of usage for each option, because they specify correct ways of entering arguments, as well as the output and the type of data in the output. | ||||||
### :warning: Attention: | ||||||
### 1)> The programm is register-dependent. | ||||||
### 2)> Before using some of the options read 'Procedures description' carefully. | ||||||
### 3)> If you input sequenses or 'options' incorrectly, the program will provide you with helpful error messages. | ||||||
Comment on lines
+4
to
+7
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Кажется тут немного перебор с оформлением) |
||||||
|
||||||
**list of options:** | ||||||
|
||||||
- 'compare' - Compare amino acids between reference sequence and other sequences; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут можно было бы сделать не одинарные кавычки, а штрихи (на букве Ё) чтобы оформить эти опции как код.
Suggested change
|
||||||
- 'length'- Сount the number of amino acids in protein sequence(s); | ||||||
- 'percentage' - Count percentage of each amino acid in sequence; | ||||||
- 'pattern' - Find all non-overlaping instances of a given pattern in sequences; | ||||||
- '3Letter_name' - Transform into a three-letter amino acids entry; | ||||||
- 'DNA_code' - Transform protein sequence(s) to DNA sequence(s). | ||||||
|
||||||
|
||||||
# Procedures description | ||||||
## compare | ||||||
### Introduction | ||||||
Comment on lines
+19
to
+21
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Понимаю что вы шли просто последовательно по заголовкам разного уровня. Но итогово опять же выглядит немного перегруженно. |
||||||
The **compare** procedure compares the first amino acid sequence provided with the following ones. | ||||||
### Inputs | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я бы эти штуки оформил не как заголовки, а просто жирным. |
||||||
To start using the length procedure, enter sevreal arguments: | ||||||
- _an arbitrary number_ of sequences, where the first sequence is a reference to which the following sequences are compared; each argument should be of type 'str'. | ||||||
- _second-to-last_ argument is the number of decimals to round the number to; type 'int' | ||||||
- _last_ argument determines whether percentages are returned instead of fractions; type 'bool' | ||||||
### Outputs | ||||||
It returns a 'dict' object where: | ||||||
- *keys* are compared-to sequences (type str) | ||||||
- *values* are either fractions or percentages (type float). | ||||||
### Usage example | ||||||
```python | ||||||
protein_tool('LAlLAlwWGPdPA', 'LAlLAl', 3, False, options = 'compare') # {'LAlLAl': 1.0} | ||||||
protein_tool('LAlLAlwWGPdPA', 'LAlLAl', 'GPdPA', 3, True, options = 'compare')) # {'LAlLAl': 100.0, 'GPdPA': 20.0} | ||||||
Comment on lines
+32
to
+35
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔥 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. только у меня это дело падает с ошибкой)) |
||||||
``` | ||||||
|
||||||
## length | ||||||
### Introduction | ||||||
The **length** procedure calculates the length of protein sequence(s) (equal to the number of amino acids). | ||||||
### Inputs | ||||||
To start using the length procedure, enter one or more protein sequences for which you want to get a summary, and at the end add `options = ‘length’`. | ||||||
### Outputs | ||||||
The result of the procedure is a list with the numbers of amino acids in each sequence. The list contains only numbers of amico acids in the sequence. | ||||||
### Usage example | ||||||
```python | ||||||
protein_tool('LAlLAlwWGPdPA', options = 'length') # [13] | ||||||
protein_tool('RRRrrrR', 'WGPdPA', 'LAlLAlw', options = 'length') # [7, 6, 7] | ||||||
``` | ||||||
|
||||||
## percentage | ||||||
### Introduction | ||||||
The **percentage** procedure calculates the percentage of all 20 proteinogenic amino acid residues, case-sensitive in the protein sequence. | ||||||
### Inputs | ||||||
To start using the count_percentage procedure, enter one or more protein sequences for which you want to get a summary, and at the end add `options = ‘percentage’`. | ||||||
### Outputs | ||||||
The result of the procedure is a list of dictionaries with the percentages of the corresponding amino acids in each sequence. The dictionary contains only amino acid residues whose percentage in the sequence is not equal to 0 (which are contained in the sequence at all). Also, the dictionary is ordered from the largest percentage of content to the smallest. Cases of amino acid residues are taken into account. | ||||||
> :warning: Attention: We use rounding to 2 decimal places. In some cases, **the sum of percentages** of all amino acid residues for sequence **may not be exactly 100%** due to rounding. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔥 |
||||||
### Usage example | ||||||
```python | ||||||
protein_tool('LAlLAlwWGPdPA', options = 'percentage') # [{'A': 23.08, 'L': 15.38, 'l': 15.38, 'P': 15.38, 'w': 7.69, 'W': 7.69, 'G': 7.69, 'd': 7.69}] | ||||||
protein_tool('RRRrrrR', 'WGPdPA', 'LAlLAlw', options = 'percentage') # [{'R': 57.14, 'r': 42.86}, {'P': 33.33, 'W': 16.67, 'G': 16.67, 'd': 16.67, 'A': 16.67}, {'L': 28.57, 'A': 28.57, 'l': 28.57, 'w': 14.29}] | ||||||
``` | ||||||
|
||||||
## pattern | ||||||
### Introduction | ||||||
The **pattern** procedure finds all non-overlaping cases of a given pattern in amino acid sequence(s) provided. | ||||||
### Inputs | ||||||
To start using the pattern procedure, enter one or more protein sequences for which you want to get a summary, where the first sequence is a pattern, which is searched for in the following sequences; each argument should be of type 'str' and at the end add `options = ‘pattern’`. | ||||||
The *find_pattern()* function goes through a sequence in the following way: it takes a subsequence of amino acids in front of an index equal in length to the pattern and compares it to the pattern. If there is no match, index is moved one amino acid to the end of the sequence. If there is a match, the index is saved, and the function jumps to an aminoacid next to the end of the subsequence, then the algorithm repeats. Comparison is performed by *compare_pattern* subfunction. | ||||||
The image explanation of that function. | ||||||
 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Йоу, круто! Только jpg тоже можно было бы назвать более информативно |
||||||
|
||||||
### Outputs | ||||||
The result of this procedure is a 'dict' object where: | ||||||
- *keys* are amino acid sequences (type 'str') | ||||||
- _values_ are lists where the first element is a number of pattern instances in a given sequence, and the following elements are indexes of these occurances | ||||||
### Usage example | ||||||
```python | ||||||
protein_tool('LAlLAlwWGPdPA', 'LAlLAl', 'GPdPA', options = 'pattern') # {'LAlLAl': [2, 0, 3], 'GPdPA': [0]} | ||||||
protein_tool('LAlLAlwWGPdPA', 'AlLAl', options = 'pattern') # {'AlLAl': [1, 2]} | ||||||
``` | ||||||
|
||||||
## 3Letter_name | ||||||
### Introduction | ||||||
The **3Letter_name** procedure transforms one-letter amino acid entry sequences to three-letter amino acid sequences, separated by a specified separator. It is a case-sensitive procedure. | ||||||
### Inputs | ||||||
To start using the rename_three_letter_name procedure, enter one or more protein sequences for which you want to get three-letter sequences. After the protein sequences put a symbol (type 'str') that will be a separator. And specify the `options = ‘3Letter_name’`. | ||||||
### Outputs | ||||||
The result of the procedure is a list of three-letter sequences. Each amino acid is separated by the specified separator. The case of the three-letter amino acid coincides with the case of the one-letter designation at the input. | ||||||
### Usage example | ||||||
```python | ||||||
protein_tool('wWGPdPA', '', options = '3Letter_name') # ['trpTRPGLYPROaspPROALA'] | ||||||
protein_tool('LAlLAlwWGPdPA', '-', options = '3Letter_name') # ['LEU-ALA-leu-LEU-ALA-leu-trp-TRP-GLY-PRO-asp-PRO-ALA'] | ||||||
protein_tool('RRRrrrR', 'WGPdPA', 'LAlLAlw', options = 'percentage') # [{'R': 57.14, 'r': 42.86}, {'P': 33.33, 'W': 16.67, 'G': 16.67, 'd': 16.67, 'A': 16.67}, {'L': 28.57, 'A': 28.57, 'l': 28.57, 'w': 14.29}] | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. этого тут не должно быть вроде |
||||||
protein_tool('qwerty', 'G', options = '3Letter_name') # ['glnGtrpGgluGargGthrGtyr'] | ||||||
``` | ||||||
|
||||||
## DNA_code | ||||||
### Introduction | ||||||
The **DNA_code** procedure transforms a protein into a DNA sequence that may encode it (this can be used in genetic ingeneering). | ||||||
P.S. codons chosen at the discretion of the tool authors. | ||||||
### Inputs | ||||||
To start using the DNA_code procedure, enter one or more protein sequences for which you want to get a summary, and at the end add `options = ‘DNA_code’`. | ||||||
### Outputs | ||||||
The result of the procedure is a list with type 'str' elements - nucleotide sequence that corresponds to the amino acid sequence. | ||||||
### Usage example | ||||||
```python | ||||||
protein_tool('LAlLAlwWGPdPA', options = 'DNA_code') # ['TTAGCAttaTTAGCAttatggTGGGGGCCCgcaCCCGCA'] | ||||||
protein_tool('RRRrrrR', 'WGPdPA', 'LAlLAlw', options = 'DNA_code') # ['CGACGACGAcgacgacgaCGA', 'TGGGGGCCCgcaCCCGCA', 'TTAGCAttaTTAGCAttatgg'] | ||||||
``` | ||||||
|
||||||
# Contacts | ||||||
[Gleb Bobkov](https://github.com/GlebBobkov): teamlead, count_length and transform_to_DNA_code functions; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Круто что указали обязанности каждого члена команды! |
||||||
[Dmitry Matach](https://github.com/zmitserbio): compare, find_pattern functions, is_protein, string_check, verify; | ||||||
[Olga Bagrova](https://github.com/Olga-Bagrova): count_percentage and rename_three_letter_name functions. | ||||||
|
||||||
|
||||||
 | ||||||
|
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,220 @@ | ||||||||||||||||||||||||||||||||||||
def compare(sequences: list, round_dec=3, percentages=False)->dict: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Пробелы и аннотация типов:
Suggested change
|
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Compare aminoacids between reference sequence and other sequences | ||||||||||||||||||||||||||||||||||||
arguments: | ||||||||||||||||||||||||||||||||||||
- sequences (list): reference sequence and other sequences for comparison | ||||||||||||||||||||||||||||||||||||
- round_dec (int): a number of decimals to round the number to | ||||||||||||||||||||||||||||||||||||
- percentages (bool): whether percentages are returned instead of fractions | ||||||||||||||||||||||||||||||||||||
return: | ||||||||||||||||||||||||||||||||||||
- comparisons (dict): dictionary with compared sequences as keys and percentages/fractions as their values | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
comparisons={} | ||||||||||||||||||||||||||||||||||||
for seq in range(1,len(sequences)): | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Так,
Suggested change
|
||||||||||||||||||||||||||||||||||||
comparison=[] | ||||||||||||||||||||||||||||||||||||
for j in range(0,len(sequences[seq])): | ||||||||||||||||||||||||||||||||||||
comparison.append(sequences[0][j]==sequences[seq][j]) | ||||||||||||||||||||||||||||||||||||
Comment on lines
+14
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. У вас программа падает с ошибкой если сиквенс 0 короче чем какой-то из тех с которыми сравниваете) |
||||||||||||||||||||||||||||||||||||
if percentages: | ||||||||||||||||||||||||||||||||||||
comparisons[sequences[seq]]=round(sum(comparison)*100/len(sequences[seq]),round_dec) | ||||||||||||||||||||||||||||||||||||
else: | ||||||||||||||||||||||||||||||||||||
comparisons[sequences[seq]]=round(sum(comparison)/len(sequences[seq]),round_dec) | ||||||||||||||||||||||||||||||||||||
return comparisons | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В целом функция конечно ок, за исключением момента с ошибкой. Но выглядит довольно громоздко. В первую очередь главное что вы написали логику, это главное. Мне на самом деле только не нравится что вы сравниваете прям по буквам. Это конечно ок, но все таки когда у вас 3хбуквенный код, то сравнивать надо не буквы а аминокислоты. А аминокислоты это же по 3 буквы. Чтобы вы понимали, работает правильно! Я про логику. Можно было бы перевести в однобуквенный код или шагать по 3 символа за раз. Чтобы чуть упростить сам код, тут могу рассказать про следующую штуковину в питоне для итерирования: При этом оно автоматически решает проблему с тем что что-то может быть короче другого. Попробуйте погонять код ниже, чтобы понять о чем я for z in zip('123', 'ABC'):
print(z)
for z in zip('12', 'ABC'):
print(z)
for z in zip('123', 'AB'):
print(z) |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def count_length(protein: str) -> list: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ну уж вы совсем упростили себе задачу) Хотя б добавили поддержку 3х-буквенного кода))) |
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Сounting the length of an amino acid sequence/protein in the number of amino acids | ||||||||||||||||||||||||||||||||||||
:param protein: sequence of protein | ||||||||||||||||||||||||||||||||||||
:return: number of amino acids in an amino acid sequence/protein | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
length_p = len(protein) | ||||||||||||||||||||||||||||||||||||
return length_p | ||||||||||||||||||||||||||||||||||||
Comment on lines
+29
to
+30
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def count_percentage(seq: str)->dict: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В целом ок, но обычно такие вещи с "содержанием чего-то" называются используя слова в духе info или stats. |
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Count percentage of each amino acid in sequence | ||||||||||||||||||||||||||||||||||||
arguments: | ||||||||||||||||||||||||||||||||||||
- seq (str): sequence for counting | ||||||||||||||||||||||||||||||||||||
return: | ||||||||||||||||||||||||||||||||||||
- dict: dictionary with counted percentage | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
l = count_length(seq) | ||||||||||||||||||||||||||||||||||||
res = {} | ||||||||||||||||||||||||||||||||||||
for aa in seq: | ||||||||||||||||||||||||||||||||||||
if aa not in res: | ||||||||||||||||||||||||||||||||||||
res[aa] = 1 | ||||||||||||||||||||||||||||||||||||
else: | ||||||||||||||||||||||||||||||||||||
res[aa]+=1 | ||||||||||||||||||||||||||||||||||||
res.update((key, round(value/l*100, 2)) for key, value in res.items()) | ||||||||||||||||||||||||||||||||||||
Comment on lines
+43
to
+48
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В целом ок, здорово что сделали это дело за 1 проход. Можно кстати наверное сразу было бы добавлять единичку деленную на длину. Хотя с другой стороны тут у вас разнесена четко логика: отдельно подсчет штук, отдельно получение процента. Тоже ок. Только за пробелами следите) Ну и res ок, хотя можно было бы информативно как то назвать. Если вы его сразу возвращаете, то ладно. А тут вы с ним еще работу какую-то делаете, тогда лучше более осмысленно назвать. |
||||||||||||||||||||||||||||||||||||
res={key: value for key, value in sorted(res.items(), key=lambda item: item[1], reverse=True)} | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Жуть, ахахах. Хотя кажется тут так это и делается. В любом случае идея отсортировать по процентам кажется хорошей. |
||||||||||||||||||||||||||||||||||||
return res | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def compare_pattern(sequence: str, pattern: str)->bool: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Из названия не совсем понятно что в функции должно происходить) |
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Compare a given pattern to a fragment of sequence of the same length | ||||||||||||||||||||||||||||||||||||
arguments: | ||||||||||||||||||||||||||||||||||||
- sequence (str): sequence fragment to compare with the pattern | ||||||||||||||||||||||||||||||||||||
- pattern (str): pattern for comparison | ||||||||||||||||||||||||||||||||||||
return: | ||||||||||||||||||||||||||||||||||||
- (bool): whether pattern and fragment match | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
for i in range(0,len(sequence)): | ||||||||||||||||||||||||||||||||||||
if not sequence[i]==pattern[i]: | ||||||||||||||||||||||||||||||||||||
Comment on lines
+62
to
+63
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ну-у, смотрите Если идейно вещи похожие, но биологический смысл разный, то имеет смысл написать какую-то общую функцию-начинку, которая будет вызываться и там и там. |
||||||||||||||||||||||||||||||||||||
return False | ||||||||||||||||||||||||||||||||||||
break | ||||||||||||||||||||||||||||||||||||
Comment on lines
+64
to
+65
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А зачем break после return? Мы же если попадем на return то уже аж из функции выйдем, не то что из цикла) |
||||||||||||||||||||||||||||||||||||
return True | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def find_pattern(sequences: list, pattern: str)->dict: | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Find all non-overlaping instances of a given pattern in sequences | ||||||||||||||||||||||||||||||||||||
arguments: | ||||||||||||||||||||||||||||||||||||
- sequences (list): sequences to find the pattern in | ||||||||||||||||||||||||||||||||||||
- pattern (str): pattern in question | ||||||||||||||||||||||||||||||||||||
return | ||||||||||||||||||||||||||||||||||||
- finds(dict): dictionary with sequences as keys and lists of indexes of patterns and the number of patterns as values | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
finds={} | ||||||||||||||||||||||||||||||||||||
for j in range(0, len(sequences)): | ||||||||||||||||||||||||||||||||||||
find=[] | ||||||||||||||||||||||||||||||||||||
for i in range(0, len(sequences[j])): | ||||||||||||||||||||||||||||||||||||
if compare_pattern(sequences[j][i:i+len(pattern)], pattern): | ||||||||||||||||||||||||||||||||||||
find.append(i) | ||||||||||||||||||||||||||||||||||||
i+=len(pattern) | ||||||||||||||||||||||||||||||||||||
else: | ||||||||||||||||||||||||||||||||||||
continue | ||||||||||||||||||||||||||||||||||||
Comment on lines
+84
to
+85
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это кажется и не особо нужно) |
||||||||||||||||||||||||||||||||||||
finds[sequences[j]]=[len(find)]+find | ||||||||||||||||||||||||||||||||||||
return finds | ||||||||||||||||||||||||||||||||||||
Comment on lines
+68
to
+87
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. С одной стороны здорово что вы попробовали пописать эту логику сами руками. С другой стороны, так-то у строки уже есть метод find. В принципе вполне валидно было бы использовать уже имеющийся функционал. |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def transform_to_DNA_code(protein): | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Transforming of an amino acid sequence/protein to DNA sequence | ||||||||||||||||||||||||||||||||||||
:param protein: amino acid sequence of protein | ||||||||||||||||||||||||||||||||||||
:return: sequence of protein in the DNA sequence form | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
retrnaslation_dict = { | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Такие вещи лучше определять в начале модуля вне всех функций и называть капсом. На консультации 03.10.2023 мы это подробно обсуждали, советую глянуть. |
||||||||||||||||||||||||||||||||||||
'F': 'TTC', 'f': 'ttc', | ||||||||||||||||||||||||||||||||||||
'L': 'TTA', 'l': 'tta', | ||||||||||||||||||||||||||||||||||||
'S': 'TCG', 's': 'tcg', | ||||||||||||||||||||||||||||||||||||
'Y': 'TAC', 'y': 'tac', | ||||||||||||||||||||||||||||||||||||
'C': 'TGC', 'c': 'tgc', | ||||||||||||||||||||||||||||||||||||
'W': 'TGG', 'w': 'tgg', | ||||||||||||||||||||||||||||||||||||
'P': 'CCC', 'p': 'ccc', | ||||||||||||||||||||||||||||||||||||
'H': 'CAT', 'h': 'cat', | ||||||||||||||||||||||||||||||||||||
'Q': 'GAA', 'q': 'gaa', | ||||||||||||||||||||||||||||||||||||
'R': 'CGA', 'r': 'cga', | ||||||||||||||||||||||||||||||||||||
'I': 'ATT', 'i': 'att', | ||||||||||||||||||||||||||||||||||||
'M': 'ATG', 'm': 'atg', | ||||||||||||||||||||||||||||||||||||
'T': 'ACC', 't': 'acc', | ||||||||||||||||||||||||||||||||||||
'N': 'AAT', 'n': 'aat', | ||||||||||||||||||||||||||||||||||||
'K': 'AAA', 'k': 'aaa', | ||||||||||||||||||||||||||||||||||||
'V': 'GTT', 'v': 'gtt', | ||||||||||||||||||||||||||||||||||||
'A': 'GCA', 'a': 'gca', | ||||||||||||||||||||||||||||||||||||
'D': 'GAT', 'd': 'gca', | ||||||||||||||||||||||||||||||||||||
'E': 'GAG', 'e': 'gag', | ||||||||||||||||||||||||||||||||||||
'G': 'GGG', 'g': 'ggg' | ||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
return ''.join([retrnaslation_dict[i] for i in protein]) | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Так то ок. Тут правда лучше было бы:
Suggested change
Одна лишняя буква места не сильно съест, а понимаемости прям добавит. Разве что получается вы тут вы даете только один вариант гена. Для первой версии тула ок, но если его поддерживать, но как-то про это еще глубже подумать. |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def rename_three_letter_name (seqs: list, sep = '')->list: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут понятно что вы переименовываете, но не понятно во что. |
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Transform into a three-letter amino acids entry. | ||||||||||||||||||||||||||||||||||||
arguments: | ||||||||||||||||||||||||||||||||||||
- seqs (list): list of sequences for transforming to three-letter entire | ||||||||||||||||||||||||||||||||||||
- sep (str): separator between aminoacids, default = '' | ||||||||||||||||||||||||||||||||||||
return: | ||||||||||||||||||||||||||||||||||||
- list: transformed sequences with separators | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
res=[] | ||||||||||||||||||||||||||||||||||||
threel = {'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': "ASP", 'V': 'VAL', | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Опять же это дело лучше бы вынести в константы.
Suggested change
|
||||||||||||||||||||||||||||||||||||
'H': 'HIS', 'G': "GLY", 'Q': "GLN", 'E': 'GLU', 'I': 'ILE', | ||||||||||||||||||||||||||||||||||||
'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'P': 'PRO', 'S': 'SER', | ||||||||||||||||||||||||||||||||||||
'Y': 'TYR', 'T': 'THR', 'W': 'TRP', 'F': 'PHE', 'C': 'CYS', | ||||||||||||||||||||||||||||||||||||
'a': 'ala', 'r': 'arg', 'n': 'asn', 'd': "asp", 'v': 'val', | ||||||||||||||||||||||||||||||||||||
'h': 'his', 'g': "gly", 'q': "gln", 'e': 'glu', 'i': 'ile', | ||||||||||||||||||||||||||||||||||||
'l': 'leu', 'k': 'lys', 'm': 'met', 'p': 'pro', 's': 'ser', | ||||||||||||||||||||||||||||||||||||
'y': 'tyr', 't': 'thr', 'w': 'trp', 'f': 'phe', 'c': 'cys'} | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В PEP8 принято закрывающую скобку в многострочных конструцкциях ставить на новой строке.
Suggested change
Либо по левому краю:
Suggested change
Вот эти 2 варианта уже на ваше усмотрение |
||||||||||||||||||||||||||||||||||||
for seq in seqs: | ||||||||||||||||||||||||||||||||||||
threel_form = '' | ||||||||||||||||||||||||||||||||||||
for aa in seq: | ||||||||||||||||||||||||||||||||||||
threel_form = threel_form + threel[aa] + sep | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||||||||||||
if sep: | ||||||||||||||||||||||||||||||||||||
threel_form = threel_form[:-1] | ||||||||||||||||||||||||||||||||||||
Comment on lines
+144
to
+145
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вот из-за этого выглядит немного сложно. Вы добавляете всегда sep через +, потом его надо отрезать. Так то ок, но мудрено. Мне кажется питонисто и попроще было бы сперва набрать все 3хбуквенные формы в список, а потом их слепить в строчку через join. |
||||||||||||||||||||||||||||||||||||
res.append(threel_form) | ||||||||||||||||||||||||||||||||||||
return res | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def is_protein(seq): | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Checking wheter a sequence is a protein sequence | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
aminoacids=['F','f','L','l','S','s','Y','y','C','c','W','w','P','p','H','h','Q','q','R','r','I','i','M','m','T','t','N','n','K','k','V','v','A','a','D','d','E','e','G','g'] | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тоже константа |
||||||||||||||||||||||||||||||||||||
for i in seq: | ||||||||||||||||||||||||||||||||||||
if i not in aminoacids: | ||||||||||||||||||||||||||||||||||||
Comment on lines
+154
to
+155
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут мб стоило бы сделать это дело просто на сравнении словарей) Как у нас на лекции было в |
||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input: protein sequences containing 20 common aminoacids in one-letter format were expected. Please try again') | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А вот это плохо. Поэтому if not is_protein(seq):
raise ValueError Если же вы прям хотите чтобы эта функция падала, то тогда назовите ее как-нибудь иначе. Например, можно использовать префикс "check_". От такой функции я уже не ожидаю что она что-то вернет. Я ожидаю что она что-то сделает. И для такой функции падение с ошибкой опять же вполне ожидаемо и все ок. Такую функцию можно просто писать на отдельной строчке для выполнения вашей проверки check_input(seq) Вообще здорово если у вас функция check внутри использует функцию is_, которая у вас тоже где-то есть. |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def string_check(sequences): | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Checking whether a sequence is a protein sequence and is of type str | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
for seq in sequences: | ||||||||||||||||||||||||||||||||||||
if type(seq) != str: | ||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input type: protein sequences of type str were expected. Please try again') | ||||||||||||||||||||||||||||||||||||
is_protein(seq) | ||||||||||||||||||||||||||||||||||||
Comment on lines
+158
to
+165
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А, ну вот, вы прям были близки чтобы сделать совсем хорошо.
Suggested change
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def verify(sequences,options): | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А чего verify-то? Хотя бы "verify_input" или "verify_arguments". |
||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
Argument verification for all options | ||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||
if options=='length' or options=='percentage' or options=='DNA_code': | ||||||||||||||||||||||||||||||||||||
string_check(sequences) | ||||||||||||||||||||||||||||||||||||
elif options=='3Letter_name': | ||||||||||||||||||||||||||||||||||||
string_check(sequences[:-1]) | ||||||||||||||||||||||||||||||||||||
elif options=='compare': | ||||||||||||||||||||||||||||||||||||
string_check(sequences[:-2]) | ||||||||||||||||||||||||||||||||||||
for i in range(0,len(sequences[:-2])): | ||||||||||||||||||||||||||||||||||||
if len(sequences[i])!=len(sequences[0]): | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А-а-а, вы тут проверяете чтобы длины были равные. Ну слушайте, это же не обязательно для compare. Просто тогда сиквенсы не равны на 100% |
||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input: same length protein sequences were expected. Please try again') | ||||||||||||||||||||||||||||||||||||
if type(sequences[-2]) != int or sequences[-2]<0: | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А вот тут я сломался. Как у вас второй с конца сиквенс может быть целым числом??? Секвенсы же это только строки. Вот почему важен нейминг. |
||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input type: positive integer value was expected as the second-to-last argument. Please try again') | ||||||||||||||||||||||||||||||||||||
if type(sequences[-1]) != bool: | ||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input type: bool value was expected as the last argument. Please try again') | ||||||||||||||||||||||||||||||||||||
elif options=='pattern': | ||||||||||||||||||||||||||||||||||||
string_check(sequences) | ||||||||||||||||||||||||||||||||||||
for i in range(1,len(sequences)): | ||||||||||||||||||||||||||||||||||||
if len(sequences[0])>len(sequences[i]): | ||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect input: pattern length shorter or equal to protein sequence length was expected. Please try again') | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
def protein_tool(*proteins, options = None): | ||||||||||||||||||||||||||||||||||||
proteins = list(proteins) | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Да в целом был бы кортежем, не обязательно переводить в список. |
||||||||||||||||||||||||||||||||||||
verify(proteins, options) | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Очень круто что вы сделали такой чекер ввода. Это хорошо. |
||||||||||||||||||||||||||||||||||||
operations = { | ||||||||||||||||||||||||||||||||||||
'compare': compare, | ||||||||||||||||||||||||||||||||||||
'length': count_length, | ||||||||||||||||||||||||||||||||||||
'percentage': count_percentage, | ||||||||||||||||||||||||||||||||||||
'pattern': find_pattern, | ||||||||||||||||||||||||||||||||||||
'3Letter_name': rename_three_letter_name, | ||||||||||||||||||||||||||||||||||||
'DNA_code': transform_to_DNA_code | ||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
if options == 'compare': | ||||||||||||||||||||||||||||||||||||
result = operations[options](proteins[:-2], proteins[-2], proteins[-1]) | ||||||||||||||||||||||||||||||||||||
return (result) | ||||||||||||||||||||||||||||||||||||
elif options == 'pattern': | ||||||||||||||||||||||||||||||||||||
result = operations[options](proteins[1:len(proteins)],proteins[0]) | ||||||||||||||||||||||||||||||||||||
return (result) | ||||||||||||||||||||||||||||||||||||
elif options == '3Letter_name': | ||||||||||||||||||||||||||||||||||||
result = operations[options](proteins[:-1], proteins[-1]) | ||||||||||||||||||||||||||||||||||||
return (result) | ||||||||||||||||||||||||||||||||||||
elif options == 'length' or options =='percentage' or options == 'DNA_code': | ||||||||||||||||||||||||||||||||||||
result = [] | ||||||||||||||||||||||||||||||||||||
for protein in proteins: | ||||||||||||||||||||||||||||||||||||
res = operations[options](protein) | ||||||||||||||||||||||||||||||||||||
result.append(res) | ||||||||||||||||||||||||||||||||||||
return (result) | ||||||||||||||||||||||||||||||||||||
else: | ||||||||||||||||||||||||||||||||||||
raise ValueError('Incorrect options input, please try again') | ||||||||||||||||||||||||||||||||||||
Comment on lines
+193
to
+218
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ахах, ну не, смотрите. У всех методов есть область применимости. Кое где словари хороши, кое где нет. У вас тут у каждой функции свой набор аргументов. Поэтому получается вообще нет смысла писать через словари. Просто if-else и там вызываете нужную функцию. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я бы это вынес в начало тоже в проверку аргументов, что опция есть в списке опций. Чтобы разнести логику проверок и работы. |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
protein_tool() | ||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не надо было эту функцию тут вызывать. Тем более зачем? Она же без аргументов и не работает |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Классное README!