Welcome back to Ori Finder!

Imagine a team of scientists finds a tiny organism they’d like to understand better. They use a sequencing machine to read its DNA. The machine gives them letters in stretches called reads. Another team uses the places where those stretches overlap to put them in order and build the full genome sequence. That’s genome assembly. If that sounds like an interesting Python project in its own right, it is. Imagine starting with those reads and working out how they fit together.

Now the teams have a genome file they can share with us. They ask, “Can you look through these letters and tell us where you’d start looking for the place where the cell begins copying its DNA?”

That place is called an origin of replication. A good candidate region gives the scientists somewhere to start. They can take a closer look at the letters there, ask what might help the cell start copying, and design an experiment to check the region. That’s what we’re building toward with Ori Finder. We want to open the genome in Python and help narrow down where to look.

How do we teach our program to do that? Let’s start with an organism where scientists have already done some of that work.

In Part 1, we gave ourselves a small advantage. Scientists had already studied where copying begins in Pyrococcus abyssi. We could start with the region they studied and ask what we can see there. In Part 2, we downloaded the complete chromosome and saved those 799 letters in a separate FASTA file. Now we can open that file and try the experiments we talked about in Part 1 together.

In This Part

Do any 13-letter patterns repeat in our sample? And how did we know to try 13? Why not 9 or 10? In Ori Finder Part 1, we looked at a paper that showed short patterns the researchers studied near the origin of replication. Those patterns are 13 letters long. We’re using that length so our count answers a question about the very same patterns. A count of 9-letter patterns would answer a different question.

Then we’ll ask which of the paper’s patterns can we find in those same 799 letters? Why start there when we have the whole chromosome? This is the little cheat we talked about in Ori Finder Part 1. Earlier experiments gave us a region to start with. By checking the DNA from that region, we can compare what our code finds with patterns other scientists already reported. That gives us something to check before we ask our program to search a whole chromosome without being told where to look.

Part 1. Reopen Our Project and Find Our Two Clues

Open the same ori-finder folder in VS Code. If you’re joining us here, the project at the end of Part 2 already includes the two FASTA files in samples.

Look at the file names in the Explorer. They tell the story of what we did last time.

Table
File in samples Where the letters came from
NC_000868.1.fasta The complete chromosome from NCBI, all 1,765,118 letters.
NC_000868.1_known_ori_799.fasta The 799 letters we copied from the same chromosome using the positions reported in DoriC.

On the DoriC page, look for Reported experimental region in record aORI10010003. The row points to 122,701 through 123,499 on NC_000868.1. We counted both ends when we prepared our sample in Ori Finder Part 2. From 122,701 through 123,499, there are 123499 - 122701 + 1, or 799 letters. That number is the length of this particular region. We’ll open the smaller file directly today and keep the full chromosome for later.

That’s our first clue, where to look. Our second clue comes from Figure 2A of the paper by Matsunaga and colleagues. The researchers call these short sequences mini-ORB patterns (ORB stands for origin recognition box). We’ll count all the 13-letter sequences first to see if any stand out by frequency. Then we’ll count the eight from the paper and see what we learn when we know which letters to look for.

We saw these patterns in Ori Finder Part 1. Here are the eight different sequences from that list. Can our own Python code find any of them in the sample we saved?

Text
ATTTCCACTGGAG
ATTTCCAGTGGAA
GTTTCCACTGGAA
ATTTCCACAGGAA
ATTTCCGATGGAA
ATTTCCACTGGAA
GGTTCCAGTGGAA
AGTTCCACTGGAA

Part 2. Count One Pattern

Suppose a paper gives us a short DNA pattern. How many times do those exact letters appear in the DNA we saved? That’s the question count_kmer() will answer. We’ll give it the DNA and the pattern we know, and it will give us back the number of matches. Try it with your eyes first. In ACACA, look for ACA. Starting from the first letter, we see ACA. Starting from the second, we see CAC. Starting from the third, we see ACA again. The two matches share a letter, and both count. If we jumped three letters after the first match, we’d miss the second one.

A short stretch of letters taken from a longer sequence is a subsequence. When we choose a length for a stretch of DNA like this, we call it a k-mer. The k is the number of letters, so ACA is a 3-mer.

