BYU-PRISM / GEKKO

GEKKO Python for Machine Learning and Dynamic Optimization
https://machinelearning.byu.edu
Other
580 stars 103 forks source link

Compatibility with copy.deepcopy #49

Closed strahl21 closed 5 years ago

strahl21 commented 5 years ago

This is an enhancement not a bug. There is a python module "copy" that contains a function "deepcopy" which recursively creates a deep copy of a custom made object. For the value attribute of the currently defined GEKKO object (which can be a scalar or an array) the deepcopy function attempts to iterate regardless of whether the value is a scalar (which is not iterable) or an array. The following fix to gk_operators.py allows compatibility with deepcopy (not extensively tested, worked for simple model):

line 160 of gk_operators.py:

def iter(self):

    try:
        for v in self.value:
            yield v
    except:
        return self.value

feel free to email me at willstrahl32@gmail.com -Will

APMonitor commented 5 years ago

Committed to repository. Thanks for the suggestion.

APMonitor commented 5 years ago

From Abe: The commit enabling deep copy appears to have broken things. Attempting to import the latest gekko gives:

File "/home/pi/.local/lib/python2.7/site-packages/gekko/gk_operators.py", line 165 return self.value SyntaxError: 'return' with argument inside generator

I reverted back to the original version until it can be resolved.

    def __iter__(self):
        try:
            for v in self.value:
                yield v
        except:
            return self.value  
abe-mart commented 5 years ago

I received that error running Python 2.7 on my Raspberry Pi, so it may be a Python 2 vs 3 thing.

strahl21 commented 5 years ago

For generator functions before Python 3.3 it is illegal to combine yield and return statements. (see https://www.python.org/dev/peps/pep-0255/#specification-yield) I changed the 'return' statement to 'yield' and it runs with correct functionality with deepcopy in python 3.6. Perhaps this change will eliminate the syntax error reported in python 2.7?

def __iter__(self):
        try:
            for v in self.value:
                yield v
        except:
            yield self.value  
APMonitor commented 5 years ago

Included new deepcopy capability in test release at https://test.pypi.org/project/gekko/

APMonitor commented 5 years ago

The update works with Python 2.7 and 3+. It will be included in the next GEKKO release 0.1rc5.