# -- Create a variable with the data,
# -- 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=" ")
Ejemplo n.º 2
0
from Client0 import Client
from Seq1 import Seq

IP = "127.0.0.1"
PORT = 8080

FOLDER = "../Session-04/"
GENE = "FRAT1"

c = Client(IP, PORT)
print(c)
s = Seq("").read_fasta(FOLDER + GENE)
bases = str(s)
print(f"Gene {GENE}: {bases}")
LENGTH = 10
c.talk(f"Sending {GENE} gene to the server, in fragments of {LENGTH} bases")
for i in range(5):
    frag = bases[i*LENGTH:(i+1)*LENGTH]
    print(f"Fragment {i+1}: {frag}")
    c.talk(f"Fragment {i+1}: {frag}")
def comp(seq):
    s = Seq(seq)
    result = str(Seq.complement(s))
    context = {"seq": s, "op": "Comp", "res": result}
    content = read_template("./html/operation.html").render(context=context)
    return content
Ejemplo n.º 4
0
from Seq1 import Seq

print("-----| Practice 1, Exercise 3 |------")


s1 = Seq('NULL')


s2 = Seq("ACTGA")


s3 = Seq("ERROR")

print("Sequence 1: ", s1)
print("Sequence 2: ", s2)
print("Sequence 3: ", s3)
Ejemplo n.º 5
0
from Seq1 import Seq


def print_result(i, sequence):
    print('Sequence ' + str(i) + ': (Length: ' + str(sequence.len()) + ') ' +
          str(sequence))
    print('Bases: ', sequence.count())
    print('Rev: ', sequence.reverse())


print('----- Practice 1, Exercise 7 -----')

s1 = Seq()
s2 = Seq('ACTGA')
s3 = Seq('Invalid seq!')

list_seq = [s1, s2, s3]
for i in range(0, len(list_seq)):
    print_result(i, list_seq[i])