Create algorithms.py beside ori_finder.py. We’ll put the two functions there and call them from the experiment in ori_finder.py. If you followed Genome Toolkit, you’ll recognise the idea of counting one pattern from Part 2 and finding the most frequent patterns from Part 3. Here we’ll work with plain strings and keep the fixes we learned from Genome Toolkit, including checking the last possible match and accepting lowercase patterns.

Add the first function to algorithms.py.

Python
def count_kmer(sequence, kmer):
    # 1. Make sure we have a pattern and compare letters in uppercase.
    if not isinstance(kmer, str) or not kmer:
        raise ValueError("Please give us a pattern with at least one letter.")

    sequence = sequence.upper()
    kmer = kmer.upper()

    # 2. Look at every place where the pattern could fit.
    count = 0
    for start in range(len(sequence) - len(kmer) + 1):
        subsequence = sequence[start : start + len(kmer)]
        if subsequence == kmer:
            count += 1

    # 3. Give back the number of matches.
    return count
  1. Get the letters ready. sequence is the DNA we want to look through. kmer is the pattern we want to find. We check that the pattern is text and has at least one letter. If you type aca, we know it means the same DNA pattern as ACA. Python sees different characters. A lowercase a and an uppercase A have different character codes, so "a" == "A" is false. That’s why we call upper() on both strings before we compare them. It gives us an uppercase copy of each string. We use those copies for the search, so aca can match ACA.
  2. Look at one subsequence at a time. In ACACA, the three-letter window can start at positions 0, 1, or 2. range() gives us those three positions because 5 - 3 + 1 is 3. The + 1 matters. Without it, we’d stop one window too soon and miss a match in this example. At each position we use a slice to read part of the string. Python starts at the first number and stops just before the second. So sequence[0:3] takes letters at positions 0, 1, and 2. That gives us ACA from ACACA. We save those letters in subsequence.
  3. Compare the letters and give back the count. The == asks whether the letters in subsequence are exactly the same as the letters in kmer, in the same order. When they match, count += 1 adds one to the count we already have. When they differ, the count stays the same. After the last window, return count gives us the total, even if it stayed at zero.

Now watch the same function on ten letters. The frame shows which letters we’re checking. When it reads ACA, the frame turns green and the count goes up by one. Watch for another match in the last window.

We check eight windows in all and find three matches for ACA.

Try one slower pass. The first window matches. The second doesn’t. The third matches again. The next four windows each miss. Then the last window reads ACA and takes our total to three. Follow the frame one letter at a time and see if you get the same count.

Part 3. Find Which Patterns Appear Most Often

What if we have the DNA and know how many letters to look at, but nobody has told us which letters to search for? That’s a different question. We can ask Python to count every pattern of that length and show us which ones appeared the most.

This gives us two ways to look at the same DNA. count_kmer() checks a pattern we already know, like one from a paper. find_most_frequent_kmers() helps us look for repeats when we only know the length. If several patterns appear the same number of times at the top, we want to see all of them. Later in this lesson we’ll use the two answers side by side.

Let’s look at the same ten letters, ACACAGTACA, with a window two letters wide. Watch the window and the counts beside it. The first pair, AC, gets a count of one. The next pair, CA, gets a count of its own. When AC comes back, we know which count to change. Python can keep these numbers for us in a dictionary. Each pair of letters has its own count.

AC and CA both appear three times, so the function returns both patterns and the count of three.

Which two-letter patterns appeared most often? Look at the final counts. Both AC and CA reached three. Now let’s write the function that does this for us.

Add this function below the first one in algorithms.py.

