Commit 65b2fe50 authored by KASIA RADZIWON's avatar KASIA RADZIWON
Browse files

Upload New File

parent 6c254c36
Loading
Loading
Loading
Loading
+349 −0
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

# (Very Basic) Intro to Object Oriented Programming -- Classes & Methods

%% Cell type:code id: tags:

``` python
#defining the simplest class

class Protein:
    def __init__(self):
        self.name ="name"
        self.sequence = "sequence"

#when we call the class we create object or instance
#(people prefer calling them instances because using word object might be confusing
#because classes are also called objects ;))

new_protein = Protein()
new_protein.name = "OspF"
new_protein.sequence = "AAAARTGSW"

#now if we try to print the instance it won't show us what's inside
print(new_protein)
```

%% Cell type:code id: tags:

``` python
#you need to unravel it variable by variable, so e.g.

print(new_protein.name)
print(new_protein.sequence)
```

%% Cell type:code id: tags:

``` python
#okay, creating that instance took 3 lines, that sucks
#let's make it simpler

class Protein_faster:
    def __init__(self, name, seq):
        self.name = name
        self.sequence = seq

new_protein2 = Protein_faster("OspF/A3G", "AAGARTGSW") #now it's just one line

print(new_protein2.name)
print(new_protein2.sequence)
```

%% Cell type:code id: tags:

``` python
#the variables in class can be of any kind

class Protein_extended:
    def __init__(self, name, seq):
        self.name = name
        self.sequence = seq #strings
        self.extCoeff = 0 #integers
        self.Abs = 0.0 #floats
        self.WT = True #booleans
        self.PDB_IDs = [] #lists

#functions in the classes are called methods. they really work like regular functions

    def concentration(self):
        self.conc = round(self.Abs / self.extCoeff * 1e6, 2)
        return "Concentration of this sample of {0} is equal to {1} mM".format(self.name, self.conc) #useful construction
                                                #for creating strings with class attributes, works easier than % imo

new_protein = Protein_extended("OspF", "AAAARTGSW")
new_protein.extCoeff = 11111
new_protein.Abs = 2.1

print(new_protein.concentration())
```

%% Cell type:code id: tags:

``` python
# okay, when I said variables (AKA attributes) can be of any kind, I meant it... class can be a variable too!!!


class Prot:
    def __init__(self, name, expression):
        self.name = name
        self.expression = expression

class Expression(Prot):
    def __init__(self, ecoli=False, yeast=False, mouse=False, human=False): #I set the values to False on default
        self.ecoli = ecoli
        self.yeast = yeast
        self.mouse = mouse
        self.human = human


new_prot = Prot("SpvC", Expression(True)) #here I write "True" only once, because the rest is assumed False

print(new_prot.name)
print(new_prot.expression.ecoli)
print(new_prot.expression.yeast)
```

%% Cell type:code id: tags:

``` python
#exercise time!

#write a class called "ExpressionPlan"
#The class should have attributes "name", "organism", "conditions"
#Create another class "Conditions" with attributes "temp" and "duration"
#Create an instance of this class called "protein", with those variables set to EspV, Ecoli, 37, 4
#Write a function that prints the result as "Express EspV in Ecoli for 4 hours at 37 deg C" and execute it for "protein"

#write your code here
```

%% Cell type:markdown id: tags:

# A little more complex Concepts from chapter 7

%% Cell type:code id: tags:

``` python
# A Python class for handling biological sequences
class Sequence:
    def __init__(self,name,sequence):
        self.name = name
        self.sequence = sequence
    def search(self,pattern):
        return self.sequence.find(pattern)
```

%% Cell type:code id: tags:

``` python
#method to compare sequences

def compareNames(self,other):
    if self.name == other.name:
        return True
    else:
        return False
```

%% Cell type:code id: tags:

``` python
#testing if the class works

mySequence = Sequence('Some made up sequence','cgtatgcgct')
print(mySequence.name)
print(mySequence.sequence)
print(mySequence.search('gcg'))
```

%% Cell type:code id: tags:

``` python
#transcription & creating subclass

class DNASequence(Sequence):
    def __init__(self,name,sequence):
        Sequence.__init__(self,name,sequence)
    def transcribe(self):
        return self.sequence.replace('t','u') #I'm aware the transcription code is incorrect
    #we all know transcribing is more than czanging T to U...
    #but I kept it as it is in the book, since it would use a very similar method anyway
```

%% Cell type:code id: tags:

``` python
#testing if method works

myDNASequence = DNASequence('My first DNA sequence','gctgatatc')
print(myDNASequence.name)
print(myDNASequence.sequence)
print(myDNASequence.search('gat'))
print(myDNASequence.transcribe())
```

%% Cell type:code id: tags:

