Andrew Cooke | Contents | Latest | RSS | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 2006-2017 Andrew Cooke (site) / post authors (content).

Matching DNA Update - Faster Java Code

From: "andrew cooke" <andrew@...>

Date: Sat, 20 Sep 2008 18:54:39 -0400 (CLT)

I have just finished implementing the main core of the algorithm outlined
here - http://www.acooke.org/cute/Identifyin0.html - directly in Java and
it runs in about 8 seconds!

There were two main problems.  First, inferring how Postgres did an
efficient search and, second, implementing that without using too much
memory (my first attempt exhausted the heap so I now have a slight 
tradeoff, which uses a sort to avoid creating more memory structures and
so adds a log term to the big-O).  It's easiest to describe both together,
by outlining the final solution, but in practice I the development had two
distinct steps.

So, as in the prototype code, I generate candidate pairs by matching small
fragments of the DNA.  More exactly: I take 25 fragments, each 8 bits,
from each individual and I categorise two individuals as a candidate pair
if they have at least 3 fragments in common.

So, in psuedocode, I do the following:

 generate a table of fragments[individual_idx][fragment_idx]
 generate a table of counts[individual1_idx][individual2_idx] = 0

 for each column of fragments in turn:
   sort the table column containing the fragments;
   scan the sorted column:
     for all fragments with the same value:
       increment the counts associated with the pairs of individuals
               that share that fragment value;
     if any count == 3:
       if the "bit distance" between the pair is < 3000:
         add the pair for that count to the graph;

And I need to repeat this 6 times with different sets of fragments (the
number of identified pairs after each set is 8116, 9623, 9935, 9988, 9998,
9999).

Instead of sorting each column of fragments the scan could be direct, but
you would need to have a separate memory structure to record which
individuals were associated with which values (for this amount of data I
suspect the log pays for itself in the simplification (reduced constant
cost) that the sorted data introduces).

Also, Java has no direct support for sorting bytes (the fragments) with
keys.  I could have wrapped everything in objects, but it was more compact
(and probably faster) to bit-pack the DNA fragment and the individual
index together in a single integer (obviously the DNA has to occupy the
more significant bits for the sorting to give the corrected order).

I am going to look for a graph library now to finish this off.

8 seconds is pretty good.  When I started out I was looking at many hours;
even the optimized Python/SQL code took 30 min...

Andrew

PS  My initial attempt at searching the hashes was to do a depth first
search trying to find common fragments for each pair in turn.  While this
would have fitted well within a constraint programming framework (see my
posts here over the last week or two when I was looking at Choco and
Gecode) it was, in retrospect, completely stupid - a huge amount of time
is spent exhaustively searching irrelevant pairs.  The direct scan
described above is much more efficient, but it's not yet clear to me how
the two approaches are related.  Is there some way in which the direct
scan with counting is a dual of the search?  Or does some kind of
optimisation of the search eventually reduce it to the scan?  I don't see
how either of those pan out, but haven't looked at the CP techniques in
any detail yet.

Core Routine

From: "andrew cooke" <andrew@...>

Date: Sat, 20 Sep 2008 19:07:14 -0400 (CLT)

public int search()
{
  byte[] counts = new byte[GenomePair.hashSize(population.size())];
  int[] scratch = new int[population.size()];
  // for each fragment in turn:
  for (int column = 0; column < nHashes; ++column) {
    // pack into an integer
    for (int row = 0; row < population.size(); ++row) {
      scratch[row] = pack(hashes[row][column], row);
    }
    // group individuals with the same hash are together
    Arrays.sort(scratch);
    // for each group
    for (int row = 0; row < population.size();) {
      // get the hash for the group
      byte hash = unpackHash(scratch[row]);
      Set<Integer> allMatching = new HashSet<Integer>();
      // note the first individual
      allMatching.add(unpackRow(scratch[row]));
      // for each additional individual
      while (++row < population.size() &&
          unpackHash(scratch[row]) == hash) {
        int higher = unpackRow(scratch[row]);
        // for each pair
        for (int lower: allMatching) {
          GenomePair pair = new GenomePair(lower, higher);
          // if we have sufficient hits, check the distance
          if (++counts[pair.hashCode()] == nMatches
              && population.connected(pair, cutoff)) {
            graph.add(pair);
          }
        }
        // extend the current set so that we generate all pairs
        allMatching.add(higher);
      }
    }
  }
  // this should tend to to population.size()-1
  return graph.size();
}

Perfect Hash

From: "andrew cooke" <andrew@...>

Date: Sat, 20 Sep 2008 19:10:22 -0400 (CLT)

I should explain that I am abusing GenomePair.hashCode() - the
implementation returns a continguous index from 0 over all possible pairs.
 So all pairs are distinct and there are no gaps.  The total number of
values is given by hashSize().

At some point I'll change the name.  Originally I was using HashMaps of
these...

Andrew

Same Results

From: "andrew cooke" <andrew@...>

Date: Sun, 21 Sep 2008 20:05:00 -0400 (CLT)

I added the final graph code (using JGraphT, which seems quite capable)
and the results are, as expected, identical to the earlier work.  I also
tried some variations on the numbers of matches and hashes (but not the
fragment size, which is hard coded at 8 bits (ie bytes) in this version) -
the code is much more stable than the Python/SQL implementation to these
changes (I now suspect Postgres was switching algorithms depending on
predicted memory usage), and the values chosen aren't particularly
critical.

I'm considering sending it off to the company that posted the problem, but
they only accept submissions that are employment applications, so it seems
a bit silly (I'm not looking for a job, and won't move to Boston...).

Andrew

Comment on this post