| 1 | package AI::Termites::VicinusOccurro; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Math::Vector::Real; | ||
| 7 | use Math::Vector::Real::kdTree; | ||
| 8 | use Math::nSphere qw(nsphere_volumen); | ||
| 9 | |||
| 10 | use parent 'AI::Termites'; | ||
| 11 | |||
| 12 | my $nlog2 = -log 2; | ||
| 13 | |||
| 14 | sub before_termites_action { | ||
| 15 | my $self = shift; | ||
| 16 | my @ixs = grep !$self->{wood}[$_]{taken}, 0..$#{$self->{wood}}; | ||
| 17 | $self->{kdtree_ixs} = \@ixs; | ||
| 18 | $self->{kdtree} = Math::Vector::Real::kdTree->new(map $_->{pos}, @{$self->{wood}}[@ixs]); | ||
| 19 | # print "dim: $self->{dim}, near: $self->{near}, density: $self->{wood_density}\n"; | ||
| 20 | $self->{alpha} = $nlog2/(nsphere_volumen($self->{dim} - 1, $self->{near}) * $self->{wood_density}); | ||
| 21 | |||
| 22 | |||
| 23 | |||
| 24 | } | ||
| 25 | |||
| 26 | sub termite_take_wood_p { | ||
| 27 | my ($self, $termite) = @_; | ||
| 28 | my $pos = $termite->{pos}; | ||
| 29 | my $near = $self->{near}; | ||
| 30 | my $wood_ix = $self->{kdtree}->find_nearest_neighbor($pos, $near); | ||
| 31 | if (defined $wood_ix) { | ||
| 32 | my $count = $self->{kdtree}->find_in_ball($pos, $near, $wood_ix); | ||
| 33 | if (exp($self->{alpha} * $count) > rand) { | ||
| 34 | return $self->{kdtree_ixs}[$wood_ix]; | ||
| 35 | } | ||
| 36 | } | ||
| 37 | undef | ||
| 38 | } | ||
| 39 | |||
| 40 | sub termite_leave_wood_p { | ||
| 41 | my ($self, $termite) = @_; | ||
| 42 | my $pos = $termite->{pos}; | ||
| 43 | my $near = $self->{near}; | ||
| 44 | my $count = $self->{kdtree}->find_in_ball($pos, $near); | ||
| 45 | if (exp($self->{alpha} * $count) < rand) { | ||
| 46 | return 1; | ||
| 47 | } | ||
| 48 | undef; | ||
| 49 | } | ||
| 50 | |||
| 51 | 1; |