Advertisement
Guest User

hardy_weinberg.js

a guest
Feb 3rd, 2017
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const assert = require('assert');
  2.  
  3. // This is an implementation of the Hardy-Weinberg frequencies in Javascript.
  4. //
  5. // We are going to consider a simple gene with 2 alleles, and 3 genotypes (A1A1, A1A2, A2A2)
  6. // We are going to model this by using p for the frequency of the A1 allele, q for
  7. // the frequency of the A2 allele, and using the HW principle, we get the following frequencies
  8. // based on our original input:
  9. //
  10. //   A1A1 = p * p = p^2
  11. //   A1A2 = p * q = pq
  12. //   A2A1 = q * p = qp  (--> follows from above = 2pq)
  13. //   A2A2 = q * q = q^2
  14. //
  15. // So we get a final polynomial function of p^2 + 2pq + q^2 = 1.
  16.  
  17. var a1a1 = 0.15;
  18. var a2a2 = 0.35;
  19. var a1a2 = 1 - (a1a1 + a2a2);
  20.  
  21. var p = a1a1 + (a1a2 / 2);  // Because half of them are from the heterozygous cell
  22. var q = 1 - p;              // Because both of them must add up to 1.
  23.  
  24. function create_next_generations(runs, first_gen_prob) {
  25.     console.log("generation 0:\t" + a1a1 + "\t" + a1a2 + "\t" + a2a2);
  26.  
  27.     function _round_number(value, decimals) {
  28.         var shifter = Math.pow(10, decimals);
  29.         return Math.round(value * shifter) / shifter;
  30.     }
  31.  
  32.     function _next_gen(runs, current_gen, gen_prob) {
  33.         p = gen_prob[0];
  34.         q = gen_prob[1];
  35.  
  36.         // Now, let's calculate the next generation
  37.         a1a1 = _round_number(p * p, 2);
  38.         a1a2 = _round_number(2 * p * q, 2);
  39.         a2a2 = _round_number(q * q, 2);
  40.  
  41.         // Verify correctness of the result.
  42.         all = a1a1 + a1a2 + a2a2;
  43.         assert.equal(all, 1);
  44.  
  45.         next_gen = current_gen+1;
  46.  
  47.         console.log("generation " + next_gen +":\t" + a1a1 + "\t" + a1a2 + "\t" + a2a2);
  48.  
  49.         next_generation_probabilities = [a1a1, a1a2, a2a2];
  50.         allelic_probabilities = [p, q];
  51.  
  52.         if (current_gen == runs-1) {
  53.             return next_generation_probabilities;
  54.         } else {
  55.             _next_gen(runs, current_gen+1, allelic_probabilities);
  56.         }
  57.     }
  58.  
  59.     return _next_gen(runs, 0, first_gen_prob);
  60. }
  61.  
  62. create_next_generations(12, [p, q]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement