/usr/share/pyshared/Epigrass/data_io.py is in epigrass 2.0.4-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | """
This module contains functions to read and write from ascii files, as well as to/from MySQL databases.
"""
from numpy import *
from string import *
from sqlobject import *
from difflib import *
import sys
def load(fname, sep=None):
"""
Load ASCII data from fname into an array and return the array.
The data must be regular, same number of values in every row
fname must be a filename.
optional argument sep must be set if the separators are not some kind of white space.
well suited for GRASS ascii site data.
Example usage::
x,y = load('test.dat') # data in two columns
X = load('test.dat') # a matrix of data
x = load('test.dat') # a single column of data
X = load('test.dat, sep = ',') # file is csv
"""
f = open(fname,'r')
linelist = f.readlines()
f.close()
X = []
numCols = None
for line in linelist:
line = line.strip()
if not len(line): continue
row = [float(val) for val in line.split(str(sep))]
thisLen = len(row)
if numCols is not None and thisLen != numCols:
raise ValueError('All rows must have the same number of columns')
X.append(row)
X = array(X)
r,c = X.shape
if r==1 or c==1:
X.shape = max([r,c]),
return X
def loadData(fname,sep = ',', encoding='utf-8'):
"""
Loads from ascii files with separated values
and returns a list of lists.
"""
f = open(fname,'r')
linelist = f.readlines()
f.close()
sitelist = []
#numCols = None
for line in linelist:
line = line.strip()
#if not len(line): continue
row = [unicode(strip(elmt),encoding) for elmt in line.split(str(sep))]
#thisLen = len(row)
#if numCols is not None and thisLen != numCols:
# raise ValueError('All rows must have the same number of columns')
sitelist.append(row)
return sitelist
def queryDb(usr,passw,db,table, host='localhost',port=3306,sql=''):
"""
Fetch the contents of a table on a MySQL database
sql,usr,passw,db,table and host must be strings.
returns a tuple of tuples and a list of dictionaries.
"""
import MySQLdb
con = MySQLdb.connect(host=host, port=port, user=usr,passwd=passw, db=db)
Cursor = con.cursor()
#get column names
Cursor.execute('show columns from '+table)
cout = Cursor.fetchall()
cnames=[]
for i in cout:
cnames.append(i[0])
if sql == '':
sql = 'SELECT * FROM ' + table
Cursor.execute(sql)
results = Cursor.fetchall()
con.close()
res=[]
for i in results: #creates a list of dictionaries
res.append(dict([x for x in zip(cnames,i)]))
return res
def loadEdgeData(fname):
"""
"""
fname = 'antt2002TODOS.csv'
dados = loadData(fname ,',')
dicCity = queryDb('root','mysql','epigrass','localidades')
dados[0].append('codigo1')
dados[0].append('codigo2')
for i in xrange(1,len(dados)):
cidade1 = dados[i][1].lower() #word
UF1 = dados[i][2]
cidade2 = dados[i][3].lower() #word2
UF2 = dados[i][4]
ln1 = [x['NM_NOME'].lower() for x in dicCity if x['UF'] == UF1]
ld1 = [x for x in dicCity if x['UF'] == UF1]
mat = get_close_matches(cidade1,ln1,5)
if not mat:
dados[i].append('NA')
else:
geoc1 = [x['GEOCODIGO'] for x in ld1 if x['NM_NOME'].lower() == mat[0]]
#print i,mat[0]
try:
dados[i].append(geoc1[0])
except IndexError:
print 'No match for city name ', cidade1
sys.exit()
#print cidade1,UF1, mat
ln2 = [x['NM_NOME'].lower() for x in dicCity if x['UF'] == UF2]
ld2 = [x for x in dicCity if x['UF'] == UF2]
mat2 = get_close_matches(cidade2,ln2,5)
if not mat2:
dados[i].append('NA')
else:
geoc2 = [x['GEOCODIGO'] for x in ld2 if x['NM_NOME'].lower() == mat2[0]]
try:
dados[i].append(geoc2[0])
except IndexError:
print 'No match for city name ', cidade2
sys.exit()
#print cidade2,UF2, mat2
fout = open('edgesout.csv','w')
for i in dados:
for j in i:
fout.write(j+',')
fout.write('\n')
fout.close()
return dados
def getSiteFromGeo(fin=None,fout=None):
"""
Search the locality and census databases tables for codes in a file and creates a
sites file.
"""
if not fin:
fname = 'scodes.csv'
else:
fname = fin
f = open (fname, 'r')
codes = f.readlines()
dicCity = queryDb('root','mysql','epigrass','localidades')
dicTodos = queryDb('root','mysql','epigrass','universo')
sitios = ['latitude,longitude,localidade,populacao urb.,geocodigo\n']#header
x=0
for i in codes:
for j in dicCity:
#x+=1;print x
#print len(strip(i)),'g2: ',len(j['GEOCODIGO']),type(i), type(j['GEOCODIGO'])
if j['GEOCODIGO'] == strip(i):
line = j['MD_LATITUD']+','+j['MD_LONGITU']+','+j['NM_NOME']
for k in dicTodos:
if k['ID_'] == i[:6]:
line = line+','+str(k['V04'])+','+strip(i)+'\n'
sitios.append(line)
f.close()
#print sitios[0]
if not fout:
fout='sitios.csv'
outf = open(fout,'w')
outf.writelines(sitios)
outf.close()
def sitesToDb(fname,table,db='epigrass',usr='root',passw='mysql', host='localhost',port=3306):
"""
Creates a site table on a mysql db from a sites file (fname).
"""
import MySQLdb
try:
#now = time.asctime().replace(' ','_').replace(':','')
#table = #table+'_'+now
con = MySQLdb.connect(host=host, port=port, user=usr,passwd=passw, db=db)
Cursor = con.cursor()
sql = """CREATE TABLE %s(
`latitude` VARCHAR( 12 ) DEFAULT '0' NOT NULL ,
`longitude` VARCHAR( 12 ) DEFAULT '' NOT NULL,
`locality` VARCHAR(64),
`population` INT(11),
`geocodigo` INT(9)
);
""" % table
Cursor.execute(sql)
f = open(fname,'r')
listsites = f.readlines()
f.close()
sql2 = 'INSERT INTO %s' % table + ' VALUES(%s,%s,%s,%s,%s)'
for site in listsites:
values = tuple([strip(i) for i in site.split(',')])
Cursor.execute(sql2,values)
finally:
con.close()
|