def info(seq): s = Seq(seq) s_length = s.len() counter_A = s.count_base("A") counter_C = s.count_base("C") counter_G = s.count_base("G") counter_T = s.count_base("T") per_A = "{:.1f}".format(100 * counter_A / s_length) per_C = "{:.1f}".format(100 * counter_C / s_length) per_G = "{:.1f}".format(100 * counter_G / s_length) per_T = "{:.1f}".format(100 * counter_T / s_length) response_message = f"""Sequence: {s} f"Total length: {s_length}" A: {counter_A} ({per_A}%) C: {counter_C} ({per_C}%) G: {counter_G} ({per_G}%) T: {counter_T} ({per_T}%)""" return response_message
from P1.Seq1 import Seq print('-----| Practice 1, Exercise 4 |------') seq1 = Seq() seq2 = Seq("ACTGA") seq3 = Seq("Invalid sequence") print("Sequence 1 : (Length: ", seq1.len(), ')', seq1) print("Sequence 2 : (Length: ", seq2.len(), ')', seq2) print("Sequence 3 : (Length: ", seq3.len(), ')', seq3)
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" # Define the sequences that we are going to use in "get" and the bases for exercise 4 sequence = ["GTAGCA", "ACGTTA", "CGTAGG", "ATTGTC"] all_bases = ["A", "C", "G", "T"] # 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] # All the information appears in "form-4.html" if arg0 == "/": contents = Path("form-4.html").read_text() status = 200 elif arg0 == "/ping": contents = """ <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> ping </title > </head > <body> <h2> PING ok!</h2> <p> The SEQ2 Server in running... </p> <a href="/">Main page</a> </body> </html> """ status = 200 elif arg0 == "/get": # We define our second argument, the one after the "?" that we have split. arg1 = argument[1] # To split the "&" that is after the value args = arg1.split("&") # Is necessary to split the "=" after our name ("msg") name, value = args[0].split("=") # We define the argument n n = int(value) seq = sequence[n - 1] contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> get </title > </head > <body> <h2>Sequence number {n}</h2> <p> {seq}</p> <a href="/">Main page</a> </body> </html> """ status = 200 elif arg0 == "/gene": # We define our second argument, the one after the "?" that we have split. arg1 = argument[1] # To split the "&" that is after the value args = arg1.split("&") # Is necessary to split the "=" after our name ("msg") name, gene_name = args[0].split("=") # Sequence of the gene s = Seq() s_string = str(s.read_fasta(FOLDER + gene_name)) contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> gene </title > </head > <body> <h2>Gene {gene_name}</h2> <textarea readonly rows="20" cols="80"> {s_string} </textarea> <a href="/">Main page</a> </body> </html> """ status = 200 elif arg0 == "/operation": # We define our second argument, the one after the "?" that we have split. arg1 = argument[1] # To split the "&" that is after the value args = arg1.split("&") # Name and values (=arguments) #seq in order to create the sequence name, seq = args[0].split("=") #op are the different options that can be chosen after the sequence is written name, op = args[1].split("=") #Introduce the sequence s = Seq(seq) if "info" in op: s = Seq(seq) s_length = s.len() list1 = [] list2 = [] 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 list1.append( count_b) # list 1: where we put the total bases list2.append( p ) # list2 : where we put the percentage of all the bases response = f""" Total length: {s_length} <p>A: {list1[0]} ({list2[0]}%)</p> <p>C: {list1[1]} ({list2[1]}%)</p> <p>G: {list1[2]} ({list2[2]}%)</p> <p>G: {list1[3]} ({list2[3]}%)</p> """ elif "comp" in op: response = s.complement() elif "rev" in op: response = s.reverse() 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>{op}</p> <h2>Result :</h2> <p>{response}</p> <a href="/">Main page</a> </body> </html> """ status = 200 else: # Error.html file contents = Path("Error.html").read_text() status = 404 # Generating the response message 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
from P1.Seq1 import Seq print("-----| Exercise 1 |------") seq = Seq("ACTGA") print("Sequence" + str(1) + ": (Length: " +str(seq.len()), ")" + str(seq))
# -- form the JSON received response = json.loads(data1) # Information of the gene Description = response["desc"] termcolor.cprint(f"Gene:", "green", end=" ") print(gene_input) termcolor.cprint(f"Description:", "green", end=" ") print(Description) # Introduce the sequence seq = Seq(response["seq"]) s_length = seq.len() counter_A = seq.count_base(all_bases[0]) counter_C = seq.count_base(all_bases[1]) counter_G = seq.count_base(all_bases[2]) counter_T = seq.count_base(all_bases[3]) per_A = "{:.1f}".format(100 * counter_A / s_length) per_C = "{:.1f}".format(100 * counter_C / s_length) per_G = "{:.1f}".format(100 * counter_G / s_length) per_T = "{:.1f}".format(100 * counter_T / s_length) # Print the length termcolor.cprint(f"Total length:", "green", end=" ") print(s_length) termcolor.cprint(f"A", "blue", end=" ") print(f"{counter_A} {per_A}%")
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) termcolor.cprint("Most frequent base", 'green', end="") print(f": {BASES[list_values.index(max_base)]}")
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())
from P1.Seq1 import Seq print('----| Exercise 1 |------') seq = Seq("ACTGA") print("Sequence 1:", "(Length: ", seq.len(), ')', seq)
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
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 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))
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
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) termcolor.cprint("REV", 'green') response = seq0.reverse() elif cmd1 == "GENE": seq0 = Seq("") seq0 = seq0.read_fasta(folder + cmd2 + '.txt')
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))