63 lines
1.9 KiB
PHP
63 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Events;
|
|
|
|
use Illuminate\Broadcasting\Channel;
|
|
use Illuminate\Broadcasting\InteractsWithSockets;
|
|
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
|
|
use Illuminate\Foundation\Events\Dispatchable;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Queue\SerializesModels;
|
|
|
|
class PerceptronTrainingIteration implements ShouldBroadcast
|
|
{
|
|
use Dispatchable, InteractsWithSockets, SerializesModels;
|
|
|
|
/**
|
|
* Create a new event instance.
|
|
*/
|
|
public function __construct(
|
|
public array $iterations, // ["epoch" => int, "exampleIndex" => int, "error" => float, "synaptic_weights" => array]
|
|
public string $sessionId,
|
|
public string $trainingId,
|
|
) {
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Get the channels the event should broadcast on.
|
|
*
|
|
* @return array<int, \Illuminate\Broadcasting\Channel>
|
|
*/
|
|
public function broadcastOn(): array
|
|
{
|
|
// Log::debug("Broadcasting on channel: " . $this->sessionId . '-perceptron-training');
|
|
return [
|
|
new Channel($this->sessionId.'-perceptron-training'),
|
|
];
|
|
}
|
|
|
|
public function broadcastWith(): array
|
|
{
|
|
$weights = collect($this->iterations)
|
|
->pluck('weights')
|
|
->first(fn (array $weights): bool => $weights !== []);
|
|
$shouldBroadcastAllWeights = $weights !== null
|
|
&& count(Arr::flatten($weights)) <= config('perceptron.max_displayed_weights');
|
|
|
|
$lastIterationIndex = count($this->iterations) - 1;
|
|
$iterations = array_map(
|
|
fn (array $iteration, int $index): array => $shouldBroadcastAllWeights || $index === $lastIterationIndex
|
|
? $iteration
|
|
: [...$iteration, 'weights' => []],
|
|
$this->iterations,
|
|
array_keys($this->iterations),
|
|
);
|
|
|
|
return [
|
|
'iterations' => $iterations,
|
|
'trainingId' => $this->trainingId,
|
|
];
|
|
}
|
|
}
|