import unittest
import numpy as np
from scipy.special import expit
from native import Booster, BoostConfig, ArrayProvider, split_gain

class NativeTests(unittest.TestCase):
    def test_hand_gain(self):
        self.assertAlmostEqual(split_gain(1.,.5,-1.,.5,1.,.1),.5666666666666667)

    def test_hard_growth_learns_and_reload_exact(self):
        x=np.arange(100,dtype=np.float32)[:,None]
        y=(x[:,0]>=50).astype(float)
        p=ArrayProvider(x,['x'])
        m=Booster(BoostConfig(trees=8,depth=2,min_leaf=4,min_hessian=.01,l2=1,learning_rate=.5)).fit(p,y)
        scores=m.predict_proba(p)
        loss=-np.mean(y*np.log(scores)+(1-y)*np.log1p(-scores))
        self.assertLess(loss,.15)
        np.testing.assert_array_equal(scores,Booster.from_dict(m.to_dict()).predict_proba(p))
        self.assertTrue(m.trees[0]['feature']==0)

    def test_memory_changes_actual_partition(self):
        class Evidence(ArrayProvider):
            memory_names=['failure']; path_strength=0.; comparable_features=1
            def __init__(self,v): super().__init__(np.zeros((80,1)),['x']); self.v=v
            def features(self,idx,path=()): return self.v[np.asarray(idx),None]
            def root_features(self): return self.features(np.arange(80))
        y=np.r_[np.zeros(40),np.ones(40)]
        m=Booster(BoostConfig(trees=2,depth=1,min_leaf=4,min_hessian=.01,l2=1)).fit(Evidence(y),y)
        self.assertEqual(m.trees[0]['feature'],1)
        self.assertGreater(np.mean(m.predict_proba(Evidence(y))[40:]),np.mean(m.predict_proba(Evidence(y))[:40]))
        np.testing.assert_array_equal(m.predict_proba(Evidence(y)),m.predict_proba(Evidence(1-y))[::-1])

    def test_single_class_and_constraints(self):
        p=ArrayProvider(np.arange(20)[:,None])
        for label in [0,1]:
            m=Booster(BoostConfig(trees=3,min_leaf=50)).fit(p,np.full(20,label))
            self.assertTrue(np.isfinite(m.predict_proba(p)).all())
            self.assertTrue(all('leaf' in t for t in m.trees))

if __name__=='__main__': unittest.main()