Python
def find_most_frequent_kmers(sequence, k_len):
    # 1. Choose a length that fits the sequence.
    sequence = sequence.upper()
    if type(k_len) is not int or not 1 <= k_len <= len(sequence):
        raise ValueError("Choose a whole number from 1 to the sequence length.")

    # 2. Keep a count for every pattern we see.
    counts = {}
    for start in range(len(sequence) - k_len + 1):
        subsequence = sequence[start : start + k_len]
        counts[subsequence] = counts.get(subsequence, 0) + 1

    # 3. Keep every pattern with the highest count.
    highest = max(counts.values())
    winners = []
    for subsequence, count in counts.items():
        if count == highest:
            winners.append(subsequence)

    return winners, highest
  1. Check how many letters to take. k_len is the number of letters in each window. We first turn the DNA letters uppercase again, so ac and AC go under the same count. Then we check that the length is a whole number from one through the length of the sequence. For our ten-letter string, that means one through ten. A request for eleven letters would give us no full window to count.

  2. Update the count for the subsequence we just read. We start with an empty dictionary, counts = {}. When we first find AC, counts.get(subsequence, 0) gives us zero because there’s no entry for AC yet. We add one, and counts[subsequence] = ... saves that one under AC. The next time we find AC, we get its saved count of one, add one, and replace that count with two. When we first see CA, it gets its own entry.

  3. Find the highest count and keep every pattern with that count. Go back to where we filled counts. Each entry has a two-letter pattern and the number of times we saw it. When we call counts.values(), we ask for just the numbers. Look at the last step of the animation. The numbers we saved are 3, 3, 1, 1, and 1. max() picks the biggest one, so highest is 3.

    Now we want to know which patterns reached that count. This time we use counts.items() because we need each pattern alongside its number. We read each pair and compare its number with highest. If they’re equal, winners.append(subsequence) adds the letters to our list. Both AC and CA reached three, so we give back both patterns and the count they share.

Let’s go back to the animation above and take one slower pass. Watch what happens the first time a pair appears. The dictionary has no count for it yet, so the code starts at zero and adds one. When the same pair appears again, the code gets the number it saved and adds one to that number. At the end, we can see why the function gives back both AC and CA, along with the count of three.

Part 4. Check Both Functions on Ten Letters

Before we try this on DNA from a real organism, let’s run both functions on ACACAGTACA, the same ten letters we watched in the animations. We already know what to look for in the output, so we can check our work one line at a time. Open ori_finder.py and replace its contents with the complete example below. In a moment we’ll turn this same file into our first experiment.

Python
# 1. Bring in the two functions we just wrote.
from algorithms import count_kmer, find_most_frequent_kmers

# 2. Show the ten letters we used in the animations.
example = "ACACAGTACA"
print("Sequence:", example)

# 3. Check what both functions give back.
print("Matches for ACA:", count_kmer(example, "aca"))
patterns, highest = find_most_frequent_kmers(example, 2)
print("Most frequent two-letter patterns:", ", ".join(patterns))
print("Highest count:", highest)
  1. Bring over the functions. The import makes both functions from algorithms.py available in ori_finder.py.
  2. Show the input. We save the ten letters in example so both calls can use the same string. We print it first so we can check which letters we actually searched.
  3. Check the answers. In the first call, example tells the function where to look and "aca" tells it which pattern to count. We type the pattern in lowercase to check that the uppercase copies we made inside the function do their job. We expect three matches. In the second call, 2 is how many letters to look at in each window. The function gives us back two things. We keep the list of patterns in patterns and their shared count in highest. ", ".join(patterns) puts a comma and a space between the patterns so we can read them together. The final print shows their count.

Save the file and run it from the project folder.

Shell
uv run ori_finder.py
Shell
Sequence: ACACAGTACA
Matches for ACA: 3
Most frequent two-letter patterns: AC, CA
Highest count: 3

That matches what we saw in both animations. ACA appears three times, including right at the end. AC and CA each appear three times when we look two letters at a time. We can now keep the same two functions and change where the letters come from.

Part 5. Try Both Questions on Real DNA

Now that we’ve checked both functions on ten letters, let’s use ori_finder.py for our first experiment on real DNA. This file is where we’ll try our ideas as we add new algorithms throughout the series. For our first run, we’ll open the 799-letter FASTA and ask which 13-letter patterns repeat in that DNA. Then we’ll try the short patterns from the paper on the same letters.

In the list we copied from Figure 2A in Ori Finder Part 1, ATTTCCAGTGGAA appears on two lines. The letters are identical. If we searched for that same sequence twice, Python would print the same answer twice. We’ll put it in our search list once, which leaves eight different patterns to check.

Replace the contents of ori_finder.py with this complete file.

Python
# 1. Bring in the two counting functions we just checked.
from algorithms import count_kmer, find_most_frequent_kmers

# Bring in the FASTA reader we wrote in Part 2.
from helpers import read_fasta

# 2. Open the 799-letter sample we saved in Part 2.
sample_path = "samples/NC_000868.1_known_ori_799.fasta"
sample_name, sample_dna = read_fasta(sample_path)
print("Sample:", sample_name)
print("Letters in the sample:", len(sample_dna))

