1<?php
2
3namespace Rubix\ML\Transformers;
4
5use Rubix\ML\DataType;
6use Rubix\ML\Exceptions\InvalidArgumentException;
7
8use function is_string;
9use function is_int;
10use function is_bool;
11
12/**
13 * Boolean Converter
14 *
15 * Convert boolean true/false values to continuous or categorical values.
16 *
17 * @category    Machine Learning
18 * @package     Rubix/ML
19 * @author      Zach Vander Velden
20 */
21class BooleanConverter implements Transformer
22{
23    /**
24     * The value used to replace boolean value `true` with.
25     *
26     * @var string|int
27     */
28    protected $trueValue;
29
30    /**
31     * The value used to replace boolean value `false` with.
32     *
33     * @var string|int
34     */
35    protected $falseValue;
36
37    /**
38     * @param mixed $trueValue
39     * @param mixed $falseValue
40     * @throws \Rubix\ML\Exceptions\InvalidArgumentException
41     */
42    public function __construct($trueValue = 'true', $falseValue = 'false')
43    {
44        if (!is_string($trueValue) and !is_int($trueValue)) {
45            throw new InvalidArgumentException('True value must be'
46                . ' a string or numeric type.');
47        }
48
49        if (!is_string($falseValue) and !is_int($falseValue)) {
50            throw new InvalidArgumentException('False value must be'
51                . ' a string or numeric type.');
52        }
53
54        $this->trueValue = $trueValue;
55        $this->falseValue = $falseValue;
56    }
57
58    /**
59     * Return the data types that this transformer is compatible with.
60     *
61     * @internal
62     *
63     * @return list<\Rubix\ML\DataType>
64     */
65    public function compatibility() : array
66    {
67        return DataType::all();
68    }
69
70    /**
71     * Transform the dataset in place.
72     *
73     * @param list<list<mixed>> $samples
74     */
75    public function transform(array &$samples) : void
76    {
77        foreach ($samples as &$sample) {
78            foreach ($sample as &$value) {
79                if (is_bool($value)) {
80                    $value = $value
81                        ? $this->trueValue
82                        : $this->falseValue;
83                }
84            }
85        }
86    }
87
88    /**
89     * Return the string representation of the object.
90     *
91     * @return string
92     */
93    public function __toString() : string
94    {
95        return "Boolean Converter (true_value: {$this->trueValue}, false_value: {$this->falseValue})";
96    }
97}
98