<?php

function array_mean($array) {
    return array_sum($array) / count($array);
}

$dir = $argv[1];
$results = [];

$iterator = new \RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO);
foreach ($iterator as $file) {
    if (!$file->isFile()) continue;

    $path = $file->getPathname();
    $lines = preg_split("/\R/", file_get_contents($path));
    $headers = str_getcsv(array_shift($lines)); // headers
    
    $lines = array_map(function($line) { return preg_replace("/tensor\((.*?)\)/si", '$1', $line); }, $lines);
    $lines = array_filter($lines);
    $csv   = array_map('str_getcsv', $lines);
    $csv   = array_map(function($line) use($headers) { return @array_combine($headers, $line); }, $csv);

    $result[(int)str_replace('loss_epoch_', '', $file->getBasename('.csv'))] = [
        'generator' => array_mean(array_column($csv, 'g_loss')),
        'discriminator' => array_mean(array_column($csv, 'd_loss')),
        'data' => $csv
    ];
}

ksort($result);
echo "epoch,g,d\n";
// foreach($result as $epoch => $loss) {
//     echo sprintf("%d,%.4f,%.4f\n", $epoch, $loss['generator'], $loss['discriminator']);
// }
$iteration = 0;
foreach($result as $epoch => $loss) {
    foreach($loss['data'] as $row) {
        if ($iteration++ % 5 != 0) continue;

        echo sprintf("%.4f,%.4f,%.4f\n", $iteration/100., $row['g_loss'], $row['d_loss']);
    }
}
