Changeset 7742
- Timestamp:
- May 24, 2010, 4:34:13 PM (15 years ago)
- Location:
- anuga_core/source/anuga
- Files:
-
- 7 added
- 3 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
anuga_core/source/anuga/shallow_water/data_manager.py
r7736 r7742 1656 1656 fid.close() 1657 1657 1658 1659 ##1660 # @brief Convert ASC file to DEM file.1661 # @param basename_in Stem of input filename.1662 # @param basename_out Stem of output filename.1663 # @param use_cache ??1664 # @param verbose True if this function is to be verbose.1665 # @return1666 # @note A PRJ file with same stem basename must exist and is used to fix the1667 # UTM zone, datum, false northings and eastings.1668 def convert_dem_from_ascii2netcdf(basename_in, basename_out=None,1669 use_cache=False,1670 verbose=False):1671 """Read Digital Elevation model from the following ASCII format (.asc)1672 1673 Example:1674 ncols 31211675 nrows 18001676 xllcorner 7220001677 yllcorner 58930001678 cellsize 251679 NODATA_value -99991680 138.3698 137.4194 136.5062 135.5558 ..........1681 1682 Convert basename_in + '.asc' to NetCDF format (.dem)1683 mimicking the ASCII format closely.1684 1685 An accompanying file with same basename_in but extension .prj must exist1686 and is used to fix the UTM zone, datum, false northings and eastings.1687 1688 The prj format is assumed to be as1689 1690 Projection UTM1691 Zone 561692 Datum WGS841693 Zunits NO1694 Units METERS1695 Spheroid WGS841696 Xshift 0.00000000001697 Yshift 10000000.00000000001698 Parameters1699 """1700 1701 kwargs = {'basename_out': basename_out, 'verbose': verbose}1702 1703 if use_cache is True:1704 from caching import cache1705 result = cache(_convert_dem_from_ascii2netcdf, basename_in, kwargs,1706 dependencies=[basename_in + '.asc',1707 basename_in + '.prj'],1708 verbose=verbose)1709 1710 else:1711 result = apply(_convert_dem_from_ascii2netcdf, [basename_in], kwargs)1712 1713 return result1714 1715 1716 ##1717 # @brief Convert an ASC file to a DEM file.1718 # @param basename_in Stem of input filename.1719 # @param basename_out Stem of output filename.1720 # @param verbose True if this function is to be verbose.1721 def _convert_dem_from_ascii2netcdf(basename_in, basename_out = None,1722 verbose = False):1723 """Read Digital Elevation model from the following ASCII format (.asc)1724 1725 Internal function. See public function convert_dem_from_ascii2netcdf1726 for details.1727 """1728 1729 import os1730 from Scientific.IO.NetCDF import NetCDFFile1731 1732 root = basename_in1733 1734 # Read Meta data1735 if verbose: log.critical('Reading METADATA from %s' % (root + '.prj'))1736 1737 metadatafile = open(root + '.prj')1738 metalines = metadatafile.readlines()1739 metadatafile.close()1740 1741 L = metalines[0].strip().split()1742 assert L[0].strip().lower() == 'projection'1743 projection = L[1].strip() #TEXT1744 1745 L = metalines[1].strip().split()1746 assert L[0].strip().lower() == 'zone'1747 zone = int(L[1].strip())1748 1749 L = metalines[2].strip().split()1750 assert L[0].strip().lower() == 'datum'1751 datum = L[1].strip() #TEXT1752 1753 L = metalines[3].strip().split()1754 assert L[0].strip().lower() == 'zunits' #IGNORE1755 zunits = L[1].strip() #TEXT1756 1757 L = metalines[4].strip().split()1758 assert L[0].strip().lower() == 'units'1759 units = L[1].strip() #TEXT1760 1761 L = metalines[5].strip().split()1762 assert L[0].strip().lower() == 'spheroid' #IGNORE1763 spheroid = L[1].strip() #TEXT1764 1765 L = metalines[6].strip().split()1766 assert L[0].strip().lower() == 'xshift'1767 false_easting = float(L[1].strip())1768 1769 L = metalines[7].strip().split()1770 assert L[0].strip().lower() == 'yshift'1771 false_northing = float(L[1].strip())1772 1773 #Read DEM data1774 datafile = open(basename_in + '.asc')1775 1776 if verbose: log.critical('Reading DEM from %s' % (basename_in + '.asc'))1777 1778 lines = datafile.readlines()1779 datafile.close()1780 1781 if verbose: log.critical('Got %d lines' % len(lines))1782 1783 ncols = int(lines[0].split()[1].strip())1784 nrows = int(lines[1].split()[1].strip())1785 1786 # Do cellsize (line 4) before line 2 and 31787 cellsize = float(lines[4].split()[1].strip())1788 1789 # Checks suggested by Joaquim Luis1790 # Our internal representation of xllcorner1791 # and yllcorner is non-standard.1792 xref = lines[2].split()1793 if xref[0].strip() == 'xllcorner':1794 xllcorner = float(xref[1].strip()) # + 0.5*cellsize # Correct offset1795 elif xref[0].strip() == 'xllcenter':1796 xllcorner = float(xref[1].strip())1797 else:1798 msg = 'Unknown keyword: %s' % xref[0].strip()1799 raise Exception, msg1800 1801 yref = lines[3].split()1802 if yref[0].strip() == 'yllcorner':1803 yllcorner = float(yref[1].strip()) # + 0.5*cellsize # Correct offset1804 elif yref[0].strip() == 'yllcenter':1805 yllcorner = float(yref[1].strip())1806 else:1807 msg = 'Unknown keyword: %s' % yref[0].strip()1808 raise Exception, msg1809 1810 NODATA_value = int(lines[5].split()[1].strip())1811 1812 assert len(lines) == nrows + 61813 1814 if basename_out == None:1815 netcdfname = root + '.dem'1816 else:1817 netcdfname = basename_out + '.dem'1818 1819 if verbose: log.critical('Store to NetCDF file %s' % netcdfname)1820 1821 # NetCDF file definition1822 fid = NetCDFFile(netcdfname, netcdf_mode_w)1823 1824 #Create new file1825 fid.institution = 'Geoscience Australia'1826 fid.description = 'NetCDF DEM format for compact and portable storage ' \1827 'of spatial point data'1828 1829 fid.ncols = ncols1830 fid.nrows = nrows1831 fid.xllcorner = xllcorner1832 fid.yllcorner = yllcorner1833 fid.cellsize = cellsize1834 fid.NODATA_value = NODATA_value1835 1836 fid.zone = zone1837 fid.false_easting = false_easting1838 fid.false_northing = false_northing1839 fid.projection = projection1840 fid.datum = datum1841 fid.units = units1842 1843 # dimension definitions1844 fid.createDimension('number_of_rows', nrows)1845 fid.createDimension('number_of_columns', ncols)1846 1847 # variable definitions1848 fid.createVariable('elevation', netcdf_float, ('number_of_rows',1849 'number_of_columns'))1850 1851 # Get handles to the variables1852 elevation = fid.variables['elevation']1853 1854 #Store data1855 n = len(lines[6:])1856 for i, line in enumerate(lines[6:]):1857 fields = line.split()1858 if verbose and i % ((n+10)/10) == 0:1859 log.critical('Processing row %d of %d' % (i, nrows))1860 1861 if len(fields) != ncols:1862 msg = 'Wrong number of columns in file "%s" line %d\n' % (basename_in + '.asc', i)1863 msg += 'I got %d elements, but there should have been %d\n' % (len(fields), ncols)1864 raise Exception, msg1865 1866 elevation[i, :] = num.array([float(x) for x in fields])1867 1868 fid.close()1869 1658 1870 1659 -
anuga_core/source/anuga/shallow_water/sww_file.py
r7736 r7742 7 7 from anuga.config import max_float 8 8 from anuga.utilities.numerical_tools import ensure_numeric 9 import anuga.utilities.log as log 9 10 from Scientific.IO.NetCDF import NetCDFFile 10 11 -
anuga_core/source/anuga/shallow_water/test_data_manager.py
r7736 r7742 18 18 from anuga.shallow_water.data_manager import * 19 19 from anuga.shallow_water.sww_file import SWW_file 20 from anuga. shallow_water.file_conversion import tsh2sww, \21 asc_csiro2sww, pmesh_to_domain_instance , \22 dem2pts, _get_min_max_indexes20 from anuga.file_conversion.file_conversion import tsh2sww, \ 21 asc_csiro2sww, pmesh_to_domain_instance 22 23 23 from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees 24 24 from anuga.abstract_2d_finite_volumes.util import file_function … … 735 735 #Cleanup 736 736 os.remove(sww.filename) 737 738 739 740 def test_dem2pts_bounding_box_v2(self):741 """Test conversion from dem in ascii format to native NetCDF format742 """743 744 import time, os745 from Scientific.IO.NetCDF import NetCDFFile746 747 #Write test asc file748 root = 'demtest'749 750 filename = root+'.asc'751 fid = open(filename, 'w')752 fid.write("""ncols 10753 nrows 10754 xllcorner 2000755 yllcorner 3000756 cellsize 1757 NODATA_value -9999758 """)759 #Create linear function760 ref_points = []761 ref_elevation = []762 x0 = 2000763 y = 3010764 yvec = range(10)765 xvec = range(10)766 z = -1767 for i in range(10):768 y = y - 1769 for j in range(10):770 x = x0 + xvec[j]771 z += 1772 ref_points.append ([x,y])773 ref_elevation.append(z)774 fid.write('%f ' %z)775 fid.write('\n')776 777 fid.close()778 779 #print 'sending pts', ref_points780 #print 'sending elev', ref_elevation781 782 #Write prj file with metadata783 metafilename = root+'.prj'784 fid = open(metafilename, 'w')785 786 787 fid.write("""Projection UTM788 Zone 56789 Datum WGS84790 Zunits NO791 Units METERS792 Spheroid WGS84793 Xshift 0.0000000000794 Yshift 10000000.0000000000795 Parameters796 """)797 fid.close()798 799 #Convert to NetCDF pts800 convert_dem_from_ascii2netcdf(root)801 dem2pts(root, easting_min=2002.0, easting_max=2007.0,802 northing_min=3003.0, northing_max=3006.0,803 verbose=self.verbose)804 805 #Check contents806 #Get NetCDF807 fid = NetCDFFile(root+'.pts', netcdf_mode_r)808 809 # Get the variables810 #print fid.variables.keys()811 points = fid.variables['points']812 elevation = fid.variables['elevation']813 814 #Check values815 assert fid.xllcorner[0] == 2002.0816 assert fid.yllcorner[0] == 3003.0817 818 #create new reference points819 newz = []820 newz[0:5] = ref_elevation[32:38]821 newz[6:11] = ref_elevation[42:48]822 newz[12:17] = ref_elevation[52:58]823 newz[18:23] = ref_elevation[62:68]824 ref_elevation = []825 ref_elevation = newz826 ref_points = []827 x0 = 2002828 y = 3007829 yvec = range(4)830 xvec = range(6)831 for i in range(4):832 y = y - 1833 ynew = y - 3003.0834 for j in range(6):835 x = x0 + xvec[j]836 xnew = x - 2002.0837 ref_points.append ([xnew,ynew]) #Relative point values838 839 assert num.allclose(points, ref_points)840 841 assert num.allclose(elevation, ref_elevation)842 843 #Cleanup844 fid.close()845 846 847 os.remove(root + '.pts')848 os.remove(root + '.dem')849 os.remove(root + '.asc')850 os.remove(root + '.prj')851 852 853 def test_dem2pts_bounding_box_removeNullvalues_v2(self):854 """Test conversion from dem in ascii format to native NetCDF format855 """856 857 import time, os858 from Scientific.IO.NetCDF import NetCDFFile859 860 #Write test asc file861 root = 'demtest'862 863 filename = root+'.asc'864 fid = open(filename, 'w')865 fid.write("""ncols 10866 nrows 10867 xllcorner 2000868 yllcorner 3000869 cellsize 1870 NODATA_value -9999871 """)872 #Create linear function873 ref_points = []874 ref_elevation = []875 x0 = 2000876 y = 3010877 yvec = range(10)878 xvec = range(10)879 #z = range(100)880 z = num.zeros(100, num.int) #array default#881 NODATA_value = -9999882 count = -1883 for i in range(10):884 y = y - 1885 for j in range(10):886 x = x0 + xvec[j]887 ref_points.append ([x,y])888 count += 1889 z[count] = (4*i - 3*j)%13890 if j == 4: z[count] = NODATA_value #column inside clipping region891 if j == 8: z[count] = NODATA_value #column outside clipping region892 if i == 9: z[count] = NODATA_value #row outside clipping region893 if i == 4 and j == 6: z[count] = NODATA_value #arbitrary point inside clipping region894 ref_elevation.append( z[count] )895 fid.write('%f ' %z[count])896 fid.write('\n')897 898 fid.close()899 900 #print 'sending elev', ref_elevation901 902 #Write prj file with metadata903 metafilename = root+'.prj'904 fid = open(metafilename, 'w')905 906 907 fid.write("""Projection UTM908 Zone 56909 Datum WGS84910 Zunits NO911 Units METERS912 Spheroid WGS84913 Xshift 0.0000000000914 Yshift 10000000.0000000000915 Parameters916 """)917 fid.close()918 919 #Convert to NetCDF pts920 convert_dem_from_ascii2netcdf(root)921 dem2pts(root, easting_min=2002.0, easting_max=2007.0,922 northing_min=3003.0, northing_max=3006.0,923 verbose=self.verbose)924 925 #Check contents926 #Get NetCDF927 fid = NetCDFFile(root+'.pts', netcdf_mode_r)928 929 # Get the variables930 #print fid.variables.keys()931 points = fid.variables['points']932 elevation = fid.variables['elevation']933 934 #Check values935 assert fid.xllcorner[0] == 2002.0936 assert fid.yllcorner[0] == 3003.0937 938 #create new reference points939 newz = num.zeros(19, num.int) #array default#940 newz[0:2] = ref_elevation[32:34]941 newz[2:5] = ref_elevation[35:38]942 newz[5:7] = ref_elevation[42:44]943 newz[7] = ref_elevation[45]944 newz[8] = ref_elevation[47]945 newz[9:11] = ref_elevation[52:54]946 newz[11:14] = ref_elevation[55:58]947 newz[14:16] = ref_elevation[62:64]948 newz[16:19] = ref_elevation[65:68]949 950 951 ref_elevation = newz952 ref_points = []953 new_ref_points = []954 x0 = 2002955 y = 3007956 yvec = range(4)957 xvec = range(6)958 for i in range(4):959 y = y - 1960 ynew = y - 3003.0961 for j in range(6):962 x = x0 + xvec[j]963 xnew = x - 2002.0964 if j <> 2 and (i<>1 or j<>4):965 ref_points.append([x,y])966 new_ref_points.append ([xnew,ynew])967 968 969 assert num.allclose(points, new_ref_points)970 assert num.allclose(elevation, ref_elevation)971 972 #Cleanup973 fid.close()974 975 976 os.remove(root + '.pts')977 os.remove(root + '.dem')978 os.remove(root + '.asc')979 os.remove(root + '.prj')980 981 982 def test_dem2pts_bounding_box_removeNullvalues_v3(self):983 """Test conversion from dem in ascii format to native NetCDF format984 Check missing values on clipping boundary985 """986 987 import time, os988 from Scientific.IO.NetCDF import NetCDFFile989 990 #Write test asc file991 root = 'demtest'992 993 filename = root+'.asc'994 fid = open(filename, 'w')995 fid.write("""ncols 10996 nrows 10997 xllcorner 2000998 yllcorner 3000999 cellsize 11000 NODATA_value -99991001 """)1002 #Create linear function1003 ref_points = []1004 ref_elevation = []1005 x0 = 20001006 y = 30101007 yvec = range(10)1008 xvec = range(10)1009 #z = range(100)1010 z = num.zeros(100, num.int) #array default#1011 NODATA_value = -99991012 count = -11013 for i in range(10):1014 y = y - 11015 for j in range(10):1016 x = x0 + xvec[j]1017 ref_points.append ([x,y])1018 count += 11019 z[count] = (4*i - 3*j)%131020 if j == 4: z[count] = NODATA_value #column inside clipping region1021 if j == 8: z[count] = NODATA_value #column outside clipping region1022 if i == 6: z[count] = NODATA_value #row on clipping boundary1023 if i == 4 and j == 6: z[count] = NODATA_value #arbitrary point inside clipping region1024 ref_elevation.append( z[count] )1025 fid.write('%f ' %z[count])1026 fid.write('\n')1027 1028 fid.close()1029 1030 #print 'sending elev', ref_elevation1031 1032 #Write prj file with metadata1033 metafilename = root+'.prj'1034 fid = open(metafilename, 'w')1035 1036 1037 fid.write("""Projection UTM1038 Zone 561039 Datum WGS841040 Zunits NO1041 Units METERS1042 Spheroid WGS841043 Xshift 0.00000000001044 Yshift 10000000.00000000001045 Parameters1046 """)1047 fid.close()1048 1049 #Convert to NetCDF pts1050 convert_dem_from_ascii2netcdf(root)1051 dem2pts(root, easting_min=2002.0, easting_max=2007.0,1052 northing_min=3003.0, northing_max=3006.0,1053 verbose=self.verbose)1054 1055 #Check contents1056 #Get NetCDF1057 fid = NetCDFFile(root+'.pts', netcdf_mode_r)1058 1059 # Get the variables1060 #print fid.variables.keys()1061 points = fid.variables['points']1062 elevation = fid.variables['elevation']1063 1064 #Check values1065 assert fid.xllcorner[0] == 2002.01066 assert fid.yllcorner[0] == 3003.01067 1068 #create new reference points1069 newz = num.zeros(14, num.int) #array default#1070 newz[0:2] = ref_elevation[32:34]1071 newz[2:5] = ref_elevation[35:38]1072 newz[5:7] = ref_elevation[42:44]1073 newz[7] = ref_elevation[45]1074 newz[8] = ref_elevation[47]1075 newz[9:11] = ref_elevation[52:54]1076 newz[11:14] = ref_elevation[55:58]1077 1078 1079 1080 ref_elevation = newz1081 ref_points = []1082 new_ref_points = []1083 x0 = 20021084 y = 30071085 yvec = range(4)1086 xvec = range(6)1087 for i in range(4):1088 y = y - 11089 ynew = y - 3003.01090 for j in range(6):1091 x = x0 + xvec[j]1092 xnew = x - 2002.01093 if j <> 2 and (i<>1 or j<>4) and i<>3:1094 ref_points.append([x,y])1095 new_ref_points.append ([xnew,ynew])1096 1097 1098 #print points[:],points[:].shape1099 #print new_ref_points, len(new_ref_points)1100 1101 assert num.allclose(elevation, ref_elevation)1102 assert num.allclose(points, new_ref_points)1103 1104 1105 #Cleanup1106 fid.close()1107 1108 1109 os.remove(root + '.pts')1110 os.remove(root + '.dem')1111 os.remove(root + '.asc')1112 os.remove(root + '.prj')1113 737 1114 738
Note: See TracChangeset
for help on using the changeset viewer.