~ubuntu-branches/ubuntu/precise/code-saturne/precise

« back to all changes in this revision

Viewing changes to gui/Base/XMLengine.py

  • Committer: Package Import Robot
  • Author(s): Sylvestre Ledru
  • Date: 2011-11-01 17:43:32 UTC
  • mto: (6.1.7 sid)
  • mto: This revision was merged to the branch mainline in revision 11.
  • Revision ID: package-import@ubuntu.com-20111101174332-tl4vk45no0x3emc3
Tags: upstream-2.1.0
Import upstream version 2.1.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# -*- coding: utf-8 -*-
2
 
#
 
2
 
3
3
#-------------------------------------------------------------------------------
4
 
#
5
 
#     This file is part of the Code_Saturne User Interface, element of the
6
 
#     Code_Saturne CFD tool.
7
 
#
8
 
#     Copyright (C) 1998-2009 EDF S.A., France
9
 
#
10
 
#     contact: saturne-support@edf.fr
11
 
#
12
 
#     The Code_Saturne User Interface is free software; you can redistribute it
13
 
#     and/or modify it under the terms of the GNU General Public License
14
 
#     as published by the Free Software Foundation; either version 2 of
15
 
#     the License, or (at your option) any later version.
16
 
#
17
 
#     The Code_Saturne User Interface is distributed in the hope that it will be
18
 
#     useful, but WITHOUT ANY WARRANTY; without even the implied warranty
19
 
#     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 
#     GNU General Public License for more details.
21
 
#
22
 
#     You should have received a copy of the GNU General Public License
23
 
#     along with the Code_Saturne Kernel; if not, write to the
24
 
#     Free Software Foundation, Inc.,
25
 
#     51 Franklin St, Fifth Floor,
26
 
#     Boston, MA  02110-1301  USA
27
 
#
 
4
 
 
5
# This file is part of Code_Saturne, a general-purpose CFD tool.
 
6
#
 
7
# Copyright (C) 1998-2011 EDF S.A.
 
8
#
 
9
# This program is free software; you can redistribute it and/or modify it under
 
10
# the terms of the GNU General Public License as published by the Free Software
 
11
# Foundation; either version 2 of the License, or (at your option) any later
 
12
# version.
 
13
#
 
14
# This program is distributed in the hope that it will be useful, but WITHOUT
 
15
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 
16
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 
17
# details.
 
18
#
 
19
# You should have received a copy of the GNU General Public License along with
 
20
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
 
21
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
22
 
28
23
#-------------------------------------------------------------------------------
29
24
 
30
25
"""
44
39
# String for the root node of the xml document from the case
45
40
#-------------------------------------------------------------------------------
46
41
 
47
 
rootNode = '<Code_Saturne_GUI study="" case="" version="2.0"/>'
48
 
#rootNode = '<NeptuneCFD study="" case=""/>'
 
42
rootNode = None
49
43
 
50
44
#-------------------------------------------------------------------------------
51
45
# Library modules import
59
53
# Application modules import
60
54
#-------------------------------------------------------------------------------
61
55
 
62
 
from Toolbox import GuiParam
 
56
from Base.Toolbox import GuiParam
63
57
 
64
58
#-------------------------------------------------------------------------------
65
59
# log config
87
81
        """
88
82
        self.data = {}
89
83
 
90
 
        self.data['new']                    = ""
91
 
        self.data['saved']                  = "yes"
92
 
        self.data['xmlfile']                = ""
93
 
        self.data['mesh_path']              = ""
94
 
        self.data['user_src_path']          = ""
95
 
        self.data['data_path']              = ""
96
 
        self.data['resu_path']              = ""
97
 
        self.data['scripts_path']           = ""
98
 
        self.data['relevant_subdir']        = "no"
99
 
        self.data['case_path']              = ""
100
 
        self.data['batchScript']            = {}
101
 
        self.data['backupBatchScript']      = {}
102
 
        self.data['computer']               = ""
 
