/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/Model/table.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/Model/table.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 839 by bh, Tue May 6 15:54:18 2003 UTC revision 1025 by frank, Mon May 26 11:46:17 2003 UTC
# Line 2  Line 2 
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4  # Jan-Oliver Wagner <[email protected]>  # Jan-Oliver Wagner <[email protected]>
5    # Frank Koormann <[email protected]>
6  #  #
7  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
8  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
# Line 12  Classes for handling tables of data. Line 13  Classes for handling tables of data.
13    
14  __version__ = "$Revision$"  __version__ = "$Revision$"
15    
16    import os
17  import inspect  import inspect
18  import warnings  import warnings
19    
20    from base import TitledObject
21    
22  import dbflib  import dbflib
23    
24  # the field types supported by a Table instance.  # the field types supported by a Table instance.
# Line 107  class DBFColumn: Line 111  class DBFColumn:
111          self.index = index          self.index = index
112    
113    
114  class DBFTable(OldTableInterfaceMixin):  class DBFTable(TitledObject, OldTableInterfaceMixin):
115    
116      """      """
117      Table interface for the data in a DBF file      Table interface for the data in a DBF file
# Line 129  class DBFTable(OldTableInterfaceMixin): Line 133  class DBFTable(OldTableInterfaceMixin):
133    
134      def __init__(self, filename):      def __init__(self, filename):
135          self.filename = filename          self.filename = filename
136            title = os.path.basename(self.filename)
137            TitledObject.__init__(self, title)
138          self.dbf = dbflib.DBFFile(filename)          self.dbf = dbflib.DBFFile(filename)
139    
140          # If true, self.dbf is open for writing.          # If true, self.dbf is open for writing.
# Line 218  class DBFTable(OldTableInterfaceMixin): Line 224  class DBFTable(OldTableInterfaceMixin):
224          values.sort()          values.sort()
225          return values          return values
226    
227        def Dependencies(self):
228            """Return an empty sequence. The DBFTable doesn't depend on anything"""
229            return ()
230    
231      # DBF specific interface parts.      # DBF specific interface parts.
232    
233        def Precision(self, col):
234            """Return column precision"""
235            return self.column_map[col].prec
236    
237        def Width(self, col):
238            """Return column width"""
239            return self.column_map[col].width
240    
241      def Destroy(self):      def Destroy(self):
242          self.dbf.close()          self.dbf.close()
243          self.dbf = None          self.dbf = None
# Line 246  class DBFTable(OldTableInterfaceMixin): Line 263  class DBFTable(OldTableInterfaceMixin):
263          self.dbf.write_record(record, values)          self.dbf.write_record(record, values)
264          self.dbf.commit()          self.dbf.commit()
265    
266        def FileName(self):
267            """Return the filename the DBFTable was instantiated with"""
268  # Temporary backwards compatibility          return self.filename
 Table = DBFTable  
   
