def test_eval_gradient(self):
        top = set_as_top(Assembly())
        top.add('comp1', Simple())
        top.comp1.a = 5.2
        top.comp1.b = 1.8

        top.run()

        exp = ExprEvaluator('3.0*comp1.c', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp1.c'], 3.0, 0.00001)
        self.assertEqual(top.comp1.c, 7.0)

        # Commented out this test, until we find a case that can't be
        # handled analytically
        # interface test: step size
        # (for linear slope, larger stepsize more accurate because of
        # python's rounding)
        #grad2 = exp.evaluate_gradient(scope=top, stepsize=0.1)
        #assert( abs(grad['comp1.c'] - 3.0) > abs(grad2['comp1.c'] - 3.0) )

        # More complicated, multiple comps
        top.add('comp2', Simple())

        exp = ExprEvaluator('comp2.b*comp1.c**2', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        self.assertEqual(len(grad), 2)
        assert_rel_error(self, grad['comp1.c'], 70.0, 0.00001)
        assert_rel_error(self, grad['comp2.b'], 49.0, 0.00001)

        # test limited varset
        grad = exp.evaluate_gradient(scope=top, wrt=['comp2.b'])
        self.assertEqual(len(grad), 1)

        exp = ExprEvaluator('pow(comp2.b,2)', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp2.b'], 10.0, 0.00001)

        exp = ExprEvaluator('pow(comp2.b,3)', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp2.b'], 75.0, 0.00001)

        exp = ExprEvaluator('log(comp2.a)', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp2.a'], 1./top.comp2.a, 0.00001)

        exp = ExprEvaluator('sin(cos(comp2.b))+sqrt(comp2.a)/comp1.c', top.driver)
        grad = exp.evaluate_gradient(scope=top)

        g1 = -sin(top.comp2.b)*cos(cos(top.comp2.b)) #true gradient components
        g2 = (2*sqrt(top.comp2.a)*top.comp1.c)**-1
        g3 = -sqrt(top.comp2.a)/top.comp1.c**2


        assert_rel_error(self, grad['comp2.b'], g1, 0.00001)
        assert_rel_error(self, grad['comp2.a'], g2, 0.00001)
        assert_rel_error(self, grad['comp1.c'], g3, 0.00001)

        exp = ExprEvaluator('gamma(comp2.a)', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        from scipy.special import polygamma

        g1 = gamma(top.comp2.a)*polygamma(0, top.comp2.a) #true partial derivative

        assert_rel_error(self, grad['comp2.a'], g1, 0.001)

        exp = ExprEvaluator('abs(comp2.a)', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp2.a'], 1.0, 0.0001)
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_evalexpr.py/ExprEvalTestCase.test_eval_gradient/original