84
        self.data['new']              = ""
 
85
        self.data['saved']            = "yes"
 
86
        self.data['xmlfile']          = ""
 
87
        self.data['mesh_path']        = ""
 
88
        self.data['user_src_path']    = ""
 
89
        self.data['data_path']        = ""
 
90
        self.data['resu_path']        = ""
 
91
        self.data['scripts_path']     = ""
 
92
        self.data['relevant_subdir']  = "no"
 
93
        self.data['case_path']        = ""
 
94
        self.data['batch']            = ""
 
95
        self.data['batch_type']       = ""
103
96
        self.data['no_boundary_conditions'] = False
104
 
        self.data['salome']                 = False
 
97
        self.data['salome']           = False
 
98
        self.data['package']          = None
105
99
 
106
100
 
107
101
    def _errorExit(self, msg):
108
102
        """
109
103
        """
110
 
        print 'CASE DICO ERROR'
111
 
        raise ValueError, msg
 
104
        print('CASE DICO ERROR')
 
105
        raise ValueError(msg)
112
106
 
113
107
 
114
108
    def __setitem__(self, key, name):
115
109
        """
116
 
        Store values in the data dictionary when the key existe
 
110
        Store values in the data dictionary when the key exists
117
111
        in the  dictionary.
118
112
        """
119
113
        if hasattr(self, 'data'):
123
117
                msg = "There is an error in the use of the dictionary "+ \
124
118
                      "with the key named: " + key + ". \n" + \
125
119
                      "The application will finish.\n" \
126
 
                      "Please contact the devlopment team."
 
120
                      "Please contact the development team."
127
121
 
128
 
                print self._errorExit(msg)
 
122
                print(self._errorExit(msg))
129
123
 
130
124
 
131
125
    def __getitem__(self, key):
145
139
        """
146
140
        if hasattr(self, 'data'):
147
141
            for i in self.data.keys():
148
 
                print "%s -> %s" % (i, self.data[i])
 
142
                print("%s -> %s" % (i, self.data[i]))
149
143
 
150
144
 
151
145
#-------------------------------------------------------------------------------
181
175
    def _errorExit(self, msg):
182
176
        """
183
177
        """
184
 
        print 'XML ERROR'
185
 
        raise ValueError, msg
 
178
        print('XML ERROR')
 
179
        raise ValueError(msg)
186
180
 
187
181
 
188
182
    def toString(self):
1093
1087
#-------------------------------------------------------------------------------
1094
1088
 
1095
1089
class Case(Dico, XMLDocument):
1096
 
    def __init__(self, file_name=""):
 
1090
    def __init__(self, package=None, file_name=""):
1097
1091
        """
1098
1092
        Instantiate a new dico and a new xml doc
1099
1093
        """
1100
1094
        Dico.__init__(self)
1101
1095
        XMLDocument.__init__(self, case=self)
1102
1096
 
 
1097
        self['package'] = package
 
1098
        rootNode = '<' + self['package'].code_name +'_GUI study="" case="" version="2.0"/>'
 
1099
 
1103
1100
        if file_name:
1104
1101
            self.parse(file_name)
1105
1102
            self['new'] = "no"
1154
1151
 
1155
1152
    def xmlSaveDocument(self):
1156
1153
        """
1157
 
        This method write the associated xml file.
 
1154
        This method writes the associated xml file.
1158
1155
        See saveCase and saveCaseAs methods in the Main module.
1159
1156
        """
1160
1157
        try:
1169
1166
        except IOError:
1170
1167
            msg = "Error: unable to save the XML document file." ,
1171
1168
            "(XMLengine module, Case class, xmlSaveDocument method)"
1172
 
            print msg
 
1169
            print(msg)
1173
1170
 
1174
 
##  def xmlSaveDocument(self):
1175
 
##      """
1176
 
##      This method write the associated xml file.
1177
 
##      See saveCase and saveCaseAs methods in the Main module.
1178
 