``` python
#translation & creating subclass

import string

rnaToProtein = {'uuu':'F','uuc':'F','uua':'L','uug':'L',
                'ucu':'S','ucc':'S','uca':'S','ucg':'S',
                'uau':'Y','uac':'Y','uaa':'STOP','uag':'STOP',
                'ugu':'C','ugc':'C','uga':'STOP','ugg':'W',
                'cuu':'L','cuc':'L','cua':'L','cug':'L',
                'ccu':'P','ccc':'P','cca':'P','ccg':'P',
                'cau':'H','cac':'H','caa':'Q','cag':'Q',
                'cgu':'R','cgc':'R','cga':'R','cgg':'R',
                'auu':'I','auc':'I','aua':'I','aug':'M',
                'acu':'T','acc':'T','aca':'T','acg':'T',
                'aau':'N','aac':'N','aaa':'K','aag':'K',
                'agu':'S','agc':'S','aga':'R','agg':'R',
                'guu':'V','guc':'V','gua':'V','gug':'V',
                'gcu':'A','gcc':'A','gca':'A','gcg':'A',
                'gau':'D','gac':'D','gaa':'E','gag':'E',
                'ggu':'G','ggc':'G','gga':'G','ggg':'G'}

class RNASequence(Sequence):
    def __init__(self,name,sequence):
        Sequence.__init__(self,name,sequence)
    def translate(self):
        peptide = []
        for n in range(0,len(self.sequence),3):
            codon = self.sequence[n:n+3]
            peptide.append(rnaToProtein[codon])
        peptideSequence = ''.join(peptide) #funny enough, there was another mistake here, they used " instead of '' ;)
        return peptideSequence
```

%% Cell type:code id: tags:

``` python
#testing if method works

myRNASequence = RNASequence('My first RNA sequence','gcugauauc')
print(myRNASequence.name)
print(myRNASequence.sequence)
print(myRNASequence.search('gau'))
print(myRNASequence.translate())
```

%% Cell type:code id: tags:

``` python
#creating one last subclass

class ProteinSequence(Sequence):
    def __init__(self,name,sequence):
        Sequence.__init__(self,name,sequence)

myProteinSequence = ProteinSequence('My first protein sequence','MDVTLFSLQY')
print(myProteinSequence.name)
print(myProteinSequence.sequence)
print(myProteinSequence.search('LFS'))
```

%% Cell type:code id: tags:

``` python
#another attempt at transcription

class DNASequence(Sequence):
    def __init__(self,name,sequence):
        Sequence.__init__(self,name,sequence)
        self.residues = {'a':313.2,'c':289.2,'t':304.2,'g':329.2}
    def transcribe(self):
        return self.sequence.replace('t','u')
    def transcribeToRNA(self):
        rnaSequence = self.sequence.replace('t','u')
        rnaName = 'Transcribed from ' + self.name
        return RNASequence(rnaName,rnaSequence)

newRNASequence = myDNASequence.transcribeToRNA()
print(newRNASequence.name)
print(newRNASequence.sequence)
```

%% Cell type:code id: tags:

``` python
#MW calculation

class Sequence:
    def __init__(self,name,sequence):
        self.name = name
        self.sequence = sequence
        self.residues = {}
    def search(self,pattern):
        return self.sequence.find(pattern)
    def molecularWeight(self):
        mwt = 0.0
        for residue in self.sequence:
            mwt += self.residues[residue]
        return mwt
    def validSequence(self):
        for residue in self.sequence:
            if not residue in self.residues:
                return False
        return True
```

%% Cell type:code id: tags:

``` python
#testing

print(myDNASequence.molecularWeight())
print(myDNASequence.validSequence())
```

%% Cell type:code id: tags:

``` python
#writing a class to be an attribute in another class (instead of "residues" in previous cells)

class DNANucleotide:
    nucleotides = {'a': 313.2, 'c': 289.2, 't': 304.2, 'g': 329.2}
    def __init__(self,nuc):
        self.name = nuc
        self.weight = DNANucleotide.nucleotides[nuc]
```

%% Cell type:code id: tags:

``` python
#and inserting this class into DNASequence class

class NewDNASequence:
    def __init__(self,name,sequence):
        self.name = name
        self.sequence = []
        for s in sequence:
            d = DNANucleotide(s)
            self.sequence.append(d)
    def molecularWeight(self):
        mwt = 0.0
        for s in self.sequence:
            mwt += s.weight
        return mwt
    def __str__(self):
        nucs = []
        for s in self.sequence:
            nucs.append(s.name)
        return ''.join(nucs)
```

%% Cell type:code id: tags:

``` python
#testing

myDNASequence = NewDNASequence('My new DNA sequence','gctgatatc')
print(myDNASequence.sequence[0])
print(myDNASequence.sequence[0].name)
print(myDNASequence.sequence[0].weight)
print(myDNASequence.molecularWeight())
```