269    
270    
271  class MemoryColumn:  class MemoryColumn:
# Line 260  class MemoryColumn: Line 275  class MemoryColumn:
275          self.type = type          self.type = type
276          self.index = index          self.index = index
277    
278  class MemoryTable(OldTableInterfaceMixin):  class MemoryTable(TitledObject, OldTableInterfaceMixin):
279    
280      """Very simple table implementation that operates on a list of tuples"""      """Very simple table implementation that operates on a list of tuples"""
281    
# Line 272  class MemoryTable(OldTableInterfaceMixin Line 287  class MemoryTable(OldTableInterfaceMixin
287          data -- List of tuples, one for each row of data          data -- List of tuples, one for each row of data
288          """          """
289          self.data = data          self.data = data
290            title = 'MemoryTable'
291            TitledObject.__init__(self, title)
292    
293          # Create the column information objects          # Create the column information objects
294          self.columns = []          self.columns = []
# Line 338  class MemoryTable(OldTableInterfaceMixin Line 355  class MemoryTable(OldTableInterfaceMixin
355          return min(values), max(values)          return min(values), max(values)
356    
357      def UniqueValues(self, col):      def UniqueValues(self, col):
358          """Return a sorted list of all unique values in the column col"""          """Return a sorted list of all unique values in the column col
359    
360            col can be either column index or name.
361            """
362          dict = {}          dict = {}
363    
364          for i in range(self.NumRows()):          for i in range(self.NumRows()):
# Line 349  class MemoryTable(OldTableInterfaceMixin Line 369  class MemoryTable(OldTableInterfaceMixin
369          values.sort()          values.sort()
370          return values          return values
371    
372        def Width(self, col):
373            """Return the maximum width of values in the column
374    
375            The return value is the the maximum length of string representation
376            of the values in the column (represented by index or name)."""
377            max = 0
378            
379            type  = self.column_map[col].type
380            index = self.column_map[col].index
381            values = [row[index] for row in self.data]
382            if not values:
383                return None
384    
385            if type == FIELDTYPE_DOUBLE:
386                prec = self.Precision(col)
387                format = "%%.%df" % prec
388            elif type == FIELDTYPE_INT:
389                format = "%d"
390            else:
391                format = "%s"
392            for value in values:
393                l = len(format % value)
394                if l > max:
395                    max = l
396    
397            return max
398    
399        def Precision(self, col):
400            """Return the precision of the column
401    
402            The return value is the maximum number of numeric characters after the
403            decimal if column type is double. Else precision zero is returned.
404            The column can be represented by index or name.
405            """
406        
407            type  = self.column_map[col].type
408            if type == FIELDTYPE_DOUBLE:
409                index = self.column_map[col].index
410                values = [row[index] for row in self.data]
411                if not values:
412                    return 0
413                
414                max = 0
415                for value in values:
416                    l = len(str(value % 1))
417                    if l > max:
418                        max = l
419                if max > 2:
420                    return max - 2
421                else:
422                    return 0
423            else:
424                return 0
425              
426        def Dependencies(self):
427            """Return an empty sequence. The MemoryTable doesn't depend on anything
428            """
429            return ()
430    
431      def write_record(self, record, values):      def write_record(self, record, values):
432          # TODO: Check for correct lenght and perhaps also          # TODO: Check for correct lenght and perhaps also
# Line 356  class MemoryTable(OldTableInterfaceMixin Line 434  class MemoryTable(OldTableInterfaceMixin
434          # TODO: Allow values to be a dictionary and write the single          # TODO: Allow values to be a dictionary and write the single
435          # fields that are specified.          # fields that are specified.
436          self.data[record] = values          self.data[record] = values
437    
438    
439    def table_to_dbf(table, filename):
440        """Create the dbf file filename from the table"""
441        dbf = dbflib.create(filename)
442    
443        dbflib_fieldtypes = {FIELDTYPE_STRING: dbflib.FTString,
444                             FIELDTYPE_INT: dbflib.FTInteger,
445                             FIELDTYPE_DOUBLE: dbflib.FTDouble}
446    
447        # Initialise the header. Distinguish between DBFTable and others.
448        for col in table.Columns():
449            prec  = table.Precision(col.name)
450            width = table.Width(col.name)
451            dbf.add_field(col.name, dbflib_fieldtypes[col.type], width, prec)
452    
453        for i in range(table.NumRows()):
454            record = table.ReadRowAsDict(i)
455            dbf.write_record(i, record)
456        dbf.close()
457    
458    def table_to_csv(table, filename):
459        """Export table to csv file."""
460    
461        file = open(filename,"w")
462        columns = table.Columns()
463        if columns:
464            header = "#%s" % columns[0].name
465            for col in columns[1:]:
466                header = header + ",%s" % col.name
467            header = header + "\n"
468            file.write(header)
469    
470            for i in range(table.NumRows()):
471                record = table.ReadRowAsDict(i)
472                if len(record):
473                    line = "%s" % record[columns[0].name]
474                    for col in columns[1:]:
475                        line = line + ",%s" % record[col.name]
476                line = line + "\n"
477                file.write(line)
478        file.close()
479    

Legend:
Removed from v.839  
changed lines
  Added in v.1025

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26