##      """
1179
 
##      try:
1180
 
##          file = open(self['xmlfile'], 'w')
1181
 
##          file.write(self.toPrettyString())
1182
 
##          file.close()
1183
 
##          self['new'] = "no"
1184
 
##          self['saved'] = "yes"
1185
 
##      except IOError:
1186
 
##          msg = "Error: unable to save the XML document file." ,
1187
 
##          "(XMLengine module, Case class, xmlSaveDocument method)"
1188
 
##          print msg
1189
1171
 
1190
1172
#-------------------------------------------------------------------------------
1191
1173
# XMLengine test case
1474
1456
 
1475
1457
    def checkXmlNodeFromString(self):
1476
1458
        """"Check whether two XML nodes could be compared."""
1477
 
        print '\n'
 
1459
        print('\n')
1478
1460
        n1 = self.xmlNodeFromString(u'<fruits taste="ok" color="red"><a>toto</a><c a="2é"/></fruits>')
1479
1461
        n2 = XMLDocument().parseString(u'<fruits color="red" taste="ok"><c a="2é"/><a>toto</a></fruits>').root()
1480
1462
        assert n1 == n2, 'This two node are not identical'
1569
1551
 
1570
1552
def runTest():
1571
1553
    """unittest function"""
1572
 
    print "XMLengineTestCase to be completed..."
 
1554
    print("XMLengineTestCase to be completed...")
1573
1555
    runner = unittest.TextTestRunner()
1574
1556
    runner.run(suite())
1575
1557
 
1606
1588
    def __call__(self, filename):
1607
1589
        try:
1608
1590
            self.parsefile(filename)
1609
 
            print "%s is well-formed" % filename
 
1591
            print("%s is well-formed" % filename)
1610
1592
        except Exception, e:
1611
 
            print "%s is NOT well-formed! %s" % (filename, e)
 
1593
            print("%s is NOT well-formed! %s" % (filename, e))
1612
1594
            sys.exit(0)
1613
1595
 
1614
1596
    def parsefile(self, file):
1731
1713
##    table.add("field", name="counter", type="int")
1732
1714
##    table.add("field", name="name", type="varchar")
1733
1715
##    table.add("field", name="info", type="text")
1734
 
##    print doc
 
1716
##    print(doc)
1735
1717
##
1736
1718
##    # Simulate reading a XML file
1737
1719
##    ndoc = XMLDocument()
1739
1721
##    root = ndoc.getAll("database")
1740
1722
##    if root:
1741
1723
##        db = root[0]
1742
 
##        print "Database:", db["name"]
 
1724
##        print("Database:", db["name"])
1743
1725
##        for table in db.getAll("table"):
1744
 
##            print "  Table:", table["name"]
 
1726
##            print("  Table:", table["name"])
1745
1727
##            for field in db.getAll("field"):
1746
 
##                print "    Field:", field["name"], "- Type:", field["type"]
 
1728
##                print("    Field:", field["name"], "- Type:", field["type"])
1747
1729
##
1748
1730
##    # It's object oriented
1749
 
##    print XMLDocument("notice").add("text",format="plain").addText("Some text")
 
1731
##    print(XMLDocument("notice").add("text",format="plain").addText("Some text"))
1750
1732
#
1751
1733
#-------------------------------------------------------------------------------
1752
1734
# Testing part
1758
1740
    sys.exit(0)
1759
1741
 
1760
1742
 
1761
 
    print "------------------------------------------------------"
1762
 
    print "    Lightweight XML constructor and reader testing"
1763
 
    print "------------------------------------------------------\n"
 
1743
    print("------------------------------------------------------")
 
1744
    print("    Lightweight XML constructor and reader testing")
 
1745
    print("------------------------------------------------------\n")
1764
1746
 
1765
1747
    # Example of dumping a database structure
1766
1748
    #
1767
1749
    xmldoc = XMLDocument("", "", "database", name="testdb")
