Skip to content

Hw14 part II#3

Open
zmitserbio wants to merge 29 commits into
mainfrom
HW14
Open

Hw14 part II#3
zmitserbio wants to merge 29 commits into
mainfrom
HW14

Conversation

@zmitserbio
Copy link
Copy Markdown
Owner

No description provided.

Add create_results_dir_if_doesnt_exist function
Copy link
Copy Markdown

@eksytnik eksytnik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Увы, не совсем реализовано то, что было в задании. Есть начало работы с классами, но сами классы полноценно не реализованы.

FastQ - 3 балла.
Биологические последовательности - 7 баллов.

Comment thread beginner_bioinf_tools.py
Comment on lines +66 to +69
sequence_to_str_list = []
for nucleotide in self:
sequence_to_str_list.append(nucleotide)
return ''.join(sequence_to_str_list)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Получается создание строки из строки через список. Интересно, но цель не ясна с:

Comment thread beginner_bioinf_tools.py
Comment on lines +94 to +105
def __init__(self, sequence: str):
self.alphabet = 'AUGCaugc'
self.complement_dictionary = {
'A': 'U',
'U': 'A',
'G': 'C',
'C': 'G',
'a': 'u',
'u': 'a',
'g': 'c',
'c': 'g'
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self - это ссылка на экземпляр класса. Такие штуки, как общие алфавиты - обычно нет смысла хранить на уровне экземпляра, это что-то общее и неизменное, их можно сделать классовыми атрибутами.
А вот sequence ровно наоборот - был смысл сделать именно атрибутом в self.
Должно было быть что-то в таком духе:

alphabet = '...'
complement_dict = {...}

def __init__(self, sequence: str):
    self.sequence = sequence

Comment thread beginner_bioinf_tools.py
}

def transcribe(self) -> RNASequence:
transcription_dictionary = {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогичное замечание про алфавиты.

Comment thread beginner_bioinf_tools.py
Comment on lines +307 to +339
def run_dna_rna_tools(inputs: tuple) -> list | str:
"""
Produce a list of either transcripts, reverse sequences, complementary sequences or reverse complementary sequences
arguments:
- inputs (tuple): an arbitrary amount of strings where the last one is the name of desired operation, and other strings are sequences
return
- complement_seqs (list): a list of complementary sequences
"""
if len(inputs) < 2:
raise ValueError('Invalid input: the function requires at least one sequence and an operation name!')
*seqs, operation = inputs
if operation == 'transcribe':
transcribed_seqs = []
for seq in seqs:
transcribed_seqs.append(str(DNASequence(seq).transcribe()))
return transcribed_seqs
elif operation == 'reverse':
result = reverse(seqs)
elif operation == 'complement':
complement_seqs = []
for seq in seqs:
if 'U' in seq or 'u' in seq:
complement_seqs.append(str(RNASequence(seq).complement()))
else:
complement_seqs.append(str(DNASequence(seq).complement()))
return complement_seqs
elif operation == 'reverse_complement':
result = reverse_complement(seqs)
else:
raise ValueError('Invalid input: unknown operation! Check the last argument.')
if len(result) == 1:
result = ''.join(result)
return result
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Получилось немного смешанное задание. Подразумевалось, что вся реализация через функции будет переписана на классы, и это всё станет методами или атрибутами классов, а вышло нечто смешанное и в результате не совсем то, что требовалось.

Comment thread beginner_bioinf_tools.py
quality_check = sum(quality_per_letter) / len(quality_per_letter) >= quality_threshold
if gc_check and length_check and quality_check:
seqs_filtered.append(record)
return seqs_filtered
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не хватает чтения и записи через методы библиотек.

Comment thread beginner_bioinf_tools.py
return info_dict


def reverse(seqs: list) -> list:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функции должны были стать методами классов.

Comment thread beginner_bioinf_tools.py
Comment on lines +133 to +136
dna_transcript_list = []
for nucleotide in self:
dna_transcript_list.append(transcription_dictionary[nucleotide])
return RNASequence(''.join(dna_transcript_list))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно делать как-то так. Получается одновременно короче и более читаемо:

transcribed_sequence = ''.join(transcription_dictionary[nucleotide] for nucleotide in self.sequence)
return RNASequence(transcribed_sequence)

Comment thread beginner_bioinf_tools.py
"""
reverse_seqs = []
for seq in seqs:
reverse_seqs.append(seq[::-1])
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seq[::-1] работает на строках без доп списков.

Comment thread beginner_bioinf_tools.py
Comment on lines +78 to +79
if not self.is_correct_alphabet():
raise InvalidInputError('Cannot complement: incorrect input sequence. Only nucleotides (in both cases) are supported!')
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проверка то хорошая, только на уровне complement как будто чуть поздно, это стоит делать на попытке создать такой экземпляр класса.

Comment thread beginner_bioinf_tools.py
for nucleotide in self:
if nucleotide == 'G' or nucleotide == 'C' or nucleotide == 'g' or nucleotide == 'c':
gc_count += 1
return gc_count / len(self)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всегда классно предусматривать, что пользователь может дать пустую последовательность. Например, потому что у него что-то криво прочиталось в скрипте, работающем с файлами с данными. Ошибку деления на ноль он и так увидит, конечно, но.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants