Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions CNTN6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
class BiologicalSequence:
def __init__(self, sequence):

Choose a reason for hiding this comment

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

В целом, как говорили на паре, идеальный абстрактный класс init не содержит (чтобы нельзя было создавать его экзмепляры). Но тут конечно логично, что у каждого наследника должна быть последовательность, но лучше бы переписать это все в наследниках.

Copy link

Choose a reason for hiding this comment

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

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

self.sequence = sequence

Choose a reason for hiding this comment

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

Суть абстрактного класса - не держать в себе готовые атрибуты и методы, а только говорить какие атрибуты и/или методы должны обязательно быть у его наследников. Здесь выходит так, что у наследуемых классов с нуклеотидными последовательностями будет алфавит белков по умолчанию :(

self.ALPHABET = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
Copy link

Choose a reason for hiding this comment

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

кажется, что каждая биологическая последовательность должна иметь алфавит - это логично и верно, что прописано. Но определять его здесь не нужно, так как каждая конкертная последовательность - ДНК, РНК или белок - будет иметь свой алфавит


def __len__(self):
return len(self.sequence)

def __getitem__(self, idx):
return self.sequence[idx]

def __get_slice__(self, start, end):
if start < 0 or start > len(self.sequence):
raise IndexError("start index out of range")

if end < 0 or end > len(self.sequence):
raise IndexError("end index out of range")

if start > end:
raise ValueError("start index must be less than or equal to end index")

return self.sequence[start:end]

def __str__(self):
return self.sequence

def __repr__(self):
return f'{self.__class__.__name__}({self.sequence!r})'
Comment on lines +27 to +28

Choose a reason for hiding this comment

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

Класс, даже repr не забыт! И все методы строки есть! Супер!


def is_valid_bioseq(self):
for char in self.sequence:
if char not in self.ALPHABET:
return False
return True
Comment on lines +31 to +34

Choose a reason for hiding this comment

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

Suggested change
for char in self.sequence:
if char not in self.ALPHABET:
return False
return True
unique_chars = set(self.sequence)
if not (unique_chars <= self.ALPHABET):
return False
return True

Choose a reason for hiding this comment

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

Можно избежать лишних циелов используя set :) Это не обязательно, но кажется будет работать чуть быстрее. Особенно если алфивиты тоже сразу сделаны сетами - удобная вещь!)



class NucleicAcidSequence(BiologicalSequence):
def complement(self, COMPLEMENT_NUCLEOTIDES=None):

Choose a reason for hiding this comment

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

Suggested change
def complement(self, COMPLEMENT_NUCLEOTIDES=None):
COMPLEMENT_NUCLEOTIDES = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
def complement(self, COMPLEMENT_NUCLEOTIDES=None):

if COMPLEMENT_NUCLEOTIDES is None:
COMPLEMENT_NUCLEOTIDES = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
Comment on lines +39 to +40

Choose a reason for hiding this comment

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

Suggested change
if COMPLEMENT_NUCLEOTIDES is None:
COMPLEMENT_NUCLEOTIDES = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}

Кажется, комплементарные нуклеотиды у РНК и ДНК, которые от этого класса наследуются, будут разные. Так что лучше это определить в дочерних классах - или еще лучше - получать это из дочерних классов!

Choose a reason for hiding this comment

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

Так как это сильно поменяет структура дальнейшего кода - внесу только маленькое изменение - если есть какие-то константы, то их не надо объявлять внутри методов - лучше вынести в атрибут класса

Copy link

Choose a reason for hiding this comment

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

Наверное эта часть должна быть в ДНК и РНК отдельно, так как это позволит сразу создать их с верным алфавитом


complement_seq = ''
for nucleotide in self.sequence:
complement_seq += COMPLEMENT_NUCLEOTIDES.get(nucleotide)
return complement_seq

def gc_content(self):
return (self.sequence.count('G') + self.sequence.count('C'))/len(self.sequence)
Comment on lines +47 to +48

Choose a reason for hiding this comment

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

О, супер! Правда очень логично держать эту функцию тут - мы ведь ее можем и для РНК, и для ДНК использовать!



class RNASequence(NucleicAcidSequence):
REV_TRANSCRTPTION_COMPLEMENT = {'A': 'T', 'U': 'A', 'C': 'G', 'G': 'C'}

Choose a reason for hiding this comment

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

о! Класс!

Choose a reason for hiding this comment

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

алфавит тоже сюда можн перенести)

Suggested change
REV_TRANSCRTPTION_COMPLEMENT = {'A': 'T', 'U': 'A', 'C': 'G', 'G': 'C'}
REV_TRANSCRTPTION_COMPLEMENT = {'A': 'T', 'U': 'A', 'C': 'G', 'G': 'C'}
ALPHABET = {'A','U','G','C'}


def __init__(self, sequence):
super().__init__(sequence)
Copy link

Choose a reason for hiding this comment

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

если я не ошибаюсь, получается что все super().__init__ отсылаются к биологической последовательности, но было бы лучше если бы они были в самих классах ДНК, РНК и белоков

self.ALPHABET = {'A','U','G','C'}

Choose a reason for hiding this comment

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

Suggested change
self.ALPHABET = {'A','U','G','C'}

Нет смысл держать его тут, он же относится ко всему классу. Зачем на его переобъявлять для каждого экземпляра?


def reverse_transribe(self):
return DnaSequence(self.complement(self.REV_TRANSCRTPTION_COMPLEMENT))
Comment on lines +58 to +59

Choose a reason for hiding this comment

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

Супер! И дополнительная функция, и еще и может возвращать другой класс!!!

Copy link

Choose a reason for hiding this comment

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

верно, что возвращает объект правильного класса



class DnaSequence(NucleicAcidSequence):
TRANSCRTPTION_COMPLEMENT = {'A': 'U', 'T': 'A', 'C': 'G', 'G': 'C'}
def __init__(self, sequence):
super().__init__(sequence)
self.ALPHABET = {'A', 'T', 'G', 'C'}
Comment on lines +63 to +66

Choose a reason for hiding this comment

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

Suggested change
TRANSCRTPTION_COMPLEMENT = {'A': 'U', 'T': 'A', 'C': 'G', 'G': 'C'}
def __init__(self, sequence):
super().__init__(sequence)
self.ALPHABET = {'A', 'T', 'G', 'C'}
TRANSCRTPTION_COMPLEMENT = {'A': 'U', 'T': 'A', 'C': 'G', 'G': 'C'}
ALPHABET = {'A', 'T', 'G', 'C'}
def __init__(self, sequence):
super().__init__(sequence)


def transcribe(self):
return RNASequence(self.complement(self.TRANSCRTPTION_COMPLEMENT))


class AminoAcidSequence(BiologicalSequence):
AMINOACID_ALPHABET_1TO3 = {'A': 'Ala', 'R': 'Arg', 'N': 'Asn', 'D': 'Asp', 'C': 'Cys',
'Q': 'Gln', 'E': 'Glu', 'G': 'Gly', 'H': 'His', 'I': 'Ile',
'L': 'Leu', 'K': 'Lys', 'M': 'Met', 'F': 'Phe', 'P': 'Pro',
'S': 'Ser', 'T': 'Thr', 'W': 'Trp', 'Y': 'Tyr', 'V': 'Val'}

def __init__(self, sequence):
super().__init__(sequence)

Choose a reason for hiding this comment

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

Suggested change
super().__init__(sequence)
super().__init__(sequence)
self.ALPHABET = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
  • кажется тут смотрится логично :)


def convert_1_to_str3(self) -> str:
seq3 = ''
if len(self.sequence) > 0:
for aminoacid in self.sequence:
if aminoacid in self.AMINOACID_ALPHABET_1TO3:
seq3 += self.AMINOACID_ALPHABET_1TO3[aminoacid]

return seq3