Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The (Ruby) Sims

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for Bryan Liles Bryan Liles
December 09, 2013

The (Ruby) Sims

Ever thought about writing a simulator in Ruby?

Avatar for Bryan Liles

Bryan Liles

December 09, 2013
Tweet

More Decks by Bryan Liles

Other Decks in Technology

Transcript

  1. SIMULATION_LENGTH = 100 PEOPLE_COUNT = 100 def create_people(people_count); end def

    report; end def simulate_to(count) 1.upto(count) {|i| yield i } end people = create_people(PEOPLE_COUNT) simulate_to(SIMULATION_LENGTH) do |iteration| # mish and mash people end report
  2. class Simulator def initialize(length, count) # ... end end s

    = Simulator.new 3650, 100 Define inputs
  3. s = Simulator.new 3650, 100 s.run s.infected_people.each do |p| i

    = p.infections.to_a d = p.diseases.to_a puts "#{p} #{i} #{d}" end Analyze output
  4. class Simulation def transmit(iteration) current_pairs(iteration).each{|pair| pair.contact(iteration)} end end class Pair

    def contact(iteration) @alpha.infect(iteration, @beta) @beta.infect(iteration, @alpha) end end class Person def infect(iteration, person); end def acquire(infection); end end
  5. class Person def progress_infections(iteration) @infections.each do |infection| if rand <=

    infection.chance_to_acquire_disease unless has_disease? infection.disease @diseases << infection.disease.new(iteration) end end end end end
  6. %self total self wait child calls name 30.32 386.26 117.53

    0.00 268.72 21904 Array#each 28.08 180.05 108.88 0.00 71.18 78738195 Comparable#between? 21.74 84.29 84.29 0.00 0.00 78738195 Pair#duration 18.36 71.18 71.18 0.00 0.00 157476390 Fixnum#<=> 0.29 2.11 1.11 0.00 1.06 414957 Set#each 0.13 1.15 0.50 0.00 0.65 365100 Person#infected? 0.13 2.36 0.50 0.00 1.86 365000 Person#infect 0.12 0.65 0.48 0.00 0.17 365100 Set#empty?
  7. module Enumerable # create a thread and execute in parallel

    def parallel_each(&block) # create thread yield # cleanup end end
  8. digraph g { "person59" -> "person5"; "person23" -> "person18"; "person72"

    -> "person23"; "person78" -> "person44"; "person78" -> "person59"; "person59" -> "person72"; "person1" -> "person78"; "person83" -> "person81"; "person59" -> "person83"; "person59" -> "person92"; }; Graphviz
  9. ?!

  10. irb(main):003:0> rand 1..7 TypeError: can't convert Range into Integer from

    org/jruby/RubyKernel.java:1580:in `rand' from (irb):3:in `evaluate' from org/jruby/RubyKernel.java:1070:in `eval' from org/jruby/RubyKernel.java:1395:in `loop' from org/jruby/RubyKernel.java:1178:in `catch' from org/jruby/RubyKernel.java:1178:in `catch' from /Users/bryan/.rbenv/versions/jruby-1.7.0-preview2/bin/irb:13:in `(root)' JRuby 1.7 pre2