1768
 
    print "XMLDocument:\n", xmldoc
 
1750
    print("XMLDocument:\n", xmldoc)
1769
1751
 
1770
1752
    table = xmldoc.xmlAddChild("table", name="test")
1771
1753
    table.xmlAddChild("field", name="counter", type="int")
1772
1754
    table.xmlAddChild("field", name="name", type="varchar")
1773
1755
    table.xmlAddChild("field", name="info", type="text")
1774
 
    print "table:\n", table
 
1756
    print("table:\n", table)
1775
1757
 
1776
 
    print "name:", table.xmlGetAttribute("name")
 
1758
    print("name:", table.xmlGetAttribute("name"))
1777
1759
    table.xmlDelAttribute("name")
1778
1760
    table.xmlCreateAttribute(truc="super", toto="méga")
1779
1761
    table.xmlCreateAttribute(name="atchoum")
1780
1762
    for field in table.xmlGetNodeList("field", "name", "type", type="text"):
1781
 
        print "field:", field.toString()
1782
 
    print "truc:", table.xmlGetAttribute("truc")
 
1763
        print("field:", field.toString())
 
1764
    print("truc:", table.xmlGetAttribute("truc"))
1783
1765
    #table.xmlGetAttribute("tru") # Uncomment this line for testing
1784
1766
    l = table.xmlGetNodeList("camion", "jacky", moquette="moche")
1785
1767
    if not l:
1786
1768
        l = table.xmlAddChild("camion", jacky="", moquette="moche")
1787
 
        print "child:", l.toString()
 
1769
        print("child:", l.toString())
1788
1770
    l = table.xmlInitNodeList("camion", "jacky", moquette="bêlle")[0]
1789
 
    print "child:", l.toString()
 
1771
    print("child:", l.toString())
1790
1772
 
1791
1773
    l.xmlSetData("camion", "rétro")
1792
1774
    l.xmlSetData("camion", "chèvre")
1793
1775
    for i in table.xmlGetNodeList("camion"):
1794
 
        print "List camion :", i.toString(), "\n"
 
1776
        print("List camion :", i.toString(), "\n")
1795
1777
    for i in table.xmlGetChildNodeList("camion"):
1796
 
        print "Child camion:", i.toString(), "\n"
 
1778
        print("Child camion:", i.toString(), "\n")
1797
1779
 
1798
1780
    table.xmlAddComment("Ceci est un commentaire")
1799
1781
    table.xmlInitNodeList('scalar', 'roue', 'box', auto='yes', type='model')
1810
1792
 
1811
1793
    chaise = xmldoc.xmlAddChild("chaise", name="test")
1812
1794
    p = chaise.xmlSetData("pieds", 4)
1813
 
    print p[0].toString()
1814
 
    print chaise.xmlGetStringList("pieds")
1815
 
    print chaise.xmlGetIntList("pieds")
1816
 
    print chaise.xmlGetString("pieds")
1817
 
    print chaise.xmlGetInt("pieds")
1818
 
    print chaise.xmlGetDouble("pieds")
1819
 
    print p[0].xmlGetTextNode()
 
1795
    print(p[0].toString())
 
1796
    print(chaise.xmlGetStringList("pieds"))
 
1797
    print(chaise.xmlGetIntList("pieds"))
 
1798
    print(chaise.xmlGetString("pieds"))
 
1799
    print(chaise.xmlGetInt("pieds"))
 
1800
    print(chaise.xmlGetDouble("pieds"))
 
1801
    print(p[0].xmlGetTextNode())
1820
1802
 
1821
 
    print xmldoc
 
1803
    print(xmldoc)
1822
1804
 
1823
1805
    # Direct acces to node's methods
1824
 
    #print dir(xmldoc.doc.documentElement)
1825
 
    #print _encode(xmldoc.doc.documentElement.toxml())
1826
 
    #print _encode(xmldoc.doc.documentElement.childNodes[0].childNodes[2].attributes.get("name").value)
