11import unittest
22
3+ import deap
34import pandas as pd
45
5- from causal_testing .estimation .genetic_programming_regression_fitter import GP
6+ from causal_testing .estimation .genetic_programming_regression_fitter import GP , mut_insert
67
78
89def root (x ):
@@ -11,10 +12,16 @@ def root(x):
1112
1213class TestGP (unittest .TestCase ):
1314 def test_init_invalid_fun_name (self ):
15+ """
16+ Test that GP raises ValueError if sympy conversions are provided for invalid function names.
17+ """
1418 with self .assertRaises (ValueError ):
1519 GP (df = pd .DataFrame (), features = [], outcome = "" , max_order = 2 , sympy_conversions = {"power_1" : "" })
1620
1721 def test_simplify_string (self ):
22+ """
23+ Test GP simplification
24+ """
1825 gp = GP (
1926 df = None ,
2027 features = ["x1" ],
@@ -24,6 +31,9 @@ def test_simplify_string(self):
2431 self .assertEqual (str (gp .simplify ("power_1(x1)" )), "x1" )
2532
2633 def test_fitness (self ):
34+ """
35+ Test GP fitness function for perfect expression.
36+ """
2737 gp = GP (
2838 df = pd .DataFrame ({"x1" : [1 , 2 , 3 ], "outcome" : [2 , 3 , 4 ]}),
2939 features = ["x1" ],
@@ -33,6 +43,9 @@ def test_fitness(self):
3343 self .assertEqual (gp .fitness ("add(x1, 1)" ), (0 ,))
3444
3545 def test_fitness_inf (self ):
46+ """
47+ Test that GP returns infinity fitness for incalculable expressions.
48+ """
3649 gp = GP (
3750 df = pd .DataFrame ({"x1" : [1 , 2 , 3 ], "outcome" : [2 , 3 , 4 ]}),
3851 features = ["x1" ],
@@ -41,3 +54,17 @@ def test_fitness_inf(self):
4154 extra_operators = [(root , 1 )],
4255 )
4356 self .assertEqual (gp .fitness ("root(-1)" ), (float ("inf" ),))
57+
58+ def test_mut_insert_no_primitives (self ):
59+ """Test that mut_insert returns the unmodified expression if there are no
60+ primitives of the appropriate type."""
61+ pset = deap .gp .PrimitiveSet ("MAIN" , 1 )
62+ pset .addPrimitive (lambda x1 , x2 : x1 + x2 , 1 , name = "add" )
63+ expression = deap .gp .PrimitiveTree .from_string ("add(ARG0, 1)" , pset )
64+ self .assertEqual (
65+ mut_insert (
66+ expression ,
67+ deap .gp .PrimitiveSet ("MAIN" , 1 ),
68+ ),
69+ (expression ,),
70+ )
0 commit comments