Changeset 5794


Ignore:
Timestamp:
May 20, 2012 7:03:49 PM (7 years ago)
Author:
wehart
Message:

Bug fixes in new model for the create() method.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/trunk/coopr/pyomo/base/PyomoModel.py

    r5793 r5794  
    2525from pyutilib.component.core import alias, ExtensionPoint
    2626from pyutilib.math import *
    27 from pyutilib.misc import quote_split, tuplize, Container, PauseGC
    28 
     27from pyutilib.misc import quote_split, tuplize, Container, PauseGC, Bunch
     28
     29import coopr.core
    2930import coopr.opt
    3031from coopr.opt import ProblemFormat, ResultsFormat, guess_format
     
    109110        return [ProblemFormat.pyomo]
    110111
    111     def create(self, filename=None, name=None, namespace=None, namespaces=None, preprocess=True, profile_memory=0):
     112    def create(self, filename=None, **kwargs):
    112113        """
    113114        Create a concrete instance of this Model, possibly using data
    114115        read in from a file.
    115116        """
    116         if name is None:
    117             name = self.name
    118         #
    119         # Generate a warning if this is a concrete model but the filename is specified.
    120         # A concrete model is already constructed, so passing in a data file is a waste of time.
    121         #
    122         if (self._defer_construction is False) and isinstance(filename,basestring) and filename is not None:
    123             msg = "The filename=%s will not be loaded - supplied as an argument to the create() method of a ConcreteModel instance with name=%s." % (filename, name)
    124             logger.warning(msg)
    125         #
    126         # If construction is deferred, then clone the model and
    127         #   
    128         if self._defer_construction:
    129             instance = self.clone()
    130 
    131             if namespaces is None or len(namespaces) == 0:
    132                 instance.load(filename, namespaces=[None], profile_memory=profile_memory)
    133             else:
    134                 instance.load(filename, namespaces=namespaces+[None], profile_memory=profile_memory)
     117        kwargs['filename'] = filename
     118        process = kwargs.pop('process', None)
     119        if process is None:
     120            return coopr.core.CooprAPIFactory(self._create)({}, model=self, **kwargs).instance
    135121        else:
    136             instance = self
    137         #
    138         # Preprocess the new model
    139         #   
    140         if preprocess is True:
    141             if (pympler_available is True) and (profile_memory >= 2):
    142                 memory_tracker = tracker.SummaryTracker()
    143                 memory_tracker.create_summary()
    144             #
    145             instance.preprocess()
    146             #
    147             if (pympler_available is True) and (profile_memory >= 2):
    148                 print "Objects created during instance preprocessing:"
    149                 memory_tracker.print_diff()
    150         #
    151         if not name is None:
    152             instance.name=name
    153         return instance
     122            return coopr.core.CooprAPIFactory(process)({}, model=self, **kwargs).instance
    154123
    155124    def clone(self):
    156125        """Create a copy of this model"""
    157         # TODO: check that this works recursively for nested models
    158        
    159         # Self: Clear the weakrefs for _model and _parent
    160126        self._model = None
    161127        for block in self.all_blocks():
     
    163129                for comp in compMap.itervalues():
    164130                    comp._parent = None
    165         # Perform the copy
     131        #
     132        # Monkey-patch for deepcopying weakrefs
     133        # Only required on Python <= 2.6
     134        #
     135        if sys.version_info[0] == 2 and sys.version_info[1] <= 6:
     136            copy._copy_dispatch[weakref.ref] = copy._copy_immutable
     137            copy._deepcopy_dispatch[weakref.ref] = copy._deepcopy_atomic
     138            copy._deepcopy_dispatch[weakref.KeyedRef] = copy._deepcopy_atomic
     139
     140            def dcwvd(self, memo):
     141                """Deepcopy implementation for WeakValueDictionary class"""
     142                from copy import deepcopy
     143                new = self.__class__()
     144                for key, wr in self.data.items():
     145                    o = wr()
     146                    if o is not None:
     147                        new[deepcopy(key, memo)] = o
     148                return new
     149            weakref.WeakValueDictionary.__copy__ = weakref.WeakValueDictionary.copy
     150            weakref.WeakValueDictionary.__deepcopy__ = dcwvd
     151
     152            def dcwkd(self, memo):
     153                """Deepcopy implementation for WeakKeyDictionary class"""
     154                from copy import deepcopy
     155                new = self.__class__()
     156                for key, value in self.data.items():
     157                    o = key()
     158                    if o is not none:
     159                        new[o] = deepcopy(value, memo)
     160                return new
     161            weakref.WeakKeyDictionary.__copy__ = weakref.WeakKeyDictionary.copy
     162            weakref.WeakKeyDictionary.__deepcopy__ = dcwkd
     163        #
     164        # Actually do the copy
     165        #
    166166        instance = copy.deepcopy(self)
    167         # Self: Setup the weakrefs for _model and _parent
    168167        self._model = weakref.ref(self)
    169168        for block in self.all_blocks():
     
    171170                for comp in compMap.itervalues():
    172171                    comp._parent = weakref.ref(block)
    173         # Instance: Setup the weakrefs for _model and _parent
     172        #
    174173        instance._model = weakref.ref(instance)
    175174        for block in instance.all_blocks():
     
    10671066        Model.__init__(self, *args, **kwds)
    10681067        self._defer_construction=False
     1068        self._create = 'pyomo.model.default_constructor'
    10691069
    10701070    alias("ConcreteModel", 'A concrete optimization model that does not defer construction of components.')
     
    10811081        Model.__init__(self, *args, **kwds)
    10821082        self._defer_construction=True
     1083        self._create = 'pyomo.model.default_constructor'
    10831084
    10841085    alias("AbstractModel", 'An abstract optimization model that defers construction of components.')
    10851086
     1087
     1088@coopr.core.coopr_api(namespace='pyomo.model')
     1089def default_constructor(data, model=None, filename=None, name=None, namespace=None, namespaces=None, preprocess=True, profile_memory=0, clone=None):
     1090    """
     1091    Create a concrete instance of this Model, possibly using data
     1092    read in from a file.
     1093
     1094    Required:
     1095        model:              An AbstractModel object.
     1096
     1097    Optional:
     1098        filename:           The name of a Pyomo Data File that will be used to load
     1099                                data into the model.
     1100        name:               The name given to the model.
     1101        namespace:          A namespace used to select data.
     1102        namespaces:         A list of namespaces used to select data.
     1103        preprocess:         If False, then preprocessing is suppressed.
     1104        profile_memory:     A number that indicates the profiling level.
     1105        clone:              Force a clone of the model if this is True.
     1106
     1107    Return:
     1108        instance:           Return the model that is constructed.
     1109    """
     1110    if name is None:
     1111        name = model.name
     1112    #
     1113    # Generate a warning if this is a concrete model but the filename is specified.
     1114    # A concrete model is already constructed, so passing in a data file is a waste
     1115    # of time.
     1116    #
     1117    if (model._defer_construction is False) and isinstance(filename,basestring) and filename is not None:
     1118        msg = "The filename=%s will not be loaded - supplied as an argument to the create() method of a ConcreteModel instance with name=%s." % (filename, name)
     1119        logger.warning(msg)
     1120    #
     1121    # If construction is deferred, then clone the model and
     1122    #   
     1123    if model._defer_construction:
     1124        instance = model.clone()
     1125
     1126        if namespaces is None or len(namespaces) == 0:
     1127            instance.load(filename, namespaces=[None], profile_memory=profile_memory)
     1128        else:
     1129            instance.load(filename, namespaces=namespaces+[None], profile_memory=profile_memory)
     1130    else:
     1131        if clone:
     1132            instance = model.clone()
     1133        else:
     1134            instance = model
     1135    #
     1136    # Preprocess the new model
     1137    #   
     1138    if preprocess is True:
     1139        if (pympler_available is True) and (profile_memory >= 2):
     1140            memory_tracker = tracker.SummaryTracker()
     1141            memory_tracker.create_summary()
     1142        #
     1143        instance.preprocess()
     1144        #
     1145        if (pympler_available is True) and (profile_memory >= 2):
     1146            print "Objects created during instance preprocessing:"
     1147            memory_tracker.print_diff()
     1148    #
     1149    if not name is None:
     1150        instance.name=name
     1151    #
     1152    return Bunch(instance=instance)
     1153
Note: See TracChangeset for help on using the changeset viewer.