Ejemplo n.º 6
0
    def do_GET(self):
        """This method
        is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Print request line
        print(self.requestline)

        # Split request line by space and get the path
        req_line = self.requestline.split(' ')
        path = req_line[1]

        # Split path
        arguments = path.split('?')

        # Action is the first argument
        action = arguments[0]

        # If there is no argument we will receive an error
        contents = Path('error.html').read_text()
        code = 404

        # The main program composed by basic and medium levels starts at this point

        try:

            # First we open index.html if we don´t specify any action or it is /index we will be taken to  the initial
            # menu that returns us the index.html file

            if action == "/" or action == "/index":
                contents = Path('index.html').read_text()

            # Once we are in the initial menu we have different options to perform, basic and medium levels.

            # In the first option we are asked to introduce a limit value, once we have done it the program will take us
            # to an html file in which we can see a list, whose is equal to the limit, of species stored in the ensembl
            # data base

            elif action == "/listSpecies":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                <html lang = "en">
                <head>
                 <meta charset = "utf-8" >
                 <title>List of species in the browser</title >
                </head >
                <body>
                <p>The total number of species in ensembl is: 286</p>"""

                # We get the arguments that go after the ? in the path, Limit = "whatever input we introduce"
                get_value = arguments[1]
                limit_input = get_value.split('?')

                # We have the couple of elements, split by = and get them separated, the value that will be used is
                # limit value

                limit_action, limit_value = limit_input[0].split("=")

                # We try to convert it into an integer to return error page if there is a value error. Also if we leave
                # it in blank we should get the full list
                if limit_value == "":
                    limit_value = "286"
                limit_value = int(limit_value)
                if limit_value <= 0:
                    contents = Path('error.html').read_text()
                if limit_value > 0:
                    # Just addition to html response...
                    contents += f"""<p>The number of species you selected are: {limit_value} </p>"""

                    # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                    # previously searched for this function and parameters
                    server = 'rest.ensembl.org'
                    endpoint = 'info/species'
                    parameters = '?content-type=application/json'
                    request = endpoint + parameters

                    # Connect with the server
                    conn = http.client.HTTPConnection(server)

                    # Send the request message, using the GET method. We are
                    # requesting the main page (/)
                    try:
                        conn.request("GET", request)
                    except ConnectionRefusedError:
                        print("ERROR! Cannot connect to the Server")
                        exit()

                    # Read the response message from the server
                    response = conn.getresponse()

                    # Read the response's body
                    body = response.read().decode()

                    # We create blank list where we will store the data received from JSON
                    limit_list = []

                    # Create a variable with the data, form the JSON received. We get the key that interest us, species.
                    body = json.loads(body)
                    species = body["species"]

                    # First we compare if our input of limit is higher than the available numbre of species. On that
                    # case we will be taken to an error page

                    if limit_value > len(species):
                        contents = f"""<!DOCTYPE html>
                                <html lang = "en">
                                <head>
                                 <meta charset = "utf-8" >
                                 <title>ERROR</title >
                                </head>
                                <body>
                                <p>ERROR LIMIT OUT OF RANGE. Introduce a valid limit value</p>
                                <a href="/">Main page</a></body></html>"""

                    # In case our input is valid, we iterate through all the species and get the key we are looking for,
                    # their names, which appears as display_name. We will introduce them to our blank list; once its
                    # lengthis equal to the limit value we introduce we stop iterating and get the  final list of
                    # species

                    else:
                        for element in species:
                            limit_list.append(element["display_name"])
                            if len(limit_list) == limit_value:
                                contents += f"""<p>The species are: </p>"""
                                for specie in limit_list:
                                    contents += f"""<p> - {specie} </p>"""
                        contents += f"""<a href="/">Main page</a></body></html>"""
                        code = 200

                        # We just add the final info to our html to be given us back, if we got here everything has
                        # gone correctly

            # In this option we are asked to introduce the name of a specie of the ensembl data base, the program should
            # give us back a list of the chromosomes of that specie

            elif action == "/karyotype":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                <html lang = "en">
                <head>
                <meta charset = "utf-8">
                <title> Karyotype </title >
                </head >
                <body>
                <h2> The names of the chromosomes are:</h2>"""

                # We get the arguments that go after the ? in the path, Specie = "whatever input we introduce"
                get_value = arguments[1]
                specie_input = get_value.split('?')

                # We have the couple of elements, split by = and get them separated, the value that will be used is
                # specie name. We introduce a change so if we write an specie compose by two names we
                # will also get its info
                specie_action, name = specie_input[0].split("=")
                name_sp = name.replace("+", "_")

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                endpoint = 'info/assembly/'
                parameters = '?content-type=application/json'
                request = endpoint + name_sp + parameters

                # Connect with the server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()

                # Read the response's body
                body = response.read().decode("utf-8")

                # Create a variable with the data, form the JSON received. We get the key that interest us, karyotype.
                body = json.loads(body)
                karyotype_data = body["karyotype"]
                if len(karyotype_data) == 0:
                    contents = f"""<!DOCTYPE html>
                <html lang = "en">
                <head>
                <meta charset = "utf-8">
                <title> Karyotype </title >
                </head >
                <body>
                <h2> Ups...</h2>
                <p> It seems that the karyotype of {name.replace("+"," ")} is not available in ensembl database <p>
                <a href="/">Main page </a></body></html>"""
                    code = 200
                else:

                    # This key has associated a list with the different chromosomes, we just get them and add to our
                    # html
                    for chromosome in karyotype_data:
                        contents += f"""<p> - {chromosome} </p>"""

                    # We just add an option to return to the index and our html is now completed,if we got here
                    # everything has gone correctly
                    contents += f"""<a href="/">Main page </a></body></html>"""
                    code = 200

            # In this option we are asked to introduce the name of a specie of the ensembl data base and the name of one
            # of its chromosomes, the program should give us back the length of the chromosome

            elif action == "/chromosomeLength":

                # We get the arguments that go after the ? in the path, Specie = "whatever input we introduce" and
                # Chromosome = "whatever input we introduce"
                pair = arguments[1]
                pairs = pair.split('&')

                # We have two couple of elements, split each by =. The values that will be used are specie and
                # chromosome that we introduced.  We introduce a change so if we write an specie compose by two names we
                # will also get its info
                specie_name, name = pairs[0].split("=")
                chromosome_index, chromosome = pairs[1].split("=")
                specie = name.replace("+", "%20")
                chromosome = chromosome.capitalize()

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                endpoint = f'info/assembly/'
                parameters = '?content-type=application/json'
                request = endpoint + specie + parameters

                # Connect with the server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()

                # Read the response's body
                body = response.read().decode()

                # Create a variable with the data, form the JSON received. We get the key that interest us, chromosomic
                # data
                chromosomic_data = json.loads(body)

                # As it was researched at the Api of ensembl this will give us a superdictionary, we are looking for
                # specific elements that are inside key top_level_region, we will iterate through
                for chromo in chromosomic_data["top_level_region"]:

                    # The "sub"key we are looking for is name, we compare with the chromosome we introduced and if we
                    # get a coincidence we will get the value of key length of that specific chromosome
                    if chromosome == chromo["name"]:

                        # Once we have the value we will directly create the html with the info, the aim of this is
                        # to deal with possible errors in an easy way
                        length = chromo["length"]
                        contents = f"""<!DOCTYPE html><html lang = "en">
                            <head>
                            <meta charset = "utf-8" >
                            <title> Length Chromosome</title >
                            </head>
                            <body>
                            <h2> Chromosome length</h2>
                            <meta charset = "utf-8" >
                            <title> Chromosome length </title >
                            <p>The lenght of the chromosome {chromosome} from {specie.replace("%20", " ")} is : </p>
                            <p> {length}</p>
                            <a href="/">Main page</a></body></html>"""
                        code = 200
                # If we got here everything has gone correctly

            # This is the start of the medium level. The first option asks us to introduce the name of a gen of the
            # ensembl database and get back its  genomic sequence
            elif action == "/geneSeq":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                <html lang = "en">            
                <head>  
                <meta charset = "utf-8"
                <title> Gene Sequence </title>
                </head>"""

                # We get the arguments that go after the ? in the path, Gen name = "whatever input we introduce"
                get_value = arguments[1]
                pair = get_value.split('?')

                # We have a couple of elements, split each by =. The value that will be used is the name of the gen
                gen, name_gene = pair[0].split("=")

                # Just addition to html response...
                contents += f"""<p> The sequence of gene {name_gene} is:  </p>"""

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                first_endpoint = "xrefs/symbol/homo_sapiens/"
                parameters = '?content-type=application/json'
                first_request = first_endpoint + name_gene + parameters

                # Connect with the server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", first_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()

                # -- Read the response's body
                body = response.read().decode()

                # Create a variable with the data, form the JSON received. We get the first element and the key of
                # dictionary that interest us, id
                body = json.loads(body)
                id_gene = body[0]
                id_gene = id_gene["id"]

                # Once we have the id (how it appears in ensemble database) of the gen that we want we perform a second
                # connection, now for getting the sequence that gene in concrete. We use the endpoint previously
                # researched in the ensembl api

                second_endpoint = "sequence/id/"
                second_request = second_endpoint + id_gene + parameters

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", second_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the second response message from the server
                response2 = conn.getresponse()

                # Read the second response's body
                body2 = response2.read().decode()

                # Create a variable with the data, form the second JSON received. We get the first element and the key
                # of dictionary that interest us, seq
                body2 = json.loads(body2)

                # We get the value associated to that key, the sequence of the gen. We add it to our html page
                sequence = body2["seq"]
                contents += f"""<p>{sequence}</p><a href="/">Main page</a></body></html>"""
                code = 200
                # If we got here everything has gone correctly

            # In this option we are asked to introduce a gene and get specific info about it

            elif action == "/geneInfo":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                <html lang = "en">            
                <head>  
                <meta charset = "utf-8"
                <title> Gene Information</title>
                </head>"""

                # We get the arguments that go after the ? in the path, Gen name = "whatever input we introduce"
                get_value = arguments[1]
                pair = get_value.split('?')

                # We have a couple of elements, split each by =. The value that will be used is the name of the gen
                gen, name_gene = pair[0].split("=")

                # Just addition to html response...
                contents += f"""<p> The information of gene {name_gene} is:  </p>"""

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                first_endpoint = "xrefs/symbol/homo_sapiens/"
                parameters = '?content-type=application/json'
                first_request = first_endpoint + name_gene + parameters

                # Connect to server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", first_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()

                # Read the response's body
                body = response.read().decode()

                # Create a variable with the data, form the JSON received. We get the first element and the key of
                # dictionary that interest us, id
                body = json.loads(body)
                id_gene = body[0]
                id_gene = id_gene["id"]

                # Once we have the id (how it appears in ensemble database) of the gen that we want we perform a second
                # connection, now for getting the info that gene in concrete. We use the endpoint previously researched
                # in the ensembl api
                second_endpoint = "lookup/id/"
                second_request = second_endpoint + id_gene + parameters

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", second_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the second response message from the server
                response2 = conn.getresponse()

                # Read the second response's body
                body2 = response2.read().decode()

                # Create a variable with the data, form the JSON received. We get diferent values associated to the
                # keys that contain the info we are looking for
                body2 = json.loads(body2)
                length = int(body2["end"]) - int(body2["start"])

                # Once we have all the info collected, just complete the html response
                contents += f"""<p> The gene starts at: {body2["start"]} </p><p> The gene ends at: {body2["end"]} </p>
                <p> The gene length is: {length}</p>
                <p> The gene id is at: {id_gene} </p> <p> The gene is on chromosome: {body2["seq_region_name"]} </p>
                <a href="/">Main page</a></body></html>"""
                code = 200
                # If we got here everything has gone correctly

            # In this option we are asked to introduce a gene and perform some calculations with it, we will need Seq
            # from Seq1

            elif action == "/geneCalc":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                <html lang = "en">            
                <head>  
                <meta charset = "utf-8"
                <title> Gene Calculations</title>
                </head>"""

                # We get the arguments that go after the ? in the path, Gen name = "whatever input we introduce"
                get_value = arguments[1]
                pair = get_value.split('?')

                # We have a couple of elements, split each by =. The value that will be used is the name of the gen
                seq_name, name_seq = pair[0].split("=")

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                first_endpoint = "xrefs/symbol/homo_sapiens/"
                parameters = '?content-type=application/json'
                first_request = first_endpoint + name_seq + parameters

                # Connect with the server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", first_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()
                # Read the response's body
                body = response.read().decode()

                # Create a variable with the data, form the JSON received. We get the first element and the key of
                # dictionary that interest us, id
                body = json.loads(body)
                id_gene = body[0]
                id_gene = id_gene["id"]

                # Once we have the id (how it appears in ensemble database) of the gen that we want we perform a second
                # connection, now for getting the info that gene in concrete. We use the endpoint previously researched
                # in the ensembl api
                second_endpoint = "sequence/id/"
                second_request = second_endpoint + id_gene + parameters

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", second_request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the second response message from the server
                response2 = conn.getresponse()

                # Read the second response's body
                body2 = response2.read().decode()
                body2 = json.loads(body2)

                # Create a variable with the data, form the JSON received. We get  value associated to the
                # key that contain the info we are looking for, the gen sequence. We convert it into an object of our
                # class Seq in order to perform the calculations with it
                sequence = Seq(body2["seq"])
                list_of_bases = ["A", "C", "G", "T"]

                # Just addition to html response...
                contents += f"""<p> The length of gene {name_seq} is: {sequence.len()} </p>"""

                # We perform some calculations with the functions of Seq and add them to the html response to complete
                for base in list_of_bases:
                    perc_base = round(
                        sequence.count_base(base) * 100 / sequence.len(), 2)
                    contents += f"""<p> {base} : {sequence.count_base(base)} ({perc_base}%) </p>"""
                contents += f"""<a href="/">Main page</a></body></html>"""
                code = 200
                # If we got here everything has gone correctly

            # In this last option we are asked to introduce a chromosome, an initial and final position within it and
            # get the list of genes that compose it located within thi interval

            elif action == "/geneList":

                # This is the basic structure of the html page that we will get, it is incomplete...
                contents = f"""<!DOCTYPE html>
                  <html lang = "en">            
                  <head>  
                  <meta charset = "utf-8"
                  <title> Gene List</title>
                  </head>"""

                # We get the arguments that go after the ? in the path, Chromosome  name = "whatever input we introduce"
                # Start = "whatever input we introduce" and End = "whatever input we introduce". We split this 3 couples
                # by &
                get_value = arguments[1]
                pairs = get_value.split('&')

                # We have a couple of elements, split each by =. The value that will be used is the name of the gen
                chromosome_name, chromosome = pairs[0].split("=")
                chromosome_start, start = pairs[1].split("=")
                chromosome_end, end = pairs[2].split("=")
                chromosome = chromosome.capitalize()
                # Just in case we leave start at blank, it will start from 0
                if start == "":
                    start = "0"

                # Just addition to html response...
                contents += f"""<p> List of genes of the chromosome {chromosome}, which goes from {start} to {end} </p>
                """

                # We set the main elements that will be used to get the list: ensembl server, endpoint that was
                # previously searched for this function and parameters
                server = 'rest.ensembl.org'
                parameters = "?feature=gene;content-type=application/json"
                endpoint = "overlap/region/human/"
                request = endpoint + chromosome + ":" + start + "-" + end + parameters

                # Connect with the server
                conn = http.client.HTTPConnection(server)

                # Send the request message, using the GET method. We are
                # requesting the main page (/)
                try:
                    conn.request("GET", request)
                except ConnectionRefusedError:
                    print("ERROR! Cannot connect to the Server")
                    exit()

                # Read the response message from the server
                response = conn.getresponse()

                # Read the response's body
                body = response.read().decode("utf-8")

                # Read the response's body
                body = json.loads(body)

                # We iterate through the dictionary and get the values associated with the key we are interested in
                for element in body:

                    # We add this info and our html response is now complete
                    contents += f"""<p>{element["external_name"]}</p>"""
                contents += f"""<a href="/">Main page</a></body></html>"""
                code = 200

        # With except we will be able to deal with whatever possible error, such as introducing invalid inputs or inputs
        # that don´t appear at the database, exceed the number of possible items of a list...
        except (KeyError, ValueError, IndexError, TypeError):
            contents = Path('error.html').read_text()

        # 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
