ometah-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[oMetah-devel] ometah/experiment metahtest.py


From: Jean-Philippe Aumasson
Subject: [oMetah-devel] ometah/experiment metahtest.py
Date: Mon, 06 Jun 2005 11:37:53 -0400

CVSROOT:        /cvsroot/ometah
Module name:    ometah
Branch:         
Changes by:     Jean-Philippe Aumasson <address@hidden> 05/06/06 15:37:52

Modified files:
        experiment     : metahtest.py 

Log message:
        * added : xml parser (not working...), classes Header, Point, and some 
function...

CVSWeb URLs:
http://savannah.gnu.org/cgi-bin/viewcvs/ometah/ometah/experiment/metahtest.py.diff?tr1=1.2&tr2=1.3&r1=text&r2=text

Patches:
Index: ometah/experiment/metahtest.py
diff -u ometah/experiment/metahtest.py:1.2 ometah/experiment/metahtest.py:1.3
--- ometah/experiment/metahtest.py:1.2  Mon Jun  6 12:06:07 2005
+++ ometah/experiment/metahtest.py      Mon Jun  6 15:37:52 2005
@@ -1,6 +1,6 @@
 #!/usr/bin/python
 # -*- coding: iso-8859-1 -*-
-
+# $Id:
 # Author: Jean-Philippe Aumasson <address@hidden>
 
 #  Open Metaheuristic is a Library aimed at the conception of metaheuristics 
@@ -31,104 +31,200 @@
 
 TODO
 
+!!! Parser : fdXML --> dictionary !!! 
 interface / structure globale :
-recueil des paramètres
-lancement ometah
-récupération de sa sortie (fichier XML... )
 plotage de la distribution avec R, dans un fichier ps (cf fx hist de R)
-prog oO, ie class avec infos sur le lancement courant
+
+
+Exceptions !
 
 NOTES
 fonction math :
 import math
 import Numeric
 
+
 pour XML parsing :
 http://pyxml.sourceforge.net/
 
http://communaute.openesub.org/softs/externe/cvs/chora/co.php/enki/openNewRapport.py?r=1.7
 
+sortie parsing : liste d'instances de Point
+
 """
 
 import os
 import sys
 import string
 from rpy import *
-
-OMETAH_PATH = "../ometah"
-OMETAH_OUT = "temp"
-R_OUT = "results.ps"
+import datetime
 
 
-
-def set_output(filename):
-    """  set the postscript output file """
-    r.postscript(filename, paper='letter')
+def setPostscriptOutput(filename):
+    """  set a postscript output file """
+    s = filename + ".ps"
+    r.postscript(s, paper='letter')
+
+def setBitmapOutput(filename):
+    """ set a bitmap (png) output file """
+    s= filename + ".png"
+    r.bitmap(s, res=100)
+
+def datedFileName(name):
+    """ return a string of today's date + given string """
+    s = datetime.date.today().isoformat()
+    return s + name
 
 
 class Interface:
     """ the main interface with ometah output """
-    argv = ['']
-    dimension = 0
-    iterations = 0
-    problemName = ''
-    metahName = ''
-    xmlOutput = 'temp'    
-
-    
+        
     def __init__(self, args):
         """ constructor, from command line arguments """
-        self.argv = [''] + args[1:]
+        self.__argv = [''] + args[1:]
+        self.__dimension = 1
+        self.__iterations = 0
+        self.__problemName = ''
+        self.__metahName = ''
     
     def execOmetah(self, path, output):
         """ execute ometah with given arguments,
-        redirecting output to the file output"""
-        buf = sys.stdout
-        sys.stdout = open(output, 'w')
-        os.execv(path, self.argv)
-        sys.stdout = buf
-        
-
+        returns the file objects corresponding to the cmd output """
+        cmd = path + string.join(self.__argv)
+        fd = os.popen(cmd)
+        return fd
+    
     def setAttributes():
         """ set class attributes from XML parsing """
         dimension = 1
-    
-    
-    def plot(self):
+        
+    def plotDistribution(self, list):
         """ plot from informations read in xml file """
-        f = open(self.xmlOutput, 'r')
+        # KEEP OLD CODE for the moment ... (plotted from a file)
+        """
+        f = open(self.__xmlOutput, 'r')
         line = f.readline()
         coord = line.split()        
