Skip to content

Instantly share code, notes, and snippets.

@dejw
Created January 11, 2010 14:54
Show Gist options
  • Select an option

  • Save dejw/274286 to your computer and use it in GitHub Desktop.

Select an option

Save dejw/274286 to your computer and use it in GitHub Desktop.
require "rubygems"
require "Node"
require "CoreService"
require "Configuration"
require "example-services"
require "mocha"
class NameService
def initialize(bus)
(@mock = Mocha::Mock.new).stubs(:register_address).returns("Agent1", "Agent2")
end
def register_address(suggest)
@mock.register_address
end
end
class Service < CoreService::Service
def finalize
super()
children.values.min {|a, b| a.finalize <=> b.finalize }.finalize
end
def notify(who)
self.logger.info("CoreService: '#{who.address}' stopped")
super(who)
end
def detached
self.logger.info("Minimum of f(x) = #{Function.to_s} is #{self.finalize}")
self.logger.debug("CoreService: detached")
end
def init
super()
end
end
class Function
class << self
attr_accessor :a, :b, :line
end
def self.call(x)
eval(to_s)
end
def self.to_s
self.line.strip
end
end
class Agent < CoreService::Workplace
attr_reader :minimum
attr_writer :max_iterations
after :init do
@a = Function.a
@b = Function.b
@function = Function
@minimum = 1/0.0
@other = self.address == "Agent1" ? "Agent2" : "Agent1"
@iterations_without_new_min = 0
self.stop_condition = CoreService::Condition::Block.new do
@iterations_without_new_min >= @max_iterations
end
end
def perform
n = self.fetch_all_messages
say("received #{n} message#{n != 1 ? "s" : ""}") if n > 0
x = @a + rand()*(@b - @a)
if (min = @function.call(x)) < @minimum
@minimum = min
self.service.send_message(@other, :found, @minimum)
say("found new minimum = #{@minimum}")
@iterations_without_new_min = 0
else
@iterations_without_new_min += 1
end
end
with_message :found do
new_min = self.message.content
if @minimum > new_min
@minimum = new_min
@iterations_without_new_min = 0
say("received new minimum from agent named '#{@other}'")
end
end
def finalize
@minimum
end
protected
def say(msg)
self.logger.info("#{self.address}: #{msg}")
end
end
SERVICES = {
:logger => ExampleServices::LoggerService,
:starter => ExampleServices::StarterMock,
:nameService => NameService,
:configService => Configuration::Configuration,
:coreService => Service
}
config = <<EOF
# mozna zmienic domyslna nazwe drzewa
agents_tree_name:
value: `custom_agents_tree`
custom_agents_tree:
value:
- agent
- agent
agent:
class: Agent
autowire: false
setter-parameters:
max_iterations: 10000
EOF
print "Give f(x) = "
Function.line = gets
print "Give range <a, b> = "
Function.a, Function.b = gets.split(" ").collect(&:to_f)
bus = Node::Bus.new(SERVICES)
bus.get(:configService).set_configuration(YAML::load(config.gsub("\t", " ")))
bus.wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment