source: branches/numpy/anuga/geospatial_data/geospatial_data.py @ 6428

Last change on this file since 6428 was 6428, checked in by rwilson, 15 years ago

numpy changes

File size: 69.4 KB
Line 
1"""Class Geospatial_data
2
3Manipulation of locations on the planet and associated attributes.
4"""
5
6from sys import maxint
7from os import access, F_OK, R_OK,remove
8from types import DictType
9from warnings import warn
10from string import lower
11from RandomArray import randint, seed, get_seed
12from copy import deepcopy
13
14from Scientific.IO.NetCDF import NetCDFFile
15import numpy as num
16
17from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
18from anuga.utilities.numerical_tools import ensure_numeric
19from anuga.coordinate_transforms.geo_reference import Geo_reference, \
20     TitleError, DEFAULT_ZONE, ensure_geo_reference, write_NetCDF_georeference
21from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
22from anuga.utilities.system_tools import clean_line
23from anuga.utilities.anuga_exceptions import ANUGAError
24from anuga.config import points_file_block_line_size as MAX_READ_LINES
25from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
26from anuga.config import netcdf_float
27
28
29DEFAULT_ATTRIBUTE = 'elevation'
30
31
32##
33# @brief ??
34class Geospatial_data:
35
36    ##
37    # @brief
38    # @param data_points Mx2 iterable of tuples or array of x,y coordinates.
39    # @param attributes Associated values for each data point.
40    # @param geo_reference ??
41    # @param default_attribute_name ??
42    # @param file_name
43    # @param latitudes ??
44    # @param longitudes ??
45    # @param points_are_lats_longs True if points are lat/long, not UTM.
46    # @param max_read_lines Size of block to read, if blocking.
47    # @param load_file_now True if blocking but we eant to read file now.
48    # @param verbose True if this class instance is verbose.
49    def __init__(self,
50                 data_points=None, # this can also be a points file name
51                 attributes=None,
52                 geo_reference=None,
53                 default_attribute_name=None,
54                 file_name=None,
55                 latitudes=None,
56                 longitudes=None,
57                 points_are_lats_longs=False,
58                 max_read_lines=None,
59                 load_file_now=True,
60                 verbose=False):
61        """Create instance from data points and associated attributes
62
63        data_points: x,y coordinates in meters. Type must be either a
64        sequence of 2-tuples or an Mx2 numeric array of floats.  A file name
65        with extension .txt, .cvs or .pts can also be passed in here.
66
67        attributes: Associated values for each data point. The type
68        must be either a list or an array of length M or a dictionary
69        of lists (or arrays) of length M. In the latter case the keys
70        in the dictionary represent the attribute names, in the former
71        the attribute will get the default name "elevation".
72
73        geo_reference: Object representing the origin of the data
74        points. It contains UTM zone, easting and northing and data
75        points are assumed to be relative to this origin.
76        If geo_reference is None, the default geo ref object is used.
77
78        default_attribute_name: Name of default attribute to be used with
79        get_attribute_values. The idea is that the dataset can be
80        equipped with information about which attribute to return.
81        If None, the default is the "first"
82
83        latitudes, longitudes: Vectors of latitudes and longitudes,
84        used to specify location instead of points.
85
86        points_are_lats_longs: Set this as true if the points are actually
87        lats and longs, not UTM
88
89        max_read_lines: The number of rows read into memory when using
90        blocking to read a file.
91
92        load_file_now:  If true the file is automatically loaded
93        into the geospatial instance. Used when blocking.
94
95        file_name: Name of input netCDF file or .txt file. netCDF file must
96        have dimensions "points" etc.
97        .txt file is a comma seperated file with x, y and attribute
98        data.
99
100        The first line has the titles of the columns.  The first two
101        column titles are checked to see if they start with lat or
102        long (not case sensitive).  If so the data is assumed to be
103        latitude and longitude, in decimal format and converted to
104        UTM.  Otherwise the first two columns are assumed to be the x
105        and y, and the title names acually used are ignored.
106
107
108        The format for a .txt file is:
109            1st line:     [column names]
110            other lines:  x y [attributes]
111
112            for example:
113            x, y, elevation, friction
114            0.6, 0.7, 4.9, 0.3
115            1.9, 2.8, 5, 0.3
116            2.7, 2.4, 5.2, 0.3
117
118        The first two columns have to be x, y or lat, long
119        coordinates.
120
121
122        The format for a Points dictionary is:
123          ['pointlist'] a 2 column array describing points. 1st column x,
124          2nd column y.
125          ['attributelist'], a dictionary of 1D arrays, representing
126          attribute values at the point.  The dictionary key is the attribute
127          header.
128          ['geo_reference'] a Geo_refernece object. Use if the point
129          information is relative. This is optional.
130            eg
131            dic['pointlist'] = [[1.0,2.0],[3.0,5.0]]
132            dic['attributelist']['elevation'] = [[7.0,5.0]
133
134        verbose:
135        """
136
137        if isinstance(data_points, basestring):
138            # assume data_points is really a file name
139            file_name = data_points
140
141        self.set_verbose(verbose)
142        self.geo_reference = None
143        self.file_name = file_name
144
145        if max_read_lines is None:
146            self.max_read_lines = MAX_READ_LINES
147        else:
148            self.max_read_lines = max_read_lines
149
150        if file_name is None:
151            if (latitudes is not None or longitudes is not None
152                    or points_are_lats_longs):
153                data_points, geo_reference = \
154                    _set_using_lat_long(latitudes=latitudes,
155                                        longitudes=longitudes,
156                                        geo_reference=geo_reference,
157                                        data_points=data_points,
158                                        points_are_lats_longs=
159                                            points_are_lats_longs)
160            self.check_data_points(data_points)
161            self.set_attributes(attributes)
162            self.set_geo_reference(geo_reference)
163            self.set_default_attribute_name(default_attribute_name)
164        elif load_file_now is True:
165            # watch for case where file name and points,
166            # attributes etc are provided!!
167            # if file name then all provided info will be removed!
168
169            if verbose is True:
170                if file_name is not None:
171                    print 'Loading Geospatial data from file: %s' % file_name
172
173            self.import_points_file(file_name, verbose=verbose)
174
175            self.check_data_points(self.data_points)
176            self.set_attributes(self.attributes)
177            self.set_geo_reference(self.geo_reference)
178            self.set_default_attribute_name(default_attribute_name)
179
180        if verbose is True:
181            if file_name is not None:
182                print 'Geospatial data created from file: %s' % file_name
183                if load_file_now is False:
184                    print 'Data will be loaded blockwise on demand'
185
186                    if file_name.endswith('csv') or file_name.endswith('txt'):
187                        pass
188                        # This message was misleading.
189                        # FIXME (Ole): Are we blocking here or not?
190                        # print 'ASCII formats are not that great for '
191                        # print 'blockwise reading. Consider storing this'
192                        # print 'data as a pts NetCDF format'
193
194    ##
195    # @brief Return length of the points set.
196    def __len__(self):
197        return len(self.data_points)
198
199    ##
200    # @brief Return a string representation of the points set.
201    def __repr__(self):
202        return str(self.get_data_points(absolute=True))
203
204    ##
205    # @brief Check data points.
206    # @param data_points Points data to check and store in instance.
207    # @note Throws ValueError exception if no data.
208    def check_data_points(self, data_points):
209        """Checks data points"""
210
211        if data_points is None:
212            self.data_points = None
213            msg = 'There is no data or file provided!'
214            raise ValueError, msg
215        else:
216            self.data_points = ensure_numeric(data_points)
217            if not (0,) == self.data_points.shape:
218                assert len(self.data_points.shape) == 2
219                assert self.data_points.shape[1] == 2
220
221    ##
222    # @brief Check and assign attributes data.
223    # @param attributes Dictionary or scalar to save as .attributes.
224    # @note Throws exception if unable to convert dict keys to numeric.
225    def set_attributes(self, attributes):
226        """Check and assign attributes dictionary"""
227
228        if attributes is None:
229            self.attributes = None
230            return
231
232        if not isinstance(attributes, DictType):
233            # Convert single attribute into dictionary
234            attributes = {DEFAULT_ATTRIBUTE: attributes}
235
236        # Check input attributes
237        for key in attributes.keys():
238            try:
239                attributes[key] = ensure_numeric(attributes[key])
240            except:
241                msg = ("Attribute '%s' (%s) could not be converted to a"
242                       "numeric vector" % (str(key), str(attributes[key])))
243                raise Exception, msg
244
245        self.attributes = attributes
246
247    ##
248    # @brief Set the georeference of geospatial data.
249    # @param geo_reference The georeference data to set.
250    # @note Will raise exception if param not instance of Geo_reference.
251    def set_geo_reference(self, geo_reference):
252        """Set the georeference of geospatial data.
253
254        It can also be used to change the georeference and will ensure that
255        the absolute coordinate values are unchanged.
256        """
257
258        if geo_reference is None:
259            # Use default - points are in absolute coordinates
260            geo_reference = Geo_reference()
261
262        # Allow for tuple (zone, xllcorner, yllcorner)
263        geo_reference = ensure_geo_reference(geo_reference)
264
265        if not isinstance(geo_reference, Geo_reference):
266            # FIXME (Ole): This exception will be raised even
267            # if geo_reference is None. Is that the intent Duncan?
268            msg = ('Argument geo_reference must be a valid Geo_reference '
269                   'object or None.')
270            raise Expection, msg
271
272        # If a geo_reference already exists, change the point data according to
273        # the new geo reference
274        if  self.geo_reference is not None:
275            self.data_points = self.get_data_points(geo_reference=geo_reference)
276
277        self.geo_reference = geo_reference
278
279    ##
280    # @brief Set default attribute name.
281    # @param default_attribute_name The default to save.
282    def set_default_attribute_name(self, default_attribute_name):
283        self.default_attribute_name = default_attribute_name
284
285    ##
286    # @brief Set the instance verbose flag.
287    # @param verbose The value to save.
288    # @note Will raise exception if param is not True or False.
289    def set_verbose(self, verbose=False):
290        if verbose in [False, True]:
291            self.verbose = verbose
292        else:
293            msg = 'Illegal value: %s' % str(verbose)
294            raise Exception, msg
295
296    ##
297    # @brief Clip geospatial data by a given polygon.
298    # @param polygon The polygon to clip with.
299    # @param closed True if points on clip boundary are not included in result.
300    # @param verbose True if this function is verbose.
301    def clip(self, polygon, closed=True, verbose=False):
302        """Clip geospatial data by a polygon
303
304        Input
305          polygon - Either a list of points, an Nx2 array or
306                    a Geospatial data object.
307          closed - (optional) determine whether points on boundary should be
308          regarded as belonging to the polygon (closed = True)
309          or not (closed = False). Default is True.
310
311        Output
312          New geospatial data object representing points inside
313          specified polygon.
314
315
316        Note - this method is non-destructive and leaves the data in 'self'
317        unchanged
318        """
319
320        from anuga.utilities.polygon import inside_polygon
321
322        if isinstance(polygon, Geospatial_data):
323            # Polygon is an object - extract points
324            polygon = polygon.get_data_points()
325
326        points = self.get_data_points()
327        inside_indices = inside_polygon(points, polygon, closed, verbose)
328
329        clipped_G = self.get_sample(inside_indices)
330
331        return clipped_G
332
333    ##
334    # @brief Clip points data by polygon, return points outside polygon.
335    # @param polygon The polygon to clip with.
336    # @param closed True if points on clip boundary are not included in result.
337    # @param verbose True if this function is verbose.
338    def clip_outside(self, polygon, closed=True, verbose=False):
339        """Clip geospatial date by a polygon, keeping data OUTSIDE of polygon
340
341        Input
342          polygon - Either a list of points, an Nx2 array or
343                    a Geospatial data object.
344          closed - (optional) determine whether points on boundary should be
345          regarded as belonging to the polygon (closed = True)
346          or not (closed = False). Default is True.
347
348        Output
349          Geospatial data object representing point OUTSIDE specified polygon
350        """
351
352        from anuga.utilities.polygon import outside_polygon
353
354        if isinstance(polygon, Geospatial_data):
355            # Polygon is an object - extract points
356            polygon = polygon.get_data_points()
357
358        points = self.get_data_points()
359        outside_indices = outside_polygon(points, polygon, closed,verbose)
360
361        clipped_G = self.get_sample(outside_indices)
362
363        return clipped_G
364
365    ##
366    # @brief Get instance geo_reference data.
367    def get_geo_reference(self):
368        return self.geo_reference
369
370    ##
371    # @brief Get coordinates for all data points as an Nx2 array.
372    # @param absolute If True, return UTM, else relative to xll/yll corners.
373    # @param geo_reference If supplied, points are relative to it.
374    # @param as_lat_long If True, return points as lat/lon.
375    # @param isSouthHemisphere If True, return lat/lon points in S.Hemi.
376    # @return A set of data points, in appropriate form.
377    def get_data_points(self,
378                        absolute=True,
379                        geo_reference=None,
380                        as_lat_long=False,
381                        isSouthHemisphere=True):
382        """Get coordinates for all data points as an Nx2 array
383
384        If absolute is False returned coordinates are relative to the
385        internal georeference's xll and yll corners, otherwise
386        absolute UTM coordinates are returned.
387
388        If a geo_reference is passed the points are returned relative
389        to that geo_reference.
390
391        isSH (isSouthHemisphere) is only used when getting data
392        points "as_lat_long" is True and if FALSE will return lats and
393        longs valid for the Northern Hemisphere.
394
395        Default: absolute is True.
396        """
397
398        if as_lat_long is True:
399            msg = "Points need a zone to be converted into lats and longs"
400            assert self.geo_reference is not None, msg
401            zone = self.geo_reference.get_zone()
402            assert self.geo_reference.get_zone() is not DEFAULT_ZONE, msg
403            lats_longs = []
404            for point in self.get_data_points(True):
405                # UTMtoLL(northing, easting, zone,
406                lat_calced, long_calced = UTMtoLL(point[1], point[0],
407                                                  zone, isSouthHemisphere)
408                lats_longs.append((lat_calced, long_calced)) # to hash
409            return lats_longs
410
411        if absolute is True and geo_reference is None:
412            return self.geo_reference.get_absolute(self.data_points)
413        elif geo_reference is not None:
414            return geo_reference.change_points_geo_ref(self.data_points,
415                                                       self.geo_reference)
416        else:
417            # If absolute is False
418            return self.data_points
419
420    ##
421    # @brief Get value for attribute name.
422    # @param attribute_name Name to get value for.
423    # @note If name passed is None, return default attribute value.
424    def get_attributes(self, attribute_name=None):
425        """Return values for one named attribute.
426
427        If attribute_name is None, default_attribute_name is used
428        """
429
430        if attribute_name is None:
431            if self.default_attribute_name is not None:
432                attribute_name = self.default_attribute_name
433            else:
434                attribute_name = self.attributes.keys()[0]
435                # above line takes the first one from keys
436
437        if self.verbose is True:
438            print 'Using attribute %s' %attribute_name
439            print 'Available attributes: %s' %(self.attributes.keys())
440
441        msg = 'Attribute name %s does not exist in data set' % attribute_name
442        assert self.attributes.has_key(attribute_name), msg
443
444        return self.attributes[attribute_name]
445
446    ##
447    # @brief Get all instance attributes.
448    # @return The instance attribute dictionary, or None if no attributes.
449    def get_all_attributes(self):
450        """Return values for all attributes.
451        The return value is either None or a dictionary (possibly empty).
452        """
453
454        return self.attributes
455
456    ##
457    # @brief Override __add__() to allow addition of geospatial objects.
458    # @param self This object.
459    # @param other The second object.
460    # @return The new geospatial object.
461    def __add__(self, other):
462        """Returns the addition of 2 geospatial objects,
463        objects are concatencated to the end of each other
464
465        NOTE: doesn't add if objects contain different
466        attributes
467
468        Always return absolute points!
469        This also means, that if you add None to the object,
470        it will be turned into absolute coordinates
471
472        other can be None in which case nothing is added to self.
473        """
474
475        # find objects zone and checks if the same
476        geo_ref1 = self.get_geo_reference()
477        zone1 = geo_ref1.get_zone()
478
479        if other is not None:
480            geo_ref2 = other.get_geo_reference()
481            zone2 = geo_ref2.get_zone()
482            geo_ref1.reconcile_zones(geo_ref2)
483            new_points = num.concatenate((self.get_data_points(absolute=True),
484                                          other.get_data_points(absolute=True)),
485                                         axis = 0)
486
487            # Concatenate attributes if any
488            if self.attributes is None:
489                if other.attributes is not None:
490                    msg = ('Geospatial data must have the same '
491                           'attributes to allow addition.')
492                    raise Exception, msg
493
494                new_attributes = None
495            else:
496                new_attributes = {}
497                for x in self.attributes.keys():
498                    if other.attributes.has_key(x):
499                        attrib1 = self.attributes[x]
500                        attrib2 = other.attributes[x]
501                        new_attributes[x] = num.concatenate((attrib1, attrib2),
502                                                            axis=0) #??default#
503                    else:
504                        msg = ('Geospatial data must have the same '
505                               'attributes to allow addition.')
506                        raise Exception, msg
507        else:
508            # other is None:
509            new_points = self.get_data_points(absolute=True)
510            new_attributes = self.attributes
511
512        # Instantiate new data object and return absolute coordinates
513        new_geo_ref = Geo_reference(geo_ref1.get_zone(), 0.0, 0.0)
514        return Geospatial_data(new_points, new_attributes, new_geo_ref)
515
516    ##
517    # @brief Override the addition case where LHS isn't geospatial object.
518    # @param self This object.
519    # @param other The second object.
520    # @return The new geospatial object.
521    def __radd__(self, other):
522        """Handle cases like None + Geospatial_data(...)"""
523
524        return self + other
525
526################################################################################
527#  IMPORT/EXPORT POINTS FILES
528################################################################################
529
530    ##
531    # @brief Import a .txt, .csv or .pts points data file.
532    # @param file_name
533    # @param delimiter
534    # @param verbose True if this function is to be verbose.
535    # @note Will throw IOError or SyntaxError if there is a problem.
536    def import_points_file(self, file_name, delimiter=None, verbose=False):
537        """ load an .txt, .csv or .pts file
538
539        Note: will throw an IOError/SyntaxError if it can't load the file.
540        Catch these!
541
542        Post condition: self.attributes dictionary has been set
543        """
544
545        if access(file_name, F_OK) == 0 :
546            msg = 'File %s does not exist or is not accessible' % file_name
547            raise IOError, msg
548
549        attributes = {}
550        if file_name[-4:] == ".pts":
551            try:
552                data_points, attributes, geo_reference = \
553                             _read_pts_file(file_name, verbose)
554            except IOError, e:
555                msg = 'Could not open file %s ' % file_name
556                raise IOError, msg
557        elif file_name[-4:] == ".txt" or file_name[-4:]== ".csv":
558            try:
559                data_points, attributes, geo_reference = \
560                             _read_csv_file(file_name, verbose)
561            except IOError, e:
562                # This should only be if a file is not found
563                msg = ('Could not open file %s. Check the file location.'
564                       % file_name)
565                raise IOError, msg
566            except SyntaxError, e:
567                # This should only be if there is a format error
568                msg = ('Problem with format of file %s.\n%s'
569                       % (file_name, Error_message['IOError']))
570                raise SyntaxError, msg
571        else:
572            msg = 'Extension %s is unknown' % file_name[-4:]
573            raise IOError, msg
574
575        self.data_points = data_points
576        self.attributes = attributes
577        self.geo_reference = geo_reference
578
579    ##
580    # @brief Write points data to a file (.csv or .pts).
581    # @param file_name Path to file to write.
582    # @param absolute ??
583    # @param as_lat_long ??
584    # @param isSouthHemisphere ??
585    def export_points_file(self, file_name, absolute=True,
586                           as_lat_long=False, isSouthHemisphere=True):
587        """write a points file as a text (.csv) or binary (.pts) file
588
589        file_name is the file name, including the extension
590        The point_dict is defined at the top of this file.
591
592        If absolute is True data the xll and yll are added to the points value
593        and the xll and yll of the geo_reference are set to 0.
594
595        If absolute is False data points at returned as relative to the xll
596        and yll and geo_reference remains uneffected
597
598        isSouthHemisphere: is only used when getting data
599        points "as_lat_long" is True and if FALSE will return lats and
600        longs valid for the Northern Hemisphere.
601        """
602
603        if (file_name[-4:] == ".pts"):
604            if absolute is True:
605                geo_ref = deepcopy(self.geo_reference)
606                geo_ref.xllcorner = 0
607                geo_ref.yllcorner = 0
608                _write_pts_file(file_name,
609                                self.get_data_points(absolute),
610                                self.get_all_attributes(),
611                                geo_ref)
612            else:
613                _write_pts_file(file_name,
614                                self.get_data_points(absolute),
615                                self.get_all_attributes(),
616                                self.get_geo_reference())
617        elif file_name[-4:] == ".txt" or file_name[-4:] == ".csv":
618            msg = "ERROR: trying to write a .txt file with relative data."
619            assert absolute, msg
620            _write_csv_file(file_name,
621                            self.get_data_points(absolute=True,
622                                                 as_lat_long=as_lat_long,
623                                           isSouthHemisphere=isSouthHemisphere),
624                            self.get_all_attributes(),
625                            as_lat_long=as_lat_long)
626        elif file_name[-4:] == ".urs" :
627            msg = "ERROR: Can not write a .urs file as a relative file."
628            assert absolute, msg
629            _write_urs_file(file_name,
630                            self.get_data_points(as_lat_long=True,
631                                           isSouthHemisphere=isSouthHemisphere))
632        else:
633            msg = 'Unknown file type %s ' %file_name
634            raise IOError, msg
635
636    ##
637    # @brief Get a subset of data that is referred to by 'indices'.
638    # @param indices A list of indices to select data subset with.
639    # @return A geospatial object containing data subset.
640    def get_sample(self, indices):
641        """ Returns a object which is a subset of the original
642        and the data points and attributes in this new object refer to
643        the indices provided
644
645        Input
646            indices- a list of integers that represent the new object
647        Output
648            New geospatial data object representing points specified by
649            the indices
650        """
651
652        # FIXME: add the geo_reference to this
653        points = self.get_data_points()
654        sampled_points = num.take(points, indices, axis=0)
655
656        attributes = self.get_all_attributes()
657
658        sampled_attributes = {}
659        if attributes is not None:
660            for key, att in attributes.items():
661                sampled_attributes[key] = num.take(att, indices, axis=0)
662
663        return Geospatial_data(sampled_points, sampled_attributes)
664
665    ##
666    # @brief Split one geospatial object into two.
667    # @param factor Relative size to make first result object.
668    # @param seed_num Random 'seed' - used only for unit test.
669    # @param verbose True if this function is to be verbose.
670    # @note Points in each result object are selected randomly.
671    def split(self, factor=0.5, seed_num=None, verbose=False):
672        """Returns two geospatial_data object, first is the size of the 'factor'
673        smaller the original and the second is the remainder. The two
674        new objects are disjoint sets of each other.
675
676        Points of the two new object have selected RANDOMLY.
677
678        This method create two lists of indices which are passed into
679        get_sample.  The lists are created using random numbers, and
680        they are unique sets eg.  total_list(1,2,3,4,5,6,7,8,9)
681        random_list(1,3,6,7,9) and remainder_list(0,2,4,5,8)
682
683        Input -  the factor which to split the object, if 0.1 then 10% of the
684                 together object will be returned
685
686        Output - two geospatial_data objects that are disjoint sets of the
687                 original
688        """
689
690        i = 0
691        self_size = len(self)
692        random_list = []
693        remainder_list = []
694        new_size = round(factor * self_size)
695
696        # Find unique random numbers
697        if verbose: print "make unique random number list and get indices"
698
699        total = num.array(range(self_size), num.int)    #array default#
700        total_list = total.tolist()
701
702        if verbose: print "total list len", len(total_list)
703
704        # There will be repeated random numbers however will not be a
705        # problem as they are being 'pop'ed out of array so if there
706        # are two numbers the same they will pop different indicies,
707        # still basically random
708        ## create list of non-unquie random numbers
709        if verbose: print "create random numbers list %s long" %new_size
710
711        # Set seed if provided, mainly important for unit test!
712        # plus recalcule seed when no seed provided.
713        if seed_num is not None:
714            seed(seed_num, seed_num)
715        else:
716            seed()
717
718        if verbose: print "seed:", get_seed()
719
720        random_num = randint(0, self_size-1, (int(new_size),))
721        random_num = random_num.tolist()
722
723        # need to sort and reverse so the pop() works correctly
724        random_num.sort()
725        random_num.reverse()
726
727        if verbose: print "make random number list and get indices"
728
729        j = 0
730        k = 1
731        remainder_list = total_list[:]
732
733        # pops array index (random_num) from remainder_list
734        # (which starts as the total_list and appends to random_list)
735        random_num_len = len(random_num)
736        for i in random_num:
737            random_list.append(remainder_list.pop(i))
738            j += 1
739            # prints progress
740            if verbose and round(random_num_len/10*k) == j:
741                print '(%s/%s)' % (j, random_num_len)
742                k += 1
743
744        # FIXME: move to tests, it might take a long time
745        # then create an array of random length between 500 and 1000,
746        # and use a random factor between 0 and 1
747        # setup for assertion
748        test_total = random_list[:]
749        test_total.extend(remainder_list)
750        test_total.sort()
751        msg = ('The two random lists made from the original list when added '
752               'together DO NOT equal the original list')
753        assert total_list == test_total, msg
754
755        # Get new samples
756        if verbose: print "get values of indices for random list"
757        G1 = self.get_sample(random_list)
758        if verbose: print "get values of indices for opposite of random list"
759        G2 = self.get_sample(remainder_list)
760
761        return G1, G2
762
763    ##
764    # @brief Allow iteration over this object.
765    def __iter__(self):
766        """Read in the header, number_of_points and save the
767        file pointer position
768        """
769
770        # FIXME - what to do if the file isn't there
771
772        # FIXME (Ole): Shouldn't this go into the constructor?
773        # This method acts like the constructor when blocking.
774        # ... and shouldn't it be called block_size?
775        #
776        if self.max_read_lines is None:
777            self.max_read_lines = MAX_READ_LINES
778
779        if self.file_name[-4:] == ".pts":
780            # See if the file is there.  Throw a QUIET IO error if it isn't
781            fd = open(self.file_name,'r')
782            fd.close()
783
784            # Throws prints to screen if file not present
785            self.fid = NetCDFFile(self.file_name, netcdf_mode_r)
786
787            (self.blocking_georef,
788             self.blocking_keys,
789             self.number_of_points) = _read_pts_file_header(self.fid,
790                                                            self.verbose)
791            self.start_row = 0
792            self.last_row = self.number_of_points
793            self.show_verbose = 0
794            self.verbose_block_size = (self.last_row + 10)/10
795            self.block_number = 0
796            self.number_of_blocks = self.number_of_points/self.max_read_lines
797            # This computes the number of full blocks. The last block may be
798            # smaller and won't be included in this estimate.
799
800            if self.verbose is True:
801                print ('Reading %d points (in ~%d blocks) from file %s. '
802                       % (self.number_of_points, self.number_of_blocks,
803                          self.file_name)),
804                print ('Each block consists of %d data points'
805                       % self.max_read_lines)
806        else:
807            # Assume the file is a csv file
808            file_pointer = open(self.file_name)
809            self.header, self.file_pointer = _read_csv_file_header(file_pointer)
810            self.blocking_georef = None # Used for reconciling zones
811
812        return self
813
814    ##
815    # @brief Read another block into the instance.
816    def next(self):
817        """read a block, instanciate a new geospatial and return it"""
818
819        if self.file_name[-4:] == ".pts":
820            if self.start_row == self.last_row:
821                # Read the end of the file last iteration
822                # Remove blocking attributes
823                self.fid.close()
824                del self.max_read_lines
825                del self.blocking_georef
826                del self.last_row
827                del self.start_row
828                del self.blocking_keys
829                del self.fid
830                raise StopIteration
831            fin_row = self.start_row + self.max_read_lines
832            if fin_row > self.last_row:
833                fin_row = self.last_row
834
835            if self.verbose is True:
836                if (self.show_verbose >= self.start_row
837                    and self.show_verbose < fin_row):
838                    print ('Reading block %d (points %d to %d) out of %d'
839                           % (self.block_number, self.start_row,
840                              fin_row, self.number_of_blocks))
841
842                    self.show_verbose += max(self.max_read_lines,
843                                             self.verbose_block_size)
844
845            # Read next block
846            pointlist, att_dict, = _read_pts_file_blocking(self.fid,
847                                                           self.start_row,
848                                                           fin_row,
849                                                           self.blocking_keys)
850
851            geo = Geospatial_data(pointlist, att_dict, self.blocking_georef)
852            self.start_row = fin_row
853
854            self.block_number += 1
855        else:
856            # Assume the file is a csv file
857            try:
858                (pointlist,
859                 att_dict,
860                 geo_ref,
861                 self.file_pointer) = _read_csv_file_blocking(self.file_pointer,
862                                                              self.header[:],
863                                                              max_read_lines= \
864                                                           self.max_read_lines,
865                                                              verbose= \
866                                                                  self.verbose)
867
868                # Check that the zones haven't changed.
869                if geo_ref is not None:
870                    geo_ref.reconcile_zones(self.blocking_georef)
871                    self.blocking_georef = geo_ref
872                elif self.blocking_georef is not None:
873                    msg = ('Geo reference given, then not given.'
874                           ' This should not happen.')
875                    raise ValueError, msg
876                geo = Geospatial_data(pointlist, att_dict, geo_ref)
877            except StopIteration:
878                self.file_pointer.close()
879                del self.header
880                del self.file_pointer
881                raise StopIteration
882            except ANUGAError:
883                self.file_pointer.close()
884                del self.header
885                del self.file_pointer
886                raise
887            except SyntaxError:
888                self.file_pointer.close()
889                del self.header
890                del self.file_pointer
891                # This should only be if there is a format error
892                msg = ('Could not open file %s.\n%s'
893                       % (self.file_name, Error_message['IOError']))
894                raise SyntaxError, msg
895        return geo
896
897##################### Error messages ###########
898Error_message = {}
899Em = Error_message
900Em['IOError'] = ('NOTE: The format for a comma separated .txt/.csv file is:\n'
901                 '        1st line:     [column names]\n'
902                 '        other lines:  [x value], [y value], [attributes]\n'
903                 '\n'
904                 '           for example:\n'
905                 '           x, y, elevation, friction\n'
906                 '           0.6, 0.7, 4.9, 0.3\n'
907                 '           1.9, 2.8, 5, 0.3\n'
908                 '           2.7, 2.4, 5.2, 0.3\n'
909                 '\n'
910                 'The first two columns are assumed to be x, y coordinates.\n'
911                 'The attribute values must be numeric.\n')
912
913##
914# @brief ??
915# @param latitudes ??
916# @param longitudes ??
917# @param geo_reference ??
918# @param data_points ??
919# @param points_are_lats_longs ??
920def _set_using_lat_long(latitudes,
921                        longitudes,
922                        geo_reference,
923                        data_points,
924                        points_are_lats_longs):
925    """If the points has lat long info, assume it is in (lat, long) order."""
926
927    if geo_reference is not None:
928        msg = ('A georeference is specified yet latitude and longitude '
929               'are also specified!')
930        raise ValueError, msg
931
932    if data_points is not None and not points_are_lats_longs:
933        msg = ('Data points are specified yet latitude and longitude are '
934               'also specified.')
935        raise ValueError, msg
936
937    if points_are_lats_longs:
938        if data_points is None:
939            msg = "Data points are not specified."
940            raise ValueError, msg
941        lats_longs = ensure_numeric(data_points)
942        latitudes = num.ravel(lats_longs[:,0:1])
943        longitudes = num.ravel(lats_longs[:,1:])
944
945    if latitudes is None and longitudes is None:
946        msg = "Latitudes and Longitudes are not specified."
947        raise ValueError, msg
948
949    if latitudes is None:
950        msg = "Longitudes are specified yet latitudes aren't."
951        raise ValueError, msg
952
953    if longitudes is None:
954        msg = "Latitudes are specified yet longitudes aren't."
955        raise ValueError, msg
956
957    data_points, zone  = convert_from_latlon_to_utm(latitudes=latitudes,
958                                                    longitudes=longitudes)
959    return data_points, Geo_reference(zone=zone)
960
961
962##
963# @brief Read a .pts data file.
964# @param file_name Path to file to read.
965# @param verbose True if this function is to be verbose.
966# @return (pointlist, attributes, geo_reference)
967def _read_pts_file(file_name, verbose=False):
968    """Read .pts NetCDF file
969
970    Return a dic of array of points, and dic of array of attribute
971    eg
972    dic['points'] = [[1.0,2.0],[3.0,5.0]]
973    dic['attributelist']['elevation'] = [[7.0,5.0]]
974    """
975
976    if verbose: print 'Reading ', file_name
977
978    # See if the file is there.  Throw a QUIET IO error if it isn't
979    fd = open(file_name,'r')
980    fd.close()
981
982    # Throws prints to screen if file not present
983    fid = NetCDFFile(file_name, netcdf_mode_r)
984
985    pointlist = num.array(fid.variables['points'])
986    keys = fid.variables.keys()
987
988    if verbose: print 'Got %d variables: %s' % (len(keys), keys)
989
990    try:
991        keys.remove('points')
992    except IOError, e:
993        fid.close()
994        msg = "Expected keyword 'points' but could not find it"
995        raise IOError, msg
996
997    attributes = {}
998    for key in keys:
999        if verbose: print "reading attribute '%s'" % key
1000
1001        attributes[key] = num.array(fid.variables[key])
1002
1003    try:
1004        geo_reference = Geo_reference(NetCDFObject=fid)
1005    except AttributeError, e:
1006        geo_reference = None
1007
1008    fid.close()
1009
1010    return pointlist, attributes, geo_reference
1011
1012
1013##
1014# @brief Read a .csv data file.
1015# @param file_name Path to the .csv file to read.
1016# @param verbose True if this function is to be verbose.
1017def _read_csv_file(file_name, verbose=False):
1018    """Read .csv file
1019
1020    Return a dic of array of points, and dic of array of attribute
1021    eg
1022    dic['points'] = [[1.0,2.0],[3.0,5.0]]
1023    dic['attributelist']['elevation'] = [[7.0,5.0]]
1024    """
1025
1026    file_pointer = open(file_name)
1027    header, file_pointer = _read_csv_file_header(file_pointer)
1028    try:
1029        (pointlist,
1030         att_dict,
1031         geo_ref,
1032         file_pointer) = _read_csv_file_blocking(file_pointer,
1033                                                 header,
1034                                                 max_read_lines=1e30)
1035                                    # If the file is bigger that this, block..
1036                                    # FIXME (Ole) What's up here?
1037    except ANUGAError:
1038        file_pointer.close()
1039        raise
1040
1041    file_pointer.close()
1042
1043    return pointlist, att_dict, geo_ref
1044
1045
1046##
1047# @brief Read a .csv file header.
1048# @param file_pointer Open descriptor of the file to read.
1049# @param delimiter Header line delimiter string, split on this string.
1050# @param verbose True if this function is to be verbose.
1051# @return A tuple of (<cleaned header string>, <input file_pointer>)
1052
1053CSV_DELIMITER = ','
1054
1055def _read_csv_file_header(file_pointer,
1056                          delimiter=CSV_DELIMITER,
1057                          verbose=False):
1058    """Read the header of a .csv file
1059    Return a list of the header names
1060    """
1061
1062    line = file_pointer.readline()
1063    header = clean_line(line, delimiter)
1064
1065    return header, file_pointer
1066
1067##
1068# @brief Read a .csv file, with blocking.
1069# @param file_pointer Open descriptor of the file to read.
1070# @param header List of already read .csv header fields.
1071# @param delimiter Delimiter string header was split on.
1072# @param max_read_lines The max number of lines to read before blocking.
1073# @param verbose True if this function is to be verbose.
1074# @note Will throw IndexError, SyntaxError exceptions.
1075def _read_csv_file_blocking(file_pointer,
1076                            header,
1077                            delimiter=CSV_DELIMITER,
1078                            max_read_lines=MAX_READ_LINES,
1079                            verbose=False):
1080    """Read the body of a .csv file.
1081    header: The list header of the csv file, with the x and y labels.
1082    """
1083
1084    points = []
1085    pointattributes = []
1086    att_dict = {}
1087
1088    # This is to remove the x and y headers.
1089    header = header[:]
1090    try:
1091        x_header = header.pop(0)
1092        y_header = header.pop(0)
1093    except IndexError:
1094        # if there are not two columns this will occur.
1095        # eg if it is a space seperated file
1096        raise SyntaxError
1097
1098    read_lines = 0
1099    while read_lines < max_read_lines:
1100        line = file_pointer.readline()
1101        numbers = clean_line(line, delimiter)
1102        if len(numbers) <= 1:
1103            break
1104        if line[0] == '#':
1105            continue
1106
1107        read_lines += 1
1108
1109        try:
1110            x = float(numbers[0])
1111            y = float(numbers[1])
1112            points.append([x,y])
1113            numbers.pop(0)
1114            numbers.pop(0)
1115            if len(header) != len(numbers):
1116                file_pointer.close()
1117                msg = ('File load error. '
1118                       'There might be a problem with the file header.')
1119                raise SyntaxError, msg
1120            for i,n in enumerate(numbers):
1121                n.strip()
1122                if n != '\n' and n != '':
1123                    att_dict.setdefault(header[i],[]).append(float(n))
1124        except ValueError:
1125            raise SyntaxError
1126
1127    if points == []:
1128        raise StopIteration
1129
1130    pointlist = num.array(points, num.float)
1131    for key in att_dict.keys():
1132        att_dict[key] = num.array(att_dict[key], num.float)
1133
1134    # Do stuff here so the info is in lat's and longs
1135    geo_ref = None
1136    x_header = lower(x_header[:3])
1137    y_header = lower(y_header[:3])
1138    if (x_header == 'lon' or  x_header == 'lat') \
1139       and (y_header == 'lon' or  y_header == 'lat'):
1140        if x_header == 'lon':
1141            longitudes = num.ravel(pointlist[:,0:1])
1142            latitudes = num.ravel(pointlist[:,1:])
1143        else:
1144            latitudes = num.ravel(pointlist[:,0:1])
1145            longitudes = num.ravel(pointlist[:,1:])
1146
1147        pointlist, geo_ref = _set_using_lat_long(latitudes,
1148                                                 longitudes,
1149                                                 geo_reference=None,
1150                                                 data_points=None,
1151                                                 points_are_lats_longs=False)
1152
1153    return pointlist, att_dict, geo_ref, file_pointer
1154
1155
1156##
1157# @brief Read a .pts file header.
1158# @param fid Handle to the open .pts file.
1159# @param verbose True if the function is to be verbose.
1160# @return (geo_reference, keys, fid.dimensions['number_of_points'])
1161# @note Will throw IOError and AttributeError exceptions.
1162def _read_pts_file_header(fid, verbose=False):
1163    '''Read the geo_reference and number_of_points from a .pts file'''
1164
1165    keys = fid.variables.keys()
1166    try:
1167        keys.remove('points')
1168    except IOError, e:
1169        fid.close()
1170        msg = "Expected keyword 'points' but could not find it."
1171        raise IOError, msg
1172
1173    if verbose: print 'Got %d variables: %s' % (len(keys), keys)
1174
1175    try:
1176        geo_reference = Geo_reference(NetCDFObject=fid)
1177    except AttributeError, e:
1178        geo_reference = None
1179
1180    return geo_reference, keys, fid.dimensions['number_of_points']
1181
1182
1183##
1184# @brief Read the body of a .csf file, with blocking.
1185# @param fid Handle to already open file.
1186# @param start_row Start row index of points to return.
1187# @param fin_row End row index of points to return.
1188# @param keys Iterable of keys to return.
1189# @return Tuple of (pointlist, attributes).
1190def _read_pts_file_blocking(fid, start_row, fin_row, keys):
1191    '''Read the body of a .csv file.'''
1192
1193    pointlist = num.array(fid.variables['points'][start_row:fin_row])
1194
1195    attributes = {}
1196    for key in keys:
1197        attributes[key] = num.array(fid.variables[key][start_row:fin_row])
1198
1199    return pointlist, attributes
1200
1201
1202##
1203# @brief Write a .pts data file.
1204# @param file_name Path to the file to write.
1205# @param write_data_points Data points to write.
1206# @param write_attributes Attributes to write.
1207# @param write_geo_reference Georef to write.
1208def _write_pts_file(file_name,
1209                    write_data_points,
1210                    write_attributes=None,
1211                    write_geo_reference=None):
1212    """Write .pts NetCDF file
1213
1214    NOTE: Below might not be valid ask Duncan : NB 5/2006
1215
1216    WARNING: This function mangles the point_atts data structure
1217    # F??ME: (DSG)This format has issues.
1218    # There can't be an attribute called points
1219    # consider format change
1220    # method changed by NB not sure if above statement is correct
1221
1222    should create new test for this
1223    legal_keys = ['pointlist', 'attributelist', 'geo_reference']
1224    for key in point_atts.keys():
1225        msg = 'Key %s is illegal. Valid keys are %s' %(key, legal_keys)
1226        assert key in legal_keys, msg
1227    """
1228
1229    # NetCDF file definition
1230    outfile = NetCDFFile(file_name, netcdf_mode_w)
1231
1232    # Create new file
1233    outfile.institution = 'Geoscience Australia'
1234    outfile.description = ('NetCDF format for compact and portable storage '
1235                           'of spatial point data')
1236
1237    # Dimension definitions
1238    shape = write_data_points.shape[0]
1239    outfile.createDimension('number_of_points', shape)
1240    outfile.createDimension('number_of_dimensions', 2) # This is 2d data
1241
1242    # Variable definition
1243    outfile.createVariable('points', netcdf_float,
1244                           ('number_of_points', 'number_of_dimensions'))
1245
1246    # create variables
1247    outfile.variables['points'][:] = write_data_points
1248
1249    if write_attributes is not None:
1250        for key in write_attributes.keys():
1251            outfile.createVariable(key, netcdf_float, ('number_of_points',))
1252            outfile.variables[key][:] = write_attributes[key]
1253
1254    if write_geo_reference is not None:
1255        write_NetCDF_georeference(write_geo_reference, outfile)
1256
1257    outfile.close()
1258
1259
1260##
1261# @brief Write a .csv data file.
1262# @param file_name Path to the file to write.
1263# @param write_data_points Data points to write.
1264# @param write_attributes Attributes to write.
1265# @param as_lat_long True if points are lat/lon, else x/y.
1266# @param delimiter The CSV delimiter to use.
1267def _write_csv_file(file_name,
1268                    write_data_points,
1269                    write_attributes=None,
1270                    as_lat_long=False,
1271                    delimiter=','):
1272    """Write a .csv file."""
1273
1274    points = write_data_points
1275    pointattributes = write_attributes
1276
1277    fd = open(file_name, 'w')
1278
1279    if as_lat_long:
1280        titlelist = "latitude" + delimiter + "longitude"  + delimiter
1281    else:
1282        titlelist = "x" + delimiter + "y"  + delimiter
1283
1284    if pointattributes is not None:
1285        for title in pointattributes.keys():
1286            titlelist = titlelist + title + delimiter
1287        titlelist = titlelist[0:-len(delimiter)] # remove the last delimiter
1288
1289    fd.write(titlelist + "\n")
1290
1291    # <x/lat> <y/long> [attributes]
1292    for i, vert in enumerate( points):
1293        if pointattributes is not None:
1294            attlist = ","
1295            for att in pointattributes.keys():
1296                attlist = attlist + str(pointattributes[att][i]) + delimiter
1297            attlist = attlist[0:-len(delimiter)] # remove the last delimiter
1298            attlist.strip()
1299        else:
1300            attlist = ''
1301
1302        fd.write(str(vert[0]) + delimiter + str(vert[1]) + attlist + "\n")
1303
1304    fd.close()
1305
1306
1307##
1308# @brief Write a URS file.
1309# @param file_name The path of the file to write.
1310# @param points
1311# @param delimiter
1312def _write_urs_file(file_name, points, delimiter=' '):
1313    """Write a URS format file.
1314    export a file, file_name, with the urs format
1315    the data points are in lats and longs
1316    """
1317
1318    fd = open(file_name, 'w')
1319
1320    # first line is # points
1321    fd.write(str(len(points)) + "\n")
1322
1323    # <lat> <long> <id#>
1324    for i, vert in enumerate( points):
1325        fd.write(str(round(vert[0],7)) + delimiter +
1326                 str(round(vert[1],7)) + delimiter + str(i) + "\n")
1327
1328    fd.close()
1329
1330
1331##
1332# @brief ??
1333# @param point_atts ??
1334# @return ??
1335def _point_atts2array(point_atts):
1336    point_atts['pointlist'] = num.array(point_atts['pointlist'], num.float)
1337
1338    for key in point_atts['attributelist'].keys():
1339        point_atts['attributelist'][key] = \
1340                num.array(point_atts['attributelist'][key], num.float)
1341
1342    return point_atts
1343
1344
1345##
1346# @brief Convert geospatial object to a points dictionary.
1347# @param geospatial_data The geospatial object to convert.
1348# @return A points dictionary.
1349def geospatial_data2points_dictionary(geospatial_data):
1350    """Convert geospatial data to points_dictionary"""
1351
1352    points_dictionary = {}
1353    points_dictionary['pointlist'] = geospatial_data.data_points
1354
1355    points_dictionary['attributelist'] = {}
1356
1357    for attribute_name in geospatial_data.attributes.keys():
1358        val = geospatial_data.attributes[attribute_name]
1359        points_dictionary['attributelist'][attribute_name] = val
1360
1361    points_dictionary['geo_reference'] = geospatial_data.geo_reference
1362
1363    return points_dictionary
1364
1365
1366##
1367# @brief Convert a points dictionary to a geospatial object.
1368# @param points_dictionary A points dictionary to convert.
1369def points_dictionary2geospatial_data(points_dictionary):
1370    """Convert points_dictionary to geospatial data object"""
1371
1372    msg = "Points dictionary must have key 'pointlist'"
1373    assert points_dictionary.has_key('pointlist'), msg
1374
1375    msg = "Points dictionary must have key 'attributelist'"
1376    assert points_dictionary.has_key('attributelist'), msg
1377
1378    if points_dictionary.has_key('geo_reference'):
1379        geo = points_dictionary['geo_reference']
1380    else:
1381        geo = None
1382
1383    return Geospatial_data(points_dictionary['pointlist'],
1384                           points_dictionary['attributelist'],
1385                           geo_reference=geo)
1386
1387
1388##
1389# @brief Ensure that points are in absolute coordinates.
1390# @param points A list or array of points to check, or geospatial object.
1391# @param geo_reference If supplied,
1392# @return ??
1393def ensure_absolute(points, geo_reference=None):
1394    """Ensure that points are in absolute coordinates.
1395
1396    This function inputs several formats and
1397    outputs one format. - a numeric array of absolute points.
1398
1399    Input formats are;
1400      points: List or numeric array of coordinate pairs [xi, eta] of
1401              points or geospatial object or points file name
1402
1403    mesh_origin: A geo_reference object or 3-tuples consisting of
1404                 UTM zone, easting and northing.
1405                 If specified vertex coordinates are assumed to be
1406                 relative to their respective origins.
1407    """
1408
1409    # Input check
1410    if isinstance(points, basestring):
1411        # It's a string - assume it is a point file
1412        points = Geospatial_data(file_name=points)
1413
1414    if isinstance(points, Geospatial_data):
1415        points = points.get_data_points(absolute=True)
1416        msg = 'Use a Geospatial_data object or a mesh origin, not both.'
1417        assert geo_reference == None, msg
1418    else:
1419        points = ensure_numeric(points, num.float)
1420
1421    # Sort of geo_reference and convert points
1422    if geo_reference is None:
1423        geo = None    # Geo_reference()
1424    else:
1425        if isinstance(geo_reference, Geo_reference):
1426            geo = geo_reference
1427        else:
1428            geo = Geo_reference(geo_reference[0],
1429                                geo_reference[1],
1430                                geo_reference[2])
1431        points = geo.get_absolute(points)
1432
1433    return points
1434
1435
1436##
1437# @brief
1438# @param points
1439# @param geo_reference
1440# @return A geospatial object.
1441def ensure_geospatial(points, geo_reference=None):
1442    """Convert various data formats to a geospatial_data instance.
1443
1444    Inputed formats are;
1445    points:      List or numeric array of coordinate pairs [xi, eta] of
1446                 points or geospatial object
1447
1448    mesh_origin: A geo_reference object or 3-tuples consisting of
1449                 UTM zone, easting and northing.
1450                 If specified vertex coordinates are assumed to be
1451                 relative to their respective origins.
1452    """
1453
1454    # Input check
1455    if isinstance(points, Geospatial_data):
1456        msg = "Use a Geospatial_data object or a mesh origin, not both."
1457        assert geo_reference is None, msg
1458        return points
1459    else:
1460        # List or numeric array of absolute points
1461        points = ensure_numeric(points, num.float)
1462
1463    # Sort out geo reference
1464    if geo_reference is None:
1465        geo = None
1466    else:
1467        if isinstance(geo_reference, Geo_reference):
1468            geo = geo_reference
1469        else:
1470            geo = Geo_reference(geo_reference[0],
1471                                geo_reference[1],
1472                                geo_reference[2])
1473
1474    # Create Geospatial_data object with appropriate geo reference and return
1475    points = Geospatial_data(data_points=points, geo_reference=geo)
1476
1477    return points
1478
1479
1480##
1481# @brief
1482# @param data_file
1483# @param alpha_list
1484# @param mesh_file
1485# @param boundary_poly
1486# @param mesh_resolution
1487# @param north_boundary
1488# @param south_boundary
1489# @param east_boundary
1490# @param west_boundary
1491# @param plot_name
1492# @param split_factor
1493# @param seed_num
1494# @param cache
1495# @param verbose
1496def find_optimal_smoothing_parameter(data_file,
1497                                     alpha_list=None,
1498                                     mesh_file=None,
1499                                     boundary_poly=None,
1500                                     mesh_resolution=100000,
1501                                     north_boundary=None,
1502                                     south_boundary=None,
1503                                     east_boundary=None,
1504                                     west_boundary=None,
1505                                     plot_name='all_alphas',
1506                                     split_factor=0.1,
1507                                     seed_num=None,
1508                                     cache=False,
1509                                     verbose=False):
1510    """Removes a small random sample of points from 'data_file'.
1511    Then creates models with different alpha values from 'alpha_list' and
1512    cross validates the predicted value to the previously removed point data.
1513    Returns the alpha value which has the smallest covariance.
1514
1515    data_file: must not contain points outside the boundaries defined
1516               and it either a pts, txt or csv file.
1517
1518    alpha_list: the alpha values to test in a single list
1519
1520    mesh_file: name of the created mesh file or if passed in will read it.
1521               NOTE, if there is a mesh file mesh_resolution,
1522               north_boundary, south... etc will be ignored.
1523
1524    mesh_resolution: the maximum area size for a triangle
1525
1526    north_boundary... west_boundary: the value of the boundary
1527
1528    plot_name: the name for the plot contain the results
1529
1530    seed_num: the seed to the random number generator
1531
1532    USAGE:
1533        value, alpha = find_optimal_smoothing_parameter(data_file=fileName,
1534                                             alpha_list=[0.0001, 0.01, 1],
1535                                             mesh_file=None,
1536                                             mesh_resolution=3,
1537                                             north_boundary=5,
1538                                             south_boundary=-5,
1539                                             east_boundary=5,
1540                                             west_boundary=-5,
1541                                             plot_name='all_alphas',
1542                                             seed_num=100000,
1543                                             verbose=False)
1544
1545    OUTPUT: returns the minumum normalised covalance calculate AND the
1546           alpha that created it. PLUS writes a plot of the results
1547
1548    NOTE: code will not work if the data_file extent is greater than the
1549    boundary_polygon or any of the boundaries, eg north_boundary...west_boundary
1550    """
1551
1552    from anuga.shallow_water import Domain
1553    from anuga.geospatial_data.geospatial_data import Geospatial_data
1554    from anuga.pmesh.mesh_interface import create_mesh_from_regions
1555    from anuga.utilities.numerical_tools import cov
1556    from anuga.utilities.polygon import is_inside_polygon
1557    from anuga.fit_interpolate.benchmark_least_squares import mem_usage
1558
1559    attribute_smoothed = 'elevation'
1560
1561    if mesh_file is None:
1562        if verbose: print "building mesh"
1563        mesh_file = 'temp.msh'
1564
1565        if (north_boundary is None or south_boundary is None
1566            or east_boundary is None or west_boundary is None):
1567            no_boundary = True
1568        else:
1569            no_boundary = False
1570
1571        if no_boundary is True:
1572            msg = 'All boundaries must be defined'
1573            raise Expection, msg
1574
1575        poly_topo = [[east_boundary, south_boundary],
1576                     [east_boundary, north_boundary],
1577                     [west_boundary, north_boundary],
1578                     [west_boundary, south_boundary]]
1579
1580        create_mesh_from_regions(poly_topo,
1581                                 boundary_tags={'back': [2],
1582                                                'side': [1,3],
1583                                                'ocean': [0]},
1584                                 maximum_triangle_area=mesh_resolution,
1585                                 filename=mesh_file,
1586                                 use_cache=cache,
1587                                 verbose=verbose)
1588
1589    else: # if mesh file provided
1590        # test mesh file exists?
1591        if verbose: "reading from file: %s" % mesh_file
1592        if access(mesh_file,F_OK) == 0:
1593            msg = "file %s doesn't exist!" % mesh_file
1594            raise IOError, msg
1595
1596    # split topo data
1597    if verbose: print 'Reading elevation file: %s' % data_file
1598    G = Geospatial_data(file_name = data_file)
1599    if verbose: print 'Start split'
1600    G_small, G_other = G.split(split_factor, seed_num, verbose=verbose)
1601    if verbose: print 'Finish split'
1602    points = G_small.get_data_points()
1603
1604    if verbose: print "Number of points in sample to compare: ", len(points)
1605
1606    if alpha_list == None:
1607        alphas = [0.001,0.01,100]
1608        #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01,
1609        #          0.1, 1.0, 10.0, 100.0,1000.0,10000.0]
1610    else:
1611        alphas = alpha_list
1612
1613    # creates array with columns 1 and 2 are x, y. column 3 is elevation
1614    # 4 onwards is the elevation_predicted using the alpha, which will
1615    # be compared later against the real removed data
1616    data = num.array([], dtype=num.float)
1617
1618    data = num.resize(data, (len(points), 3+len(alphas)))
1619
1620    # gets relative point from sample
1621    data[:,0] = points[:,0]
1622    data[:,1] = points[:,1]
1623    elevation_sample = G_small.get_attributes(attribute_name=attribute_smoothed)
1624    data[:,2] = elevation_sample
1625
1626    normal_cov = num.array(num.zeros([len(alphas), 2]), dtype=num.float)
1627
1628    if verbose: print 'Setup computational domains with different alphas'
1629
1630    for i, alpha in enumerate(alphas):
1631        # add G_other data to domains with different alphas
1632        if verbose:
1633            print '\nCalculating domain and mesh for Alpha =', alpha, '\n'
1634        domain = Domain(mesh_file, use_cache=cache, verbose=verbose)
1635        if verbose: print domain.statistics()
1636        domain.set_quantity(attribute_smoothed,
1637                            geospatial_data=G_other,
1638                            use_cache=cache,
1639                            verbose=verbose,
1640                            alpha=alpha)
1641
1642        # Convert points to geospatial data for use with get_values below
1643        points_geo = Geospatial_data(points, domain.geo_reference)
1644
1645        # returns the predicted elevation of the points that were "split" out
1646        # of the original data set for one particular alpha
1647        if verbose: print 'Get predicted elevation for location to be compared'
1648        elevation_predicted = \
1649                domain.quantities[attribute_smoothed].\
1650                    get_values(interpolation_points=points_geo)
1651
1652        # add predicted elevation to array that starts with x, y, z...
1653        data[:,i+3] = elevation_predicted
1654
1655        sample_cov = cov(elevation_sample)
1656        ele_cov = cov(elevation_sample - elevation_predicted)
1657        normal_cov[i,:] = [alpha, ele_cov / sample_cov]
1658
1659        if verbose:
1660            print 'Covariance for alpha ', normal_cov[i][0], '= ', \
1661                      normal_cov[i][1]
1662            print '-------------------------------------------- \n'
1663
1664    normal_cov0 = normal_cov[:,0]
1665    normal_cov_new = num.take(normal_cov, num.argsort(normal_cov0), axis=0)
1666
1667    if plot_name is not None:
1668        from pylab import savefig, semilogx, loglog
1669
1670        semilogx(normal_cov_new[:,0], normal_cov_new[:,1])
1671        loglog(normal_cov_new[:,0], normal_cov_new[:,1])
1672        savefig(plot_name, dpi=300)
1673
1674    if mesh_file == 'temp.msh':
1675        remove(mesh_file)
1676
1677    if verbose:
1678        print 'Final results:'
1679        for i, alpha in enumerate(alphas):
1680            print ('covariance for alpha %s = %s '
1681                   % (normal_cov[i][0], normal_cov[i][1]))
1682        print ('\nOptimal alpha is: %s '
1683               % normal_cov_new[(num.argmin(normal_cov_new, axis=0))[1], 0])
1684
1685    # covariance and optimal alpha
1686    return (min(normal_cov_new[:,1]),
1687            normal_cov_new[(num.argmin(normal_cov_new,axis=0))[1],0])
1688
1689
1690##
1691# @brief
1692# @param data_file
1693# @param alpha_list
1694# @param mesh_file
1695# @param boundary_poly
1696# @param mesh_resolution
1697# @param north_boundary
1698# @param south_boundary
1699# @param east_boundary
1700# @param west_boundary
1701# @param plot_name
1702# @param split_factor
1703# @param seed_num
1704# @param cache
1705# @param verbose
1706def old_find_optimal_smoothing_parameter(data_file,
1707                                         alpha_list=None,
1708                                         mesh_file=None,
1709                                         boundary_poly=None,
1710                                         mesh_resolution=100000,
1711                                         north_boundary=None,
1712                                         south_boundary=None,
1713                                         east_boundary=None,
1714                                         west_boundary=None,
1715                                         plot_name='all_alphas',
1716                                         split_factor=0.1,
1717                                         seed_num=None,
1718                                         cache=False,
1719                                         verbose=False):
1720    """
1721    data_file: must not contain points outside the boundaries defined
1722               and it either a pts, txt or csv file.
1723
1724    alpha_list: the alpha values to test in a single list
1725
1726    mesh_file: name of the created mesh file or if passed in will read it.
1727               NOTE, if there is a mesh file mesh_resolution,
1728               north_boundary, south... etc will be ignored.
1729
1730    mesh_resolution: the maximum area size for a triangle
1731
1732    north_boundary... west_boundary: the value of the boundary
1733
1734    plot_name: the name for the plot contain the results
1735
1736    seed_num: the seed to the random number generator
1737
1738    USAGE:
1739        value, alpha = find_optimal_smoothing_parameter(data_file=fileName,
1740                                             alpha_list=[0.0001, 0.01, 1],
1741                                             mesh_file=None,
1742                                             mesh_resolution=3,
1743                                             north_boundary=5,
1744                                             south_boundary=-5,
1745                                             east_boundary=5,
1746                                             west_boundary=-5,
1747                                             plot_name='all_alphas',
1748                                             seed_num=100000,
1749                                             verbose=False)
1750
1751    OUTPUT: returns the minumum normalised covalance calculate AND the
1752            alpha that created it. PLUS writes a plot of the results
1753
1754    NOTE: code will not work if the data_file extend is greater than the
1755          boundary_polygon or the north_boundary...west_boundary
1756    """
1757
1758    from anuga.shallow_water import Domain
1759    from anuga.geospatial_data.geospatial_data import Geospatial_data
1760    from anuga.pmesh.mesh_interface import create_mesh_from_regions
1761    from anuga.utilities.numerical_tools import cov
1762    from anuga.utilities.polygon import is_inside_polygon
1763    from anuga.fit_interpolate.benchmark_least_squares import mem_usage
1764
1765    attribute_smoothed = 'elevation'
1766
1767    if mesh_file is None:
1768        mesh_file = 'temp.msh'
1769
1770        if (north_boundary is None or south_boundary is None
1771            or east_boundary is None or west_boundary is None):
1772            no_boundary = True
1773        else:
1774            no_boundary = False
1775
1776        if no_boundary is True:
1777            msg = 'All boundaries must be defined'
1778            raise Expection, msg
1779
1780        poly_topo = [[east_boundary, south_boundary],
1781                     [east_boundary, north_boundary],
1782                     [west_boundary, north_boundary],
1783                     [west_boundary, south_boundary]]
1784
1785        create_mesh_from_regions(poly_topo,
1786                                 boundary_tags={'back': [2],
1787                                                'side': [1,3],
1788                                                'ocean': [0]},
1789                                 maximum_triangle_area=mesh_resolution,
1790                                 filename=mesh_file,
1791                                 use_cache=cache,
1792                                 verbose=verbose)
1793
1794    else: # if mesh file provided
1795        # test mesh file exists?
1796        if access(mesh_file,F_OK) == 0:
1797            msg = "file %s doesn't exist!" % mesh_file
1798            raise IOError, msg
1799
1800    # split topo data
1801    G = Geospatial_data(file_name=data_file)
1802    if verbose: print 'start split'
1803    G_small, G_other = G.split(split_factor, seed_num, verbose=verbose)
1804    if verbose: print 'finish split'
1805    points = G_small.get_data_points()
1806
1807    if verbose: print "Number of points in sample to compare: ", len(points)
1808
1809    if alpha_list == None:
1810        alphas = [0.001,0.01,100]
1811        #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01,
1812        #          0.1, 1.0, 10.0, 100.0,1000.0,10000.0]
1813    else:
1814        alphas = alpha_list
1815
1816    domains = {}
1817
1818    if verbose: print 'Setup computational domains with different alphas'
1819
1820    for alpha in alphas:
1821        # add G_other data to domains with different alphas
1822        if verbose:
1823            print '\nCalculating domain and mesh for Alpha =', alpha, '\n'
1824        domain = Domain(mesh_file, use_cache=cache, verbose=verbose)
1825        if verbose: print domain.statistics()
1826        domain.set_quantity(attribute_smoothed,
1827                            geospatial_data=G_other,
1828                            use_cache=cache,
1829                            verbose=verbose,
1830                            alpha=alpha)
1831        domains[alpha] = domain
1832
1833    # creates array with columns 1 and 2 are x, y. column 3 is elevation
1834    # 4 onwards is the elevation_predicted using the alpha, which will
1835    # be compared later against the real removed data
1836    data = num.array([], dtype=num.float)
1837
1838    data = num.resize(data, (len(points), 3+len(alphas)))
1839
1840    # gets relative point from sample
1841    data[:,0] = points[:,0]
1842    data[:,1] = points[:,1]
1843    elevation_sample = G_small.get_attributes(attribute_name=attribute_smoothed)
1844    data[:,2] = elevation_sample
1845
1846    normal_cov = num.array(num.zeros([len(alphas), 2]), dtype=num.float)
1847
1848    if verbose:
1849        print 'Determine difference between predicted results and actual data'
1850
1851    for i, alpha in enumerate(domains):
1852        if verbose: print'Alpha =', alpha
1853
1854        points_geo = domains[alpha].geo_reference.change_points_geo_ref(points)
1855        # returns the predicted elevation of the points that were "split" out
1856        # of the original data set for one particular alpha
1857        elevation_predicted = \
1858                domains[alpha].quantities[attribute_smoothed].\
1859                        get_values(interpolation_points=points_geo)
1860
1861        # add predicted elevation to array that starts with x, y, z...
1862        data[:,i+3] = elevation_predicted
1863
1864        sample_cov = cov(elevation_sample)
1865        ele_cov = cov(elevation_sample - elevation_predicted)
1866        normal_cov[i,:] = [alpha,ele_cov / sample_cov]
1867        print 'memory usage during compare', mem_usage()
1868        if verbose: print 'cov', normal_cov[i][0], '= ', normal_cov[i][1]
1869
1870    normal_cov0 = normal_cov[:,0]
1871    normal_cov_new = num.take(normal_cov, num.argsort(normal_cov0), axis=0)
1872
1873    if plot_name is not None:
1874        from pylab import savefig,semilogx,loglog
1875
1876        semilogx(normal_cov_new[:,0], normal_cov_new[:,1])
1877        loglog(normal_cov_new[:,0], normal_cov_new[:,1])
1878        savefig(plot_name, dpi=300)
1879    if mesh_file == 'temp.msh':
1880        remove(mesh_file)
1881
1882    return (min(normal_cov_new[:,1]),
1883            normal_cov_new[(num.argmin(normal_cov_new, axis=0))[1],0])
1884
1885
1886if __name__ == "__main__":
1887    pass
1888
Note: See TracBrowser for help on using the repository browser.