-        r.plot_default(coord[0], coord[1], col='red')
+        r.plot_default(coord[0], coord[1], col='red', xlim=(0, 1), ylim=(0, 1))
         line = f.readline()
         while len(string.split(line, sep=","))  != 2:            
-            if len(line.split()) == 2:
-                coord = line.split()
-                a = round(float(coord[0]), 4)
-                b = round(float(coord[1]), 4)
-                print a, ", ",  b
-                r.points(a, b, col='blue')
-            else:
-                print "empty line"
-            line = f.readline()        
-        f.close()
-    
-    
+        if len(line.split()) == 2:
+        coord = line.split()
+        a = round(float(coord[0]), 4)
+        b = round(float(coord[1]), 4)
+        print a, ", ",  b
+        r.points(a, b, col='blue')
+        else:
+        print "empty line"
+        line = f.readline()        
+        f.close() """
+        
     def log(self):
         """ will write log of current job in a *.log file with date,
         pb name, output files... """
         print "log..."
 
+    def getProblemName():
+        return self.__problemName
+
+    def getMetahName():
+        return self.__metahName
+
+    def getDimension():
+        return self.__dimension
 
+    def getIterations():
+        return self.__iterations
 
-set_output(R_OUT)
 
-main = Interface(sys.argv)
 
-main.execOmetah(OMETAH_PATH, OMETAH_OUT)
+class XMLParser:
+    """ to parse the XML output """
 
-# main.plot()
+    __currentNode__ = None
+    __pointsList__ = None
+    
+    def __init__(self, xmlFile):
+        """ constructor, xmlFile is the file object of the XML output """
+        self.__xmlFile = xmlFile
+
+    def readXml(self):
+        from xml.dom.minidom import parse
+        self.doc = parse(self.__xmlFile)
+
+    def getRootElement(self):
+        """ returns the rool element of the XML tree """
+        if self.__currentNode__ == None:
+            self.__currentNode__ = self.doc.documentElement
+        return self.__currentNode__
+    
+    def getPoints(self):
+        """ returns a list of Points """
+        if self.__pointsList__ != None:
+            return self.__pointsList__
+        self.__pointsList__ = []
+        # "triple for" nécessaire ? (sur root, iteration, sample)
+        # pour les attributs :
+        #  help(xml.dom.minidom.Element)
+        #  -> ... getAttribute(self, attname) !!
+        for point in self.getRootElement().getElementsByTagName('point'):
+            if point.nodeType == point.ELEMENT_NODE:
+                p = Point()
+                try:
+                    p.value = 
self.getText(point.getElementsByTagName('values')[0])
+                    p.coords = 
self.getText(point.getElementsByTagName('solution')) # returns a list ?
+                except:
+                    print 'XML element missing'
+                self.__pointsList__.append(p)
+        return self.__pointsList__
+
+
+class Header:
+    """ for additional informations in XML file """
+    
+    def __init__(self):
+        pass
+
+
+class Point:
+    """ a point has a set of coordinates, and a value """
+
+    coords = None
+    value = None
+
+    def __init__(self):
+        pass
+
+
+def main():
+    """ main() """
+    OMETAH_PATH = "../ometah"
+    OMETAH_OUT = "temp"
+    R_OUT = "results"
+    
+    # set_postscript_output(R_OUT)
+    setBitmapOutput(datedFileName(R_OUT))
+    
+    main = Interface(sys.argv)
+
+    # fd ~ XML output
+    fd = main.execOmetah(OMETAH_PATH, OMETAH_OUT)
+    
+    print "readline() : " + fd.readline()
+
+    parser = XMLParser(fd)
+    parser.readXml()
+
+    # !! donner un dicionnaire en paramètre de plot !
+    # parser = Parser(fd)    
+    # parser.parse()
+    # list = parser.getPointList()
+    # main.plotDistribution(list)
+    
+    r.dev_off()
+    
 
-r.dev_off()
+if __name__ == '__main__':
+    main()
 
 
 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]