Ejemplo n.º 7
0
from Seq1 import Seq
print("-----| Exercise 4 |------")
# -- Create a Null sequence
s1 = Seq('')

# -- Create a valid sequence
s2 = Seq("ACTGA")

# -- Create an invalid sequence
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)
Ejemplo n.º 8
0
def gene(cs,argument):
    seq_gene = argument
    response = ("Gene: " +  "\n"+ argument + str(Seq.read_fasta(seq_gene)) + "\n")
    print_colored(response, 'blue')
    cs.send(str(response).encode())
from Seq1 import Seq
from P0 import sequences

print("-----|Practice1 ,Exercise 5|-----")

GENE_FOLDER = "./sequences2/"
gene_list = ["U5", "ADA", "FRAT1", "FXN", "RNU6_269P"]

for gene in gene_list:
    s = Seq()
    s.read_fasta(GENE_FOLDER + gene)
    print("Gene", gene, ":", "Most frequent Base:", s.most_repeated_base())
Ejemplo n.º 10
0
def comp(cs,argument):
    seq_comp = argument
    response = ("Sequence: " +  "\n" + str(seq_comp) + "\n" +
                "Complement sequence: " + str(Seq.complement(seq_comp)))
    print_colored(response, 'blue')
    cs.send(str(response).encode())
Ejemplo n.º 11
0
def rev(cs,argument):
    seq_rev = argument
    response = ("Sequence: " +  "\n" + str(seq_rev) + "\n" +
                "Reverse sequence: " + str(Seq.reverse(seq_rev)))
    print_colored(response,'yellow')
    cs.send(str(response).encode())
Ejemplo n.º 12
0
            elif command == "GET":
                termcolor.cprint("GET command!", "green")

                response = list_seq[int(argument)] + "\n"
                print(response)

            elif command == "INFO":
                termcolor.cprint("INFO command!", "green")

                response = info_seq(argument) + "\n"
                print(response)

            elif command == "COMP":
                termcolor.cprint("COMP command!", "green")

                seq = Seq(argument)

                response = seq.complement() + "\n"
                print(response)

            elif command == "REV":
                termcolor.cprint("REV command!", "green")

                seq = Seq(argument)

                response = seq.reverse() + "\n"
                print(response)

            elif command == "GENE":
                termcolor.cprint("GENE command!", "green")
Ejemplo n.º 13
0
    r1 = conn.getresponse()

    print(f"Response received!: {r1.status} {r1.reason}\n")

    data1 = r1.read().decode("utf-8")

    response = json.loads(data1)
    description = response["desc"]
    bases = response["seq"]

    termcolor.cprint(f"Gene: ", "green", end="")
    print(gene)
    termcolor.cprint(f"Description: ", "green", end="")
    print(description)

    sequence = Seq(bases)
    termcolor.cprint(f"Total lenght: ", "green", end="")
    print(sequence.len())

    counter = 0

    for base in list_bases:
        termcolor.cprint(f"{base}: ", "blue", end="")
        print(
            f"{sequence.seq_count_base(base)[0]} ({sequence.seq_count_base(base)[1]}%)"
        )

        if sequence.seq_count_base(base)[0] > counter:
            counter = sequence.seq_count_base(base)[0]
            mostfrbase = base