1827
 
    #print _encode(xmldoc.doc.firstChild.firstChild.childNodes[1].attributes.items())
1828
 
    #print dir(xmldoc.doc.firstChild.firstChild.childNodes[1].attributes)
 
1806
    #print(dir(xmldoc.doc.documentElement))
 
1807
    #print(_encode(xmldoc.doc.documentElement.toxml()))
 
1808
    #print(_encode(xmldoc.doc.documentElement.childNodes[0].childNodes[2].attributes.get("name").value))
 
1809
    #print(_encode(xmldoc.doc.firstChild.firstChild.childNodes[1].attributes.items()))
 
1810
    #print(dir(xmldoc.doc.firstChild.firstChild.childNodes[1].attributes))
1829
1811
 
1830
1812
    # Simulate reading a XML file
1831
1813
    ndoc = XMLDocument("", "")
1832
 
    print "XML DOC:", ndoc.toString()
 
1814
    print("XML DOC:", ndoc.toString())
1833
1815
    ndoc.parseString(str(xmldoc))
1834
 
    print "XML DOC:", ndoc.toString()
 
1816
    print("XML DOC:", ndoc.toString())
1835
1817
    root = ndoc.xmlGetNodeList("database")
1836
1818
    if root:
1837
1819
        db = root[0]
1838
 
        print "Database:", db.xmlGetAttribute("name")
 
1820
        print("Database:", db.xmlGetAttribute("name"))
1839
1821
        for table in db.xmlGetNodeList("table"):
1840
 
            print "  Table:", table.xmlGetAttribute("name")
 
1822
            print("  Table:", table.xmlGetAttribute("name"))
1841
1823
            for field in table.xmlGetNodeList("field"):
1842
 
                print "    Field:", field.xmlGetAttribute("name"), \
1843
 
                      "- Type:", field.xmlGetAttribute("type")
 
1824
                print("    Field:", field.xmlGetAttribute("name"), \
 
1825
                      "- Type:", field.xmlGetAttribute("type"))
1844
1826
 
1845
1827
 
1846
1828
    ndoc.parseString('<?xml version="2.0" encoding="utf-8" ?><foo><baré/></foo>')
1847
 
    print "1 XML DOC:\n", ndoc
 
1829
    print("1 XML DOC:\n", ndoc)
1848
1830
 
1849
1831
    ndoc.parse("../misc/foo.txt")
1850
 
    print "2 XML DOC:\n", ndoc
1851
 
 
1852
 
 
1853
 
    print "------------------------------------------------------"
1854
 
    print "        Case class testing"
1855
 
    print "------------------------------------------------------\n"
 
1832
    print("2 XML DOC:\n", ndoc)
 
1833
 
 
1834
 
 
1835
    print("------------------------------------------------------")
 
1836
    print("        Case class testing")
 
1837
    print("------------------------------------------------------\n")
1856
1838
 
1857
1839
    case = Case()
1858
1840
    case['new'] = 'toto'
1859
 
    print "case:", case['new']
 
1841
    print("case:", case['new'])
1860
1842
    models = case.xmlGetNodeList('thermophysical_models')[0]
1861
1843
    models = case.xmlInitNodeList('thermophysical_models')[0]
1862
 
    #print "models :", dir(models)
 
1844
    #print("models :", dir(models))
1863
1845
    variables = models.xmlGetNodeList('variable')
1864
1846
    for var in variables:
1865
1847
        name = var['name']
1866
 
        print var.toString(), name
 
1848
        print(var.toString(), name)
1867
1849
        var['label'] = name
1868
1850
        #var.xmlSetAttribute(label='truc')
1869
1851
 
1870
 
    #print case
 
1852
    #print(case)
1871
1853
    #case.xmlRemoveChild('variable')
1872
 
    #print case
 
1854
    #print(case)
1873
1855
 
1874
1856
 
1875
1857
#-------------------------------------------------------------------------------