Skip to content

Conversation

nvaulin
Copy link
Member

@nvaulin nvaulin commented Feb 26, 2024

Review RASA2

print(str(self.sequence))

def is_valid_alphabet(self):
valid_nucleotides = {'A', 'C', 'G', 'T', 'U'}
Copy link

Choose a reason for hiding this comment

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

Можно было добавить проверку для строчных букв, либо перевести все в заглавные

Comment on lines +123 to +128
if nucl.upper() == 'A':
transcribe_sequence += nucl
elif nucl.upper() == 'G':
transcribe_sequence += nucl
elif nucl.upper() == 'C':
transcribe_sequence += nucl
Copy link

Choose a reason for hiding this comment

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

Как вариант, можно было бы это не писать и только рассматривать случай с T:

    def transcribe(self):
        list_input = list(self.seq)
        for i in range(len(self.seq)):
            if (list_input[i] == 'T'):
                list_input[i] = 'U'
            elif (list_input[i] == 't'):
                list_input[i]='u'
        return "".join(list_input)

Или еще короче:

    def transcribe(self) -> RNASequence:
        return RNASequence(str(self).translate(str.maketrans(('Tt'), ('Uu'))))

Copy link
Member Author

Choose a reason for hiding this comment

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

О, вот, с подсветкой и само предложение тоже супер

transcribe_sequence += nucl
elif nucl.upper() == 'C':
transcribe_sequence += nucl
elif nucl.upper() == 'T':
Copy link

Choose a reason for hiding this comment

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

Не очень понимаю, если выполнен метод upper(), почему на следующей строчке рассмотрен вариант t строчной?



class BiologicalSequence:
@abstractmethod
Copy link

Choose a reason for hiding this comment

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

абстрактный метод задан верно, только можно добавить наследование:

class BiologicalSequence(ABC):

quality_threshold: int = 0, output_filename='') -> None:
seqs = SeqIO.parse(input_path, 'fastq')
if seqs is None:
raise ValueError('Your fastq_files are None')

Choose a reason for hiding this comment

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

тут не совсем понятный вывод получается. файла нет или файл пустой, лучше поменять или вывести потенциальные ошибки

if not os.path.exists(output_dir):
os.mkdir(output_dir)

with open(os.path.join(output_dir, f'{output_filename}.fastq'), 'w') as fq:

Choose a reason for hiding this comment

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

хорошая конструкция, для того, что бы не забывать закрывать файл, но чуть проще читается код и чувствуется больше уверенености, когда в конце есть явное закрытие файла

length_bounds[1]:
gc_content = SeqUtils.GC123(record.seq)
if gc_bounds[1] >= gc_content[0] >= gc_bounds[0]:
SeqIO.write(record, fq, 'fastq')

Choose a reason for hiding this comment

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

Suggested change
SeqIO.write(record, fq, 'fastq')
SeqIO.write(record, fq, 'fastq')
fq.close()

SeqIO.write(record, fq, 'fastq')


class BiologicalSequence:

Choose a reason for hiding this comment

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

потерялось наследование)

print(str(self.sequence))

def is_valid_alphabet(self):
valid_nucleotides = {'A', 'C', 'G', 'T', 'U'}

Choose a reason for hiding this comment

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

хорошая проверка нуклеиновых кислот, но они могут быть прописаны в другом регистре, тогда стоит добавить с нижним регистром тоже

transcribe_sequence += nucl
elif nucl.upper() == 'T':
if nucl == 't':
transcribe_sequence += 'u'

Choose a reason for hiding this comment

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

Это вероятно лишнее, потому что все в верхний регистр переводится же

3)]
for divided_acid in divided_acids:
if divided_acid not in self.AMINOACIDS_DICT.keys():
raise ValueError('Non-protein aminoacids in sequence')

Choose a reason for hiding this comment

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

тут стоит добавить какое-то объяснение для пользователей, вероятно пользователю будет не сразу понятна ошибка. Наличие проверки - хорошо, но её как будто бы лучше вынести перед работой или в самом начале функции

for letter in self.sequence:
if letter not in self.TRANSCRIBE_DICT.keys():
return False
return True

Choose a reason for hiding this comment

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

Монжо чуть чуть изменить эту функцию, так она будет работать побыстрее

Suggested change
return True
valid_alphabet_set = set(self.TRANSCRIBE_DICT.keys())
return set(self.sequence).issubset(valid_alphabet_set)

Copy link
Member Author

Choose a reason for hiding this comment

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

Отличное замечание. Даже тут не только быстрее, но и просто более питонистый стиль. Не вручную копаем отдельные элементы коллекции, а используем более высокоуровневые методы самих коллекций.

Parameters:
*parameters (str): Variable number of DNA or RNA sequences and the tool name.

Returns:

Choose a reason for hiding this comment

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

Это прям сильно. слишком подробно, в коде наверное стоит писать более емко все

elif answer is None:
raise ValueError('Answer is None')
else:
return answer

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.

3 participants