Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.23 KB | None | 0 0
  1. from os.path import dirname, join
  2. import sys
  3. import numpy as np
  4. import pandas.io.sql as psql
  5.  
  6. import psycopg2
  7. from datetime import datetime
  8. from bokeh.plotting import figure
  9. from bokeh.layouts import layout, widgetbox
  10. from bokeh.models import ColumnDataSource, HoverTool, Div
  11. from bokeh.models.widgets import Slider, Select, TextInput, DatePicker, DateRangeSlider
  12. from bokeh.io import curdoc
  13.  
  14. try:
  15.  
  16. #Create a database session
  17. conn = psycopg2.connect(database='movies', user='postgres', password='postgres')
  18.  
  19. #Create a client cursor to execute commands
  20. cursor = conn.cursor()
  21.  
  22. #The variables placeholder must always be a %s, psycop2 will automatically convert the values to SQL literal
  23. query = "SELECT * FROM atrocities_details"
  24. movies = psql.read_sql(query, conn)
  25.  
  26. movies["color"] = np.where(movies["gender"] == 'Male', "orange", "grey")
  27. movies["alpha"] = np.where(movies["gender"] == 'Male', 0.9, 0.25)
  28. movies.fillna(0, inplace=True) # just replace missing values with zero
  29.  
  30. axis_map = {
  31. "Date": "date_published",
  32. "State": "state",
  33. "Gender": "gender",
  34. "Religion": "religion",
  35. "Caste": "caste"
  36. }
  37.  
  38. desc = Div(text=open(join(dirname(__file__), "description.html")).read(), width=800)
  39.  
  40. # Create Input controls
  41. min_date = Slider(title="Date From", start=2000, end=2017, value=2010, step=1)
  42. max_date = Slider(title="Date To", start=2001, end=2018, value=2018, step=1)
  43. religion = Select(title="Religion", value="All",
  44. options=open(join(dirname(__file__), 'religion.txt')).read().split())
  45. state = Select(title="State", value="All",
  46. options=open(join(dirname(__file__), 'states.txt')).read().split())
  47. incident_name = TextInput(title="Incident name contains")
  48. x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value="Caste")
  49. y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="Date")
  50.  
  51. # Create Column Data Source that will be used by the plot
  52. source = ColumnDataSource(data=dict(x=[], y=[], color=[], title=[], alpha=[]))
  53.  
  54. hover = HoverTool(tooltips=[
  55. ("Title", "@title")
  56. ])
  57.  
  58. p = figure(plot_height=500, plot_width=500, title="", toolbar_location=None, tools=[hover])
  59. p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None, fill_alpha="alpha")
  60.  
  61. def select_movies():
  62. religion_val = religion.value
  63. state_val = state.value
  64. incident_name_val = incident_name.value.strip()
  65.  
  66. # Compare form details with the database object that we created above and return the result
  67. selected = movies[
  68. (movies.date_published >= str(min_date.value) + "-01-01 00:00:00") &
  69. (movies.date_published <= str(max_date.value) + "-01-01 00:00:00")
  70. ]
  71.  
  72. if (religion_val != "All"):
  73. selected = selected[selected.religion.str.contains(religion_val)==True]
  74. if (state_val != "All"):
  75. selected = selected[selected.state.str.contains(state_val)==True]
  76. if (incident_name_val != ""):
  77. selected = selected[selected.title.str.contains(incident_name_val)==True]
  78. return selected
  79.  
  80. def update():
  81. df = select_movies()
  82. x_name = axis_map[x_axis.value]
  83. y_name = axis_map[y_axis.value]
  84. p.xaxis.axis_label = x_axis.value
  85. p.yaxis.axis_label = y_axis.value
  86. p.title.text = "%d incident selected" % len(df)
  87. source.data = dict(
  88. x=df[x_name],
  89. y=df[y_name],
  90. color=df["color"],
  91. title=df["title"],
  92. alpha=df["alpha"]
  93. )
  94.  
  95. controls = [religion, min_date, max_date, state, incident_name, x_axis, y_axis]
  96. for control in controls:
  97. control.on_change('value', lambda attr, old, new: update())
  98.  
  99. sizing_mode = 'fixed' # 'scale_width' also looks nice with this example
  100.  
  101. inputs = widgetbox(*controls, sizing_mode=sizing_mode)
  102. l = layout([
  103. [desc],
  104. [inputs, p],
  105. ], sizing_mode=sizing_mode)
  106.  
  107. update() # initial load of the data
  108.  
  109. curdoc().add_root(l)
  110. curdoc().title = "Movies"
  111.  
  112. #print(cursor.fetchone())
  113. except psycopg2.DatabaseError as e:
  114. print ('Error %s' % e)
  115. sys.exit(1)
  116. finally:
  117. if conn:
  118. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement