def update_bar_graph(start_date, end_date, selectedCrime, selectedLocation, start_date_fut, end_date_fut, selectedCrime_fut, selectedLocation_fut): crime_code = selectedCrime location_code = selectedLocation location = "London" if selectedLocation: zoom = 15.0 latInitial = cm.list_of_locations[selectedLocation]["lat"] lonInitial = cm.list_of_locations[selectedLocation]["lon"] location_code = cm.location_codes[selectedLocation] location = selectedLocation if selectedCrime: crime_code = cm.crime_mapping[selectedCrime] if start_date and end_date and not selectedLocation: start = dt.strptime(start_date, "%Y-%m-%d") end = dt.strptime(end_date, "%Y-%m-%d") start = start.strftime("%b %Y") end = end.strftime("%b %Y") # get the data set start_time = time.time() database = Connection() dataset = cm.barchart_database_pull(start_date, end_date, crime_code, database) print(time.time() - start_time, " update_bar_graph()") dataset.replace({"lsoa_name": cm.location_mapping_reverse}, inplace=True) locations = list(dataset["lsoa_name"]) num_crimes = list(dataset["count"]) fig = go.Figure(go.Bar(x=locations, y=num_crimes, name='Borough 1')) fig.update_layout(template="plotly_dark", ) if not selectedCrime: selectedCrime = "" else: selectedCrime += " " if start == end: return fig, 'Boroughs with most cases ({})'.format(start) else: return fig, 'Boroughs with most cases ({} - {})'.format( start, end) else: x = [] fig = go.Figure(go.Bar(x=x, y=[], name='Borough 1')) fig.update_layout(template="plotly_dark", ) return fig, 'Select London and date range to see analysis'
def display_predictions(): mapbox_key = "pk.eyJ1IjoicGxvdGx5bWFwYm94IiwiYSI6ImNqdnBvNDMyaTAxYzkzeW5ubWdpZ2VjbmMifQ.TXcBE-xg9BFdV2ocecc_7g" database = Connection() predicted_merged_2 = prediction_pull(database) colors = ["blue", "purple", "red"] with urlopen( 'https://raw.githubusercontent.com/mikeypatt/json_file_crime/master/LSOA_2011.json' ) as response: j_file = json.load(response) i = 1 for feature in j_file["features"]: feature['id'] = str(i).zfill(2) i += 1 print(j_file["features"]) print(predicted_merged_2['id']) fig = go.Figure( go.Choroplethmapbox(geojson=j_file, locations=predicted_merged_2.id, z=predicted_merged_2.prediction, showscale=False, colorscale=colors, zmin=0, zmax=20, ids=predicted_merged_2.LSOA11NM, text=predicted_merged_2.LSOA11NM, hoverinfo='z+text')) fig.update_layout(mapbox_style="dark", mapbox_accesstoken=mapbox_key, mapbox_zoom=10, mapbox_center={ "lat": 51.5074, "lon": -0.1278 }) fig.update_layout(autosize=True, height=1300, margin={ "r": 0, "t": 0, "l": 0, "b": 0 }) return fig
def abrirPopup(self): con = Connection() texto = QString(self.selectedFeature.attributes()[0]) print " id selecr is " + texto from Writes import Writes wr = Writes() wr.writefile("C:/Data/Python/read.txt", texto); self.dockWidget.readDatabyId(texto) from QuickWKT.QuickWKTDialog import QuickWKTDialog self.QuickWKTDialog = QuickWKTDialog() self.QuickWKTDialog.show()
def update_graph(n_clicks, end_date_fut, start_date, end_date, selectedCrime, selectedLocation, start_date_fut): zoom = 10.0 latInitial = 51.507879 lonInitial = -0.087732 bearing = 0 crime_code = selectedCrime location_code = selectedLocation if start_date_fut or end_date_fut: return go.Figure(cm.display_predictions()) if selectedLocation: zoom = 15.0 latInitial = cm.list_of_locations[selectedLocation]["lat"] lonInitial = cm.list_of_locations[selectedLocation]["lon"] location_code = cm.location_codes[selectedLocation] if selectedCrime: crime_code = cm.crime_mapping[selectedCrime] dataset = pd.DataFrame(columns=[ 'crime_type', 'date', 'latitude', 'longitude', 'Crime_type_num' ]) if start_date and end_date: # get the data set start_time = time.time() database = Connection() dataset = cm.database_pull_accelerated(start_date, end_date, crime_code, location_code, database) dataset["Crime_type_num"] = dataset["crime_type"] dataset.replace({"crime_type": cm.crime_mapping_reverse}, inplace=True) return go.Figure( data=[ # Data for all points plotted Scattermapbox(lat=dataset["latitude"], lon=dataset["longitude"], mode="markers", hoverinfo="lat+lon+text", text=dataset["crime_type"], marker=go.scattermapbox.Marker( size=5, color=dataset["Crime_type_num"], showscale=False)), Scattermapbox( lat=[ cm.list_of_locations[i]["lat"] for i in cm.list_of_locations ], lon=[ cm.list_of_locations[i]["lon"] for i in cm.list_of_locations ], mode="markers", hoverinfo="text", text=[i for i in cm.list_of_locations], marker=dict(size=8, color="#ffa0a0"), ), ], layout=Layout( autosize=True, margin=go.layout.Margin(l=0, r=0, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, center=dict(lat=latInitial, lon=lonInitial), # 40.7272 # -73.991251 style="dark", bearing=bearing, zoom=zoom, ), updatemenus=[ dict( buttons=([ dict( args=[{ "mapbox.zoom": zoom, "mapbox.center.lon": lonInitial, "mapbox.center.lat": latInitial, "mapbox.bearing": bearing, "mapbox.style": "dark", }], label="Reset Zoom", method="relayout", ) ]), direction="left", pad={ "r": 0, "t": 0, "b": 0, "l": 0 }, showactive=False, type="buttons", x=0.45, y=0.02, xanchor="left", yanchor="bottom", bgcolor="#323130", borderwidth=1, bordercolor="#6d6d6d", font=dict(color="#FFFFFF"), ) ], ), )
def update_pie_chart(start_date, end_date, selectedCrime, selectedLocation, start_date_fut, end_date_fut, selectedCrime_fut, selectedLocation_fut): crime_code = selectedCrime location_code = selectedLocation location = "London" if selectedLocation: zoom = 15.0 latInitial = cm.list_of_locations[selectedLocation]["lat"] lonInitial = cm.list_of_locations[selectedLocation]["lon"] location_code = cm.location_codes[selectedLocation] location = selectedLocation if selectedCrime: crime_code = cm.crime_mapping[selectedCrime] if start_date and end_date and not selectedCrime: start = dt.strptime(start_date, "%Y-%m-%d") end = dt.strptime(end_date, "%Y-%m-%d") start = start.strftime("%b %Y") end = end.strftime("%b %Y") # get the data set start_time = time.time() database = Connection() dataset = cm.database_pull_accelerated(start_date, end_date, crime_code, location_code, database) print(time.time() - start_time, " update_pie_chart()") dataset["Crime_type_num"] = dataset["crime_type"] dataset.replace({"crime_type": cm.crime_mapping_reverse}, inplace=True) # count number of crimes crime_count = [0] * 16 crime_counts = dataset["Crime_type_num"].value_counts() values = list(crime_counts.values.astype(int)) index = list(crime_counts.index.astype(int)) labels = [cm.crime_mapping_reverse[i] for i in index] colors = [ 'rgb(61,73,154)', 'rgb(67,80,168)', 'rgb(72,86,182)', 'rgb(86,99,188)', 'rgb(100,112,193)', 'rgb(114,125,199)', 'rgb(128,138,205)', 'rgb(142,151,210)', 'rgb(156,164,216)', 'rgb(170,177,221)', 'rgb(184,190,227)', 'rgb(198,203,232)', 'rgb(212,216,238)', 'rgb(226,229,244)', 'rgb(240,241,249)', 'rgb(251,253,254)' ] colors = colors[0:len(labels)] layout = go.Layout( margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", showlegend=False, ) trace1 = { "labels": labels, "values": values, "textinfo": "none", "marker": { "colors": colors } } if start == end: return go.Figure( data=[go.Pie(**trace1)], layout=layout ), "Total crime in " + location + " (" + start + ")" else: return go.Figure( data=[go.Pie(**trace1)], layout=layout ), "Total crime in " + location + " (" + start + " - " + end + ")" else: labels = [] values = [] fig = go.Figure(data=[go.Pie(labels=labels, values=values)]) fig.update_layout(template="plotly_dark", ) # Please return figure data and new title: x is amount of crimes, Date is the date return fig, "Select All Crimes and date range to see analysis"
def update_avg_serious(start_date, end_date, selectedCrime, selectedLocation, start_date_fut, end_date_fut, selectedCrime_fut, selectedLocation_fut): crime_code = selectedCrime location_code = selectedLocation if selectedLocation: zoom = 15.0 latInitial = cm.list_of_locations[selectedLocation]["lat"] lonInitial = cm.list_of_locations[selectedLocation]["lon"] location_code = cm.location_codes[selectedLocation] if selectedCrime: crime_code = cm.crime_mapping[selectedCrime] if start_date and end_date: # get the data set start_time = time.time() database = Connection() dataset = cm.database_pull_accelerated(start_date, end_date, crime_code, location_code, database) print(time.time() - start_time, " update_avg_serious()") dataset["Crime_type_num"] = dataset["crime_type"] dataset.replace({"crime_type": cm.crime_mapping_reverse}, inplace=True) # count number of crimes num_crimes = len(dataset.index) days, months = cm.date_interval(start_date, end_date) crimes_per_month = round(num_crimes / months, 1) layout = go.Layout( annotations=[ dict(text=str(crimes_per_month), x=0.5, y=0.5, font_size=14, showarrow=False), ], margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", showlegend=False, hovermode=False, ) trace1 = { "hole": 0.8, "labels": ["Crimes per Month: " + str(crimes_per_month)], "values": [crimes_per_month], "textinfo": "none" } else: layout = go.Layout( annotations=[ dict(text=str(0), x=0.5, y=0.5, font_size=14, showarrow=False), ], margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", showlegend=False, hovermode=False, ) trace1 = { "hole": 0.8, "labels": ["No Interval Chosen"], "values": [0], "textinfo": "none" } return go.Figure(data=[go.Pie(**trace1)], layout=layout),
def update_timeline(start_date, end_date, selectedCrime, selectedLocation, start_date_fut, end_date_fut, selectedCrime_fut, selectedLocation_fut): first_date = dt(2010, 12, 1) last_date = dt(2019, 11, 1) crime_code = selectedCrime location_code = selectedLocation location = "London" crime_str = "all crime" if selectedLocation: zoom = 15.0 latInitial = cm.list_of_locations[selectedLocation]["lat"] lonInitial = cm.list_of_locations[selectedLocation]["lon"] location_code = cm.location_codes[selectedLocation] location = selectedLocation if selectedCrime: crime_code = cm.crime_mapping[selectedCrime] crime_str = selectedCrime if start_date and end_date: start = dt.strptime(start_date, "%Y-%m-%d") end = dt.strptime(end_date, "%Y-%m-%d") start = start.strftime("%b %Y") end = end.strftime("%b %Y") if (start_date and end_date) or (not start_date and not end_date): # get the data set start_time = time.time() database = Connection() dataset = cm.timeline_database_pull(start_date, end_date, crime_code, location_code, database) print(time.time() - start_time, " update_timeline()") dates = list(dataset[0]["date"]) crimes = list(dataset[0]["count"]) if isinstance(dataset[1], pd.DataFrame): # When a date range has been entered average_crimes = list(dataset[1]["avg"])[0] fig = go.Figure( data=[ go.Scatter(x=dates, y=crimes, name="# of crimes"), # actual data, { 'x': [min(dates), max(dates)], 'y': [average_crimes, average_crimes], 'name': 'avg of period' } ], # horizontal line that represents crime level over selected period layout=go.Layout( xaxis=dict(rangeslider={'visible': True}, type="date"), margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", )) else: # When no date range has been entered fig = go.Figure( data=[go.Scatter(x=dates, y=crimes, name="# of crimes")], layout=go.Layout( xaxis=dict(rangeslider={'visible': True}, type="date"), margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", )) return fig, "Crime timeline for {} in {}".format(crime_str, location) else: fig = go.Figure(data=[go.Scatter(x=[], y=[])], layout=go.Layout( xaxis=dict(rangeslider={'visible': True}, type="date"), margin=dict(l=20, r=20, b=20, t=20, pad=4), template="plotly_dark", )) return fig, "Select full date range to see analysis"
def calculateInterdependenciesbyid(self): print " calculate interdependencies 560 " from PyQt4.QtCore import QSettings import Logica self.dockWidget.PredictionModel.setCurrentIndex(6) ''' set combo box''' AllItems = [self.dockWidget.comboBoxFromLayer.itemText(i) for i in range(self.dockWidget.comboBoxFromLayer.count())] texto = QString(self.selectedFeature.attributes()[0]) id = texto print " Items 403 " indice = 0 num = 0 for i in AllItems: try: if str(i).startswith(texto): indice = num except: print " exceot 513 " num = num + 1 self.dockWidget.comboBoxFromLayer.setCurrentIndex(indice) ''' set combo box''' s = QSettings() ## possible values are: prompt, useProject, useGlobal s.setValue("/Projections/defaultBehaviour", "useProject") idforshow = "1" id = str(self.selectedFeature.attributes()[0]) print " 475 id es " + id Logica.calculateinterdependencyById(id) # init postgres # http://gis.stackexchange.com/questions/86983/how-to-properly-establish-a-postgresql-connection-using-qgscredentials uri = QgsDataSourceURI() # assign this information before you query the QgsCredentials data sQStringtore from Connection import Connection # maquina = " -h 127.0.0.1 -p 5434" con2 = Connection() con = con2.getConnection() uri.setConnection(con.host, con.port, con.database, con.user, con.password) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, con.user, con.password) if success: QgsCredentials.instance().put(connInfo, user, passwd) print " line 501 connect " uri.setPassword(passwd) uri.setUsername(user) uri.setDataSource("public", "interdependencies", "geom") LYR = QgsVectorLayer(uri.uri(), "inter", "postgres") if (LYR.isValid()): print "Layer interdependencies valid" else: print "Layer interdependencies not valid" display_name = "inter" layerExiste = QgsMapLayerRegistry.instance().mapLayersByName(display_name) try: QgsMapLayerRegistry.instance().removeMapLayers([layerExiste[0].id()]) # primer elemento de la lista except: print " except LYR " LYR.setCrs(QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)) # QgsMapLayerRegistry.instance().addMapLayer(LYR) root = QgsProject.instance().layerTreeRoot() # mylayer = QgsVectorLayer("/Path/to/your/data.shp", "my layer", "ogr") QgsMapLayerRegistry.instance().addMapLayer(LYR, False) # root.addLayer(LYR) root.insertLayer(1, LYR) try: symbols = LYR.rendererV2().symbols() symbol = symbols[0] symbol.setColor(PyQt4.QtGui.QColor.fromRgb(255, 0, 0)) except: print " reviewing the symbols of layers " self.iface.mapCanvas().refresh()