# 3. Count every 13-letter subsequence in the sample.
pattern_length = 13
patterns, highest = find_most_frequent_kmers(sample_dna, pattern_length)
print("Patterns tied for the highest count:", len(patterns))
print("Highest count:", highest)

# 4. Check the eight different mini-ORB patterns from Figure 2A.
published_patterns = [
    "ATTTCCACTGGAG",
    "ATTTCCAGTGGAA",
    "GTTTCCACTGGAA",
    "ATTTCCACAGGAA",
    "ATTTCCGATGGAA",
    "ATTTCCACTGGAA",
    "GGTTCCAGTGGAA",
    "AGTTCCACTGGAA",
]
for pattern in published_patterns:
    matches = count_kmer(sample_dna, pattern)
    print(pattern, matches)
  1. Bring in the functions for the experiment. We import the two counting functions from algorithms.py and the FASTA reader from helpers.py. That lets this file load the DNA and pass it to either function.
  2. Open our saved region. We keep the path in sample_path so we know which file we’re giving to read_fasta(). Remember the reader we wrote in Ori Finder Part 2? Open helpers.py and find its return line. It hands us two things in order, the label and the full string of DNA letters. In ori_finder.py we save the first as sample_name and the second as sample_dna. We print the label to check which sample we opened, and its length to check that we have all 799 letters. Here’s where the work from Part 2 pays off. We already have the DNA in a string, so we can pass sample_dna to both of the functions we just tested.
  3. Ask the sample which patterns repeat. We give find_most_frequent_kmers() the 799 letters and the length we chose from the paper. The function gives us the patterns that appeared most often and how many times each of them appeared. We print len(patterns) to see how many different patterns reached that count. We print highest to see how many times each of them appeared.
  4. Look for the patterns researchers studied. This time the pattern is chosen before we start counting. Go through the list one string at a time, call count_kmer() with that string, and print the answer beside it. Keep the zeroes in the output so we can see which patterns we checked but didn’t find.

Save and run the file again.

Shell
uv run ori_finder.py
Shell
Sample: P_abyssi_GE5_NC_000868.1_known_ori_region_799bp
Letters in the sample: 799
Patterns tied for the highest count: 787
Highest count: 1
ATTTCCACTGGAG 0
ATTTCCAGTGGAA 1
GTTTCCACTGGAA 0
ATTTCCACAGGAA 1
ATTTCCGATGGAA 1
ATTTCCACTGGAA 1
GGTTCCAGTGGAA 0
AGTTCCACTGGAA 1

Take a moment to look at the output before we move on. Our reader from Part 2 gave us the DNA letters, and two small Python functions answered two different questions about them. We counted the 13-letter patterns in the sample, then checked the exact patterns from the paper. Try pointing to one of each kind of result in the terminal. Which line tells you how often a pattern appeared? Which lines show whether particular patterns were there?

That’s a real experiment on biological data, using Python we wrote ourselves. We started with a small region because we know where its letters came from and can check what our program tells us. As we add to Ori Finder, we’ll ask questions about both DNA strands and where the patterns occur. Eventually we’ll be able to search the whole chromosome and see whether our own results point us back to the region scientists found.

Conclusion

What did we find in the 799 bases?

Remember where we started. We have the full chromosome of P. abyssi, and somewhere in it there’s a place where the cell starts copying its DNA. For our first experiment, we gave Ori Finder a head start. We used the 799 bases from the known origin region we saved in Part 2. That gave us a small, well-studied part of the chromosome to try our code on before asking it to search the whole thing.

What did Python find in that sample? A window of 13 bases fits in 799 - 13 + 1, or 787, places. We got a different pattern at every position. The highest count was 1, so every 13-base pattern appeared exactly once. If we had only those counts, which pattern would we pick? Each one has the same count. Let’s see what happens when we give Python a few patterns that researchers already noticed.

What did the patterns from the paper tell us?

We found five of the eight patterns exactly as they’re written in the paper. Each appeared once. The other three got a 0. If you’re wondering, “Why would the paper list patterns we couldn’t find here?”, that’s a good question.

