Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. import sys, os
  2.  
  3. #set up psycopg2 environment
  4. import psycopg2
  5.  
  6. def river_dist_matrix(table_name):
  7.  
  8. #driving_distance module
  9. query = """
  10. select *
  11. from pgr_drivingDistance ($$
  12. select
  13. id as id,
  14. source::int4 as source,
  15. target::int4 as target,
  16. shape_leng::double precision as cost
  17. from public.'table_name'
  18. $$, %s, %s, %s, %s
  19. )
  20. """
  21.  
  22. #make connection between python and postgresql
  23. conn = psycopg2.connect("dbname = 'routing_test' user = 'postgres' host = 'localhost' password = 'xxxx'")
  24. cur = conn.cursor()
  25.  
  26. #count rows in the table
  27. cur.execute("select count(*) from 'table_name'")
  28. result = cur.fetchone()
  29. k = result[0] + 1 #number of points = number of segments + 1
  30. print k
  31.  
  32. #run loops
  33. rs = []
  34. i = 1
  35. while i <= k:
  36. cur.execute(query, (i, 100000000000, False, False))
  37. rs.append(cur.fetchall())
  38. i = i + 1
  39. # print rs
  40. #import csv module
  41. import csv
  42. import tempfile
  43. import shutil
  44.  
  45. j = 0
  46. h = 0
  47. ars = []
  48. element = list(rs)
  49. # print element
  50. #export data to every row
  51. filename = 'ck_dist_m.csv'
  52. with open(filename, 'wb') as f:
  53. writer = csv.writer(f, delimiter = ',')
  54. while j <= k - 1:
  55. while h <= k - 1:
  56. rp = element[j][h][3]
  57. ars.append(rp)
  58. h = h + 1
  59. else:
  60. h = 0
  61. writer.writerow(ars)
  62. ars = []
  63. j = j + 1
  64.  
  65. # concerning about flow-connection
  66. with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
  67. writer = csv.writer(g, delimiter = ',')
  68. for row in csv.reader(f):
  69. row = [element if float(element) < 10**6 else 'nan' for element in row]
  70. writer.writerow(row)
  71.  
  72. shutil.move(g.name, filename)
  73.  
  74.  
  75. conn.close()
  76.  
  77.  
  78.  
  79. if __name__ == "__main__":
  80.  
  81. table_name = 'tc_500wa'
  82. river_dist_matrix(table_name)
  83.  
  84. Traceback (most recent call last):
  85. File "C:UsersHeinzDesktopriver_dist_matrix.py", line 95, in <module>
  86. river_dist_matrix(table_name)
  87. File "C:UsersHeinzDesktopriver_dist_matrix.py", line 40, in river_dist_matrix
  88. cur.execute("select count(*) from 'table_name'")
  89. psycopg2.ProgrammingError: syntax error at or near "'table_name'"
  90. LINE 1: select count(*) from 'table_name'
  91. ^
  92.  
  93. [Finished in 0.2s]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement