markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Exercice 3 : calculer la matrice des distances
Tout d'abord, on découpe un texte en mot. On remplace les tirets en espaces. | texte = "à combien sont ces six saucissons-ci, ces six saucisson-ci sont à six sous".replace("-", " ").split()
texte | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
liste de listes | distl = [ [ jaccard(texte[i], texte[j]) for i in range(len(texte))] for j in range(len(texte))]
distl | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
dictionnaire | distd = { (w,y): jaccard(w,y) for w in texte for y in texte}
distd | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
On compare le nombre de coefficients : | sum(len(_) for _ in distl)
len(distd) | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Le dictionnaire paraît une meilleure option en terme de nombre de coefficients. Mais en terme d'espace mémoire occupé, le dictionnaire est largement plus conséquent. | import sys
sys.getsizeof(distl), sys.getsizeof(distd) | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Pour ce petit exemple, la matrice paraît une bonne option mais lorsque les mots sont répétés un grand nombre de fois : | texte_grand = texte * 40
distl = [ [ jaccard(texte_grand[i], texte_grand[j]) for i in range(len(texte_grand))] for j in range(len(texte_grand))]
distd = { (w,y): jaccard(w,y) for w in texte_grand for y in texte_grand}
sum(len(_) for _ in distl), len(distd)
sys.getsizeof(distl), sys.getsizeof(distd) | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Le dictionnaire permet également de vérifier aisément qu'un calcul a déjà été effectué afin de gagner du temps et de ne pas le refaire. | distd = {}
for w in texte_grand:
for y in texte_grand:
if (w,y) not in distd:
distd[w,y] = jaccard(w,y)
distd[y,w] = distd[w,y]
len(distd) | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Automating Multiple Single-Objective Spatial Optimization Models for Efficiency and Reproducibility
James D. Gaboardi | Association of American Geographers 2016
Florida State University | Department of Geography
Outline
Background & Information
Models
PM... | import IPython.display as IPd
# Local path on user's machine
path = '/Users/jgaboardi/AAG_16/Data/' | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Background & Information
$\Rightarrow$ Automating solutions for p-median and p-center problems with p={n(p)} facilities
$\Rightarrow$ Compare coverage and costs numerically and visually
PySAL 1.11.0
Python Spatial Analysis Library
[https://www.pysal.readthedocs.org]
Sergio Rey at Arizona State University leads the PyS... | # Conceptual Model Workflow
workflow = IPd.Image(path+'/AAG_16.png')
workflow | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Data & Processing
Process Imports | import pysal as ps
import geopandas as gpd
import numpy as np
import networkx as nx
import shapefile as shp
from shapely.geometry import Point
import shapely
from collections import OrderedDict
import pandas as pd
import qgrid
qgrid.nbinstall(overwrite=True) # copies javascript dependencies to your /nbextensions folde... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Define the function to calculate the cost matrix and convert to miles | def c_s_matrix(): # Define Client to Service Matrix Function
global All_Dist_MILES # in meters
All_Neigh_Dist = ntw.allneighbordistances(
sourcepattern=ntw.pointpatterns['Rand_Points_CLIENT'],
destpattern=ntw.pointpatterns['Rand_Points_SERVICE'])
All_Dist_MIL... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Define the function to solve the p-Median + p-Center Problems concurrently | def Gurobi_PMCP(sites, Ai, AiSum, All_Dist_Miles):
# Define Global Variables
global pydf_M
global selected_M
global NEW_Records_PMP
global VAL_PMP
global AVG_PMP
global pydf_C
global selected_C
global NEW_Records_PCP
global VAL_PCP
global pydf_CentDian
glob... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Reproject the street network with GeoPandas | STREETS_Orig = gpd.read_file(path+'Waverly_Trim/Waverly.shp')
STREETS = gpd.read_file(path+'Waverly_Trim/Waverly.shp')
STREETS.to_crs(epsg=2779, inplace=True) # NAD83(HARN) / Florida North
STREETS.to_file(path+'WAVERLY/WAVERLY.shp')
STREETS[:5] | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate Network and read in WAVERLY.shp | ntw = ps.Network(path+'WAVERLY/WAVERLY.shp')
shp_W = ps.open(path+'WAVERLY/WAVERLY.shp') | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create Buffer of 200 meters | buff = STREETS.buffer(200) #Buffer
buff[:5] | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Plot Buffers of Individual Streets | buff.plot() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create a Unary Union of the individual street buffers | buffU = buff.unary_union #Buffer Union
buff1 = gpd.GeoSeries(buffU)
buff1.crs = STREETS.crs
Buff = gpd.GeoDataFrame(buff1, crs=STREETS.crs)
Buff.columns = ['geometry']
Buff | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Plot the unary union buffer | Buff.plot() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create 1000 random ppoints within the bounds of WAVERLY.shp | np.random.seed(352)
x = np.random.uniform(shp_W.bbox[0], shp_W.bbox[2], 1000)
np.random.seed(850)
y = np.random.uniform(shp_W.bbox[1], shp_W.bbox[3], 1000)
coords0= zip(x,y)
coords = [shapely.geometry.Point(i) for i in coords0]
Rand = gpd.GeoDataFrame(coords)
Rand.crs = STREETS.crs
Rand.columns = ['geometry']
Rand[:5... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Plot the 1000 random | Rand.plot() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create GeoPandas DF of the random points within the Unary Buffer | Inter = [Buff['geometry'].intersection(p) for p in Rand['geometry']]
INTER = gpd.GeoDataFrame(Inter, crs=STREETS.crs)
INTER.columns = ['geometry']
INTER[:5] | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Plot the points within the Unary Buffer | INTER.plot() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Add only intersecting records to a list | # Add records that are points within the buffer
point_in = []
for p in INTER['geometry']:
if type(p) == shapely.geometry.point.Point:
point_in.append(p)
point_in[:5] | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Keep the first 100 for clients and the last 15 for service facilities | CLIENT = gpd.GeoDataFrame(point_in[:100], crs=STREETS.crs)
CLIENT.columns = ['geometry']
SERVICE = gpd.GeoDataFrame(point_in[-15:], crs=STREETS.crs)
SERVICE.columns = ['geometry']
CLIENT.to_file(path+'CLIENT')
SERVICE.to_file(path+'SERVICE')
CLIENT[:5]
SERVICE[:5] | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Plot the Unary Union, Simulated Clients, Simulated Service, and Streets | Buff.plot()
STREETS.plot()
CLIENT.plot()
SERVICE.plot(colormap=True) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instaniate non-solution graphs to be drawn | g = nx.Graph() # Roads & Nodes
g1 = nx.MultiGraph() # Edges and Vertices
GRAPH_client = nx.Graph() # Clients
g_client = nx.Graph() # Snapped Clients
GRAPH_service = nx.Graph() # Service
g_service = nx.Graph() # Snapped Service | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate and fill Client and Service point dictionaries | points_client = {}
points_service = {}
CLI = ps.open(path+'CLIENT/CLIENT.shp')
for idx, coords in enumerate(CLI):
GRAPH_client.add_node(idx)
points_client[idx] = coords
GRAPH_client.node[idx] = coords
SER = ps.open(path+'SERVICE/SERVICE.shp')
for idx, coords in enumerate(SER):
GRAPH_service.add_n... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Simulate weights for Client Demand | # Client Weights for demand
np.random.seed(850)
Ai = np.random.randint(1, 5, len(CLI))
Ai = Ai.reshape(len(Ai),1)
AiSum = np.sum(Ai) # Sum of Weights (Total Demand) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate Client .shp | client = shp.Writer(shp.POINT) # Client Shapefile
# Add Random Points
for i,j in CLI:
client.point(i,j)
# Add Fields
client.field('client_ID')
client.field('Weight')
counter = 0
for i in range(len(CLI)):
counter = counter + 1
client.record('client_' + str(counter), Ai[i])
client.save(path+'Simulated/RandomP... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate Service .shp | service = shp.Writer(shp.POINT) #Service Shapefile
# Add Random Points
for i,j in SER:
service.point(i,j)
# Add Fields
service.field('y_ID')
service.field('x_ID')
counter = 0
for i in range(len(SER)):
counter = counter + 1
service.record('y' + str(counter), 'x' + str(counter))
service.save(path+'Simulated/R... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Snap Client and Service points to the network | # Snap
Snap_C = ntw.snapobservations(path+'Simulated/RandomPoints_CLIENT.shp',
'Rand_Points_CLIENT', attribute=True)
Snap_S = ntw.snapobservations(path+'Simulated/RandomPoints_SERVICE.shp',
'Rand_Points_SERVICE', attribute=True) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create lat/lon lists of snapped service coords | # Create Lat & Lon lists of the snapped service locations
y_snapped = []
x_snapped = []
for i,j in ntw.pointpatterns['Rand_Points_SERVICE'].snapped_coordinates.iteritems():
y_snapped.append(j[0])
x_snapped.append(j[1]) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate snapped Service .shp | service_SNAP = shp.Writer(shp.POINT) # Snapped Service Shapefile
# Add Points
for i,j in ntw.pointpatterns['Rand_Points_SERVICE'].snapped_coordinates.iteritems():
service_SNAP.point(j[0],j[1])
# Add Fields
service_SNAP.field('y_ID')
service_SNAP.field('x_ID')
service_SNAP.field('LAT')
service_SNAP.field('LON')
coun... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Call Client to Service Matrix Function | # Call Client to Service Matrix Function
c_s_matrix() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create Lists to fill index and columns of GeoPandas Data Frames | # PANDAS DATAFRAME OF p/y results
p_list = []
for i in range(1, len(SER)+1):
p = 'p='+str(i)
p_list.append(p)
y_list = []
for i in range(1, len(SER)+1):
y = 'y'+str(i)
y_list.append(y) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate GeoPandas Dataframes | pydf_M = pd.DataFrame(index=p_list,columns=y_list)
pydf_C = pd.DataFrame(index=p_list,columns=y_list)
pydf_CentDian = pd.DataFrame(index=p_list,columns=y_list)
pydf_MC = pd.DataFrame(index=p_list,columns=y_list)
qgrid.show_grid(pydf_M) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create PMP, PCP, and CentDian solution graphs | # p-Median
P_Med_Graphs = OrderedDict()
for x in range(1, len(SER)+1):
P_Med_Graphs["{0}".format(x)] = nx.Graph()
# p-Center
P_Cent_Graphs = OrderedDict()
for x in range(1, len(SER)+1):
P_Cent_Graphs["{0}".format(x)] = nx.Graph()
# p-CentDian
P_CentDian_Graphs = OrderedDict()
for x in range(1, len(SER... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Instantiate lists for objective values and average values of all models | # PMP
VAL_PMP = []
AVG_PMP = []
# PCP
VAL_PCP = []
# CentDian
VAL_CentDian = []
# PMCP
VAL_PMCP = []
p_dens = [] # when the facilities for the p-median & p-center are the same | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Solutions
Solve all | Gurobi_PMCP(len(SER), Ai, AiSum, All_Dist_MILES) | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Calculate and record percentage decrease | # PMP Total
PMP_Tot_Diff = []
for i in range(len(VAL_PMP)):
if i == 0:
PMP_Tot_Diff.append('0%')
elif i <= len(VAL_PMP):
n1 = VAL_PMP[i-1]
n2 = VAL_PMP[i]
diff = n2 - n1
perc_change = (diff/n1)*100.
PMP_Tot_Diff.append(str(round(perc_change, 2))+'%')
# PMP Averag... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Data Frames adjust | # PMP
pydf_M = pydf_M[len(SER):]
pydf_M.reset_index()
pydf_M.index = p_list
pydf_M.columns.name = 'Decision\nVariables'
pydf_M.index.name = 'Facility\nDensity'
pydf_M['Tot. Obj. Value'] = VAL_PMP
pydf_M['Tot. % Change'] = PMP_Tot_Diff
pydf_M['Avg. Obj. Value'] = AVG_PMP
pydf_M['Avg. % Change'] = PMP_Avg_Diff
pydf_M = p... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create Graphs of the PMCP results | # Create Graphs of the PMCP results
PMCP_Graphs = OrderedDict()
for x in pydf_MC.index:
PMCP_Graphs[x[2:]] = nx.Graph() | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Visualizations
Draw PMP figure [p=1] large $ \rightarrow $ small [p=15] | figsize(10,10)
# Draw Network Actual Roads and Nodes
for e in ntw.edges:
g.add_edge(*e)
nx.draw(g, ntw.node_coords, node_size=5, alpha=0.25, edge_color='r', width=2)
#PMP
size = 3000
for i,j in P_Med_Graphs.iteritems():
size=size-120
# p-Median
P_Med = ps.open(path+'Results/Selected_Locations_Pmedian'... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Pandas PMP Data Frame | qgrid.show_grid(pydf_M)
#pydf_M | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Bokeh PMP [p vs. cost] trade off | #import bokeh
#from bokeh.charts import Scatter, show
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.io import output_notebook
from bokeh.models import HoverTool, BoxAnnotation
output_notebook()
source_m = ColumnDataSource(
data=dict(
x=range(1, len(SER)+1),
y=AVG_... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Draw PCP figure [p=1] large $ \rightarrow $ small [p=15] | figsize(10,10)
# Draw Network Actual Roads and Nodes
for e in ntw.edges:
g.add_edge(*e)
nx.draw(g, ntw.node_coords, node_size=5, alpha=0.25, edge_color='r', width=2)
#PCP
size = 3000
for i,j in P_Cent_Graphs.iteritems():
size=size-150
# p-Center
P_Cent = ps.open(path+'Results/Selected_Locations_Pcenter... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Pandas PCP Data Frame | pydf_C | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Bokeh PCP [p vs. cost] trade off | #output_notebook()
source_c = ColumnDataSource(
data=dict(
x=range(1, len(SER)+1),
y=VAL_PCP,
obj=VAL_PCP,
desc=p_list,
change=PCP_Diff))
TOOLS = 'wheel_zoom, pan, reset, crosshair, save'
hover = HoverTool(line_policy="nearest", mode="vline"... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Draw CentDian figure [p=1] large $ \rightarrow $ small [p=15] | pydf_CentDian | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Pandas CentDian Data Frame | figsize(10,10)
# Draw Network Actual Roads and Nodes
for e in ntw.edges:
g.add_edge(*e)
nx.draw(g, ntw.node_coords, node_size=5, alpha=0.25, edge_color='r', width=2)
#CentDian
size = 3000
for i,j in P_CentDian_Graphs.iteritems():
size=size-150
P_CentDian = ps.open(path+'Results/Selected_Locations_CentDian'... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Bokeh CentDian [p vs. cost] trade off | #output_notebook()
source_centdian = ColumnDataSource(
data=dict(
x=range(1, len(SER)+1),
y=VAL_CentDian,
obj=VAL_CentDian,
desc=p_list,
change=CentDian_Diff))
TOOLS = 'wheel_zoom, pan, reset, crosshair, save'
hover = HoverTool(line_policy="... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Draw PMCP figure | figsize(10,10)
# Draw Network Actual Roads and Nodes
for e in ntw.edges:
g.add_edge(*e)
nx.draw(g, ntw.node_coords, node_size=5, alpha=0.25, edge_color='r', width=2)
size = 500
shape = 'sdh^Vp<8>'
counter = -1
for i,j in PMCP_Graphs.iteritems():
if int(i) <= len(SER)-1:
counter = counter+1
pmcp... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Pandas PMCP Data Frame | pydf_MC | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Bokeh PMP & PCP [p vs. cost] comparision | #output_notebook()
TOOLS = 'wheel_zoom, pan, reset, crosshair, save, hover'
bokeh_df_PMCP = pd.DataFrame()
bokeh_df_PMCP['p'] = [int(i[2:]) for i in p_dens]
bokeh_df_PMCP['Total Obj. Value'] = [VAL_PMCP[x][0] for x in range(len(VAL_PMCP))]
bokeh_df_PMCP['Avg. Obj. Value'] = [VAL_PMCP[x][1] for x in range(len(VAL_PMCP... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Convert Service Facilities Back to Longitude/Latitude for Google Maps Plots | points = SERVICE
points.to_crs(epsg=32616, inplace=True) # UTM 16N
LonLat_Dict = OrderedDict()
LonLat_List = []
for i,j in points['geometry'].iteritems():
LonLat_Dict[y_list[i]] = utm.to_latlon(j.xy[0][-1], j.xy[1][-1], 16, 'N')
LonLat_List.append((utm.to_latlon(j.xy[0][-1], j.xy[1][-1], 16, 'N')))
Service_... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Create Lists of Selected Locations for Google Maps Plot | # p-Median Selected Sites
list_of_p_MEDIAN = []
for y in range(len(y_list)):
list_of_p_MEDIAN.append([])
for p in range(len(p_list)):
if pydf_M[y_list[y]][p_list[p]] == u'\u2588':
list_of_p_MEDIAN[y].append([p_list[p]])
# p-Center Selected Sites
list_of_p_CENTER = []
for y in ra... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Google Maps Plot | from bokeh.io import output_notebook, output_file, show
from bokeh.models import (GMapPlot, GMapOptions, ColumnDataSource, Circle, MultiLine,
DataRange1d, PanTool, WheelZoomTool, BoxSelectTool, ResetTool)
map_options = GMapOptions(lat=30.4855, lng=-84.265, map_type="hybrid", zoom=14)
plot =... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
Future Work & Vision
$\Longrightarrow$ Develop a python library for bring together in one package spatial analysis & spatial optimization [spanoptpy] potentially incorporating:
|QGIS| PySAL | NetworkX | Pandas | GeoPandas | NumPy | Shapely | Bokeh | CyLP
|----|---------|------------------------------------... | # Gurobi
m = gbp.Model()
m.setParam( 'OutputFlag', False )
x = m.addVar(vtype=gbp.GRB.CONTINUOUS, name='x')
y = m.addVar(vtype=gbp.GRB.CONTINUOUS, name='y')
m.update()
m.setObjective(3*x + 2*y, gbp.GRB.MINIMIZE)
m.addConstr(x >= 3)
m.addConstr(y >= 5)
m.addConstr(x - y <= 20)
m.optimize()
#m.write('path_m.lp')
print m... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
email $\Longrightarrow$ jgaboardi@fsu.edu
GitHub $\Longrightarrow$ https://github.com/jGaboardi/AAG_16 | IPd.HTML('https://github.com/jGaboardi') | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
System Specs | import datetime as dt
import os
import platform
import sys
import bokeh
import cylp
names = ['OSX', 'Processor ', 'Machine ', 'Python ','PySAL ','Gurobi ','Pandas ','GeoPandas ',
'Shapely ', 'NumPy ', 'Bokeh ', 'CyLP', 'Date & Time']
versions = [platform.mac_ver()[0], platform.processor(), platform.machine(),... | .ipynb_checkpoints/AAG_2016-checkpoint.ipynb | jGaboardi/AAG_16 | lgpl-3.0 |
download dataset | %%bash
source activate root # you need to change here to your env name
rm -rf data
mkdir -p data
pushd data
kg download
unzip -q train.zip
unzip -q test.zip
popd | cnn_dogs_cats/dataset_setup.ipynb | ikeyasu/til | mit |
Copy files to valid and sample | from glob import glob
import numpy as np
from shutil import move, copyfile
%mkdir -p data/train
%mkdir -p data/valid
%mkdir -p data/sample/train
%mkdir -p data/sample/valid
%pushd data/train
g = glob('*.jpg')
shuf = np.random.permutation(g)
for i in range(200): copyfile(shuf[i], '../sample/train/' + shuf[i])
shuf = np... | cnn_dogs_cats/dataset_setup.ipynb | ikeyasu/til | mit |
Arrangement files | %pushd data/train
% mkdir cat dog
% mv cat*.jpg cat
% mv dog*.jpg dog
%popd
%pushd data/valid
% mkdir cat dog
% mv cat*.jpg cat
% mv dog*.jpg dog
%popd
%pushd data/sample/train
% mkdir cat dog
% mv cat*.jpg cat
% mv dog*.jpg dog
%popd
%pushd data/sample/valid
% mkdir cat dog
% ... | cnn_dogs_cats/dataset_setup.ipynb | ikeyasu/til | mit |
With the counts stored in a Counter object, lets now quickly print out the top ten libraries and their respective counts. | print('Top 15 Libraries')
for label, count in library_counts.most_common(15):
print('{}: {}'.format(label, count))
| misc/library_counts.ipynb | tpin3694/tpin3694.github.io | mit |
Nothing there seems particularly suprising as this is run from my laptop meaning that a lot of the scripts written are statistical or just simple automations and the above libraries are pretty useful for that. I'd be interested to run this same script on my GPU desktop as it is there that I run any neural networks and ... | labels, counts = zip(*library_counts.most_common(15))
plt.figure(figsize=(12, 8))
plt.bar(labels, counts)
plt.xticks(rotation=60); | misc/library_counts.ipynb | tpin3694/tpin3694.github.io | mit |
Open the SPI rack connection and unlock the controller. This is necessary after bootup of the controller module. If not unlocked, no communication with the modules can take place. The virtual COM port baud rate is irrelevant as it doesn't change the actual speed. Timeout can be changed, but 1 second is a good value. | COM_speed = 1e6 # Baud rate, doesn't matter much
timeout = 1 # In seconds
spi_rack = SPI_rack('COM4', COM_speed, timeout)
spi_rack.unlock() # Unlock the controller to be able to send data | examples/S4g.ipynb | peendebak/SPI-rack | mit |
Create a new S4g module object at the correct (set) module address using the SPI object. By default the module resets the output currents to 0 Volt. Before it does this, it will read back the current value. If this value is non-zero it will slowly ramp it to zero. If reset_currents = False then the output will not be c... | S4g = S4g_module(spi_rack, module=2, max_current=50e-3, reset_currents=True) | examples/S4g.ipynb | peendebak/SPI-rack | mit |
The output span of the module can be set in software to the multiple ranges. In all these ranges the units keeps the 18-bit resolution. The actual current output depends on the maximum current. Here we asume the default 50mA:
* 0 to 50mA: range_max_uni
* -50 to 50 mA: range_max_bi
* -25 to 25 mA: range_min_bi
By defaul... | S4g.change_span_update(0, S4g.range_min_bi)
stepsize = S4g.get_stepsize(1)
print("Stepsize: " + str(stepsize/1e-9) + " nA") | examples/S4g.ipynb | peendebak/SPI-rack | mit |
The current can be set using the set_current function. If you want the output to be precisely equal to the set value, the current should be an integer multiple of the stepsize. Especially if sweeps are performed this is recommended. Otherwise the steps might nog be equidistant. Here we set the current of output 0 to 1 ... | # Changing the output by current
S4g.set_current(0, 1e-3)
# Changing the output by ditigal values
S4g.change_value_update(0, 165535) | examples/S4g.ipynb | peendebak/SPI-rack | mit |
When done with the measurement, it is recommended to close the SPI Rack connection. This will allow other measurement scripts to acces the device. | spi_rack.close() | examples/S4g.ipynb | peendebak/SPI-rack | mit |
The System Integration Test is divided into three main themes:
Baseline Assessment,
Extreme Events, and
Species Protection and Marine Habitat Classification.
The second theme, extreme events, serves to test discovery, access,
and usefulness of meteorological and oceanographic (metocean) data commonly needed to plan f... | from datetime import datetime, timedelta
bounding_box_type = "box"
bounding_box = [-123, 36, -121, 40]
# Temporal range.
now = datetime.utcnow()
start, stop = now - timedelta(days=(7)), now
# URL construction.
iso_start = start.strftime('%Y-%m-%dT%H:%M:00Z')
iso_end = stop.strftime('%Y-%m-%dT%H:%M:00Z')
print('{}... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
The cell below defines the variable of choice: currents. | data_dict = dict()
sos_name = 'Currents'
data_dict['currents'] = {"names": ['currents',
'surface_eastward_sea_water_velocity',
'*surface_eastward_sea_water_velocity*'],
"sos_name": [sos_name]} | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
The next 3 cells are very similar to what we did in the fetching data example:
Instantiate a csw object using the NGDC catalog.
Create the owslib.fes filter.
Apply the filter! | from owslib.csw import CatalogueServiceWeb
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
csw = CatalogueServiceWeb(endpoint, timeout=60)
from owslib import fes
from utilities import fes_date_filter
begin, end = fes_date_filter(start, stop)
bbox = fes.BBox(bounding_box)
or_filt = fes.O... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
The OPeNDAP URLs found were; | from utilities import service_urls
dap_urls = service_urls(csw.records, service='odp:url')
print("Total DAP: {}".format(len(dap_urls)))
print("\n".join(dap_urls)) | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
We found 12 endpoints for currents data.
Note that the last four look like model data, while all others are HF-Radar endpoints.
Can we find more near real-time data?
Let's try the Center for Operational Oceanographic Products and Services (CO-OPS) and the National Data Buoy Center (NDBC).
Both services can be queried u... | from pandas import read_csv
box_str = ','.join(str(e) for e in bounding_box)
url = (('http://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS?'
'service=SOS&request=GetObservation&version=1.0.0&'
'observedProperty=%s&bin=1&'
'offering=urn:ioos:network:NOAA.NOS.CO-OPS:CurrentsActive&'
'feat... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
We got a few CO-OPS stations inside the time/box queried.
How about NDBC buoys? | box_str = ','.join(str(e) for e in bounding_box)
url = (('http://sdf.ndbc.noaa.gov/sos/server.php?'
'request=GetObservation&service=SOS&'
'version=1.0.0&'
'offering=urn:ioos:network:noaa.nws.ndbc:all&'
'featureofinterest=BBOX:%s&'
'observedproperty=%s&'
'responseformat=t... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
No recent observation were found for NDBC buoys!
We need to get the data from the stations identified above.
(There is some boilerplate code in the cell below to show a progress bar.
That can be useful when downloading from many stations,
but it is not necessary.) | import uuid
from IPython.display import HTML, Javascript, display
from utilities.ioos import coopsCurrentRequest, ndbcSOSRequest
divid = str(uuid.uuid4())
pb = HTML("""
<div style="border: 1px solid black; width:500px">
<div id="%s" style="background-color:blue; width:0%%"> </div>
</div>
""" % divid)
display(... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
We found two CO-OPS stations and downloaded the data for both.
Now let's get the data for the HF-Radar we found.
The function get_hr_radar_dap_data filters the OPeNDAP endpoints
returning the the data only for HF-Radar that are near the observations.
(We are downloading only 6 km HF-Radar from GNOME.
The function can b... | from utilities.ioos import get_hr_radar_dap_data
df_list = get_hr_radar_dap_data(dap_urls, st_list, start, stop) | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
The models endpoints found in the CSW search are all global.
Global model runs are not very useful when looking at such a small scale like the San Francisco Bay.
Since we do know that the SFO ports operational model exits,
we can hard-code a data search for SFO and data points near the observations. | def findSFOIndexs(lats, lons, lat_lon_list):
index_list, dist_list = [], []
for val in lat_lon_list:
point1 = Point(val[1], val[0])
dist = 999999999
index = -1
for k in range(0, len(lats)):
point2 = Point(lons[k], lats[k])
val = point1.distance(point2)
... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
Let's visualize everything we got so far. | import matplotlib.pyplot as plt
for station_index in st_list.keys():
df = st_list[station_index]['obsData']
if st_list[station_index]['hasObsData']:
fig = plt.figure(figsize=(16, 3))
plt.plot(df.index, df['sea_water_speed (cm/s)'])
fig.suptitle('Station:'+station_index, fontsize=14)
... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
Any comparison will only make sense if we put that in a geographic context.
So let's create map and place the observations, model grid point, and HF-Radar
grid point on it. | import folium
from utilities import get_coordinates
station = st_list[list(st_list.keys())[0]]
mapa = folium.Map(location=[station["lat"], station["lon"]], zoom_start=10)
mapa.line(get_coordinates(bounding_box),
line_color='#FF0000',
line_weight=5)
for st in st_list:
lat = st_list[st]['lat']
... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
Bonus: we can add WMS tile layer for today's HF-Radar data on the map.
To enable the layer we must click on the top right menu of the interactive map. | now = datetime.utcnow()
mapa.add_tile_layer(tile_name='hfradar 2km',
tile_url=('http://hfradar.ndbc.noaa.gov/tilesavg.php?'
's=10&e=100&x={x}&y={y}&z={z}&t=' +
str(now.year) + '-' + str(now.month) +
'-' + str(n... | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
Map legend:
Blue: observed station
Green: model grid point
Red: HF Radar grid point
In the beginning we raised the question:
What is the extent of relevant meteorological and oceanographic data available in near real-time that could be used to support rapid deployment of a common operational picture to support respon... | HTML(html) | content/downloads/notebooks/2015-10-26-HF_Radar_Currents_west_coast.ipynb | ioos/system-test | unlicense |
Data set | # We import the data for a classification task.
from numpy import genfromtxt
# https://archive.ics.uci.edu/ml/datasets/Abalone
my_data = genfromtxt('abalone_data_set.csv', delimiter=',')
points = my_data[:,:-1]
labels_tmp = my_data[:,-1]
# We trasform the categorical variables to one hot encoding
# The problem is trea... | doc/sphinx/notebooks/dCGPANNs_for_classification.ipynb | darioizzo/d-CGP | gpl-3.0 |
Encoding and training a FFNN using dCGP
There are many ways the same FFNN could be encoded into a CGP chromosome. The utility encode_ffnn selects one for you returning the expression. | # We encode a FFNN into a dCGP expression. Note that the last layer is made by a sum activation function
# so that categorical cross entropy can be used and produce a softmax activation last layer.
# In a dCGP the concept of layers is absent and neurons are defined by activation functions R->R.
dcgpann = dcgpy.encode_... | doc/sphinx/notebooks/dCGPANNs_for_classification.ipynb | darioizzo/d-CGP | gpl-3.0 |
Same training is done using Keras (Tensor Flow backend)
IMPORTANT: no GPU is used for the comparison. The values are thus only to be taken as indications of the performances on a simple environment with 4 CPUs. | import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras import optimizers
# We define Stochastic Gradient Descent as an optimizer
sgd = optimizers.SGD(lr=1.)
# We define weight initializetion
initializerw = keras.initializers.RandomNormal(mean=0.0, stddev=1, seed=None)
in... | doc/sphinx/notebooks/dCGPANNs_for_classification.ipynb | darioizzo/d-CGP | gpl-3.0 |
Loading the dataset stored in hdf5 format | h5f = h5py.File('../dataset/LowRes_13434_overlapping_pairs.h5','r')
pairs = h5f['dataset_1'][:]
h5f.close()
print(pairs.shape)
print(pairs[0,:,:,0].dtype)
print(pairs[0,:,:,0].max()) | notebooks/Loading_13434_LowRes_Dataset.ipynb | jeanpat/DeepFISH | gpl-3.0 |
Looking at some examples | grey = pairs[0,:,:,0]
mask = pairs[0,:,:,1]
%matplotlib inline
plt.figure(figsize = (10,8))
plt.subplot(121)
plt.imshow(grey)
plt.title('max='+str(grey.max()))
plt.subplot(122)
plt.imshow(mask, interpolation = 'nearest') | notebooks/Loading_13434_LowRes_Dataset.ipynb | jeanpat/DeepFISH | gpl-3.0 |
Problem in the groundtruth label at low resolution:
The labels are a little noisy on the edge of the groundtruth label. | plt.figure(figsize = (10,12))
plt.subplot(141)
plt.imshow(mask, interpolation = 'nearest')
plt.subplot(142)
plt.title('label 1')
plt.imshow(mask == 1, interpolation = 'nearest')
plt.subplot(143)
plt.title('label 2')
plt.imshow(mask == 2, interpolation = 'nearest')
plt.subplot(144)
plt.title('label 3')
plt.imshow(mask =... | notebooks/Loading_13434_LowRes_Dataset.ipynb | jeanpat/DeepFISH | gpl-3.0 |
We can expose the trained model as a REST endpoint. This will allow other applications to consume the predictions from the model.
In order to do that, we wrap the model object in a Python function and add it to the Predictive Service. In the function you may add your own logic for transform input to the model, ensemb... | def predict(x):
# Construct an SFrame
sf = gl.SFrame(x)
# Add your own business logic here
# Call the predict method on the model.
predictions = model.predict(sf)
return predictions['prediction'] | webinars/pattern-mining/deployment.ipynb | turi-code/tutorials | apache-2.0 |
2. Create a Predictive Service (One time) <a id='create'></a>
This section shows you how to deploy a Predictive Service to EC2. The EC2 instances used by the Predictive Service will be launched in your own AWS account, so you will be responsible for the cost.
<img src="images/middle.png"></img>
To create a Predictive ... | import graphlab as gl
# Replace with your path.
ps_state_path = 's3://<your-bucket-name>/predictive_service/ps'
# Set your AWS credentials.
gl.aws.set_credentials(<key>, <secret>)
# Create an EC2 config
ec2_config = gl.deploy.Ec2Config()
# Launch a predictive service
ps = gl.deploy.predictive_service.create(name = ... | webinars/pattern-mining/deployment.ipynb | turi-code/tutorials | apache-2.0 |
Load an already created service | import graphlab as gl
ps = gl.deploy.predictive_service.load('s3://gl-demo-usw2/predictive_service/demolab/ps-1.6')
ps
# ps.add('pattern-mining', predict) (When you add this for the first time)
ps.update('pattern-mining', predict)
ps.apply_changes() | webinars/pattern-mining/deployment.ipynb | turi-code/tutorials | apache-2.0 |
Query the model <a id='query'></a>
You may do a test query before really deploying it to production. This will help detect errors in the function before deploying it the Predictive Service.
<img src="images/right.png"></img> | # test query to make sure the model works fine
ps.query('pattern-mining', x={'Receipt': [1], 'StoreNum': [2], 'Item': ['CherryTart']}) | webinars/pattern-mining/deployment.ipynb | turi-code/tutorials | apache-2.0 |
Query from external applications via REST
Now other applications can interact with our model! In the next section we will illustrate how to consume the model. We can also use other APIs like ps.update() to update a mode, ps.remove() to remove a model.
The model query is exposed through REST API. The path is:
http(s):/... | import json
import requests
def restful_query(x):
headers = {'content-type': 'application/json'}
payload = {'api_key':'b437e588-0f2b-45e1-81c8-ce3acfa81ade', "data":{"x": x}}
end_point = 'http://demolab-one-six-2015364754.us-west-2.elb.amazonaws.com/query/pattern-mining'
return requests.post(end_point,... | webinars/pattern-mining/deployment.ipynb | turi-code/tutorials | apache-2.0 |
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/probability/examples/Modeling_with_JointDistribution"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.rese... | #@title Import and set ups{ display-mode: "form" }
import functools
import numpy as np
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Prerequisite: A Bayesian Regression Problem
We'll consider a very simple Bayesian regression scenario:
$$
\begin{align}
m & \sim \text{Normal}(0, 1) \
b & \sim \text{Normal}(0, 1) \
Y & \sim \text{Normal}(mX + b, 1)
\end{align}
$$
In this model, m and b are drawn from standard normals, and the observations Y are drawn ... | X = np.arange(7)
X | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Desiderata
In probabilistic inference, we often want to perform two basic operations:
- sample: Drawing samples from the model.
- log_prob: Computing the log probability of a sample from the model.
The key contribution of TFP's JointDistribution abstractions (as well as of many other approaches to probabilistic program... | jds = tfd.JointDistributionSequential([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y
]) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
This is more or less a direct translation of the model into code. The slope m and bias b are straightforward. Y is defined using a lambda-function: the general pattern is that a lambda-function of $k$ arguments in a JointDistributionSequential (JDS) uses the previous $k$ distributions in the model. Note the "reverse" o... | dists, sample = jds.sample_distributions()
sample | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
But log_prob produces a result with an undesired shape: | jds.log_prob(sample) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
And multiple sampling doesn't work: | try:
jds.sample([5, 3])
except tf.errors.InvalidArgumentError as e:
print(e) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.