from Seq1 import Seq print("----Exercise 7----") bases = ["A", "C", "G", "T"] s1 = Seq("") s2 = Seq("ACTGA") s3 = Seq("Invalid sequence") print("Sequence 1", ": (Lenght: ", s1.len(), ")", s1) print("Bases: ", s1.count()) print("Reverse: ", s1.reverse()) print("Sequence 2", ": (Lenght: ", s2.len(), ")", s2) print("Bases: ", s2.count()) print("Reverse: ", s2.reverse()) print("Sequence 3", ": (Lenght: ", s3.len(), ")", s3) print("Bases: ", s3.count()) print("Reverse: ", s3.reverse())
from Seq1 import Seq print("----| Practice 1, Exerxise 4 |----") s1 = Seq() s2 = Seq("ACTGA") s3 = Seq("Invalid sequence") print("Sequence 1: (Length: ", s1.len(), ")", s1) print("Sequence 2: (Length: ", s2.len(), ")", s2) print("Sequence 3: (Length: ", s3.len(), ")", s3)
from Seq1 import Seq print("------| ") 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""" # Print the request line termcolor.cprint(self.requestline, 'green') #User line user_line = self.requestline.split(" ") #Take the symbol / out of the path path = user_line[1] #Read the text u_text = path.split('?') #Read the first thing of the text header = u_text[0] # Open the form1.html file # Read the index from the file contents = Path('Error.html').read_text() error_code = 404 if header == "/": # Read the index from the file open contents = Path('form-4.html').read_text() error_code = 200 elif header == "/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> """ error_code = 200 elif header == "/get": u_set = u_text[1] sets = u_set.split("&") key, value = sets[0].split("=") n = int(value) seq = SEQ_GET[n] # Html code 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> """ error_code = 200 elif header == "/gene": u_set = u_text[1] sets = u_set.split("&") key, gene = sets[0].split("=") s = Seq() s.read_fasta(FOLDER + gene + EXT) gene_str = str(s) # html code 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> """ error_code = 200 elif header == "/operation": u_set = u_text[1] sets = u_set.split("&") key, seq = sets[0].split("=") key, op = sets[1].split("=") # -- Create the sequence s = Seq(seq) if op == "comp": resp = s.complement() elif op == "rev": resp = s.reverse() else: sl = s.len() ca = s.count_base('A') pa = "{:.1f}".format(100 * ca / sl) cc = s.count_base('C') pc = "{:.1f}".format(100 * cc / sl) cg = s.count_base('G') pg = "{:.1f}".format(100 * cg / sl) ct = s.count_base('T') pt = "{:.1f}".format(100 * ct / sl) resp = f""" <p>Total length: {sl}</p> <p>A: {ca} ({pa}%)</p> <p>C: {cc} ({pc}%)</p> <p>G: {cg} ({pg}%)</p> <p>T: {ct} ({pt}%)</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>{op}</p> <h2> Result: </h2> <p>{resp}</p> <br> <br> <a href="/">Main page</a> </body> </html> """ error_code = 200 # Generating the response message self.send_response(error_code) # -- 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
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') command = self.requestline.split(' ') #Command 2 is used to delete the interrogation mark. command2 = command[1].split('?') #This is the content before interrogation mark. first_w = command2[0] output = Path('error.html').read_text() code = 404 if first_w == "/": output = Path('ex4.html').read_text() code = 200 elif first_w == '/ping': output = Path('ping.html').read_text() code = 200 elif first_w == '/get': # This is the content after interrogation mark. after_int = command2[1] # After interrogation mark there are two words, a name and a the value of the name, that are separated by an equal mark. w1, w2 = after_int.split('=') x = int(w2) sequence_n = sequence[x] output = f'''<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> RESULT </title> </head> <body> <h2> Sequence number: {x} </h2> <p> {sequence_n} </p> <a href="/">Main page</a> </body> </html>''' code = 200 elif first_w == '/gene': # This is the content after interrogation mark. after_int = command2[1] # After interrogation mark there are two words, a name and a the value of the name, that are separated by an equal mark. w1, w2 = after_int.split('=') seq = Seq() sequence_g = str(seq.read_fasta(FOLDER + w2 + EXT)) output = f'''<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> RESULT </title> </head> <body> <h2> Gene: {w2} </h2> <p> {sequence_g} </p> <a href="/">Main page</a> </body> </html>''' code = 200 elif first_w == '/operation': final = '' # This is the content after interrogation mark. after_int = command2[1] check = after_int.split('&') # After interrogation mark there are two words, a name and a the value of the name, that are separated by an equal mark. w1, w2 = check[0].split('=') x1, x2 = check[1].split('=') #x2 es la opción elegida. seq = Seq(w2) if x2 == 'Comp': final = seq.complement() elif x2 == 'Rev': final = seq.reverse() elif x2 == 'Info': length = seq.len() count_A = seq.count_base('A') count_C = seq.count_base('C') count_G = seq.count_base('G') count_T = seq.count_base('T') perc_A = round(((count_A * 100) / length), 3) perc_C = round(((count_C * 100) / length), 3) perc_G = round(((count_G * 100) / length), 3) perc_T = round(((count_T * 100) / length), 3) final = f'Total length: {length}\n A: {count_A} ({perc_A}%)\n C: {count_C} ({perc_C}%)\n G: {count_G} ({perc_G}%)\n T: {count_T} ({perc_T}%)' code = 200 output = f'''<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" <title> RESULT </title> </head> <body> <h2> Sequence:</h2> <p> {w2} </p> <h2> Operation:</h2> <p> {x2} </p> <h2> Result: </h2> <p> {final} </p> <a href="/">Main page</a> </body> </html>''' self.send_response(code) # Define the content-type header: self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(str.encode(output))) # The header is finished self.end_headers() # Send the response message self.wfile.write(str.encode(output)) return
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" # Print the request line print(self.requestline) # Analize the request line req_line = self.requestline.split(' ') # Get the path. It always start with the / symbol path = req_line[1] # separamos el path, lo que está antes del ? y lo que está depues arguments = path.split("?") action = arguments[0] sequences = [ "ACCTTGAA", "TGCATGCA", "GGGCATTA", "CTCTCAGA", "AGTAATGC" ] if path == "/": # Manda la pg principal contents = Path("form-4.html").read_text() status = 200 elif action == "/ping": # Escribe en la pg principal # después del ? 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 action == "/get": # Coger lo que está despues del interrogante (n=2) number = arguments[1] # Coger el número que seleccionas n = int(number.split("=")[1]) seq = sequences[n] # POnemos la f antes para que asà te añada las seq y el número seleccionado 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 action == "/gene": gene_and_name = arguments[1] name = gene_and_name.split("=")[1] s = Seq("") s_str = str(s.read_fasta(FOLDER + name + TEXT)) contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> GENE </title > </head > <body> <h2> Gene: {name}</h2> <textarea readonly rows="20" cols="80"> {s_str} </textarea> <br> <br> <a href="/">Main page</a> </body> </html> """ status = 200 elif action == "/operation": msg_op = arguments[1] # Cogemos msg = y el mensaje msg = msg_op.split("&")[0] # Ahora cogemos solo la cadena que se introduce gene = msg.split("=")[1] # Creamos la secuencia seq = Seq(gene) # la operación name_op = msg_op.split("&")[1] # Operación seleccionada operation_select = name_op.split("=")[1] if operation_select == "Info": seq_length = seq.len() number_of_A = seq.count_base("A") percentage_A = "{:.1f}".format(100 * number_of_A / seq_length) number_of_G = seq.count_base("G") percentage_G = "{:.1f}".format(100 * number_of_G / seq_length) number_of_T = seq.count_base("T") percentage_T = "{:.1f}".format(100 * number_of_T / seq_length) number_of_C = seq.count_base("C") percentage_C = "{:.1f}".format(100 * number_of_C / seq_length) contents_of_operations = f""" <p>Total length: {seq_length}</p> <p>A: {number_of_A} ({percentage_A}%)</p> <p>C: {number_of_C} ({percentage_C}%)</p> <p>G: {number_of_G} ({percentage_G}%)</p> <p>T: {number_of_T} ({percentage_T}%)</p>""" elif operation_select == "Comp": contents_of_operations = seq.complement() # Para cuendo sea operation_select == "Rev": else: contents_of_operations = seq.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>{operation_select}</p> <h2> Result: </h2> <p>{contents_of_operations}</p> <br> <br> <a href="/">Main page</a> </body> </html> """ status = 200 else: # -- Resource NOT FOUND print("ERROR: Not found") # Message to send back to the clinet contents = Path("Error.html").read_text() # Status code is NOT FOUND status = 404 # Generating the response message self.send_response(status) # -- 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
def do_GET(self): termcolor.cprint(self.requestline, 'green') path = self.requestline.split()[1] arguments = path.split('?') firts_argument = arguments[0] try: if firts_argument == "/": contents = Path("main-page.html").read_text() self.send_response(200) elif firts_argument == "/listSpecies": second_argument = arguments[1] parameters = second_argument.split("&") data = get_data( "info/species?content-type=application/json")["species"] if len(parameters) == 2: parameter_1, json = second_argument.split("&") number = parameter_1.split("=")[1] if json == "json=1": list = [] counter = 0 if number == "": for element in data: list.append(element["display_name"]) counter += 1 contents = dict_listSpecies(number, list) elif 267 >= int(number): for element in data: if counter < int(number): list.append(element["display_name"]) counter += 1 contents = dict_listSpecies(number, list) else: for element in data: list.append(element["display_name"]) counter += 1 contents = dict_listSpecies(number, list) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 1: number = second_argument.split("=")[1] contents = html_format("lightyellow", "List of species") contents += f"""<h1> SPECIES ON DATABASE OF ENSEMBL </h1>""" contents += f"""<p>Total number of species in the ensembl database is 267</p>""" contents += f"""<p>The limit you have selected is: {number}</p>""" contents += f"""<p>The names of the species are:</p>""" if number == "": for element in data: contents += f"""<p> - {element["display_name"]}</p> """ elif 267 >= int(number): counter = 0 for element in data: if counter < int(number): contents += f"""<p> - {element["display_name"]}</p> """ counter += 1 else: for element in data: contents += f"""<p> - {element["display_name"]}</p> """ self.send_response(200) elif firts_argument == "/karyotype": second_argument = arguments[1] parameters = second_argument.split("&") if len(parameters) == 2: parameter_1, json = second_argument.split("&") specie = parameter_1.split("=")[1] data = get_data( f"/info/assembly/{specie}?content-type=application/json" )["karyotype"] if json == "json=1": list = [] for element in data: list.append(element) contents = dict_karyotype(list) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 1: specie = second_argument.split("=")[1] data = get_data( f"/info/assembly/{specie}?content-type=application/json" ) karyotype = data["karyotype"] contents = html_format("lightgreen", "Karyotype") contents += f"""<h1> KARYOTYPE </h1>""" contents += f"""<p>The names of the chromosomes from {specie} are:</p>""" for chromosome in karyotype: contents += f"""<p> - {chromosome}</p>""" self.send_response(200) elif firts_argument == "/chromosomeLength": second_argument = arguments[1] arguments = second_argument.split("&") if len(arguments) == 3: specie, chromo, json = second_argument.split("&") specie_name = specie.split("=")[1] chromo_name = chromo.split("=")[1] data = get_data( f"/info/assembly/{specie_name}?content-type=application/json" ) if json == "json=1": info = data["top_level_region"] contents = dict_chromosomeLength(0) for element in info: if element["name"] == chromo_name: length = element["length"] contents = dict_chromosomeLength(length) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(arguments) == 2: specie, chromo = second_argument.split("&") specie_name = specie.split("=")[1] chromo_name = chromo.split("=")[1] data = get_data( f"/info/assembly/{specie_name}?content-type=application/json" ) information = data["top_level_region"] contents = html_format("salmon", "Chromosome length") contents += "<h1> CHROMOSOME LENGTH </h1>" for chromosome in information: if chromosome["coord_system"] == "chromosome": if chromosome["name"] == chromo_name: c_lenght = chromosome['length'] contents += f"""<p> The length of the chromosome {chromo_name} is: {c_lenght}</p>""" self.send_response(200) elif firts_argument == "/geneSeq": second_argument = arguments[1] parameters = second_argument.split("&") if len(parameters) == 2: parameter_1, json = second_argument.split("&") gene = parameter_1.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/sequence/id/{gene_id}?content-type=application/json""" ) if json == "json=1": contents = dict_geneSeq(data["seq"]) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 1: gene = second_argument.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/sequence/id/{gene_id}?content-type=application/json""" ) contents = html_format("pink", "Sequences") contents += "<h1> SEQUENCES OF HUMAN GENES </h1>" contents += f'<p> The sequence of gene {gene} is: </p>' contents += f'<textarea rows = "100" "cols = 500"> {data["seq"]} </textarea>' self.send_response(200) elif firts_argument == "/geneInfo": second_argument = arguments[1] parameters = second_argument.split("&") if len(parameters) == 2: parameter_1, json = second_argument.split("&") gene = parameter_1.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/lookup/id/{gene_id}?content-type=application/json""" ) if json == "json=1": length = data["end"] - data["start"] contents = dict_geneInfo(data["start"], data["end"], length, data["id"], data["seq_region_name"]) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 1: gene = second_argument.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/lookup/id/{gene_id}?content-type=application/json""" ) contents = html_format("plum", "Information") contents += f'<h1>INFORMATION ABOUT HUMAN GENE {gene} </h1>' contents += f'<p> The start point is: {data["start"]}</p>' contents += f'<p> The end point is: {data["end"]}</p>' contents += f'<p> The length of the gene is: {data["end"] - data["start"]}</p>' contents += f'<p> The id of the gene is: {gene_id}</p>' contents += f'<p> The gene is on chromosome {data["seq_region_name"]}</p>' self.send_response(200) elif firts_argument == "/geneCalc": second_argument = arguments[1] parameters = second_argument.split("&") if len(parameters) == 2: parameter_1, json = second_argument.split("&") gene = parameter_1.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/sequence/id/{gene_id}?content-type=application/json""" ) sequence = Seq(data["seq"]) if json == "json=1": bases = [] for base in list_bases: bases.append(sequence.seq_count_base(base)[1]) contents = dict_geneCalc(sequence.len(), bases) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 1: gene = second_argument.split("=")[1] gene_id = get_data( f"""/xrefs/symbol/homo_sapiens/{gene}?content-type=application/json""" )[0]["id"] data = get_data( f"""/sequence/id/{gene_id}?content-type=application/json""" ) sequence = Seq(data["seq"]) contents = html_format("lightblue", "Calculations") contents += F"<h1> CALCULATIONS OF GENE {gene}</h1>" contents += f"<p> Total length: {sequence.len()} </p>" contents += "<p> Percentage of its bases: </p>" for base in list_bases: contents += f"<p>- {base}: {sequence.seq_count_base(base)[1]}%</p>" self.send_response(200) elif firts_argument == "/geneList": second_argument = arguments[1] parameters = second_argument.split("&") if len(parameters) == 4: chromo, start, end, json = second_argument.split("&") chromo_name = chromo.split("=")[1] start_point = start.split("=")[1] end_point = end.split("=")[1] data = get_data( f"""/overlap/region/human/{chromo_name}:{start_point}-{end_point}?feature=gene;content-type=application/json""" ) if json == "json=1": list = [] for gene in data: list.append(gene["external_name"]) contents = dict_geneList(list) self.send_response(200) else: contents = Path("error.json").read_text() self.send_response(404) elif len(parameters) == 3: chromo, start, end = second_argument.split("&") chromo_name = chromo.split("=")[1] start_point = start.split("=")[1] end_point = end.split("=")[1] data = get_data( f"""/overlap/region/human/{chromo_name}:{start_point}-{end_point}?feature=gene;content-type=application/json""" ) contents = html_format("peachpuff", "List of genes") contents += "<h1> LIST OF GENES </h1>" contents += f"<p> Here is the list of some genes from chromosome {chromo_name}:</p>" for gene in data: contents += f'<p> - {gene["external_name"]}</p>' self.send_response(200) except (KeyError, TypeError, ValueError, IndexError): contents = Path('Error.html').read_text() self.send_response(404) endpoints = [ "/", "/listSpecies", "/karyotype", "/chromosomeLength", "/geneSeq", "/geneInfo", "/geneCalc", "/geneList" ] if firts_argument in endpoints: if "json" in path: type = "application/json" else: type = "text/html" self.send_header('Content-Type', type) self.send_header('Content-Length', len(str.encode(contents))) self.end_headers() self.wfile.write(str.encode(contents)) return
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" termcolor.cprint(self.requestline, "green") # We get the first request line and then the path, goes after /. We get the arguments that go after the ? symbol req_line = self.requestline.split(' ') path = req_line[1] arguments = path.split('?') # Action is the first argument action = arguments[0] contents = Path('error.html').read_text() code = 200 # First we open index.html if we don´t specify any action, this is the Index menu if action == "/": contents = Path('form-4.html').read_text() elif action == "/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>""" elif action == "/get": # We get the arguments that go after the ? symbol get_value = arguments[1] # We get the seq index, after we have a couple of elements, the one which we need is the value of the index # position of the sequence seq_n = get_value.split('?') seq_name, index = seq_n[0].split("=") index = int(index) # Once we have the index we can get our sequence from Seq_List seq = Seq_List[index] # This is the html code that will show up once we are getting back the sequence we selected contents = f"""<!DOCTYPE html><html lang = "en"><head><meta charset = "utf-8" ><title> Get </title ></head > <body><h2> Sequence number {index}</h2><p> {seq} </p><a href="/">Main page</a></body></html>""" elif action == "/gene": # We get the arguments that go after the ? symbol gene_value = arguments[1] # After we have a couple of elements, the one which we need is the name of the gene, for reading the file # using the specific function from Seq class pairs = gene_value.split('&') gene_name, gene = pairs[0].split("=") # We call Seq class and read the file correspondent to the gene variable, we read the file, get the seq and # convert into string s = Seq() filename = Folder + gene + txt seq = Seq(s.read_fasta(filename)) gene_seq = str(seq) # This is the html code that will show up once we are getting back the sequence we selected 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_seq} </textarea><br><br> <a href="/">Main page</a></body></html>""" elif action == "/operation": # We get the arguments that go after the ? symbol pair = arguments[1] # We have a couple of elements, we need the sequence that we previously wrote and the operation to perform # that we previously selected pairs = pair.split('&') seq_name, seq = pairs[0].split("=") op_name, op = pairs[1].split("=") # Using Seq class we transform the sequence we introduced. According to the operation we selected we will # use one function of the class or other seq = Seq(seq) if op == "rev": result = seq.reverse() elif op == "comp": result = seq.complement() else: length = seq.len() counter_a = seq.count_base('A') counter_g = seq.count_base('G') counter_c = seq.count_base('C') counter_t = seq.count_base('T') perc_a = 100 * counter_a / length perc_g = 100 * counter_g / length perc_c = 100 * counter_c / length perc_t = 100 * counter_t / length result = f"""<p>Total length: {length}</p><p>A: {counter_a} ({perc_a}%)</p><p>G: {counter_g} ({perc_g}%) </p><p>C: {counter_c} ({perc_c}%)</p><p>T: {counter_t} ({perc_t}%)</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>{op}</p><h2> Result: </h2><p>{result} </p><br><br><a href="/">Main page</a></body></html>""" # Generating the response message self.send_response(code) # -- 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
termcolor.cprint("PING command!", 'green') response = "OK!\n" elif comp1 == "GET": for e in range(len(sequences)): if e == int(comp2): termcolor.cprint("GET", 'green') response = sequences[e] elif comp1 == "INFO": seq0 = Seq(comp2) termcolor.cprint("INFO", 'green') response = f"Sequence: {comp2} \n" response += f"Total length: {seq0.len()} \n" for e in bases: percentage = round(seq0.count_base(e) * (100 / seq0.len()), 2) response += f"{e}: {seq0.count_base(e)} ({percentage}%) \n" elif comp1 == "COMP": seq0 = Seq(comp2) termcolor.cprint("COMP", 'green') response = seq0.complement() elif comp1 == "REV": seq0 = Seq(comp2) termcolor.cprint("REV", 'green') response = seq0.reverse() elif comp1 == "GENE": seq0 = Seq("") seq0 = seq0.read_fasta(folder + comp2)
def do_GET(self): termcolor.cprint(self.requestline, 'green') req_line = self.requestline.split(' ') path = req_line[1] arguments = path.split('?') verb = arguments[0] contents = Path('Error.html').read_text() error_code = 404 if verb == "/": contents = Path('form-4.html').read_text() error_code = 200 elif verb == "/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> """ error_code = 200 elif verb == "/get": pair = arguments[1] pairs = pair.split('&') name, value = pairs[0].split("=") n = int(value) seq = SEQ_GET[n] 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> """ error_code = 200 elif verb == "/gene": pair = arguments[1] pairs = pair.split('&') name, value = pairs[0].split("=") s = Seq() s.read_fasta(FOLDER + value + EXT) value_gene = str(s) contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> GET </title > </head > <body> <h2> Gene: {value}</h2> <p> {value_gene} </p> <a href="/">Main page</a> </body> </html> """ error_code = 200 elif verb == "/operation": pair = arguments[1] pairs = pair.split('&') name, seq = pairs[0].split("=") name, op = pairs[1].split("=") s = Seq(seq) if op == "comp": result = s.seq_complement() elif op == "rev": result = s.seq_reverse() else: slen = s.len() ca = s.count_base('A') pa = round(100 * ca / slen, 1) cc = s.count_base('C') pc = round(100 * cc / slen, 1) cg = s.count_base('G') pg = round(100 * cg / slen, 1) ct = s.count_base('T') pt = round(100 * ct / slen, 1) result = f""" <p>Total length: {slen}</p> <p>A: {ca} ({pa}%)</p> <p>C: {cc} ({pc}%)</p> <p>G: {cg} ({pg}%)</p> <p>T: {ct} ({pt}%)</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> {op} </p> <h2> Result </h2> <p> {result} </p> <a href="/">Main page</a> </body> </html> """ error_code = 200 self.send_response(error_code) self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(str.encode(contents))) self.end_headers() self.wfile.write(str.encode(contents)) return
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') req_line = self.requestline.split(' ') args = (req_line[1]).split("?") #With this .split() we separate the instruction that the program has to perform from the input first_arg = args[0] contents = Path('Error.html').read_text() self.send_response(404) try: if first_arg == "/": #This If will bring us to the main page were we choose what we are going to perform and the output contents = Path('listspecies.html').read_text() contents += Path('karyotype.html').read_text() contents += Path('chromosomeLength.html').read_text() contents += Path('geneseq.html').read_text() contents += Path('geneinfo.html').read_text() contents += Path('geneCalc.html').read_text() contents += Path('genelist.html').read_text() self.send_response(200) else: if first_arg in '/listSpecies': ENDPOINT = '/info/species' #This is the ENSEMBL REST API endpoint that will get us the list of species conn.request("GET", ENDPOINT + ALWAYS_PARAMS) resp1 = conn.getresponse() data_ = resp1.read().decode("utf-8") api_info = json.loads(data_) if len(args) > 1: args_2 = args #We change this to avoid the index out of range error second_arg = args_2[1] seq_args = second_arg.split("=") list_species = [] if seq_args[1] == '' or (len(seq_args[1]) == 5 and 'json' in seq_args[1]): #This If includes any type of request line that doesn't have a limit, puts every species in a list for e in api_info['species']: list_species.append(e['display_name']) else: #This Else will be used when we put a limit in a request line if len(seq_args) == 3: seq_args = (seq_args[1]).split('&') sp_name = api_info['species'] counter = 0 for i in sp_name: if counter < int(seq_args[0]): list_species.append(i['display_name']) counter += 1 else: sp_name = api_info['species'] counter = 0 for i in sp_name: if counter < int(seq_args[1]): list_species.append(i['display_name']) counter += 1 if 'json=1' in req_line[1]: #This If is for the advanced part, when we want the output in json format if len(args) == 1 or ('0123456789' not in seq_args[1]): dict_json = {'ListSpecies': list_species} contents = json.dumps(dict_json) self.send_response(200) else: dict_json = {'ListSpecies': {'Limit': seq_args[0], 'Species': list_species}} contents = json.dumps(dict_json) self.send_response(200) else: #This is used when we don't select the json option, we just want it in HTML format contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>LIST OF SPECIES</title> </head> <body style="background-color: lightblue;"> """ contents += f"<h2> Species List</h2>" contents += f"<p>The total number of species in ensembl is: {len(api_info['species'])}</p>" if not len(args) == 1 or ((args[1])[-1] == '='): contents += f"<p>The limit the user has selected is: {seq_args[-1]}</p>" for i in list_species: contents += f"<p>-{i}</p>" contents += '<a href="/">Main Page</a>' contents += "</body></html>" self.send_response(200) elif first_arg in '/karyotype': second_arg = args[1] seq_args = second_arg.split("=") if '&' in seq_args[1]: #This If is for the advanced part, will separate the species from the json=1 when the option is selected sp_arg = (seq_args[1]).split('&') sp_arg = sp_arg[0] #This will be the name of the species we are going to take the karyotype of else: sp_arg = seq_args[-1] ENDPOINT = '/info/assembly/' PARAMS = sp_arg + ALWAYS_PARAMS conn.request("GET", ENDPOINT + PARAMS) resp1 = conn.getresponse() data_ = resp1.read().decode("utf-8") api_info = json.loads(data_) karyotype_list = [] for i in api_info['karyotype']: #This loop will store every chromosome in a list karyotype_list.append(i) if 'json=1' in req_line[1]: dict_json = {'species':{sp_arg:{'chromosomes': karyotype_list}}} contents = json.dumps(dict_json) else: contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>KARYOTYPE</title> </head> <body style="background-color: lightblue;"> """ contents += f"<h2> Karyotype of the species: {seq_args[-1]}</h2>" #The variable between the {} will be the name of the species, same as sp_arg for e in karyotype_list: contents += f"<p>{e}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" self.send_response(200) elif first_arg in "/chromosomeLength": second_arg = args[1] seq_args = second_arg.split("=") #With this .split() we are getting the species and the chromosome together args_def = seq_args[1].split("&") #With this .split() we separate the species and chromosome chromosome = seq_args[-1] #This variable will store the name of the chromosome if 'json' in seq_args[2]: #This If will be used when we want the output in json format args_json = seq_args[2].split('&') chromosome = args_json[0] ENDPOINT = '/info/assembly/' PARAMS = args_def[0] + ALWAYS_PARAMS #args_def[0] is the name of the species that we want to know something about conn.request("GET", ENDPOINT + PARAMS) resp1 = conn.getresponse() data_ = resp1.read().decode("utf-8") api_info = json.loads(data_) chromo_length = '' for e in api_info['top_level_region']: #The top_level_region key, refers to the chromosome of which we want to know the length about if e['name'] == chromosome: chromo_length += str(e['length']) if 'json=1' in req_line[1]: #This if will be used when we check the json option dict_json = {'species':{args_def[0]:{'Chromosome':{chromosome:{'The length of the chromosome is:': chromo_length}}}}} contents = json.dumps(dict_json) else: contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CHROMOSOME LENGTH</title> </head> <body style="background-color: lightblue;"> """ contents += f"<h2> Chromosome: {seq_args[-1]} Species: {args_def[0]}</h2>" contents += f"<p>The length of the chromosome is: {chromo_length}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" self.send_response(200) elif first_arg == "/geneList": ENDPOINT = '/overlap/region/human/' second_arg = args[1] seq_args = second_arg.split("&") #With this .split(), we put on a list the arguments; start, end and chromosome values_for_params = [] contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>GENE LIST</title> </head> <body style="background-color: lightblue;"> """ for e in seq_args: #In this for we are putting on a list only the numbers, with the earlier .split() we got together the value it self and the name for ex. start=300 e = e.split('=') values_for_params.append(e[-1]) PARAMS = values_for_params[0] + ':' + values_for_params[1] + '-' + values_for_params[2] + '?feature=gene;content-type=application/json' conn.request("GET", ENDPOINT + PARAMS) resp1 = conn.getresponse() data_1 = resp1.read().decode("utf-8") api_info_genelist = json.loads(data_1) contents += f"<h2>The genes in the chromosome {values_for_params[0]} that start at {values_for_params[1]} and end at {values_for_params[2]} are:</h2>" gene_in_chromo = [] for i in api_info_genelist: #In this loop we put on a list the different genes in the range and the chromosome selected in the main page contents += f"<p>{i['external_name']}</p>" gene_in_chromo.append(i['external_name']) contents += '<a href="/">Main page</a>' contents += "</body></html>" if 'json=1' in req_line[1]: #This if will be used when we check the json option contents = '' dict_json = {'chromosome': values_for_params[0], 'Start': values_for_params[1], 'End': values_for_params[2], 'Genes': gene_in_chromo} contents = json.dumps(dict_json) self.send_response(200) else: #In this else, as you can see, we are acceding to two dictionaries already without caring about the endpoint, that is because they will be used in al three endpoints ENDPOINT1 = '/xrefs/symbol/homo_sapiens/' second_arg = args[1] seq_args = second_arg.split("=") gene_name = seq_args[1] #With the .split() above and this slicing, gene_name is going to be the name of the gene that we write in the main page if 'json' in seq_args[1]: #This If is from the advanced section, will separte the json=1 of the gene name when the option is selected args_json = seq_args[1].split('&') gene_name = args_json[0] PARAMS1 = gene_name + ALWAYS_PARAMS conn.request("GET", ENDPOINT1 + PARAMS1) resp1 = conn.getresponse() data_1 = resp1.read().decode("utf-8") api_info_id = json.loads(data_1) gene_id = api_info_id[0] gene_id = gene_id['id'] ENDPOINT2 = '/sequence/id/' PARAMS2 = gene_id + ALWAYS_PARAMS conn.request("GET", ENDPOINT2 + PARAMS2) resp2 = conn.getresponse() data_2 = resp2.read().decode("utf-8") api_info_seq = json.loads(data_2) contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>GENE</title> </head> <body style="background-color: lightblue;"> """ if first_arg == "/geneSeq": gene_seq = '' gene_seq += api_info_seq['seq'] #gene_seq will be the sequence of bases of the selected gene if 'json=1' in req_line[1]: #This if will be used when we check the json option dict_json = {'Gene name:':{gene_name:{'Sequence':gene_seq}}} contents = json.dumps(dict_json) else: contents += f"<h2>The sequence of the gene {gene_name}</h2>" contents += f"<textarea readonly rows = 20 cols = 80>{gene_seq}</textarea>" contents += '<a href="/">Main page</a>' contents += "</body></html>" elif first_arg == '/geneInfo': ENDPOINT3 = '/lookup/id/' #This is an extra dictionary that we will ned for this specific endpoint PARAMS3 = gene_id + ALWAYS_PARAMS conn.request("GET", ENDPOINT3 + PARAMS3) resp3 = conn.getresponse() data_3 = resp3.read().decode("utf-8") api_info_gene = json.loads(data_3) seq0 = Seq(api_info_seq['seq']) #We import the class Seq from Seq1, it will be useful for the things we have to do in this endpoint if 'json=1' in req_line[1]: #This if will be used when we check the json option dict_json = {'gene': gene_name, 'Start': api_info_gene['start'], 'End': api_info_gene['end'], 'Length': seq0.len(), 'Chromosome': api_info_gene['seq_region_name'], 'ID': gene_id} contents = json.dumps(dict_json) else: contents += f"<h2>Information about the gene: {gene_name}</h2>" contents += f"<p>The start: {api_info_gene['start']}</p>" contents += f"<p>The end: {api_info_gene['end']}</p>" contents += f"<p>The length of the gene's sequence is: {seq0.len()}</p>" contents += f"<p>This gene is located in the chromosome: {api_info_gene['seq_region_name']}</p>" contents += f"<p>The ID of the gene is: {gene_id}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" elif first_arg == "/geneCalc": seq0 = Seq(api_info_seq['seq']) #We import the class Seq from Seq1, it will be useful for the things we have to do in this endpoint if 'json=1' in req_line[1]: #This if will be used when we check the json option for e in bases: contents += f"<p>{e} : {seq0.count_base(e)} ({round(seq0.count_base(e) * (100 / seq0.len()), 2)}%)</p>" dict_json = {'Gene': gene_name, 'Length': seq0.len(), 'A':{seq0.count_base('A'): {'Percentage': (round(seq0.count_base('A') * (100 / seq0.len()), 2))}}, 'C':{seq0.count_base('C'): {'Percentage': (round(seq0.count_base('C') * (100 / seq0.len()), 2))}}, 'T':{seq0.count_base('T'): {'Percentage': (round(seq0.count_base('T') * (100 / seq0.len()), 2))}}, 'G':{seq0.count_base('G'): {'Percentage': (round(seq0.count_base('G') * (100 / seq0.len()), 2))}}} contents = json.dumps(dict_json) else: #This will be used when the json option is not selected contents += f"<h2>Some calculations of the gene: {gene_name}</h2>" contents += f"<p>The length of the sequence is: {seq0.len()}</p>" for e in bases: contents += f"<p>{e} : {seq0.count_base(e)} ({round(seq0.count_base(e)*(100/seq0.len()), 2)}%)</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" self.send_response(200) #All the exceptions below, are to avoid certain type of errors, instead of that it will send you tu the error page except ValueError: contents = Path('Error.html').read_text() contents += f"<p>This is a ValueError type </p>" self.send_response(404) except KeyError: contents = Path('Error.html').read_text() contents += f"<p>This is a KeyError type </p>" self.send_response(404) except IndexError: contents = Path('Error.html').read_text() contents += f"<p>This is an IndexError type </p>" self.send_response(404) except TypeError: contents = Path('Error.html').read_text() contents += f"<p>This is a TypeError type </p>" self.send_response(404) # Read the index from th # Define the content-type header: if 'json=1' in req_line: self.send_header('Content-Type', 'application/json') self.send_header('Content-Length', len(str.encode(contents))) 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
response = list_sequences[int(argument)] + "\n" cs.send(response.encode()) except IndexError: response = "The number you have introduced is out of range\n" cs.send(response.encode()) except ValueError: response = "The sequence introduces must be a number\n" cs.send(response.encode()) elif command == "INFO": s = Seq(argument) if s.create_dict() == True: response = "THE SEQUENCE SELECTED IS WRONG\n" cs.send(response.encode()) else: response = str(s.len()) + "\n" + str(s.count_bases()) + "\n" cs.send(response.encode()) elif command == "COMP": s = Seq(argument) try: response = str(s.seq_complement()) + "\n" cs.send(response.encode()) except ValueError: pass elif command == "REV": s = Seq(argument) response = str(s.seq_reverse()) + "\n" cs.send(response.encode())
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" connection = http.client.HTTPConnection(SERVER) # We just print a message print("GET received! Request line:") # Print the request line termcolor.cprint(" " + self.requestline, 'green') # Print the command received (should be GET) print(" Command: " + self.command) # Print the resource requested (the path) termcolor.cprint(" Path: " + self.path, "blue") # we are creating a parse object (easier way to work with the elements of the path o = urlparse(self.path) path_name = o.path arguments = parse_qs(o.query) print("Resource requested: ", path_name) print("Parameters: ", arguments) context = {} try: if path_name == "/": contents = su.read_template_html_file( "./html/INDEX.html").render(context=context) elif path_name == "/listSpecies": ENDPOINT = "/info/species" connection.request("GET", ENDPOINT + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) species_list = [] amount_species = len(response_dict["species"]) context["amount_species"] = amount_species limit = int(arguments["limit"][0]) context["limit"] = limit for n in range(0, limit): species_list.append( response_dict["species"][n]["common_name"]) context["names"] = species_list contents = su.read_template_html_file( "html/LISTSPECIES.html").render(context=context) elif path_name == "/karyotype": ENDPOINT = "info/assembly/" specie = arguments["species"][0] connection.request("GET", ENDPOINT + specie + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) karyotype = response_dict["karyotype"] context["species"] = arguments["species"][0] context["karyotype"] = karyotype contents = su.read_template_html_file( "./html/KARYOTYPE.html").render(context=context) elif path_name == "/chromosomeLength": ENDPOINT = "info/assembly/" specie = arguments["species"][0] connection.request("GET", ENDPOINT + specie + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) chromosome = arguments["chromosome"][0] for n in range(0, len(response_dict["top_level_region"])): if chromosome == response_dict["top_level_region"][n][ "name"]: length = response_dict["top_level_region"][n]["length"] context["length"] = length contents = su.read_template_html_file( "./html/CHROMOSOMELENGTH.html").render(context=context) elif path_name == "/geneSeq": ENDPOINT = "/sequence/id/" gene = arguments["gene"][0] id = DICT_GENES[gene] connection.request("GET", ENDPOINT + id + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) context["seq"] = response_dict["seq"] contents = su.read_template_html_file( "./html/SEQGENE.html").render(context=context) elif path_name == "/geneInfo": ENDPOINT = "/sequence/id/" gene = arguments["gene"][0] id = DICT_GENES[gene] connection.request("GET", ENDPOINT + id + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) info = response_dict["desc"].split(":") context["dict_info"] = { "Name": info[1], "ID": id, "Start": info[3], "End": info[4], "Length": (int(info[4]) - int(info[3]) + 1) } contents = su.read_template_html_file( "./html/INFOGENE.html").render(context=context) elif path_name == "/geneCalc": ENDPOINT = "/sequence/id/" gene = arguments["gene"][0] id = DICT_GENES[gene] connection.request("GET", ENDPOINT + id + Parameters) response = connection.getresponse() response_dict = json.loads(response.read().decode()) sequence = Seq(response_dict["seq"]) dict_bases = Seq.count(sequence) percentage = Seq.percentage(sequence) context["length"] = Seq.len(sequence) context["bases"] = { "A": str(dict_bases["A"]) + " (" + str(percentage[0]) + "%)", "C": str(dict_bases["C"]) + " (" + str(percentage[1]) + "%)", "T": str(dict_bases["T"]) + " (" + str(percentage[2]) + "%)", "G": str(dict_bases["G"]) + " (" + str(percentage[3]) + "%)" } contents = su.read_template_html_file( "./html/CALCGENE.html").render(context=context) else: contents = su.read_template_html_file( "./html/ERROR.html").render() except KeyError: contents = su.read_template_html_file("./html/ERROR.html").render() except IndexError: contents = su.read_template_html_file("./html/ERROR.html").render() # 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(contents.encode())) # The header is finished self.end_headers( ) # we always need to call the end headers method which forces to create an empty line of the HTTP message # Send the response message self.wfile.write(contents.encode( )) # wfile acts like a socket, its just something that we can write on # IN this simple server version: # We are NOT processing the client's request return
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') # -- Analyze the request line req_line = self.requestline.split(' ') # -- Get the path. It always start with the / symbol path = req_line[1] # -- Check all the arguments arguments = path.split('?') # -- The verb is located as the first argument verb = arguments[0] contents = Path('Error.html').read_text() status = 404 # -- Gives a response depending of the existence of de if verb == '/': # OPen form-1 file (HTML) contents = Path('form-4.html').read_text() # Status code status = 200 elif verb == '/ping': # Verification page to show that the server is on-line contents = ''' <!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 correctly... </p> <h2>Received message:</h2> <a href='/'>Main page</a> </body> </html> ''' status = 200 elif verb == '/get': pair = arguments[1] tpe = pair.split('?') ind, value = tpe[0].split('=') n = int(value) # -- Get sequence seq = seq_num[n] # -- HTML 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 verb == '/gene': # -- Get the argument to the right of the ? symbol pair = arguments[1] # -- Get all the pairs name = value pairs = pair.split('&') # -- Get the two elements: name and value name, gene = pairs[0].split('=') s = Seq() s = s.read_fasta(folder + gene) gene_str = str(s) # -- Generate the html code 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> """ status = 200 elif verb == '/operation': # -- Get the argument to the right of the ? symbol pair = arguments[1] # -- Get all the pairs name = value pairs = pair.split('&') # -- Get the two elements: name and value, and the operation name w/ the chosen operation name, seq = pairs[0].split('=') o_name, operation = pairs[1].split('=') seq = Seq(seq) if operation == 'Rev': result = seq.reverse() elif operation == 'Comp': result = seq.complement() else: # We calculate the length, amount of bases and the percentage they occupy in the sequence g_len = seq.len() counter = seq.count() per_a = 100 * int(counter['A']) / g_len per_c = 100 * int(counter['C']) / g_len per_t = 100 * int(counter['T']) / g_len per_g = 100 * int(counter['G']) / g_len result = f""" <p>Total length: {g_len}</p> <p>A: {counter['A']} ({per_a}%)</p> <p>C: {counter['C']} ({per_c}%)</p> <p>G: {counter['T']} ({per_t}%)</p> <p>T: {counter['G']} ({per_g}%)</p>""" contents = f""" <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" > <title> Operations </title > </head > <body> <h2> Seq:</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> """ status = 200 # -- Generating the response message self.send_response(status) # -- Define the content-type header: content_type = 'text/html' 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 Seq1 import Seq print("-----| Exercise 1 |------") seq_1 = Seq("ACTGA") print("Sequence", 1, ": (Length:", seq_1.len(), ")", seq_1)
from Seq1 import Seq print('--------|exercise 1|------') seq = Seq('ACTGA') print('Sequence ' + str(1) + ': (length: ' + str(seq.len()) + ') ' + str(seq))
# pip install termcolor from Seq1 import Seq print('-----EXERCISE 1 -----') seq = Seq('ACTGA') print('Sequence ' + str(1) + ': (Length '+ str(seq.len()) + ' ) ' + str(seq)) print('-----EXERCISE 2-3 -----') s1 = Seq() s2 = Seq('ACTG') s3 = Seq('Invalid Sequence') print('Sequence 1:', s1) print('Sequence 2:', s2) print('Sequence 3:', s3) print('-----EXERCISE 4 -----') s1 = Seq() s2 = Seq('ACTG') 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))
termcolor.cprint("PING command!", 'yellow') print("OK!") output += "OK!\n" elif x1 == 'GET': for element in range(len(genes)): if element == int(x2): termcolor.cprint('GET!', 'yellow') output += genes[element] print(genes[element]) elif x1 == 'INFO': sequence = Seq(x2) termcolor.cprint('INFO!', 'yellow') print('Sequence: ', x2) print("Total length: ", sequence.len()) output += f'Sequence: {x2}\n' output += f'Total length: {sequence.len()}\n' for element in bases: print( f'{element}: {sequence.count_base(element)} ({sequence.count_base(element)*100/sequence.len()}%)' ) output += f'{element}: {sequence.count_base(element)} ({sequence.count_base(element)*100/sequence.len()}%)\n' elif x1 == 'COMP': sequence = Seq(x2) termcolor.cprint('COMP!', 'yellow') print(sequence.complement()) output += sequence.complement() elif x1 == 'REV':
# PING command if "PING" == service: response = "OK!\n" # Return response OK!! # GET command elif "GET" == service: response = seq_list[int(argument)] # INFO command elif "INFO" == service: seq_info = Seq(argument) # argument is the sequence count_bases_string = "" for base, count in seq_info.count().items(): s_base = str(base) + ": " + str(count) + " (" + str( round(count / seq_info.len() * 100, 2)) + "%)" + "\n" count_bases_string += s_base response = ("Sequence: " + str(seq_info) + "\n" + "Total length: " + str(seq_info.len()) + "\n" + count_bases_string) elif "COMP" == service: seq_comp = Seq(argument) response = seq_comp.complement() + "\n" elif "REV" == service: seq_rev = Seq(argument) response = seq_rev.reverse() + "\n" elif "GENE" == service:
elif command[1] == "3": print(list_seq[3], "\n") response = list_seq[3] cs.send(response.encode()) elif command[1] == "4": print(list_seq[4], "\n") response = list_seq[4] cs.send(response.encode()) elif command[0] == "INFO": termcolor.cprint("INFO", 'green') sequence = Seq(li_command[1]) print("Sequence: ", sequence) print("Total lenght: ", sequence.len()) a_count = sequence.count_base('A') c_count = sequence.count_base('C') g_count = sequence.count_base('G') t_count = sequence.count_base('T') a_percent = (100 * a_count / sequence.len()) c_percent = (100 * c_count / sequence.len()) g_percent = (100 * g_count / sequence.len()) t_percent = (100 * t_count / sequence.len()) print("A:", a_count, "(", round(a_percent, 2), "%)") print("C:", c_count, "(", round(c_percent, 2), "%)") print("G:", g_count, "(", round(g_percent, 2), "%)") print("T:", t_count, "(", round(t_percent, 2), "%)") response = f"""Sequence: {sequence}
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 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))
# Create a variable with the data, # form the JSON received gene = json.loads(data1) termcolor.cprint("Gene", 'green', end="") print(f": {name}") termcolor.cprint("Description", 'green', end="") print(f": {gene['desc']}") gene_str = gene['seq'] # Create the object sequence from the string s = Seq(gene_str) sl = s.len() ca = s.count_base('A') pa = "{:.1f}".format(100 * ca / sl) cc = s.count_base('C') pc = "{:.1f}".format(100 * cc / sl) cg = s.count_base('G') pg = "{:.1f}".format(100 * cg / sl) ct = s.count_base('T') pt = "{:.1f}".format(100 * ct / sl) termcolor.cprint("Total length", 'green', end="") print(f": {sl}") termcolor.cprint("A", 'blue', end="") print(f": {ca} ({pa}%)") termcolor.cprint("C", 'blue', end="")
# -- Read the response's body content = answer.read().decode() # -- Create a variable with the data, # -- form the JSON received gene = json.loads(content) termcolor.cprint("Gene:", "green", end="") print(GENE_NAME) termcolor.cprint("Description:", "green", end="") print(gene["desc"]) body = gene["seq"] seq = Seq(body) l = seq.len() A_COUNTER = seq.count_base('A') C_COUNTER = seq.count_base('C') G_COUNTER = seq.count_base('G') T_COUNTER = seq.count_base('T') A_PER = 100 * A_COUNTER / l C_PER = 100 * C_COUNTER / l G_PER = 100 * G_COUNTER / l T_PER = 100 * T_COUNTER / l print(f"""Total length: {l} A: {A_COUNTER} ({A_PER}%) G: {G_COUNTER} ({G_PER}%) C: {C_COUNTER} ({C_PER}%) T: {T_COUNTER} ({T_PER}%)""")
from Seq1 import Seq #--Main prog print("-----|Practice 1, Exercise 5|-----") s1 = Seq("") s2 = Seq("ACTGA") s3 = Seq("Invalid sequence") print("Sequence", 1, ": (Length:", s1.len(), ")", s1) print( f"A: {s1.count_base('A')} , C: {s1.count_base('C')} , T: {s1.count_base('T')} , G: {s1.count_base('G')}" ) print("Sequence", 2, ": (Length:", s2.len(), ")", s2) print( f"A: {s2.count_base('A')} , C: {s2.count_base('C')} , T: {s2.count_base('T')} , G: {s2.count_base('G')}" ) print("Sequence", 3, ": (Length:", s3.len(), ")", s3) print( f"A: {s3.count_base('A')} , C: {s3.count_base('C')} , T: {s3.count_base('T')} , G: {s3.count_base('G')}" )
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']}") GENE_SEQ = GENE['seq'] # -- Create the object sequence from the string s = Seq(GENE_SEQ) s_length = s.len() ca = s.count_base('A') pa = "{:.1f}".format(100 * ca / s_length) cc = s.count_base('C') pc = "{:.1f}".format(100 * cc / s_length) cg = s.count_base('G') pg = "{:.1f}".format(100 * cg / s_length) ct = s.count_base('T') pt = "{:.1f}".format(100 * ct / s_length) termcolor.cprint("Total lengh", 'green', end="") print(f": {s_length}") termcolor.cprint("A", 'blue', end="") print(f": {ca} ({pa}%)") termcolor.cprint("C", 'blue', end="")
termcolor.cprint(gene2, 'blue') termcolor.cprint('The beginning of the gene is: ', 'magenta', end='') termcolor.cprint(info_dict['desc'].split(':')[3], 'blue') termcolor.cprint('The end of the gene is: ', 'magenta', end='') termcolor.cprint(info_dict['desc'].split(':')[4], 'blue') termcolor.cprint('The chromosome name is: ', 'magenta', end='') termcolor.cprint(info_dict['desc'].split(':')[1], 'blue') termcolor.cprint('The ID is: ', 'magenta', end='') termcolor.cprint(info_dict['id'], 'blue') termcolor.cprint('The length is: ', 'magenta', end='') termcolor.cprint(gene2_object.len(), 'blue') termcolor.cprint( '=============================================================================', 'green') endpoint6 = "/geneCalc?gene=FXN" try: conn.request("GET", endpoint6 + PARAM) # send the request except ConnectionRefusedError: print("ERROR! Cannot connect to the Server") exit() calc_response = conn.getresponse() print(f"Response received!: {calc_response.status} {calc_response.reason}\n") calc_dict = json.loads(calc_response.read().decode())
from Seq1 import Seq print("-----|Practice 1, Exercise 9|-----") folder = "../Session-04/" filename = "U5.txt" FILENAME = folder + filename s = Seq() s1 = Seq(s.read_fasta(FILENAME)) print("Sequence 1", ": (Length:", s1.len(), ")", (s1)) print(f"Bases: {s1.count()}") print(f"Reverse: {s1.reverse()}") print(f"Comp: {s1.complement()}")
def do_GET(self): """This method is called whenever the client invokes the GET method in the HTTP protocol request""" global seq_args termcolor.cprint(self.requestline, 'green') req_line = self.requestline.split(' ') args = (req_line[1]).split("?") first_arg = args[0] self.send_response(404) try: if first_arg == "/": contents = Path('listspecies.html').read_text() contents += Path('karyotype.html').read_text() contents += Path('chromosomelength.html').read_text() contents += Path('geneseq.html').read_text() contents += Path('geneinfo.html').read_text() contents += Path('geneCalc.html').read_text() contents += Path('genelist.html').read_text() self.send_response(200) else: if first_arg in '/listSpecies': endpoint = '/info/species' conn.request("GET", endpoint + INITIAL_PARAMETERS) resp1 = conn.getresponse() data_read = resp1.read().decode("utf-8") api_info = json.loads(data_read) if len(args) > 1: args_2 = args second_arg = args_2[1] seq_args = second_arg.split("=") list_species = [] if seq_args[1] == '' or (len(seq_args[1]) == 5 and 'json' in seq_args[1]): for e in api_info['species']: list_species.append(e['display_name']) else: if len(seq_args) == 3: seq_args = (seq_args[1]).split('&') sp_name = api_info['species'] counter = 0 for i in sp_name: if counter < int(seq_args[0]): list_species.append(i['display_name']) counter += 1 else: sp_name = api_info['species'] counter = 0 for i in sp_name: if counter < int(seq_args[1]): list_species.append(i['display_name']) counter += 1 if 'json=1' in req_line[1]: if len(args) == 1 or ('0123456789' not in seq_args[1]): dict_json = {'ListSpecies': list_species} contents = json.dumps(dict_json) self.send_response(200) else: dict_json = {'ListSpecies': {'Limit': seq_args[0], 'Species': list_species}} contents = json.dumps(dict_json) self.send_response(200) else: contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>LIST OF SPECIES</title> </head> <body style="background-color: yellow;"> """ contents += f"<h2> Species List</h2>" contents += f"<p>The total number of species in ensemble is: {len(api_info['species'])}</p>" if not len(args) == 1 or ((args[1])[-1] == '='): contents += f"<p>Limit: {seq_args[-1]}</p>" for i in list_species: contents += f"<p>-{i}</p>" contents += '<a href="/">Main Page</a>' contents += "</body></html>" self.send_response(200) elif first_arg in '/karyotype': second_arg = args[1] seq_args = second_arg.split("=") if '&' in seq_args[1]: sp_arg = (seq_args[1]).split('&') sp_arg = sp_arg[0] else: sp_arg = seq_args[-1] endpoint = '/info/assembly/' params = sp_arg + INITIAL_PARAMETERS conn.request("GET", endpoint + params) resp1 = conn.getresponse() data_read = resp1.read().decode("utf-8") api_info = json.loads(data_read) karyotype_list = [] for i in api_info['karyotype']: karyotype_list.append(i) if 'json=1' in req_line[1]: dict_json = {'species': {sp_arg: {'chromosomes': karyotype_list}}} contents = json.dumps(dict_json) else: contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>KARYOTYPE</title> </head> <body style="background-color: yellow;"> """ contents += f"<h2> Karyotype of the species: {seq_args[-1]}</h2>" for n in karyotype_list: contents += f"<p>{n}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" self.send_response(200) elif first_arg in "/chromosomeLength": second_arg = args[1] seq_args = second_arg.split("=") args_def = seq_args[1].split("&") chromosome = seq_args[-1] if 'json' in seq_args[2]: args_json = seq_args[2].split('&') chromosome = args_json[0] endpoint = '/info/assembly/' params = args_def[0] + INITIAL_PARAMETERS conn.request("GET", endpoint + params) resp1 = conn.getresponse() data_read = resp1.read().decode("utf-8") api_info = json.loads(data_read) chromosome_length = '' for e in api_info['top_level_region']: if e['name'] == chromosome: chromosome_length += str(e['length']) if 'json=1' in req_line[1]: dict_json = {'species': {args_def[0]: { 'Chromosome': {chromosome: {'The length of the chromosome is:': chromosome_length}}}}} contents = json.dumps(dict_json) else: contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CHROMOSOME LENGTH</title> </head> <body style="background-color: yellow;"> """ contents += f"<h2> Chromosome: {seq_args[-1]} Species: {args_def[0]}</h2>" contents += f"<p>The length of the chromosome is: {chromosome_length}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" self.send_response(200) elif first_arg == "/geneList": endpoint = '/overlap/region/human/' second_arg = args[1] seq_args = second_arg.split("&") contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CHROMOSOME LENGTH</title> </head> <body style="background-color: yellow;"> """ for e in seq_args: e = e.split('=') values_for_params.append(e[-1]) params = values_for_params[0] + ':' + values_for_params[1] + '-' + values_for_params[2] + '?feature=gene;content-type=application/json ' conn.request("GET", endpoint + params) resp1 = conn.getresponse() data_1 = resp1.read().decode("utf-8") api_info_of_genelist = json.loads(data_1) contents += f"<h2>The genes in the chromosome {values_for_params[0]} that start at {values_for_params[1]} and end at {values_for_params[2]} are:</h2> " gene_in_chromosome = [] for i in api_info_of_genelist: contents += f"<p>{i['external_name']}</p>" gene_in_chromosome.append(i['external_name']) contents += '<a href="/">Main page</a>' contents += "</body></html>" if 'json=1' in req_line[1]: dict_json = {'chromosome': values_for_params[0], 'Start': values_for_params[1], 'End': values_for_params[2], 'Genes': gene_in_chromosome} contents = json.dumps(dict_json) self.send_response(200) else: endpoint_1 = '/xrefs/symbol/homo_sapiens/' second_arg = args[1] seq_args = second_arg.split("=") gene_name = seq_args[1] if 'json' in seq_args[1]: args_json = seq_args[1].split('&') gene_name = args_json[0] params_1 = gene_name + INITIAL_PARAMETERS conn.request("GET", endpoint_1 + params_1) resp1 = conn.getresponse() data_1 = resp1.read().decode("utf-8") api_info_id = json.loads(data_1) gene_id = api_info_id[0] gene_id = gene_id['id'] endpoint_2 = '/sequence/id/' params_2 = gene_id + INITIAL_PARAMETERS conn.request("GET", endpoint_2 + params_2) resp2 = conn.getresponse() data_2 = resp2.read().decode("utf-8") api_info_seq = json.loads(data_2) contents = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>GENE</title> </head> <body style="background-color: yellow;"> """ if first_arg == "/geneSeq": gene_seq = '' gene_seq += api_info_seq['seq'] if 'json=1' in req_line[1]: dict_json = {'Gene name:': {gene_name: {'Sequence': gene_seq}}} contents = json.dumps(dict_json) else: contents += f"<h2>The sequence of the gene {gene_name}</h2>" contents += f"<textarea readonly rows = 20 cols = 80>{gene_seq}</textarea>" contents += '<a href="/">Main page</a>' contents += "</body></html>" elif first_arg == '/geneInfo': endpoint_3 = '/lookup/id/' params_3 = gene_id + INITIAL_PARAMETERS conn.request("GET", endpoint_3 + params_3) resp3 = conn.getresponse() data_3 = resp3.read().decode("utf-8") api_info_gene = json.loads(data_3) seq0 = Seq(api_info_seq['seq']) if 'json=1' in req_line[1]: dict_json = {'gene': gene_name, 'Start': api_info_gene['start'], 'End': api_info_gene['end'], 'Length': seq0.len(), 'Chromosome': api_info_gene['seq_region_name'], 'ID': gene_id} contents = json.dumps(dict_json) else: contents += f"<h2>Information about the gene: {gene_name}</h2>" contents += f"<p>The start: {api_info_gene['start']}</p>" contents += f"<p>The end: {api_info_gene['end']}</p>" contents += f"<p>The length of the gene's sequence is: {seq0.len()}</p>" contents += f"<p>This gene is located in the chromosome: {api_info_gene['seq_region_name']}</p>" contents += f"<p>The ID of the gene is: {gene_id}</p>" contents += '<a href="/">Main page</a>' contents += "</body></html>" elif first_arg == "/geneCalc": seq0 = Seq(api_info_seq['seq']) if 'json=1' in req_line[1]: for e in bases: contents += f"<p>{e} : {seq0.count_base(e)} ({round(seq0.count_base(e) * (100 / seq0.len()), 2)}%)</p> " dict_json = {'Gene': gene_name, 'Length': seq0.len(), 'A': {seq0.count_base('A'): { 'Percentage': (round(seq0.count_base('A') * (100 / seq0.len()), 2))}}, 'C': { seq0.count_base('C'): { 'Percentage': (round(seq0.count_base('C') * (100 / seq0.len()), 2))}}, 'T': { seq0.count_base('T'): { 'Percentage': (round(seq0.count_base('T') * (100 / seq0.len()), 2))}}, 'G': { seq0.count_base('G'): { 'Percentage': (round(seq0.count_base('G') * (100 / seq0.len()), 2))}}} contents = json.dumps(dict_json) else: contents += f"<h2>Some calculations of the gene: {gene_name}</h2>" contents += f"<p>The length of the sequence is: {seq0.len()}</p>" for e in bases: contents += f"<p>{e} : {seq0.count_base(e)} ({round(seq0.count_base(e) * (100 / seq0.len()), 2)}%)</p>" self.send_response(200) except (KeyError, ValueError, IndexError, TypeError): contents = Path('Error.html').read_text() if 'json=1' in req_line: self.send_header('Content-Type', 'application/json') self.send_header('Content-Length', len(str.encode(contents))) 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 Seq1 import Seq seq = Seq("ACTGA") print("Sequence 1: (Length:", seq.len(), ")", seq)