Ejemplo n.º 14
0
from Seq1 import Seq

print("-----| Practice 1, Exercise 4 |------")
s1 = Seq()
s2 = Seq("ACTGA")
s3 = Seq("Invalid Sequence")

print("Sequence" + str(1) + ": (lenght:" + str(s1.len()) + ") " + str(s1))
print("Sequence" + str(2) + ": (lenght:" + str(s2.len()) + ") " + str(s2))
print("Sequence" + str(3) + ": (lenght:" + str(s3.len()) + ") " + str(s3))
Ejemplo n.º 15
0
from Seq1 import Seq

print('"-----| Exercise 1 |------"')
seq = Seq('ACTGA')
print('Sequence ' + str(1) + ': (Length: ' + str(seq.len()) + ")" + str(seq))
Ejemplo n.º 16
0
PORT1 = 8080
PORT2 = 8081

FOLDER = "../Session-04/"
EXT = ".txt"
GENE = "FRAT1"

c1 = Client(IP, PORT1)
c2 = Client(IP, PORT2)

# Print the IP and PORTs
print(c1)
print(c2)

# Read the Gene from a file
s = Seq().seq_read_fasta(FOLDER + GENE + EXT)

bases = str(s)

# Print the Gene
print(f"Gene {GENE}: {bases}")

