Search code examples
openmdao

OpenMDAO: How to resolve 'numpy.ndarray' object has no attribute 'log' error


I am new to OpenMDAO and am trying to solve an optimization problem. When I run the code, I receive the following error "'numpy.ndarray' object has no attribute 'log'" Cannot resolve the problem? Any suggestions?

I have reviewed the OpenMDAO documentation.

Error message: 'numpy.ndarray' object has no attribute 'log'

from __future__ import division, print_function
import openmdao.api as om
import numpy as np

class Objective (om.ExplicitComponent):
    def setup(self):
        self.add_input('mu1', val = 3.84)
        self.add_input('mu2', val = 3.84)    

        self.add_output('f', val = 0.00022)

        # Finite difference all partials.
        self.declare_partials('*', '*', method='fd')

    def compute(self, inputs, outputs):
        mu1 = inputs['mu1']
        mu2 = inputs['mu2']

        outputs['f'] = np.log((mu1*(0.86))/(1.0-(mu1*0.14)))+np.log((mu2*(0.86))/(1.0-(mu2*0.14)))

# build the model
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp())
indeps.add_output('mu1', 3.84)
indeps.add_output('mu2', 3.84)  

prob.model.add_subsystem('obj', Objective())
prob.model.add_subsystem('cnst', om.ExecComp('g = 7924.8 - 2943.0*(np.log(mu1)) - 2943.0*(np.log(mu2))'))

prob.model.connect('indeps.mu1', 'obj.mu1')
prob.model.connect('indeps.mu2', 'obj.mu2')
prob.model.connect('indeps.mu1', 'cnst.mu1')
prob.model.connect('indeps.mu2', 'cnst.mu2')

# setup the optimization
prob.driver = om.ScipyOptimizeDriver()
prob.driver.options['optimizer'] = 'COBYLA'

prob.model.add_design_var('indeps.mu1', lower=0.0, upper=5.0)
prob.model.add_design_var('indeps.mu2', lower=0.0, upper=5.0)
prob.model.add_objective('obj.f')
prob.model.add_constraint('cnst.g', lower=0.0, upper=0.0)

prob.setup()
prob.run_driver()

Solution

  • The problem is in the definition of your ExecComp. You have np.log, but the way the string parsing works for that you just wanted log.

    Try this instead:

    'g = 7924.8 - 2943.0*(log(mu1)) - 2943.0*(log(mu2))'
    

    With that change I got:

       Normal return from subroutine COBYLA
    
       NFVALS =   46   F = 3.935882E+00    MAXCV = 2.892193E-10
       X = 3.843492E+00   3.843491E+00
    Optimization Complete