epigrass 4.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Epigrass/__init__.py ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+ version = "3.0.3"
Binary file
Epigrass/dataObject.py ADDED
@@ -0,0 +1,77 @@
1
+ # Module for interacting with the database backend through SQLObject
2
+ # 10/2005 - Flavio Codeco Coelho
3
+ from __future__ import absolute_import
4
+ from __future__ import print_function
5
+ from sqlobject import *
6
+ import sys,os
7
+ from six.moves import range
8
+
9
+ #initialization data -- to be reset by calling module
10
+ ##backend='mysql'
11
+ ##user='root'
12
+ ##pw='mysql'
13
+ ##host='localhost'
14
+ ##db='epigrass'
15
+
16
+ def Connect(backend, user, pw, host, port, db):
17
+ """
18
+ Initializes the connection.
19
+ """
20
+
21
+ db_filename = os.path.abspath('Epigrass.sqlite')
22
+ ##if os.path.exists(db_filename):
23
+ ## os.unlink(db_filename)
24
+ if backend == 'sqlite':
25
+ connection_string = 'sqlite:' + db_filename
26
+ elif backend == 'mysql':
27
+ connection_string = r'%s://%s:%s@%s:%s/%s'%(backend,user,pw,host,port,db)
28
+ elif backend == 'postgresql':
29
+ # TODO: check this connection string
30
+ connection_string = r'%s://%s:%s@%s:%s/%s'%(backend,user,pw,host,port,db)
31
+ else:
32
+ sys.exit('Invalid Database Backend specified: %s'%backend)
33
+ connection = connectionForURI(connection_string)
34
+ sqlhub.processConnection = connection.transaction()
35
+
36
+
37
+
38
+ class Site(SQLObject):
39
+ class sqlmeta:
40
+ name = 'site'
41
+ lazyUpdate = True
42
+ geocode = IntCol()
43
+ time = IntCol()
44
+ totpop = IntCol()
45
+ name = UnicodeCol()
46
+ lat = FloatCol()
47
+ longit = FloatCol()
48
+
49
+
50
+ class Edge(SQLObject):
51
+ #_table = 'site'+'e'
52
+ source_code = IntCol()
53
+ dest_code = IntCol()
54
+ time = IntCol()
55
+ ftheta = FloatCol()
56
+ btheta =FloatCol()
57
+ class sqlmeta:
58
+ name = 'site'+'e'
59
+ lazyUpdate = True
60
+
61
+ if __name__ =='__main__':
62
+ Connect('mysql','root','mysql','localhost', 3306, 'epigrass')
63
+ Site._table='testando'
64
+ Site.createTable()
65
+ Edge.createTable()
66
+ dicin={'geocode':0000000,'time':0,'name':'euheim','totpop':100,'lat':10.1,'longit':20.3}
67
+
68
+ for i in range(1):
69
+ pid = os.fork()
70
+ if pid:
71
+ pass
72
+ else:
73
+ Site(**dicin)
74
+ Site._connection.commit()
75
+ print("commit from process %d"%os.getpid())
76
+ sys.exit()
77
+
Epigrass/data_io.py ADDED
@@ -0,0 +1,226 @@
1
+ """
2
+ This module contains functions to read and write from ascii files, as well as to/from MySQL databases.
3
+ """
4
+ from __future__ import absolute_import
5
+ from __future__ import print_function
6
+ from numpy import *
7
+ from string import *
8
+ import codecs
9
+ import pandas as pd
10
+
11
+ from difflib import *
12
+ import sys
13
+ from six.moves import range
14
+ from six.moves import zip
15
+
16
+
17
+ def load(fname, sep=None):
18
+ """
19
+ Load ASCII data from fname into an array and return the array.
20
+
21
+ The data must be regular, same number of values in every row
22
+
23
+ fname must be a filename.
24
+
25
+ optional argument sep must be set if the separators are not some kind of white space.
26
+
27
+ well suited for GRASS ascii site data.
28
+
29
+ Example usage::
30
+
31
+ x,y = load('test.dat') # data in two columns
32
+
33
+ X = load('test.dat') # a matrix of data
34
+
35
+ x = load('test.dat') # a single column of data
36
+
37
+ X = load('test.dat, sep = ',') # file is csv
38
+
39
+ """
40
+ with codecs.open(fname, 'r') as f:
41
+ linelist = f.readlines()
42
+
43
+ X = []
44
+ numCols = None
45
+ for line in linelist:
46
+ line = line.strip()
47
+ if not len(line): continue
48
+ row = [float(val) for val in line.split(str(sep))]
49
+ thisLen = len(row)
50
+ if numCols is not None and thisLen != numCols:
51
+ raise ValueError('All rows must have the same number of columns')
52
+ X.append(row)
53
+
54
+ X = array(X)
55
+ r, c = X.shape
56
+ if r == 1 or c == 1:
57
+ X.shape = max([r, c]),
58
+ return X
59
+
60
+
61
+ def loadData(fname, sep=',', encoding='utf-8'):
62
+ """
63
+ Loads from ascii files with separated values
64
+ and returns a list of lists.
65
+ """
66
+ # f = codecs.open(fname,'r',encoding='utf8')
67
+ # linelist = f.readlines()
68
+ # f.close()
69
+ df = pd.read_csv(fname, sep=sep, encoding=encoding)
70
+
71
+ sitelist = [list(df.columns)] + df.values.tolist()
72
+
73
+ # for line in linelist:
74
+ # line = line.strip()
75
+ #
76
+ # row = [elmt.strip() for elmt in line.split(str(sep))]
77
+ #
78
+ # sitelist.append(row)
79
+
80
+ return sitelist
81
+
82
+
83
+ def queryDb(usr, passw, db, table, host='localhost', port=3306, sql=''):
84
+ """
85
+ Fetch the contents of a table on a MySQL database
86
+ sql,usr,passw,db,table and host must be strings.
87
+ returns a tuple of tuples and a list of dictionaries.
88
+ """
89
+ import MySQLdb
90
+ con = MySQLdb.connect(host=host, port=port, user=usr, passwd=passw, db=db)
91
+ Cursor = con.cursor()
92
+ # get column names
93
+ Cursor.execute('show columns from ' + table)
94
+ cout = Cursor.fetchall()
95
+ cnames = []
96
+ for i in cout:
97
+ cnames.append(i[0])
98
+
99
+ if sql == '':
100
+ sql = 'SELECT * FROM ' + table
101
+ Cursor.execute(sql)
102
+ results = Cursor.fetchall()
103
+ con.close()
104
+ res = []
105
+ for i in results: # creates a list of dictionaries
106
+ res.append(dict([x for x in zip(cnames, i)]))
107
+
108
+ return res
109
+
110
+
111
+ def loadEdgeData(fname):
112
+ """
113
+ """
114
+ fname = 'antt2002TODOS.csv'
115
+ dados = loadData(fname, ',')
116
+ dicCity = queryDb('root', 'mysql', 'epigrass', 'localidades')
117
+ dados[0].append('codigo1')
118
+ dados[0].append('codigo2')
119
+ for i in range(1, len(dados)):
120
+ cidade1 = dados[i][1].lower() # word
121
+ UF1 = dados[i][2]
122
+ cidade2 = dados[i][3].lower() # word2
123
+ UF2 = dados[i][4]
124
+
125
+ ln1 = [x['NM_NOME'].lower() for x in dicCity if x['UF'] == UF1]
126
+ ld1 = [x for x in dicCity if x['UF'] == UF1]
127
+ mat = get_close_matches(cidade1, ln1, 5)
128
+ if not mat:
129
+ dados[i].append('NA')
130
+ else:
131
+ geoc1 = [x['GEOCODIGO'] for x in ld1 if x['NM_NOME'].lower() == mat[0]]
132
+ # print i,mat[0]
133
+ try:
134
+ dados[i].append(geoc1[0])
135
+ except IndexError:
136
+ print('No match for city name ', cidade1)
137
+ sys.exit()
138
+ # print cidade1,UF1, mat
139
+
140
+ ln2 = [x['NM_NOME'].lower() for x in dicCity if x['UF'] == UF2]
141
+ ld2 = [x for x in dicCity if x['UF'] == UF2]
142
+ mat2 = get_close_matches(cidade2, ln2, 5)
143
+ if not mat2:
144
+ dados[i].append('NA')
145
+ else:
146
+ geoc2 = [x['GEOCODIGO'] for x in ld2 if x['NM_NOME'].lower() == mat2[0]]
147
+ try:
148
+ dados[i].append(geoc2[0])
149
+ except IndexError:
150
+ print('No match for city name ', cidade2)
151
+ sys.exit()
152
+ # print cidade2,UF2, mat2
153
+
154
+ fout = open('edgesout.csv', 'w')
155
+ for i in dados:
156
+ for j in i:
157
+ fout.write(j + ',')
158
+ fout.write('\n')
159
+ fout.close()
160
+ return dados
161
+
162
+
163
+ def getSiteFromGeo(fin=None, fout=None):
164
+ """
165
+ Search the locality and census databases tables for codes in a file and creates a
166
+ sites file.
167
+ """
168
+ if not fin:
169
+ fname = 'scodes.csv'
170
+ else:
171
+ fname = fin
172
+ f = open(fname, 'r')
173
+ codes = f.readlines()
174
+ dicCity = queryDb('root', 'mysql', 'epigrass', 'localidades')
175
+ dicTodos = queryDb('root', 'mysql', 'epigrass', 'universo')
176
+ sitios = ['latitude,longitude,localidade,populacao urb.,geocodigo\n'] # header
177
+ x = 0
178
+ for i in codes:
179
+ for j in dicCity:
180
+ # x+=1;print x
181
+ # print len(strip(i)),'g2: ',len(j['GEOCODIGO']),type(i), type(j['GEOCODIGO'])
182
+ if j['GEOCODIGO'] == strip(i):
183
+ line = j['MD_LATITUD'] + ',' + j['MD_LONGITU'] + ',' + j['NM_NOME']
184
+ for k in dicTodos:
185
+ if k['ID_'] == i[:6]:
186
+ line = line + ',' + str(k['V04']) + ',' + strip(i) + '\n'
187
+ sitios.append(line)
188
+ f.close()
189
+ # print sitios[0]
190
+ if not fout:
191
+ fout = 'sitios.csv'
192
+ outf = open(fout, 'w')
193
+ outf.writelines(sitios)
194
+ outf.close()
195
+
196
+
197
+ def sitesToDb(fname, table, db='epigrass', usr='root', passw='mysql', host='localhost', port=3306):
198
+ """
199
+ Creates a site table on a mysql db from a sites file (fname).
200
+ """
201
+ import MySQLdb
202
+ try:
203
+ # now = time.asctime().replace(' ','_').replace(':','')
204
+ # table = #table+'_'+now
205
+ con = MySQLdb.connect(host=host, port=port, user=usr, passwd=passw, db=db)
206
+ Cursor = con.cursor()
207
+ sql = """CREATE TABLE %s(
208
+ `latitude` VARCHAR( 12 ) DEFAULT '0' NOT NULL ,
209
+ `longitude` VARCHAR( 12 ) DEFAULT '' NOT NULL,
210
+ `locality` VARCHAR(64),
211
+ `population` INT(11),
212
+ `geocodigo` INT(9)
213
+ );
214
+ """ % table
215
+ Cursor.execute(sql)
216
+
217
+ f = open(fname, 'r')
218
+ listsites = f.readlines()
219
+ f.close()
220
+
221
+ sql2 = 'INSERT INTO %s' % table + ' VALUES(%s,%s,%s,%s,%s)'
222
+ for site in listsites:
223
+ values = tuple([strip(i) for i in site.split(',')])
224
+ Cursor.execute(sql2, values)
225
+ finally:
226
+ con.close()
Epigrass/egicon.png ADDED
Binary file