LENGTH = 10

# initial message to both servers
initial_msg = f"Sending {GENE} Gene to the server, in fragments of {LENGTH} bases..."

c1.talk(initial_msg)
c2.talk(initial_msg)

# Create the fragments
Ejemplo n.º 17
0
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))
Ejemplo n.º 18
0
    def do_GET(self):

        termcolor.cprint(self.requestline, 'green')
        req_line = self.requestline.split(' ')

        arguments = req_line[1].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":
            # -- 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, value = pairs[0].split("=")
            n = int(value)

            # -- Get the sequence
            seq = SEQ_GET[n]

            # -- Generate the 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 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.read_fasta(FOLDER + gene + EXT)
            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>
                        """
            error_code = 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
            name, seq = pairs[0].split("=")
            # -- Get the two elements of the operation
            name, op = pairs[1].split("=")

            # -- Create the sequence
            s = Seq(seq)

            if op == "comp":
                result = s.complement()
            elif op == "rev":
                result = 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)

                result = 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>{result}</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
Ejemplo n.º 19
0
from Seq1 import Seq

s1 = Seq()
s2 = Seq("ACTGA")
s3 = Seq("Invalid sequence")

print(f"Sequence 1: (Length: {s1.len()}) {s1}")
print(f"  Bases: {s1.count()}")
print(f"Reverse: {s1.reverse()}")
print(f"Complement: {s1.complement()}")
print(f"Sequence 2: (Length: {s2.len()}) {s2}")
print(f"  Bases: {s2.count()}")
print(f"Reverse: {s2.reverse()}")
print(f"Complement: {s2.complement()}")
print(f"Sequence 3: (Length: {s3.len()}) {s3}")
print(f"  Bases: {s3.count()}")
print(f"Reverse: {s3.reverse()}")
print(f"Complement: {s3.complement()}")
Ejemplo n.º 20
0
from Client0 import Client
from Seq1 import Seq

PRACTICE = 2
EXERCISE = 6
print(f"-----| Practice {PRACTICE}, Exercise {EXERCISE} |------")
IP = "192.168.1.54"
PORT = 8080
c = Client(IP, PORT)

s = Seq()
s.read_fasta('../SESSION 4/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('Fragment', count, ':', fragment)
    print(c.talk(fragment))
Ejemplo n.º 21
0
from Seq1 import Seq
"""Write a python program that automatically calculate the answer to this question:
Which is the most frequent base in each gene?
This exercise is the same than the exercise 8 of practice 0, 
but we are using the Seq Class instead of the functions developed 
in the Seq0 module"""

PROJECT_PATH = '../P0/sequences/'

print('--------- |Practice 1, Exercise 10| ---------')

list_sequences = ['U5.txt', 'ADA.txt', 'FRAT1.txt', 'FXN.txt', 'RNU6_269P.txt']

for i in list_sequences:

    seq = Seq()
    seq.seq_read_fasta(PROJECT_PATH +
                       i)  #quitan la primera línea y leen el código
    print('Gene ' + i[:-4] + ': Most frequent Base: ' + seq.processing_genes())
Ejemplo n.º 22
0
    def do_GET(self):
        global contents
        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        # IN this simple server version:
        # We are NOT processing the client's request
        # It is a happy server: It always returns a message saying
        # that everything is ok
        context = {}
        # Message to send back to the client
        PARAMETERS = '?content-type=application/json'
        SERVER = "rest.ensembl.org"
        connection = http.client.HTTPConnection(SERVER)
        if path_name == '/':
            contents = Path('./html/index.html').read_text()
        elif path_name == "/listSpecies":
            try:
                ENDPOINT = '/info/species'
                connection.request('GET', ENDPOINT + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                species_list = final_response['species']
                names_list = []
                for elem in species_list:
                    s1 = elem['name']
                    lists = [s1]
                    names_list = names_list + lists
                if 'limit' in arguments:
                    limit = int(arguments['limit'][0])
                    final_list = names_list[:limit]
                    if limit <= len(final_list):
                        context['length'] = len(names_list)
                        context['final_list'] = final_list
                        context['limit'] = limit
                        contents = su.read_template_html_file(
                            './html/limit_name_list.html').render(
                                context=context)
                    else:
                        contents = su.read_template_html_file(
                            './html/error.html').render(context=context)
                elif 'limit' not in arguments:
                    context['length'] = len(names_list)
                    context['final_list'] = names_list
                    contents = su.read_template_html_file(
                        './html/full_name_list.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/karyotype":
            try:
                species_name = arguments['species_name'][0]
                ENDPOINT = '/info/assembly/'
                connection.request('GET', ENDPOINT + species_name + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                karyotype = final_response['karyotype']
                context['karyotype'] = karyotype
                contents = su.read_template_html_file(
                    './html/karyotype.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/chromosomeLength":
            try:
                if 'species_name' not in arguments:
                    contents = su.read_template_html_file(
                        './html basic/ERROR.html').render()
                elif 'chromosome_name' not in arguments:
                    contents = su.read_template_html_file(
                        './html basic/ERROR.html').render()
                else:
                    global chromosome_length
                    species_name = arguments['species_name'][0]
                    chromosome_name = arguments['chromosome_name'][0]
                    ENDPOINT = '/info/assembly/'
                    connection.request('GET',
                                       ENDPOINT + species_name + PARAMETERS)
                    response = connection.getresponse()
                    final_response = json.loads(response.read().decode())
                    list_dict = final_response['top_level_region']
                    for elem in list_dict:
                        if (elem['name']
                                == chromosome_name) and (elem['coord_system']
                                                         == 'chromosome'):
                            chromosome_length = elem['length']
                        else:
                            contents = su.read_template_html_file(
                                './html/error.html').render(context=context)
                    context['chromosome_length'] = chromosome_length
                    contents = su.read_template_html_file(
                        './html/chromosome_length.html').render(
                            context=context)

            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/geneSeq":
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]

                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                sequence = final_response['seq']
                context['sequence'] = sequence
                contents = su.read_template_html_file(
                    './html/Seq.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/geneInfo":
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]
                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                info_list = final_response['desc'].split(':')
                context['genname'] = gene
                context['start'] = info_list[3]
                context['end'] = info_list[4]
                context['length'] = int(info_list[4]) - int(info_list[3])
                context['id'] = GENE_ID
                context['chromoname'] = info_list[1]
                contents = su.read_template_html_file(
                    './html/Info.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == '/geneCalc':
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]
                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                sequence = final_response['seq']
                s = Seq(sequence)
                context['length'] = s.len()
                context['percentageA'] = s.percentage_base('A')
                context['percentageC'] = s.percentage_base('C')
                context['percentageG'] = s.percentage_base('G')
                context['percentageT'] = s.percentage_base('T')
                contents = su.read_template_html_file(
                    './html/Calc.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        else:
            pass
        self.send_response(200)  # -- Status line: OK!

        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        content_length = len(str.encode(contents))
        self.send_header('Content-Length', content_length)

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(contents.encode())
        return
Ejemplo n.º 23
0
import operator
from Seq1 import Seq
from pathlib import Path

FOLDER = "/home/alumnos/joseepp/PycharmProjects/2019-2020-PNE-Practices/Session-04/"
FILENAME = ["U5", "ADA", "FRAT1", "FXN", "RNU6_269P"]
BASES = ["A", "C", "G", "T"]

# - - For each gene (element of FILENAME) we calculate its data:
for element in FILENAME:
    dnafile = FOLDER + element + ".txt"
    s = Seq()
    s1 = Seq(s.read_fasta(dnafile))
    print("Gene", element + ":", " Most frequent base: ",
          s1.processing_genes(BASES))
Ejemplo n.º 24
0
from Seq1 import Seq

FOLDER = "../Session-04/"
FILENAME = "U5.txt"

# -- Create a Null sequence
s = Seq()

# -- Initialize the null seq with the given file in fasta format
s.read_fasta(FOLDER+FILENAME)

print(f"Sequence : (Length: {s.len()}) {s}\n Bases: {s.seq_count()} \n "
          f"Rev: {s.seq_reverse()} \n Comp: {s.seq_complement()}")
Ejemplo n.º 25
0
    # -- Read the response's body
    data1 = r1.read().decode("utf-8")

    # -- Create a variable with the data,
    # -- form the JSON received
    response = json.loads(data1)

    termcolor.cprint(f"Gene: ", "green", end="")
    print(element)
    termcolor.cprint(f"Description: ", "green", end="")
    print(response['desc'])

    bases = response['seq']

    sequence = Seq(bases)

    termcolor.cprint(f"Total lengh: ", "green", end="")
    print(sequence.len())

    freq_counter = 0

    for base in list_bases:
        sequence.count_base(base)
        termcolor.cprint(f"{base}: ", "blue", end="")
        print(
            f"{sequence.count_base(base)[0]} ({sequence.count_base(base)[1]}%)"
        )
        if sequence.count_base(base)[0] > freq_counter:
            freq_counter = sequence.count_base(base)[0]
            freq_base = base
Ejemplo n.º 26
0
from Seq1 import Seq


def print_counts(i, sequence):
    print(f"Sequence {i}: (Length: {Seq.len(sequence)}) {sequence}")
    a, c, t, g = Seq.count_bases_no_count(sequence)
    print(f" A: {a},  C: {c},  T: {t},  G: {g}")


print("-----| Practice 1, Exercise 5 |------")

seq1 = Seq()
seq2 = Seq("ACTGA")
seq3 = Seq("Invalid sequence")

# NO LOOP
#print_counts(1, seq1)EXERCISE
#print_counts(2, seq2)
#print_counts(3, seq3)

# WITH A FOR LOOP
sequence_list = [seq1, seq2, seq3]
for i in range(1, len(sequence_list) + 1):
    print_counts(i, sequence_list[i - 1])
Ejemplo n.º 27
0
from Seq1 import Seq, test_sequences

print("-----| Practice 1, Exercise 4 |------")


slist = list(test_sequences())

Seq.print_seqs((slist))
Ejemplo n.º 28
0
def print_counts(i, sequence):
    print(f"Sequence {i}: (Length: {Seq.len(sequence)}) {sequence}")
    a, c, t, g = Seq.count_bases_no_count(sequence)
    print(f" A: {a},  C: {c},  T: {t},  G: {g}")
def rev(seq):
    s = Seq(seq)
    result = str(Seq.reverse(s))
    context = {"seq": s, "op": "Rev", "res": result}
    content = read_template("./html/operation.html").render(context=context)
    return content
Ejemplo n.º 30
0
from Client0 import Client
from Seq1 import Seq

print(f"-----| Practice 2, Exercise 5 |------")

IP = "127.0.0.1"
PORT = 8080

c = Client(IP, PORT)

FOLDER = "../Session_04/"
GENE = "U5"
EXT = ".txt"
file_name = FOLDER + GENE + EXT
sequence = Seq("")
sequence = str(sequence.read_fasta(file_name))


c.debug_talk(f"Sending the {GENE} Gene to the server...")
c.debug_talk(sequence)