Changeset 2188


Ignore:
Timestamp:
Jan 27, 2010 9:14:26 PM (11 years ago)
Author:
wehart
Message:

Rework of the COLIN OptProblem? IO management to
support IO plugins.

Location:
coopr.colin/trunk/coopr/colin/core
Files:
3 added
2 edited

Legend:

Unmodified
Added
Removed
  • coopr.colin/trunk/coopr/colin/core/__init__.py

    r2183 r2188  
    99#  _________________________________________________________________________
    1010
     11from point import *
     12import colin_xml_io
    1113from problem import *
    1214import solver
  • coopr.colin/trunk/coopr/colin/core/problem.py

    r2180 r2188  
    1414"""
    1515
     16__all__ = ['OptProblem', 'MixedIntOptProblem', 'response_enum']
     17
     18import os
     19from point import MixedIntVars
    1620import re
    17 import xml.dom.minidom
    1821import sys
    1922from pyutilib.enum import Enum
    20 from pyutilib.misc import tostr, get_xml_text
     23from pyutilib.misc import tostr
     24from problem_io import IOptProblemIO
     25from pyutilib.plugin.core import *
    2126
    2227
    2328response_enum = Enum("FunctionValue", "FunctionValues", "Gradient", "NonlinearConstraintValues", "Jacobian")
    24 
    25 class MixedIntVars(object):
    26   """
    27   A class that defines a commonly used domain type.
    28   """
    29 
    30   def __init__(self, node=None):
    31       self.reals = []
    32       self.ints = []
    33       self.bits = []
    34       if node is not None:
    35          self.process(node)
    36 
    37   def display(self):
    38       print "Reals",
    39       for val in self.reals:
    40         print val,
    41       print ""
    42       print "Integers",
    43       for val in self.ints:
    44         print val,
    45       print ""
    46       print "Binary",
    47       for val in self.bits:
    48         print val,
    49       print ""
    50 
    51   def process(self,node):
    52       for child in node.childNodes:
    53         if child.nodeType == node.ELEMENT_NODE:
    54             child_text = get_xml_text(child)
    55             if child_text == "":
    56               continue
    57             if child.nodeName == "Real":
    58               for val in re.split('[\t ]+',child_text):
    59                 self.reals.append(1.0*eval(val))
    60             elif child.nodeName == "Integer":
    61               for val in re.split('[\t ]+',child_text):
    62                 self.ints.append(eval(val))
    63             elif child.nodeName == "Binary":
    64               for val in child_text:
    65                 if val == '1':
    66                    self.bits.append(1)
    67                 elif val == '0':
    68                    self.bits.append(0)
    69 
    7029
    7130
     
    7534    by a COLIN optimizer via system calls.
    7635    """
     36
     37    io_manager = ExtensionPoint(IOptProblemIO)
    7738
    7839    def __init__(self):
     
    8647
    8748
    88     def main(self, argv, format=None):
     49    def main(self, argv, format='colin'):
    8950        """
    9051        The main routine for parsing the command-line and executing
     
    10162        # Parse XML input file
    10263        #
    103         if format is None:
    104             input_doc = xml.dom.minidom.parse(argv[1])
    105             point = self.create_point(input_doc.getElementsByTagName("Domain")[0])
    106             self.validate(point)
    107             requests = self._handleRequests(input_doc.getElementsByTagName("Requests")[0])
    108         #
    109         # Create output XML object
    110         #
    111         OUTPUT = open(sys.argv[2],"w")
    112         if format is None:
    113             output_doc = self._process(point,requests)
    114             output_doc.writexml(OUTPUT," "," ","\n","UTF-8")
    115         OUTPUT.close()
     64        iomngr = OptProblem.io_manager.service(format)
     65        if iomngr is None:
     66            raise ValueError, "Unknown IO format '%s' for COLIN OptProblem" % str(format)
     67        if not os.path.exists(argv[1]):
     68            raise IOError, "Unknown input file '%s'" % argv[1]
     69        point = self.create_point()
     70        point, requests = iomngr.read(argv[1], point)
     71        self.validate(point)
     72        response = self._compute_results(point, requests)
     73        iomngr.write(argv[2], response)
    11674
    117 
    118     def create_point(self, node):
     75    def create_point(self):
    11976        """
    120         Create a point given an XML node with the domain info.
    121 
     77        Create the point type for this domain.
    12278        By default, this generates a MixedIntVars class object, but
    12379        this method could be over-written to customized an OptProblem
    12480        for other search domains.
    12581        """
    126         return MixedIntVars(node)
    127 
     82        return MixedIntVars()
    12883
    12984    def function_value(self, point):
     
    157112        return []
    158113
    159 
    160     def _compute_response(self, point, requests):
     114    def _compute_results(self, point, requests):
    161115        """
    162         Iterate through the requested responses and compute them.
     116        Compute the requested results.
    163117        """
    164118        response = {}
    165119        for key in requests.keys():
    166120            if key not in self.response_str:
    167                 continue
     121                response[key] = "ERROR: Unsupported application request %s" % str(key)
    168122            #
    169             if key == "FunctionValue":
     123            elif key == "FunctionValue":
    170124               response[key] = str(self.function_value(point))
    171125            elif key == "FunctionValues":
     
    179133            #
    180134        return response
    181 
    182 
    183     def _process(self, point, requests):
    184         """
    185         Process the XML document
    186         """
    187         #
    188         # Compute response info
    189         #
    190         response = self._compute_response(point,requests)
    191         #
    192         # Setup document
    193         #
    194         doc = xml.dom.minidom.Document()
    195         root = doc.createElement("ColinResponse")
    196         doc.appendChild(root)
    197         for key in requests.keys():
    198             if key in response.keys():
    199                 elt = doc.createElement(str(key))
    200                 root.appendChild(elt)
    201                 text_elt = doc.createTextNode( response[key] )
    202                 elt.appendChild(text_elt)
    203             else:
    204                 elt = doc.createElement(str(key))
    205                 root.appendChild(elt)
    206                 text_elt = doc.createTextNode( "ERROR: Unsupported application request "+str(key) )
    207                 elt.appendChild(text_elt)
    208         return doc
    209 
    210 
    211     def _handleRequests(self, node):
    212         """
    213         A function that processes the requests
    214         """
    215         requests = {}
    216         for child in node.childNodes:
    217             if child.nodeType == node.ELEMENT_NODE:
    218                 tmp = {}
    219                 for (name,value) in child.attributes.items():
    220                     tmp[name]=value
    221                 requests[str(child.nodeName)] = tmp
    222         return requests
    223135
    224136    def validate(self, point):
Note: See TracChangeset for help on using the changeset viewer.