from P1.Seq1 import Seq print("-----|Practice 1 , Exercise 6 |------") s0 = Seq() s1 = Seq("AGTGCA") s2 = Seq("ADCDGD") print(f"Sequence 0 : (Length {s0.len()}) , {s0} ") print(f" Bases : {s0.count()}") print(f" Sequence 1 : (Length {s1.len()} ) , {s1}") print(f" Bases : {s1.count()}") print(f" Sequence 2 : (Length {s2.len()} ), {s2}") print(f" Bases : {s2.count()}")
from P1.Seq1 import Seq print('-----| Practice 1, Exercise 2|------') seq1 = Seq() seq2 = Seq("ACTGA") print("Sequence 1:", seq1) print("Sequence 2:", seq2)
from Client0 import Client from P1.Seq1 import Seq PRACTICE = 2 EXERCISE = 6 print(f"-----| Practice {PRACTICE}, Exercise {EXERCISE} |------") FOLDER = "../Session-04/" Filename = "FRAT1" TypeDoc = '.txt' IP = "127.0.0.1" PORT = 8080 c = Client(IP, PORT) print(c) seq = Seq().read_fasta(FOLDER + Filename + TypeDoc) bases = str(seq) print('Gene ', Filename, ':', seq) c.talk(f"Sending {Filename} Gene to the server, in fragments of 10 bases") for i in range(5): fragment = (bases[i * 10:(i + 1) * 10]) print(f"Fragment {i+1}: {fragment}") c.talk(f"Fragment {i+1}: {fragment}")
from P1.Seq1 import Seq from Client0 import Client PRACTICE = 2 EXERCISE = 6 print(f"-----| Practice {PRACTICE}, Exercise {EXERCISE} |------") IP = "127.0.0.1" PORT = 8081 c = Client(IP, PORT) s = Seq() s.read_fasta('../P2/FRAT1.txt') count = 0 i = 0 while i < len(s.strbases) and count < 5: fragment = s.strbases[i:i + 10] count += 1 i += 10 print(c.talk(fragment))
EXERCISE = 7 print(f"-----| Practice {PRACTICE}, Exercise {EXERCISE} |------") FOLDER = "../Session-04/" FILENAME = "FRAT1" # -- Parameters of the server to talk to IP = "127.0.0.1" PORT = 58788 c1 = Client(IP, PORT) c2 = Client(IP, PORT + 1) print(c1) print(c2) s = Seq() s.read_fasta(FOLDER + FILENAME) bases = str(s) length = 10 print(f"Gene {FILENAME}: {bases}") c1.talk(f"Sending {FILENAME} Gene to the server, in fragments of {length} bases...") c2.talk(f"Sending {FILENAME} Gene to the server, in fragments of {length} bases...") for index in range(0,10): fragment = bases[index * length:(index + 1) * length] print(f"Fragment {index + 1}: {fragment}") if index % 2:
from P1.Seq1 import Seq print("-----| Exercise 1 |------") seq = Seq("ACTGA") print("Sequence" + str(1) + ": (Length: " +str(seq.len()), ")" + str(seq))
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" # Define the type of content returned by the server content_type = "text/html" # Print the request line termcolor.cprint(self.requestline, 'green') # Processing the request line req = self.requestline.split(" ") # Path will be: "/" path = req[1] # We will need to split the "?" in order to leave the msg alone argument = path.split("?") # We define our first argument to determine if we could continue or an error in thrown arg0 = argument[0] contents = Path("Error.html").read_text() status = 404 # All the information appears in "form-4.html" if arg0 == "/": contents = Path("index.html").read_text() status = 200 elif arg0 == "/listSpecies": try: Endpoint = "/info/species" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") response = json.loads(data1) d = response["species"] length = len(d) limit = argument[1] l = limit.split("=")[1] limit_ = l.split("&msg")[0] counter = 0 contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Basic Level</title > </head > <body style="background-color:lightblue;"> </body> </html> """ contents += f"<p>The total number of species in the ensembl is : {length} </p>" if len(limit[1]) in range(1, length): contents += f"<p>The limit you have selected is: {limit_} </p>" contents += f"<p>The name of the species are: </p>" for i in d: if counter < int(limit_): contents += f"* {i['display_name']} " contents += f"<br><br>" counter += 1 else: contents = Path("Error.html").read_text() status = 404 contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/karyotype": try: s = argument[1] species = s.split("=")[1] Endpoint = f"/info/assembly/{species}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") karyotype_response = json.loads(data1) k = karyotype_response["karyotype"] contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Basic Level</title > </head > <body style="background-color:lightblue;"> """ contents += f"The names of the chromosomes are:" for j in k: contents += f"<p> * {j} </p>" contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/chromosomeLength": try: Endpoint = "/info/assembly/" s = argument[1] spl = s.split("=") species= spl[1].split("&") conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + species[0] + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") cl = json.loads(data1) n = cl['top_level_region'] contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Basic Level</title > </head > <body style="background-color:lightblue;"> """ for m in n: if m['name'] == spl[-1]: contents += f"<p>The length of the chromosome is: {m['length']}</p>" else: contents = Path("Error.html").read_text() status = 404 contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/geneSeq": try: s = argument[1] gene = s.split("=")[1] Endpoint = f"/xrefs/symbol/homo_sapiens/{gene}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") d1 = json.loads(data1) d = d1[0] idd = d["id"] Endpoint_ = f"sequence/id/{idd}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint_ + Parameters) r2 = conn.getresponse() d2 = r2.read().decode("utf-8") d_ = json.loads(d2) s = d_["seq"] contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Medium Level</title > </head > <body style="background-color:violet;"> """ contents += f"""<p> The sequence of the gene {gene} is: </p>""" contents += f"<textarea readonly rows = 20 cols = 80>{s}</textarea>" contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/geneInfo": try: s = argument[1] gene = s.split("=")[1] Endpoint = f"/xrefs/symbol/homo_sapiens/{gene}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") d1 = json.loads(data1) d = d1[0] idd = d["id"] Endpoint_ = f"lookup/id/{idd}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint_ + Parameters) r2 = conn.getresponse() d2 = r2.read().decode("utf-8") d_ = json.loads(d2) start = d_["start"] end = d_["end"] length = d_["end"]-d_["start"] id = d_["id"] chrom = d_["seq_region_name"] contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Medium Level</title > </head > <body style="background-color:violet;"> """ contents += f"""<h1> {gene} </h1>""" contents += f"""<p> The start of the gene is {start} </p>""" contents += f"""<p> The end of the gene is {end} </p>""" contents += f"""<p> The length of the gene is {length} </p>""" contents += f"""<p> The id of the gene is {id} </p>""" contents += f"""<p> The chromosome of the gene is {chrom}""" contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/geneCalc": try: s = argument[1] gene = s.split("=")[1] Endpoint = f"/xrefs/symbol/homo_sapiens/{gene}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameters) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") d1 = json.loads(data1) d = d1[0] idd = d["id"] Endpoint_ = f"sequence/id/{idd}" conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint_ + Parameters) r2 = conn.getresponse() d2 = r2.read().decode("utf-8") d_ = json.loads(d2) seq = d_["seq"] sequence = Seq(seq) length = sequence.len() contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Medium Level</title > </head > <body style="background-color:violet;"> """ contents += f"""<h1> {gene} </h1>""" contents += f"""<p> The total length is {length}""" for base in all_bases: count = sequence.count_base(base) c.append(count) percentage = (count / length) * 100 p.append(f"{round(percentage, 3)}") contents += f"""<p>{all_bases[0]}: {c[0]} : {p[0]} %</p>""" contents += f"""<p>{all_bases[1]}: {c[1]} : {p[1]} %</p>""" contents += f"""<p>{all_bases[2]}: {c[2]} : {p[2]} %</p>""" contents += f"""<p>{all_bases[3]}: {c[3]} : {p[3]} %</p>""" contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 elif arg0 == "/geneList": try: s = argument[1] ch = s.split('&')[0] st = s.split('&')[1] en = s.split('&')[2] chromo = ch.split("=")[1] start = st.split("=")[1] end = en.split("=")[1] Endpoint = f"overlap/region/human/{chromo}:{start}-{end}" Parameter = '?feature=gene;content-type=application/json' conn = http.client.HTTPConnection(Server) conn.request("GET", Endpoint + Parameter) r1 = conn.getresponse() data1 = r1.read().decode("utf-8") d1 = json.loads(data1) contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title>Medium Level</title > </head > <body style="background-color:violet;"> """ for i in d1: contents += f"""<p> * {i["external_name"]} </p>""" contents += f"""<p><a href="/">Main page </a></body></html>""" status = 200 except ValueError: contents = Path("Error.html").read_text() status = 404 except KeyError: contents = Path("Error.html").read_text() status = 404 self.send_response(status) # Define the content-type header: self.send_header('Content-Type', content_type) self.send_header('Content-Length', len(contents.encode())) # The header is finished self.end_headers() # Send the response message self.wfile.write(contents.encode()) return
except ConnectionRefusedError: print("ERROR! Cannot connect to the Server") exit() r1 = conn.getresponse() print(f"Response received!: {r1.status} {r1.reason}") data1 = r1.read().decode() gene = json.loads(data1) termcolor.cprint("Gene", 'green', end="") print(f": {name}") termcolor.cprint("Description", 'green', end="") print(f": {gene['desc']}") genestr = gene['seq'] s = Seq(genestr) length = s.len() termcolor.cprint("Total length", 'green', end="") print(f": {length}") for e in BASES: count = s.count_base(e) percentage = round(s.count_base(e) * (100 / s.len()), 2) termcolor.cprint(f"{e}", 'blue', end="") print(f": {count} ({percentage}%)") dictionary = s.seq_count() list_values = list(dictionary.values()) max_base = max(list_values)
from P1.Seq1 import Seq print("-----| Practice 1, Exercise 4 |------") s1 = Seq() s2 = Seq("ACTGA") s3 = Seq("Invalid Sequence") print("Sequence" + str(1) + ": (Length: " + str(s1.len()), ")" + str(s1)) print("Sequence" + str(2) + ": (Length: " + str(s2.len()), ")" + str(s2)) print("Sequence" + str(3) + ": (Length: " + str(s3.len()), ")" + str(s3))
cmd1 = msg cmd2 = '' response = '' if cmd1 == 'PING': termcolor.cprint('PING command!', 'green') response = 'OK!' elif cmd1 == "GET": for element in range(len(sequences)): if element == int(cmd2): termcolor.cprint("GET", 'green') response = sequences[element] elif cmd1 == "INFO": seq0 = Seq(cmd2) response = "" termcolor.cprint("INFO", 'green') response += f'Sequence: {cmd2}' response += f"Total length: {seq0.len()}" for element in bases: resp = round(seq0.count_base(element) * (100 / seq0.len()), 2) response += f'{element}: {seq0.count_base(element)} ( {resp}% ) \n' elif cmd1 == "COMP": seq0 = Seq(cmd2) termcolor.cprint("COMP", 'green') response = seq0.complement() elif cmd1 == "REV": seq0 = Seq(cmd2)
from P1.Seq1 import Seq print("-----|Practice 1 , Exercise 4 |------") s1 = Seq() s2 = Seq("AGCTG") s3 = Seq("AGJHMC") print(f" Sequence 1 : (Length: {s1.len()}), {s1}") print(f" Sequence 2 : (Length: {s2.len()}), {s2}") print(f" Sequence 3 : (Length: {s3.len()}), {s3}")
from P1.Seq1 import Seq folder = "../Session-04/" filenames = ["U5", "ADA", "FRAT1", "FXN", "RNU6_269P"] all_bases = ["A", "C", "G", "T"] print("-----|Practice 1 , Exercise 10 |------") for filename in filenames: s0 = Seq() s0.read_fasta(folder + filename) dictionary = s0.count() list_values = list(dictionary.values()) maximum = max(list_values) print( f"Gene {filename}: Most frequent Base: {all_bases[list_values.index(maximum)]}" )
from P1.Seq1 import Seq def print_result(i, sequence): print("Sequence" + str(i) + ": (Lenght: " + str(sequence.len()) + ") " + str(sequence)) print("Bases:", sequence.count()) print("Rev:", sequence.reverse()) print("Comp:", sequence.complement()) PROJECT_PATH = "../P1/PROJECT/" print("----- | Practice 1, Exercise 9 | ------") s1 = Seq() s1.read_fasta(PROJECT_PATH + "U5.txt") print_result("", s1)
from P1.Seq1 import Seq print("-----| Practice 1 , Exercise 2 |------") s1 = Seq() s2 = Seq("ACCGA") print(f" Sequence 1: {s1}") print(f" Sequence 2: {s2}")
from P1.Seq1 import Seq print("-----|Practice 1, Exercise 2,3|-----") s1 = Seq() s2 = Seq("ACTGA") s3 = Seq("jskdhs") print("Sequence 1: " + str(s1)) print("Sequence 2: " + str(s2)) print("Sequence 3: " + str(s3))
from P1.Seq1 import Seq s0 = Seq() s1 = Seq("ACTGA") s2 = Seq("AFCTGS") all_bases = ["A", "C", "G", "T"] print("-----| Practice 1, Exercise 5 |------") print(f" Sequence 0 : (Length {s0.len()} ), {s0}") for base in all_bases: print(base + ":", s0.count_base(base), end=" ") print(f" Sequence 1 : (Length {s1.len()} ) , {s1}") for base in all_bases: print(base + ":", s1.count_base(base), end=" ") print(f" Sequence 2 : (Length {s2.len()} ) , {s2}") for base in all_bases: print(base + ":", s2.count_base(base), end=" ")
from P1.Seq1 import Seq print("-----|Practice 1, Exercise 4|-----") s1 = Seq() s2 = Seq("ACTGA") s3 = Seq("jskdhs") print("Sequence 1: " + ": (Length:" + str(s1.len()) + " ) " + str(s1)) print("Sequence 2: " + ": (Length:" + str(s2.len()) + " ) " + str(s2)) print("Sequence 3: " + ": (Length:" + str(s3.len()) + " ) " + str(s3))
from P1.Seq1 import Seq print("-----| Practice 1, Exercise 9 |------") FOLDER = "../Session-04/" TypeDoc = '.txt' seq = Seq(FOLDER + 'U5' + TypeDoc) seq.read_fasta(FOLDER + 'U5' + TypeDoc) print("Sequence ", seq, ':', "(Length: ", seq.len(), ')', seq) print(" Bases:", seq.seq_count()) print(' Rev: ', seq.reverse(), '\n Comp: ', seq.complement())
def do_GET(self): json_option = False response_status = 200 termcolor.cprint(self.requestline, 'green') server = 'rest.ensembl.org' # -- If nothing is written after connecting the port, the page will display completely: if self.path == '/': filename = 'index.html' with open(filename, 'r') as f: contents = f.read() # -- If the user asks for any of the following functions ('elifs'), different information will be given: elif '/listSpecies' in self.path: # -- Make the request: parameters = self.extract_parameters(self.path) connection = http.client.HTTPConnection(server) endpoint = 'info/species/' params = '?content-type=application/json' connection.request('GET', endpoint + params) req = connection.getresponse() # -- Process data: req_data = req.read().decode("utf-8") answer = json.loads(req_data) data_species = answer['species'] try: if 'limit' in parameters and parameters['limit'] != '': limit = int(parameters['limit']) else: limit = len(data_species) # -- Now if 'json' is in the request, the contents will be given in this format if 'json' in parameters: json_option = True list_species = data_species[1:limit + 1] contents = json.dumps(list_species) # -- If 'json' is not in the request, the contents will be an html file else: contents = """ <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS">LIST OF SPECIES: <ol> """ # -- Iterate for each value until it reaches the desired limit counter = 0 for specie in data_species: contents = contents + f"""<li> {specie['display_name']} </li>""" counter = counter + 1 if counter == limit: break contents = contents + """ </ol> </font> <br> <a href="/">[Main page]</a> </body> </html> """ connection.close() # -- This error raises if the input is not a number except ValueError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/karyotype' in self.path: parameters = self.extract_parameters(self.path) if 'specie' in parameters and parameters['specie'] != '': specie = parameters['specie'] try: # -- Make the request: endpoint = '/info/assembly/' params = '?content-type=application/json' conn = http.client.HTTPConnection(server) conn.request('GET', endpoint + specie + params) req = conn.getresponse() # -- Process data: text_json = req.read().decode("utf-8") answer = json.loads(text_json) chromosome_data = answer['karyotype'] # -- Now if 'json' is in the request, the contents will be given in this format: if 'json' in parameters: json_option = True contents = json.dumps(chromosome_data) # -- If 'json' is not in the request, the contents will be an html file: else: contents = f""" <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS"> <This is the karyotype information of the {specie}: <ul>""" # -- Iterate on the chromosome_data so that we get the karyotype of the desired: for specie in chromosome_data: contents = contents + f"""<li> {specie} </li>""" contents = contents + """ </ul> </font> <br> <a href="/">[Main page]</a> </body> </html> """ # -- This exception raises when the specie doesn't belong in the chromosome_data, so it doesn't exist: except KeyError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank: else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/chromosomeLength' in self.path: parameters = self.extract_parameters(self.path) if 'specie' and 'chromo' in parameters and parameters[ 'specie'] != '' and parameters['chromo'] != '': specie = parameters['specie'] chromosome = parameters['chromo'] try: # -- Make the request: conn = http.client.HTTPConnection(server) endpoint = '/info/assembly/' params = '?content-type=application/json' conn.request('GET', endpoint + specie + params) req1 = conn.getresponse() # -- Process data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) chromosome_specie = answer['top_level_region'] # -- Now if 'json' is in the request, the contents will be given in this format if 'json' in parameters: json_option = True chromosome_length = 0 # -- Here we iterate in chromosome_specie so that we get the length of the desired specie for i in chromosome_specie: if i['name'] == chromosome: chromosome_length = str(i['length']) # -- Then we create a dictionary to place all the information that we got with the iteration: length_dictionary = dict() length_dictionary['length'] = chromosome_length contents = json.dumps(length_dictionary) # -- If 'json' is not in the request, the contents will be an html file else: contents = f""" <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS"> <p>This is the length of the {chromosome} chromosome of the {specie}:</p>""" # -- Here we iterate in chromosome_specie so that we get the desired chromosome # -- And the we take the value in the key 'length': chromosome_length = 0 for i in chromosome_specie: if i['name'] == chromosome: chromosome_length = str(i['length']) contents = contents + f""" <ul><li>{str(chromosome_length)}</li></ul> <br> <a href="/">[Main page]</a> </body> </html> """ # -- This error raises if the input is not a number: except ValueError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This exception raises when the specie doesn't belong in the chromosome_specie, so it doesn't exist: except KeyError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank: else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/geneSeq' in self.path: parameters = self.extract_parameters(self.path) if 'gene' in parameters and parameters['gene'] != '': gene = parameters['gene'] try: # -- Make the request: conn = http.client.HTTPConnection(server) endpoint1 = '/homology/symbol/human/' params = '?content-type=application/json' conn.request('GET', endpoint1 + gene + params) req1 = conn.getresponse() # -- Process data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) id = answer['data'][0]['id'] # -- Make the request with the new endpoint: endpoint2 = '/sequence/id/' conn.request('GET', endpoint2 + id + params) req1 = conn.getresponse() # -- Process data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) sequence = answer['seq'] # -- Now if 'json' is in the request, the contents will be given in this format: if 'json' in parameters: json_option = True # -- A dictionary with the sequence is created, so it can display the info in that format: seq_dictionary = dict() seq_dictionary['seq'] = sequence contents = json.dumps(seq_dictionary) # -- If 'json' is not in the request, the contents will be an html file else: contents = f""" <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS">The sequence corresponding to gene {gene} is:</font> <br><br> {sequence} <br><br> <a href="/">[Main page]</a> </body> </html> """ # -- This exception raises when the specie doesn't belong in the chromosome_data, so it doesn't exist: except KeyError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank: else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/geneInfo' in self.path: parameters = self.extract_parameters(self.path) if 'gene' in parameters and parameters['gene'] != '': gene = parameters['gene'] try: # -- Make the request: conn = http.client.HTTPConnection(server) endpoint1 = '/homology/symbol/human/' params1 = '?content-type=application/json' conn.request('GET', endpoint1 + gene + params1) req1 = conn.getresponse() # -- Process data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) id = answer['data'][0]['id'] # -- Make the second request: endpoint2 = '/overlap/id/' params2 = '?feature=gene;content-type=application/json' conn.request('GET', endpoint2 + id + params2) req1 = conn.getresponse() # -- Process the received data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) start = answer[0]['start'] end = answer[0]['end'] length = end - start chromosome = answer[0]['assembly_name'] # -- If 'json' is in the request, the contents will be given in this format: if 'json' in parameters: json_option = True # -- We create a dictionary to store all the values for each type of info: info_dictionary = dict() info_dictionary['start'] = start info_dictionary['end'] = end info_dictionary['length'] = length info_dictionary['chromosome'] = chromosome contents = json.dumps(info_dictionary) # -- If 'json' is not in the request, the contents will be an html file: else: contents = f""" <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS"> <p>The information corresponding to gene {gene}</p> <li>START: {str(start)}</li> <li>END: {str(end)}</li> <li>ID: {str(id)} </li> <li>LENGTH: {str(length)} <li>CHROMOSOME: {chromosome} </font> <br> <a href="/">[Main page]</a> </body> </html> """ except KeyError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/geneCalc' in self.path: parameters = self.extract_parameters(self.path) if 'gene' in parameters and parameters['gene'] != '': gene = parameters['gene'] try: # -- Make the request: connection = http.client.HTTPConnection(server) endpoint1 = '/homology/symbol/human/' params = '?content-type=application/json' connection.request('GET', endpoint1 + gene + params) req1 = connection.getresponse() # -- Process data: text_json = req1.read().decode("utf-8") answer = json.loads(text_json) id = answer['data'][0]['id'] endpoint2 = '/sequence/id/' connection.request('GET', endpoint2 + id + params) req1 = connection.getresponse() text_json = req1.read().decode("utf-8") answer = json.loads(text_json) sequence = answer['seq'] seq = Seq(sequence) length = len(sequence) percentageA = seq.percent('A') percentageC = seq.percent('C') percentageT = seq.percent('T') percentageG = seq.percent('G') # -- If 'json' is in the request, the contents will be given in this format: if 'json' in parameters: json_option = True calc_dictionary = dict() calc_dictionary['sequence'] = sequence calc_dictionary['percentage A'] = percentageA calc_dictionary['percentage C'] = percentageC calc_dictionary['percentage T'] = percentageT calc_dictionary['percentage G'] = percentageG calc_dictionary['length'] = length contents = json.dumps(calc_dictionary) else: contents = f""" <html> <body style="background-color: powderblue;"> <font face="Trebuchet MS"> <p>The sequence corresponding to gene {gene} is: </p> {sequence} <p> The calculations are: </p> <li>TOTAL LENGTH: {str(length)} <li>PERCENTAGE OF A BASES: {str(percentageA)} <li>PERCENTAGE OF C BASES: {str(percentageC)} <li>PERCENTAGE OF T BASES: {str(percentageT)} <li>PERCENTAGE OF G BASES: {str(percentageG)} </font> <br> <br> <a href="/">[Main page]</a> </body> </html> """ except KeyError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() elif '/geneList' in self.path: parameters = self.extract_parameters(self.path) if 'start' in parameters and parameters[ 'start'] != '' and 'chromo' in parameters and parameters[ 'chromo'] != '' and 'end' in parameters and parameters[ 'end'] != '': chromosome = parameters['chromo'] start = parameters['start'] end = parameters['end'] try: # -- Make the request: conn = http.client.HTTPConnection(server) endpoint = "/overlap/region/human/" params = "?content-type=application/json;feature=gene;feature=transcript;feature=cds;feature=exon" conn.request( "GET", endpoint + str(chromosome) + ":" + str(start) + "-" + str(end) + params) r1 = conn.getresponse() # -- Process data: text_json = r1.read().decode("utf-8") answer = json.loads(text_json) # -- If 'json' is in the request, the contents will be given in this format: if 'json' in parameters: json_option = True json_list = [] # -- Here, it iterates through the info received from ensembl until it reaches the # 'feature_type' key, the information there will be stored and given in a json format for element in answer: if element['feature_type'] == 'gene': gene_dictionary = dict() gene_dictionary['name'] = element[ 'external_name'] gene_dictionary['start'] = element['start'] gene_dictionary['end'] = element['end'] json_list.append(gene_dictionary) contents = json.dumps(json_list) else: contents = f""" <html> <body style= "background-color: powderblue;"> <font face="Trebuchet MS"> <p>The names of the genes located in chromosome {chromosome} from {start} to {end} are: </p> """ for element in answer: if 'feature_type' in element and ( element['feature_type'] == 'gene'): contents = contents + f"""<li> {element['external_name']} </li>""" contents = contents + """ </font> <br> <br> <a href="/">[Main page]</a> </body> </html> """ # -- This error raises if the input is not a number except ValueError: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the input is left in blank else: response_status = 404 filename = open('error.html', 'r') contents = filename.read() # -- This error raises if the URL doesn't include an existent function: else: response_status = 404 filename = 'error.html' with open(filename, 'r') as f: contents = f.read() self.send_response(response_status) # -- Status line: OK! # Define the content-type header: if json_option is True: self.send_header('Content-Type', 'application/json') else: self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(str.encode(contents))) # The header is finished self.end_headers() # Send the response message self.wfile.write(str.encode(contents)) return
from P1.Seq1 import Seq def print_result(i, sequence): print("Sequence" + str(i) + ": (Length: " + str(sequence.len()), ")" + str(sequence)) a, c, g, t = sequence.count_bases() print("A: " +str(a) + ",C :" + str(c) + ",G :"+str(g) + ",T :" + str(t)) print("-----| Practice 1, Exercise 5 |------") s1 = Seq() s2 = Seq("ACTGA") s3 = Seq("Invalid Sequence") print_result(1, s1) print_result(2, s2) print_result(3, s3)
# -- form the JSON received response = json.loads(data1) # Information of the gene Description = response["desc"] termcolor.cprint(f"Gene:","green",end=" ") print(G) termcolor.cprint(f"Description:","green",end=" ") print(Description) # Introduce the sequence s = Seq(response["seq"]) s_length = s.len() termcolor.cprint(f"Total length: ","green",end="") print(s_length) for b in all_bases: count_b = s.count_base(b) p =round(count_b *( 100 / s_length),1)#percentage calculation with just 1 decimal termcolor.cprint(f"{b}", "blue", end=" ") print(f"{count_b} {p} %") dict = s.count() # method from P1 to find the most repeated base list_dict = list(dict.values()) maximum = max(list_dict) freq_base = all_bases[list_dict.index(maximum)] termcolor.cprint("Most frequent base : ","green",end="") print(freq_base)
from P1.Seq1 import Seq print("-----| Practice 1, Exercise 6 |------") seq0 = Seq() seq1 = Seq("ACTGA") seq2 = Seq("Invalid sequence") bases = ["A", "T", "C", "G"] for seq, value in enumerate([seq0, seq1, seq2]): print("Sequence ", seq, ':', "(Length: ", value.len(), ')', value) print("Bases:", value.seq_count())
from P1.Seq1 import Seq print('----| Exercise 1 |------') seq = Seq("ACTGA") print("Sequence 1:", "(Length: ", seq.len(), ')', seq)
from P1.Seq1 import Seq FOLDER = "../Session-04/" Filename = ["U5", "ADA", "FRAT1", "FXN", "RNU6_269P"] TypeDOC = '.txt' bases = ['A', 'C', 'G', 'T'] print('----| Practice 1, Exercise 10| ----') i = 0 for element in Filename: seq = Seq() seq.read_fasta(FOLDER + element + TypeDOC) Dictionary_bases = seq.seq_count() Amount_bases = list(Dictionary_bases.values()) Most_freq = max(Amount_bases) print('Gene ', element, ': Most frequent base: ', bases[Amount_bases.index(Most_freq)])
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" # Print the request line termcolor.cprint(self.requestline, 'green') request = self.requestline.split(' ') raw_arg = request[1] clean_arg = raw_arg.split('?') argument = clean_arg[0] if argument == '/': contents = Path('form-4.html').read_text() elif argument == '/ping': contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> PING </title > </head > <body> <h2> PING OK!</h2> <p> The SEQ2 server is running </p> <a href="/">Main page</a> </body> </html> """ elif argument == '/get': argument1 = clean_arg[1].split('&') name, value = argument1[0].split('=') value = int(value) sequence = Sequences[value] contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> GET </title > </head > <body> <h2> Sequence number {value}</h2> <p> {sequence} </p> <a href="/">Main page</a> </body> </html> """ elif argument == '/gene': argument1 = clean_arg[1].split('&') name, gene = argument1[0].split('=') sequence = Seq() sequence.read_fasta(FOLDER + gene + TypeDoc) gene_str = str(sequence) contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> GENE </title > </head > <body> <h2> Gene: {gene}</h2> <textarea readonly rows="20" cols="80"> {gene_str} </textarea> <br> <br> <a href="/">Main page</a> </body> </html>""" elif argument == '/operation': argument1 = clean_arg[1].split('&') name, sequence = argument1[0].split("=") name, operation = argument1[1].split("=") seq = Seq(sequence) if operation == 'comp': result = seq.complement() elif operation == 'rev': result = seq.reverse() else: length = seq.len() num_bases = [] perc_bases = [] for element in bases: counter_bases = seq.count_base(element) percentage = round( (seq.count_base(element) * 100 / seq.len()), 2) num_bases.append(counter_bases) perc_bases.append(percentage) result = f""" <p>Total length: {length}</p> <p>A: {num_bases[0]} ({perc_bases[0]}%)</p> <p>C: {num_bases[1]} ({perc_bases[1]}%)</p> <p>G: {num_bases[2]} ({perc_bases[2]}%)</p> <p>T: {num_bases[3]} ({perc_bases[3]}%)</p>""" contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> OPERATION </title > </head > <body> <h2>Sequence</h2> <p>{seq}</p> <h2>Operation</h2> <p>{operation}</p> <h2>Result</h2> <p>{result}</p> <br> <br> <a href="/">Main page</a> </body> </html>""" else: contents = Path('error.html').read_text() # Generating the response message self.send_response(200) # -- Status line: OK! # Define the content-type header: self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(str.encode(contents))) # The header is finished self.end_headers() # Send the response message self.wfile.write(str.encode(contents)) return
from P1.Seq1 import Seq print("-----| Practice 1 , Exercise 1 |------") s1 = Seq("ACCTGA") print(f"Sequence 1: (Length: {s1.len()}), {s1}")
from P1.Seq1 import Seq print("-----|Practice 1 , Exercise 8 |------") s0 = Seq() s1 = Seq("ACGTGA") s2 = Seq("AGSTGC") print(f"Sequence 0: (Length {s0.len()} ){s0} ") print(f" Bases : {s0.count()}") print(f"Rev: {s0.reverse()}") print(f" Comp :{s0.complement()}") print(f"Sequence 0: (Length {s1.len()} ){s1} ") print(f" Bases : {s1.count()}") print(f"Rev: {s1.reverse()}") print(f" Comp :{s1.complement()}") print(f"Sequence 0: (Length {s2.len()} ){s2} ") print(f" Bases : {s2.count()}") print(f"Rev: {s2.reverse()}") print(f" Comp :{s2.complement()}")