Changeset 7772
- Timestamp:
- Jun 3, 2010, 12:45:54 PM (14 years ago)
- Location:
- trunk/anuga_core/source/anuga
- Files:
-
- 6 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/util.py
r7765 r7772 330 330 mkdir(dir) 331 331 return dir 332 333 334 ##335 # @brief336 # @param filename337 # @param separator_value338 # @return339 # @note TEMP340 def get_data_from_file(filename, separator_value=','):341 """Temporary Interface to new location"""342 from anuga.shallow_water.data_manager import \343 get_data_from_file as dm_get_data_from_file344 log.critical('get_data_from_file has moved from util.py')345 log.critical('Please use "from anuga.shallow_water.data_manager import '346 'get_data_from_file"')347 348 return dm_get_data_from_file(filename,separator_value = ',')349 332 350 333 -
trunk/anuga_core/source/anuga/file/csv_file.py
r7762 r7772 70 70 71 71 72 def load_csv_as_array(file_name, delimiter =','):72 def load_csv_as_array(file_name, delimiter = ','): 73 73 """ 74 74 Convert CSV files of the form: … … 89 89 X, _ = load_csv_as_dict(file_name, delimiter=delimiter) 90 90 91 Y = {} 91 92 # Return result as a dict of arrays 93 ret = {} 92 94 for key in X.keys(): 93 Y[key] = num.array([float(x) for x in X[key]]) 94 95 return Y 96 95 ret[key] = num.array([float(x) for x in X[key]]) 96 97 return ret 98 99 100 def load_csv_as_matrix(file_name, delimiter = ','): 101 """ 102 Convert CSV files of the form: 103 104 time, discharge, velocity 105 0.0, 1.2, 0.0 106 0.1, 3.2, 1.1 107 ... 108 109 to a numeric matrix. 110 111 file_name The path to the file to read. 112 delimiter is the delimiter used to separate the fields 113 114 See underlying function load_csv_as_dict for more details. 115 """ 116 117 X, title_indices = load_csv_as_dict(file_name, delimiter=delimiter) 118 119 col_titles = title_indices.keys() 120 121 # Return result as a 2D array 122 ret = num.zeros((len(X[col_titles[0]]), len(title_indices)), float) 123 124 header = [] 125 for col_title in col_titles: 126 index = title_indices[col_title] 127 header.append(col_title) 128 for i, x in enumerate(X[col_title]): 129 ret[i, index] = float(x) 130 131 return header, ret 132 133 134 135 ## 136 # @brief Store keyword params into a CSV file. 137 # @param verbose True if this function is to be verbose. 138 # @param kwargs Dictionary of keyword args to store. 139 # @note If kwargs dict contains 'file_name' key, that has the output filename. 140 # If not, make up a filename in the output directory. 141 def store_parameters(verbose=False, **kwargs): 142 """ 143 Store "kwargs" into a temp csv file, if "completed" is in kwargs, 144 csv file is kwargs[file_name] else it is kwargs[output_dir]+details_temp.csv 145 146 Must have a file_name keyword arg, this is what is writing to. 147 might be a better way to do this using CSV module Writer and writeDict. 148 149 writes file to "output_dir" unless "completed" is in kwargs, then 150 it writes to "file_name" kwargs 151 """ 152 153 import types 154 155 # Check that kwargs is a dictionary 156 if type(kwargs) != types.DictType: 157 raise TypeError 158 159 # is 'completed' in kwargs? 160 completed = kwargs.has_key('completed') 161 162 # get file name and removes from dict and assert that a file_name exists 163 if completed: 164 try: 165 file = str(kwargs['file_name']) 166 except: 167 raise 'kwargs must have file_name' 168 else: 169 # write temp file in output directory 170 try: 171 file = str(kwargs['output_dir']) + 'detail_temp.csv' 172 except: 173 raise 'kwargs must have output_dir' 174 175 # extracts the header info and the new line info 176 line = '' 177 header = '' 178 count = 0 179 keys = kwargs.keys() 180 keys.sort() 181 182 # used the sorted keys to create the header and line data 183 for k in keys: 184 header += str(k) 185 line += str(kwargs[k]) 186 count += 1 187 if count < len(kwargs): 188 header += ',' 189 line += ',' 190 header += '\n' 191 line += '\n' 192 193 # checks the header info, if the same, then write, if not create a new file 194 # try to open! 195 try: 196 fid = open(file, 'r') 197 file_header = fid.readline() 198 fid.close() 199 if verbose: log.critical('read file header %s' % file_header) 200 except: 201 msg = 'try to create new file: %s' % file 202 if verbose: log.critical(msg) 203 #tries to open file, maybe directory is bad 204 try: 205 fid = open(file, 'w') 206 fid.write(header) 207 fid.close() 208 file_header=header 209 except: 210 msg = 'cannot create new file: %s' % file 211 raise Exception, msg 212 213 # if header is same or this is a new file 214 if file_header == str(header): 215 fid = open(file, 'a') 216 fid.write(line) 217 fid.close() 218 else: 219 # backup plan, 220 # if header is different and has completed will append info to 221 # end of details_temp.cvs file in output directory 222 file = str(kwargs['output_dir']) + 'detail_temp.csv' 223 fid = open(file, 'a') 224 fid.write(header) 225 fid.write(line) 226 fid.close() 227 228 if verbose: 229 log.critical('file %s', file_header.strip('\n')) 230 log.critical('head %s', header.strip('\n')) 231 if file_header.strip('\n') == str(header): 232 log.critical('they equal') 233 234 msg = 'WARNING: File header does not match input info, ' \ 235 'the input variables have changed, suggest you change file name' 236 log.critical(msg) 237 -
trunk/anuga_core/source/anuga/file/test_csv.py
r7762 r7772 4 4 import numpy as num 5 5 6 from csv_file import load_csv_as_array, load_csv_as_dict 7 6 from csv_file import load_csv_as_array, load_csv_as_dict, store_parameters, \ 7 load_csv_as_matrix 8 8 9 9 class Test_csv(unittest.TestCase): … … 13 13 def tearDown(self): 14 14 pass 15 16 def _create_csv_file(self): 17 """ 18 Create a dummy csv file. 19 Return its filename. 20 """ 21 filename = tempfile.mktemp(".txt") 22 file = open(filename,"w") 23 file.write("elevation, stage\n\ 24 1.0, 3 \n\ 25 0.0, 4 \n\ 26 4.0, 3 \n\ 27 1.0, 6 \n") 28 file.close() 29 return filename 15 30 16 31 def test_get_data_from_file1(self): 17 fileName = tempfile.mktemp(".txt") 18 # print"filename",fileName 19 file = open(fileName,"w") 20 file.write("elevation stage\n\ 21 1.3 3 \n\ 22 0.0 4 \n\ 23 4.5 3.5 \n\ 24 1.0 6 \n") 25 file.close() 26 27 x = load_csv_as_array(fileName, delimiter=' ') 28 29 # header, x = load_csv_as_array(fileName, delimiter=' ') 30 os.remove(fileName) 31 32 assert num.allclose(x['elevation'], [1.3, 0.0,4.5, 1.0]) 33 assert num.allclose(x['stage'], [3.0, 4.0,3.5, 6.0]) 34 32 filename = self._create_csv_file() 33 34 x = load_csv_as_array(filename) 35 36 os.remove(filename) 37 38 assert num.allclose(x['elevation'], [1.0, 0.0, 4.0, 1.0]) 39 assert num.allclose(x['stage'], [3.0, 4.0, 3.0, 6.0]) 40 41 42 def test_get_data_from_file(self): 43 filename = self._create_csv_file() 44 45 header,x = load_csv_as_matrix(filename) 46 os.remove(filename) 47 48 assert num.allclose(x[:,0], [1.0, 0.0,4.0, 1.0]) 49 50 51 def test_store_parameters(self): 52 """tests store temporary file 53 """ 54 55 from os import sep, getenv 56 57 output_dir='' 58 file_name='details.csv' 59 60 kwargs = {'file_name':'new2.txt', 61 'output_dir':output_dir, 62 'file_name':file_name, 63 'who':'me', 64 'what':'detail', 65 'how':2, 66 'why':241, 67 # 'completed':345 68 } 69 store_parameters(verbose=False,**kwargs) 70 71 temp='detail_temp.csv' 72 fid = open(temp) 73 file_header = fid.readline() 74 file_line = fid.readline() 75 fid.close() 76 77 78 keys = kwargs.keys() 79 keys.sort() 80 line='' 81 header='' 82 count=0 83 #used the sorted keys to create the header and line data 84 for k in keys: 85 # print "%s = %s" %(k, kwargs[k]) 86 header = header+str(k) 87 line = line+str(kwargs[k]) 88 count+=1 89 if count <len(kwargs): 90 header = header+',' 91 line = line+',' 92 header+='\n' 93 line+='\n' 94 95 96 #file exists 97 assert os.access(temp, os.F_OK) 98 assert header == file_header 99 assert line == file_line 100 101 os.remove(temp) 102 103 def test_store_parameters1(self): 104 """tests store in temporary file and other file 105 """ 106 107 from os import sep, getenv 108 109 output_dir='' 110 file_name='details.csv' 111 112 kwargs = {'file_name':'new2.txt', 113 'output_dir':output_dir, 114 'file_name':file_name, 115 'who':'me', 116 'what':'detail', 117 'how':2, 118 'why':241, 119 # 'completed':345 120 } 121 store_parameters(verbose=False,**kwargs) 122 123 kwargs['how']=55 124 kwargs['completed']=345 125 126 keys = kwargs.keys() 127 keys.sort() 128 line='' 129 header='' 130 count=0 131 #used the sorted keys to create the header and line data 132 for k in keys: 133 # print "%s = %s" %(k, kwargs[k]) 134 header = header+str(k) 135 line = line+str(kwargs[k]) 136 count+=1 137 if count <len(kwargs): 138 header = header+',' 139 line = line+',' 140 header+='\n' 141 line+='\n' 142 143 kwargs['how']=55 144 kwargs['completed']=345 145 146 store_parameters(verbose=False,**kwargs) 147 148 # temp='detail_temp.csv' 149 fid = open(file_name) 150 file_header = fid.readline() 151 file_line1 = fid.readline() 152 file_line2 = fid.readline() 153 fid.close() 154 155 156 #file exists 157 # print 'header',header,'line',line 158 # print 'file_header',file_header,'file_line1',file_line1,'file_line2',file_line2 159 assert os.access(file_name, os.F_OK) 160 assert header == file_header 161 assert line == file_line1 162 163 temp='detail_temp.csv' 164 os.remove(temp) 165 os.remove(file_name) 166 167 def test_store_parameters2(self): 168 """tests appending the data to the end of an existing file 169 """ 170 171 from os import sep, getenv 172 173 output_dir='' 174 file_name='details.csv' 175 176 kwargs = {'file_name':'new2.txt', 177 'output_dir':output_dir, 178 'file_name':file_name, 179 'who':'me', 180 'what':'detail', 181 'how':2, 182 'why':241, 183 'completed':345 184 } 185 store_parameters(verbose=False,**kwargs) 186 187 kwargs['how']=55 188 kwargs['completed']=23.54532 189 190 store_parameters(verbose=False,**kwargs) 191 192 keys = kwargs.keys() 193 keys.sort() 194 line='' 195 header='' 196 count=0 197 #used the sorted keys to create the header and line data 198 for k in keys: 199 # print "%s = %s" %(k, kwargs[k]) 200 header = header+str(k) 201 line = line+str(kwargs[k]) 202 count+=1 203 if count <len(kwargs): 204 header = header+',' 205 line = line+',' 206 header+='\n' 207 line+='\n' 208 209 fid = open(file_name) 210 file_header = fid.readline() 211 file_line1 = fid.readline() 212 file_line2 = fid.readline() 213 fid.close() 214 215 assert os.access(file_name, os.F_OK) 216 assert header == file_header 217 assert line == file_line2 218 219 os.remove(file_name) 220 221 222 35 223 36 224 ################################################################################# -
trunk/anuga_core/source/anuga/interface.py
r7711 r7772 25 25 from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular_cross 26 26 27 from anuga.shallow_water.data_manager import export_grid , create_sts_boundary27 from anuga.shallow_water.data_manager import export_grid 28 28 from anuga.shallow_water.data_manager import csv2building_polygons 29 30 from anuga.file.sts import create_sts_boundary 29 31 30 32 from anuga.geometry.polygon import read_polygon, plot_polygons, polygon_area -
trunk/anuga_core/source/anuga/shallow_water/data_manager.py
r7770 r7772 805 805 806 806 807 ##808 # @brief Store keyword params into a CSV file.809 # @param verbose True if this function is to be verbose.810 # @param kwargs Dictionary of keyword args to store.811 # @note If kwargs dict contains 'file_name' key, that has the output filename.812 # If not, make up a filename in the output directory.813 def store_parameters(verbose=False, **kwargs):814 """815 Store "kwargs" into a temp csv file, if "completed" is in kwargs,816 csv file is kwargs[file_name] else it is kwargs[output_dir]+details_temp.csv817 818 Must have a file_name keyword arg, this is what is writing to.819 might be a better way to do this using CSV module Writer and writeDict.820 821 writes file to "output_dir" unless "completed" is in kwargs, then822 it writes to "file_name" kwargs823 """824 825 import types826 827 # Check that kwargs is a dictionary828 if type(kwargs) != types.DictType:829 raise TypeError830 831 # is 'completed' in kwargs?832 completed = kwargs.has_key('completed')833 834 # get file name and removes from dict and assert that a file_name exists835 if completed:836 try:837 file = str(kwargs['file_name'])838 except:839 raise 'kwargs must have file_name'840 else:841 # write temp file in output directory842 try:843 file = str(kwargs['output_dir']) + 'detail_temp.csv'844 except:845 raise 'kwargs must have output_dir'846 847 # extracts the header info and the new line info848 line = ''849 header = ''850 count = 0851 keys = kwargs.keys()852 keys.sort()853 854 # used the sorted keys to create the header and line data855 for k in keys:856 header += str(k)857 line += str(kwargs[k])858 count += 1859 if count < len(kwargs):860 header += ','861 line += ','862 header += '\n'863 line += '\n'864 865 # checks the header info, if the same, then write, if not create a new file866 # try to open!867 try:868 fid = open(file, 'r')869 file_header = fid.readline()870 fid.close()871 if verbose: log.critical('read file header %s' % file_header)872 except:873 msg = 'try to create new file: %s' % file874 if verbose: log.critical(msg)875 #tries to open file, maybe directory is bad876 try:877 fid = open(file, 'w')878 fid.write(header)879 fid.close()880 file_header=header881 except:882 msg = 'cannot create new file: %s' % file883 raise Exception, msg884 885 # if header is same or this is a new file886 if file_header == str(header):887 fid = open(file, 'a')888 fid.write(line)889 fid.close()890 else:891 # backup plan,892 # if header is different and has completed will append info to893 # end of details_temp.cvs file in output directory894 file = str(kwargs['output_dir']) + 'detail_temp.csv'895 fid = open(file, 'a')896 fid.write(header)897 fid.write(line)898 fid.close()899 900 if verbose:901 log.critical('file %s', file_header.strip('\n'))902 log.critical('head %s', header.strip('\n'))903 if file_header.strip('\n') == str(header):904 log.critical('they equal')905 906 msg = 'WARNING: File header does not match input info, ' \907 'the input variables have changed, suggest you change file name'908 log.critical(msg)909 910 911 807 912 808 ## -
trunk/anuga_core/source/anuga/shallow_water/test_data_manager.py
r7771 r7772 16 16 from Scientific.IO.NetCDF import NetCDFFile 17 17 18 from anuga.anuga_exceptions import ANUGAError 18 19 from anuga.shallow_water.data_manager import * 19 20 from anuga.shallow_water.sww_file import SWW_file … … 23 24 from anuga.utilities.system_tools import get_pathname_from_package 24 25 from anuga.utilities.file_utils import del_dir 25 from anuga.file.csv_file import load_csv_as_dict, load_csv_as_array26 from anuga.anuga_exceptions import ANUGAError27 26 from anuga.utilities.numerical_tools import ensure_numeric, mean 28 27 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 29 28 from anuga.config import netcdf_float, epsilon, g 29 30 from anuga.file.csv_file import load_csv_as_dict, load_csv_as_array 31 from anuga.file.sts import create_sts_boundary 30 32 31 33 … … 2252 2254 new_origin)),points_utm) 2253 2255 os.remove(filename) 2254 2255 def test_get_data_from_file(self):2256 # from anuga.abstract_2d_finite_volumes.util import get_data_from_file2257 2258 import os2259 2260 fileName = tempfile.mktemp(".txt")2261 # print"filename",fileName2262 file = open(fileName,"w")2263 file.write("elevation, stage\n\2264 1.0, 3 \n\2265 0.0, 4 \n\2266 4.0, 3 \n\2267 1.0, 6 \n")2268 file.close()2269 2270 header,x = get_data_from_file(fileName)2271 # print 'x',x2272 os.remove(fileName)2273 2274 assert num.allclose(x[:,0], [1.0, 0.0,4.0, 1.0])2275 2276 def test_get_data_from_file1(self):2277 # from anuga.abstract_2d_finite_volumes.util import get_data_from_file2278 2279 import os2280 2281 fileName = tempfile.mktemp(".txt")2282 # print"filename",fileName2283 file = open(fileName,"w")2284 file.write("elevation stage\n\2285 1.3 3 \n\2286 0.0 4 \n\2287 4.5 3.5 \n\2288 1.0 6 \n")2289 file.close()2290 2291 header, x = get_data_from_file(fileName,separator_value=' ')2292 os.remove(fileName)2293 # x = get_data_from_file(fileName)2294 # print '1x',x[:,0]2295 2296 assert num.allclose(x[:,0], [1.3, 0.0,4.5, 1.0])2297 2298 def test_store_parameters(self):2299 """tests store temporary file2300 """2301 2302 from os import sep, getenv2303 2304 output_dir=''2305 file_name='details.csv'2306 2307 kwargs = {'file_name':'new2.txt',2308 'output_dir':output_dir,2309 'file_name':file_name,2310 'who':'me',2311 'what':'detail',2312 'how':2,2313 'why':241,2314 # 'completed':3452315 }2316 store_parameters(verbose=False,**kwargs)2317 2318 temp='detail_temp.csv'2319 fid = open(temp)2320 file_header = fid.readline()2321 file_line = fid.readline()2322 fid.close()2323 2324 2325 keys = kwargs.keys()2326 keys.sort()2327 line=''2328 header=''2329 count=02330 #used the sorted keys to create the header and line data2331 for k in keys:2332 # print "%s = %s" %(k, kwargs[k])2333 header = header+str(k)2334 line = line+str(kwargs[k])2335 count+=12336 if count <len(kwargs):2337 header = header+','2338 line = line+','2339 header+='\n'2340 line+='\n'2341 2342 2343 #file exists2344 assert access(temp,F_OK)2345 assert header == file_header2346 assert line == file_line2347 2348 os.remove(temp)2349 2350 def test_store_parameters1(self):2351 """tests store in temporary file and other file2352 """2353 2354 from os import sep, getenv2355 2356 output_dir=''2357 file_name='details.csv'2358 2359 kwargs = {'file_name':'new2.txt',2360 'output_dir':output_dir,2361 'file_name':file_name,2362 'who':'me',2363 'what':'detail',2364 'how':2,2365 'why':241,2366 # 'completed':3452367 }2368 store_parameters(verbose=False,**kwargs)2369 2370 kwargs['how']=552371 kwargs['completed']=3452372 2373 keys = kwargs.keys()2374 keys.sort()2375 line=''2376 header=''2377 count=02378 #used the sorted keys to create the header and line data2379 for k in keys:2380 # print "%s = %s" %(k, kwargs[k])2381 header = header+str(k)2382 line = line+str(kwargs[k])2383 count+=12384 if count <len(kwargs):2385 header = header+','2386 line = line+','2387 header+='\n'2388 line+='\n'2389 2390 kwargs['how']=552391 kwargs['completed']=3452392 2393 store_parameters(verbose=False,**kwargs)2394 2395 # temp='detail_temp.csv'2396 fid = open(file_name)2397 file_header = fid.readline()2398 file_line1 = fid.readline()2399 file_line2 = fid.readline()2400 fid.close()2401 2402 2403 #file exists2404 # print 'header',header,'line',line2405 # print 'file_header',file_header,'file_line1',file_line1,'file_line2',file_line22406 assert access(file_name,F_OK)2407 assert header == file_header2408 assert line == file_line12409 2410 temp='detail_temp.csv'2411 os.remove(temp)2412 os.remove(file_name)2413 2414 def test_store_parameters2(self):2415 """tests appending the data to the end of an existing file2416 """2417 2418 from os import sep, getenv2419 2420 output_dir=''2421 file_name='details.csv'2422 2423 kwargs = {'file_name':'new2.txt',2424 'output_dir':output_dir,2425 'file_name':file_name,2426 'who':'me',2427 'what':'detail',2428 'how':2,2429 'why':241,2430 'completed':3452431 }2432 store_parameters(verbose=False,**kwargs)2433 2434 kwargs['how']=552435 kwargs['completed']=23.545322436 2437 store_parameters(verbose=False,**kwargs)2438 2439 keys = kwargs.keys()2440 keys.sort()2441 line=''2442 header=''2443 count=02444 #used the sorted keys to create the header and line data2445 for k in keys:2446 # print "%s = %s" %(k, kwargs[k])2447 header = header+str(k)2448 line = line+str(kwargs[k])2449 count+=12450 if count <len(kwargs):2451 header = header+','2452 line = line+','2453 header+='\n'2454 line+='\n'2455 2456 fid = open(file_name)2457 file_header = fid.readline()2458 file_line1 = fid.readline()2459 file_line2 = fid.readline()2460 fid.close()2461 2462 assert access(file_name,F_OK)2463 assert header == file_header2464 assert line == file_line22465 2466 os.remove(file_name)2467 2256 2468 2257
Note: See TracChangeset
for help on using the changeset viewer.