Take another look at Figure 2A. The scientists looked at about 5,000 bases, including the origin and some DNA around it. The wider view let them see a second group of patterns in a nearby gene. Our 799-base sample comes from the smaller region reported in DoriC. We chose it so we could start by asking what our code could find inside the known origin region. If we searched a larger region, we’d also find patterns in the DNA around it. That’s a useful question to ask when we start looking for matches across the chromosome.

There’s another clue in those zeros. Today’s code reads the letters in the order they’re stored in our FASTA file. We checked the three missing patterns against both DNA strands. Two are in our 799-base sample on the other strand. The third, ATTTCCACTGGAG, shows up elsewhere on the chromosome, outside the sample. Look how much a simple count helped us see. To understand a zero, it matters both where we looked and which strand we read.

How does this help us build Ori Finder?

We took a clue from a paper, loaded real DNA on our own computer, and checked the clue with two small Python functions. Now we know what our next function needs to help us do. We can use it to search the other strand, too, and see whether our program can account for those missing matches.

After that, we’ll want to know where each pattern occurs. Imagine giving Ori Finder the full chromosome and the patterns from the paper. A count can tell us that a pattern appears somewhere. If we also record the positions, we can ask a better question. Do several of these clues appear close together? If Ori Finder points us back to the area scientists studied, we’ll have recovered a candidate region without giving the program its location. That would give us a place to investigate further and a way to check that our search is working on an example we already know.

Summary

  • We searched the 799 bases we saved in Part 2. Each of the 787 different 13-base patterns appeared once.
  • When we gave the program eight specific patterns from the paper, it found five exact matches in the sequence we searched, one for each of those five patterns.
  • We now know how to count a pattern we choose and how to check whether any patterns of a chosen length appear more often than the others.

What’s Next?

Let’s take one of those zeroes and ask: Could we find a match if we looked at the other DNA strand? DNA has two strands, and we read them in opposite directions. To look for the matching pattern, we need to work out the letters on the other strand and put them in that strand’s reading order. That is what the reverse complement will do for us in the next Part.

Our first goal, as we described in Ori Finder Part 1, is to start with patterns from research and see whether they help us find a promising region without being given the location. After that, there’s an even bigger question. If nobody tells us which patterns to look for, or how long they should be, can we compare several lengths and see which groups of matches stand out? That’s a question for a later experiment. We have a way to start asking it because we can already count the patterns we choose.

Let’s bring this back to the question that started Ori Finder. Where on this circular chromosome does the cell start copying its DNA? In Part 1, we met a protein called Cdc6/Orc1. It helps recognise DNA near the place where copying begins. That gives us a reason to look closely at the patterns the researchers studied. Our two counting functions helped us check those clues on one strand. Now we have a reason to learn how the two strands fit together and write a function that helps us search the other one, too.

This is the way we learn by doing in Getting Started in Bioinformatics. We start with a question we care about, build something small to help us answer it, and see what the answer makes us wonder next. Today a few zeros gave us a reason to study the other strand. Once we can search both, we can start asking where the clues appear and whether several of them point us to the same part of the chromosome.

Your Turn

Can we work out what Python would need to search for on the other strand? Let’s try with three bases. In DNA, A pairs with T, and C pairs with G. The letters that pair with a sequence make up its complement. Under AAC, for example, we get TTG.

Text
5′ A A C 3′
   | | |
3′ T T G 5′

The two ends of a DNA strand are called 5′ (five prime) and 3′ (three prime). Look at the diagram. The strands line up with their ends pointing in opposite directions. We write a DNA sequence from its 5′ end to its 3′ end. That means we read the top row from left to right and the bottom row from right to left. When we write the bottom row as a Python string so our code can scan it from left to right, we’ve made the reverse complement.

Try writing a small function called reverse_complement(). Give it AAC, use the pairing rules to make its complement, then reverse the order of those letters. Can you get the same result by reading the diagram from the bottom row’s 5′ end? If you’d like a hint, we built this function in DNA Toolkit Part 2. We’ll use the same approach in Ori Finder.

Once you have that function, how could you use count_kmer() to check a pattern that gave us a zero today?

If this lesson helped you get started with bioinformatics or Python, you can support REBELSCIENCE and help us keep sharing open science education.

Until next time, rebelCoder, signing out.

Git repository for this lesson: Ori Finder Part 3 on GitHub. The repository includes the 799-base sample and the complete chromosome FASTA.

You can follow the Ori Finder video series in order.

Video version of this article: