{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Single-layer Territory Management. Optimizing territories considering only clients\n",
"\n",
"In territory management, a territory is a customer group or geographic area over which either an individual salesperson or a sales team has responsibility. These territories are usually defined based on geography, sales potential, number of clients or a combination of these factors.\n",
"\n",
"The main complexity in territory management is to create areas that are balanced with regards to more than one factor that usually behave very differently. There is no one-size-fits-all solution, and if the balance is off, sales management is likely to leave someone within their organization unhappy or leave money on the table. This is why it is very important to identify and understand all the components and requirements of your use case to apply the most appropriate technique.\n",
"\n",
"We can differentiate between two main use cases: when the location of sales reps is important (usually because they have to travel to visit their clients) and when it is not (travel rarely occurs). The first case is clearly more complex than the latter.\n",
"\n",
"In this notebook we will use two different techniques to solve territory management problems when only the location of clients needs to be considered, i.e., we will have a single layer of data consisting of client locations. We will prove the value Spatial Data Science techniques by showing their additional value compared to traditional techniques."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Use case description\n",
"\n",
"A pharma lab is interested in balancing their sales territories in the state of Texas based on the number of current and potential clients per territory. \n",
"\n",
"Their clients are mainly offices and clinics of medical doctors.\n",
"\n",
"They are interested in creating 5 balanced territories.\n",
"\n",
"We will use the following two datasets from [CARTO's Data Observatory](https://carto.com/spatial-data-catalog/):\n",
"- Points of Interest (POIs). In particular, office and clinic of medical doctors POIs. We will use [Pitney Bowes POI-Consumer dataset](https://carto.com/spatial-data-catalog/browser/dataset/pb_consumer_po_62cddc04/).\n",
"- Texas boundary geometry. We'll use [Who's on First GeoJSON - Global dataset](https://carto.com/spatial-data-catalog/browser/geography/wof_geojson_4e78587c/).\n",
"\n",
"*Note* the POI dataset is premium and a subscription is needed to access this data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 0. Setup\n",
"\n",
"We'll start by importing all packages we'll use."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import geopandas as gpd\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"import seaborn as sns\n",
"\n",
"from cartoframes.auth import set_default_credentials\n",
"from cartoframes.data.observatory import *\n",
"from cartoframes.viz import *\n",
"from h3 import h3\n",
"from libpysal.weights import Rook\n",
"from shapely import wkt\n",
"from shapely.geometry import mapping, Polygon\n",
"from sklearn.cluster import KMeans\n",
"from spopt.region.maxp import MaxPHeuristic\n",
"\n",
"pd.set_option('display.max_columns', None)\n",
"plt.rc('axes', titlesize='large')\n",
"plt.rc('xtick', labelsize='large')\n",
"plt.rc('ytick', labelsize='large')\n",
"sns.set_style('whitegrid')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In order to be able to use the Data Observatory via CARTOframes, you need to set your CARTO account credentials first.\n",
"\n",
"Please, visit the [Authentication guide](https://carto.com/developers/cartoframes/guides/Authentication/) for further detail."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"set_default_credentials('creds.json')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 0.1. Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following function creates an [H3](https://eng.uber.com/h3/) polyfill of the polygon and at the resolution indicated."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def create_h3_grid(polygon, resolution=8):\n",
" hex_id_list = list(h3.polyfill(geojson = mapping(polygon), res = resolution, geo_json_conformant=True))\n",
" hexagon_list = list(map(lambda x : Polygon(h3.h3_to_geo_boundary(h=x, geo_json=True)), hex_id_list))\n",
" grid = pd.DataFrame(data={'hex_id':hex_id_list, 'geometry':hexagon_list})\n",
" grid = gpd.GeoDataFrame(grid, crs='epsg:4326')\n",
" return grid"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function below is used throughout the analysis to check is clusters are balanced based on different metrics.\n",
"\n",
"The function arguments are:\n",
"- `cluster_names` so that we can provide descriptive names to clusters\n",
"- `areas_df` is the GeoDataFrame\n",
"- `groupby` is the column with the cluster to which each cell belongs to\n",
"- `**kaggregations` for the different metrics we'd like to calculate"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def plot_clinic_balance(clusters, areas_df, groupby, **kaggregations):\n",
" areas_df_g = areas_df.groupby(groupby).agg(kaggregations).reset_index()\n",
"\n",
" n_plots = len(kaggregations)\n",
" fig, axs = plt.subplots(1, n_plots, figsize=(9 + 3*n_plots,4))\n",
" if n_plots == 1:\n",
" axs = [axs]\n",
" \n",
" for i in range(n_plots):\n",
" sns.barplot(y=groupby, x=list(kaggregations.keys())[i], data=areas_df_g, order=clusters, \n",
" palette=['#7F3C8D','#11A579','#3969AC','#F2B701','#E73F74'], ax=axs[i])\n",
" axs[i].set_xlabel(list(kaggregations.keys())[i], fontsize=13)\n",
" axs[i].set_ylabel('Sales rep locations', fontsize=13)\n",
" \n",
" fig.tight_layout()\n",
" \n",
" return axs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Download and visualize data\n",
"\n",
"Next, we will download the data described in the usecase using [CARTOframes](https://carto.com/developers/cartoframes/).\n",
"\n",
"*Note* in this notebook some prior knowledge on how to explore and download data from the [Data Observatory](https://carto.com/spatial-data-catalog/) is assumed. If this is your first time exploring and downloading data from the [Data Observatory](https://carto.com/spatial-data-catalog/), take a look at [CARTOframes Guides](https://carto.com/developers/cartoframes/guides/Introduction/) and the [Data Observatory examples](https://carto.com/developers/cartoframes/guides/Data-Observatory/) and **discover how easy it is to get started!**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1 Texas boundary geometry\n",
"\n",
"We are interested in the geometry of the state of Texas. We'll download it from [Who's on First GeoJSON - Global dataset](https://carto.com/spatial-data-catalog/browser/geography/wof_geojson_4e78587c/)."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'slug': 'wof_geojson_4e78587c',\n",
" 'name': 'GeoJSON - Global',\n",
" 'description': \"The main table in Who's On First. Holds all the relevant information for a place in the 'body' JSON field.\",\n",
" 'country_id': 'glo',\n",
" 'provider_id': 'whos_on_first',\n",
" 'geom_type': 'MULTIPLE',\n",
" 'update_frequency': None,\n",
" 'is_public_data': True,\n",
" 'lang': 'eng',\n",
" 'version': '20190520',\n",
" 'provider_name': \"Who's On First\",\n",
" 'id': 'carto-do-public-data.whos_on_first.geography_glo_geojson_20190520'}"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"wof_grographies = Geography.get('wof_geojson_4e78587c')\n",
"wof_grographies.to_dict()"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
"
],
"text/plain": [
" geoid id body \\\n",
"0 85688753 85688753 {\"id\": 85688753, \"type\": \"Feature\", \"propertie... \n",
"\n",
" name country parent_id is_current placetype geometry_type \\\n",
"0 Texas US 85633793 1 region Polygon \n",
"\n",
" bbox \\\n",
"0 POLYGON((-93.508039 25.837164, -93.508039 36.5... \n",
"\n",
" geom lastmodified \\\n",
"0 POLYGON ((-103.06466 32.95910, -103.06442 32.0... 1555446728 \n",
"\n",
" lastmodified_timestamp \n",
"0 2019-04-16 20:32:08+00:00 "
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"state_name = 'Texas'\n",
"country_code = 'US'\n",
"placetype = 'region'\n",
"\n",
"sql_query = f\"\"\"SELECT * \n",
" FROM $geography$ \n",
" WHERE name = '{state_name}' AND \n",
" country = '{country_code}' AND \n",
" placetype='{placetype}'\"\"\"\n",
"\n",
"tx_boundary = wof_grographies.to_dataframe(sql_query=sql_query)\n",
"tx_boundary.crs = 'epsg:4326'\n",
"tx_boundary['geom'] = tx_boundary.simplify(0.01)\n",
"tx_boundary"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2. Client locations\n",
"\n",
"We'll download all POIs in Texas classified as \"OFFICES AND CLINICS OF MEDICAL DOCTORS\" from [Pitney Bowes POI-Consumer dataset](https://carto.com/spatial-data-catalog/browser/dataset/pb_consumer_po_62cddc04/).\n",
"\n",
"*Note* this is a premium dataset and a subscription is required."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"poi_dataset = Dataset.get('pb_consumer_po_62cddc04')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
geoid
\n",
"
do_date
\n",
"
name
\n",
"
brandname
\n",
"
pb_id
\n",
"
trade_name
\n",
"
franchise_name
\n",
"
iso3
\n",
"
areaname4
\n",
"
areaname3
\n",
"
areaname2
\n",
"
areaname1
\n",
"
stabb
\n",
"
postcode
\n",
"
formattedaddress
\n",
"
mainaddressline
\n",
"
addresslastline
\n",
"
longitude
\n",
"
latitude
\n",
"
georesult
\n",
"
confidence_code
\n",
"
country_access_code
\n",
"
tel_num
\n",
"
faxnum
\n",
"
email
\n",
"
http
\n",
"
open_24h
\n",
"
business_line
\n",
"
sic1
\n",
"
sic2
\n",
"
sic8
\n",
"
sic8_description
\n",
"
alt_industry_code
\n",
"
micode
\n",
"
trade_division
\n",
"
group
\n",
"
class
\n",
"
sub_class
\n",
"
employee_here
\n",
"
employee_count
\n",
"
year_start
\n",
"
sales_volume_local
\n",
"
sales_volume_us_dollars
\n",
"
currency_code
\n",
"
agent_code
\n",
"
legal_status_code
\n",
"
status_code
\n",
"
subsidiary_indicator
\n",
"
parent_business_name
\n",
"
parent_address
\n",
"
parent_street_address
\n",
"
parent_areaname3
\n",
"
parent_areaname1
\n",
"
parent_country
\n",
"
parent_postcode
\n",
"
domestic_ultimate_business_name
\n",
"
domestic_ultimate_address
\n",
"
domestic_ultimate_street_address
\n",
"
domestic_ultimate_areaname3
\n",
"
domestic_ultimate_areaname1
\n",
"
domestic_ultimate_postcode
\n",
"
global_ultimate_indicator
\n",
"
global_ultimate_business_name
\n",
"
global_ultimate_address
\n",
"
global_ultimate_street_address
\n",
"
global_ultimate_areaname3
\n",
"
global_ultimate_areaname1
\n",
"
global_ultimate_country
\n",
"
global_ultimate_postcode
\n",
"
family_members
\n",
"
hierarchy_code
\n",
"
ticker_symbol
\n",
"
exchange_name
\n",
"
geom
\n",
"
\n",
" \n",
" \n",
"
\n",
"
0
\n",
"
1128750296#-96.398536#32.469934
\n",
"
2020-08-01
\n",
"
SIMMONS & ASSOC SOUTH CENTRAL LLC
\n",
"
NaN
\n",
"
1128750296
\n",
"
SIMMONS & ASSOCIATES
\n",
"
NaN
\n",
"
USA
\n",
"
NaN
\n",
"
SCURRY
\n",
"
NaN
\n",
"
TEXAS
\n",
"
TX
\n",
"
75158-3304
\n",
"
9084 FM 2451, SCURRY, TX, 75158-3304
\n",
"
9084 FM 2451
\n",
"
SCURRY, TX, 75158-3304
\n",
"
-96.398536
\n",
"
32.469934
\n",
"
S8HPNTSCZA
\n",
"
HIGH
\n",
"
1.0
\n",
"
(972) 452-8013
\n",
"
NaN
\n",
"
NaN
\n",
"
WWW.SIMMONSINC.COM
\n",
"
NaN
\n",
"
OFFICES AND CLINICS MEDICAL DOCTORS,NSK
\n",
"
8011.0
\n",
"
NaN
\n",
"
80110000
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
621111.0
\n",
"
10238011
\n",
"
DIVISION I. - SERVICES
\n",
"
HEALTH SERVICES
\n",
"
OFFICES AND CLINICS OF DOCTORS OF MEDICINE
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
1.0
\n",
"
1.0
\n",
"
1997.0
\n",
"
251657.0
\n",
"
251657.0
\n",
"
20.0
\n",
"
G
\n",
"
3.0
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
N
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
POINT (-96.39854 32.46993)
\n",
"
\n",
"
\n",
"
1
\n",
"
1217171653#-96.858002#32.715481
\n",
"
2020-08-01
\n",
"
SOUTHWEST DALLAS ORTHOPEDIC ASSOCIATES
\n",
"
NaN
\n",
"
1217171653
\n",
"
NaN
\n",
"
NaN
\n",
"
USA
\n",
"
NaN
\n",
"
DALLAS
\n",
"
NaN
\n",
"
TEXAS
\n",
"
TX
\n",
"
75224-3059
\n",
"
2909 S HAMPTON RD STE D121, DALLAS, TX, 75224-...
\n",
"
2909 S HAMPTON RD STE D121
\n",
"
DALLAS, TX, 75224-3059
\n",
"
-96.858002
\n",
"
32.715481
\n",
"
S8HPNTSCZA
\n",
"
HIGH
\n",
"
1.0
\n",
"
(214) 333-3741
\n",
"
NaN
\n",
"
NaN
\n",
"
WWW.DALLASORTHO.COM
\n",
"
NaN
\n",
"
OFFICES AND CLINICS MEDICAL DOCTORS,NSK
\n",
"
8011.0
\n",
"
NaN
\n",
"
80110514
\n",
"
ORTHOPEDIC PHYSICIAN
\n",
"
621111.0
\n",
"
10942514
\n",
"
DIVISION I. - SERVICES
\n",
"
HEALTH SERVICES
\n",
"
OFFICES AND CLINICS OF DOCTORS OF MEDICINE
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
6.0
\n",
"
6.0
\n",
"
1991.0
\n",
"
620608.0
\n",
"
620608.0
\n",
"
20.0
\n",
"
G
\n",
"
13.0
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
N
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
POINT (-96.85800 32.71548)
\n",
"
\n",
"
\n",
"
2
\n",
"
1123005494#-97.104542#32.926825
\n",
"
2020-08-01
\n",
"
S ROBERT HARLA DOPA
\n",
"
NaN
\n",
"
1123005494
\n",
"
GRAPEVINE DERMATOLOGY
\n",
"
NaN
\n",
"
USA
\n",
"
NaN
\n",
"
GRAPEVINE
\n",
"
NaN
\n",
"
TEXAS
\n",
"
TX
\n",
"
76051-8632
\n",
"
2321 IRA E WOODS AVE STE 180, GRAPEVINE, TX, 7...
\n",
"
2321 IRA E WOODS AVE STE 180
\n",
"
GRAPEVINE, TX, 76051-8632
\n",
"
-97.104542
\n",
"
32.926825
\n",
"
S8HPNTSCZA
\n",
"
HIGH
\n",
"
1.0
\n",
"
(817) 329-2263
\n",
"
NaN
\n",
"
NaN
\n",
"
WWW.DERMDFW.COM
\n",
"
NaN
\n",
"
OFFICES AND CLINICS MEDICAL DOCTORS,NSK
\n",
"
8011.0
\n",
"
NaN
\n",
"
80110503
\n",
"
DERMATOLOGIST
\n",
"
621111.0
\n",
"
10942503
\n",
"
DIVISION I. - SERVICES
\n",
"
HEALTH SERVICES
\n",
"
OFFICES AND CLINICS OF DOCTORS OF MEDICINE
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
13.0
\n",
"
13.0
\n",
"
1990.0
\n",
"
1345253.0
\n",
"
1345253.0
\n",
"
20.0
\n",
"
G
\n",
"
13.0
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
N
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
POINT (-97.10454 32.92683)
\n",
"
\n",
"
\n",
"
3
\n",
"
1221252299#-101.902112#33.573453
\n",
"
2020-08-01
\n",
"
CONSULTANTS IN INFECTIOUS DISEASES LLP
\n",
"
NaN
\n",
"
1221252299
\n",
"
NaN
\n",
"
NaN
\n",
"
USA
\n",
"
NaN
\n",
"
LUBBOCK
\n",
"
NaN
\n",
"
TEXAS
\n",
"
TX
\n",
"
79410-1804
\n",
"
4102 24TH ST STE 403, LUBBOCK, TX, 79410-1804
\n",
"
4102 24TH ST STE 403
\n",
"
LUBBOCK, TX, 79410-1804
\n",
"
-101.902112
\n",
"
33.573453
\n",
"
S8HPNTSCZA
\n",
"
HIGH
\n",
"
1.0
\n",
"
(806) 725-7150
\n",
"
NaN
\n",
"
NaN
\n",
"
WWW.COVMEDGROUP.ORG
\n",
"
NaN
\n",
"
OFFICES AND CLINICS MEDICAL DOCTORS,NSK
\n",
"
8011.0
\n",
"
NaN
\n",
"
80110510
\n",
"
INFECTIOUS DISEASE SPECIALIST, PHYSICIAN/SURGEON
\n",
"
621111.0
\n",
"
10942510
\n",
"
DIVISION I. - SERVICES
\n",
"
HEALTH SERVICES
\n",
"
OFFICES AND CLINICS OF DOCTORS OF MEDICINE
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
22.0
\n",
"
22.0
\n",
"
1995.0
\n",
"
1058845.0
\n",
"
1058845.0
\n",
"
20.0
\n",
"
G
\n",
"
12.0
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
N
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
POINT (-101.90211 33.57345)
\n",
"
\n",
"
\n",
"
4
\n",
"
1217934291#-95.419502#29.170283
\n",
"
2020-08-01
\n",
"
SUZAN CARPENTER
\n",
"
NaN
\n",
"
1217934291
\n",
"
CARPENTER, SU ZAN MD
\n",
"
NaN
\n",
"
USA
\n",
"
NaN
\n",
"
ANGLETON
\n",
"
NaN
\n",
"
TEXAS
\n",
"
TX
\n",
"
77515-5836
\n",
"
1113 E CEDAR ST, ANGLETON, TX, 77515-5836
\n",
"
1113 E CEDAR ST
\n",
"
ANGLETON, TX, 77515-5836
\n",
"
-95.419502
\n",
"
29.170283
\n",
"
S8HPNTSCZA
\n",
"
HIGH
\n",
"
1.0
\n",
"
(979) 849-5703
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
OFFICES AND CLINICS MEDICAL DOCTORS,NSK
\n",
"
8011.0
\n",
"
NaN
\n",
"
80119901
\n",
"
GENERAL AND FAMILY PRACTICE, PHYSICIAN/SURGEON
\n",
"
621111.0
\n",
"
10230302
\n",
"
DIVISION I. - SERVICES
\n",
"
HEALTH SERVICES
\n",
"
OFFICES AND CLINICS OF DOCTORS OF MEDICINE
\n",
"
OFFICES AND CLINICS OF MEDICAL DOCTORS
\n",
"
3.0
\n",
"
3.0
\n",
"
1990.0
\n",
"
257133.0
\n",
"
257133.0
\n",
"
20.0
\n",
"
G
\n",
"
13.0
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
N
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
NaN
\n",
"
0.0
\n",
"
0.0
\n",
"
NaN
\n",
"
NaN
\n",
"
POINT (-95.41950 29.17028)
\n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" geoid do_date \\\n",
"0 1128750296#-96.398536#32.469934 2020-08-01 \n",
"1 1217171653#-96.858002#32.715481 2020-08-01 \n",
"2 1123005494#-97.104542#32.926825 2020-08-01 \n",
"3 1221252299#-101.902112#33.573453 2020-08-01 \n",
"4 1217934291#-95.419502#29.170283 2020-08-01 \n",
"\n",
" name brandname pb_id \\\n",
"0 SIMMONS & ASSOC SOUTH CENTRAL LLC NaN 1128750296 \n",
"1 SOUTHWEST DALLAS ORTHOPEDIC ASSOCIATES NaN 1217171653 \n",
"2 S ROBERT HARLA DOPA NaN 1123005494 \n",
"3 CONSULTANTS IN INFECTIOUS DISEASES LLP NaN 1221252299 \n",
"4 SUZAN CARPENTER NaN 1217934291 \n",
"\n",
" trade_name franchise_name iso3 areaname4 areaname3 areaname2 \\\n",
"0 SIMMONS & ASSOCIATES NaN USA NaN SCURRY NaN \n",
"1 NaN NaN USA NaN DALLAS NaN \n",
"2 GRAPEVINE DERMATOLOGY NaN USA NaN GRAPEVINE NaN \n",
"3 NaN NaN USA NaN LUBBOCK NaN \n",
"4 CARPENTER, SU ZAN MD NaN USA NaN ANGLETON NaN \n",
"\n",
" areaname1 stabb postcode \\\n",
"0 TEXAS TX 75158-3304 \n",
"1 TEXAS TX 75224-3059 \n",
"2 TEXAS TX 76051-8632 \n",
"3 TEXAS TX 79410-1804 \n",
"4 TEXAS TX 77515-5836 \n",
"\n",
" formattedaddress \\\n",
"0 9084 FM 2451, SCURRY, TX, 75158-3304 \n",
"1 2909 S HAMPTON RD STE D121, DALLAS, TX, 75224-... \n",
"2 2321 IRA E WOODS AVE STE 180, GRAPEVINE, TX, 7... \n",
"3 4102 24TH ST STE 403, LUBBOCK, TX, 79410-1804 \n",
"4 1113 E CEDAR ST, ANGLETON, TX, 77515-5836 \n",
"\n",
" mainaddressline addresslastline longitude \\\n",
"0 9084 FM 2451 SCURRY, TX, 75158-3304 -96.398536 \n",
"1 2909 S HAMPTON RD STE D121 DALLAS, TX, 75224-3059 -96.858002 \n",
"2 2321 IRA E WOODS AVE STE 180 GRAPEVINE, TX, 76051-8632 -97.104542 \n",
"3 4102 24TH ST STE 403 LUBBOCK, TX, 79410-1804 -101.902112 \n",
"4 1113 E CEDAR ST ANGLETON, TX, 77515-5836 -95.419502 \n",
"\n",
" latitude georesult confidence_code country_access_code tel_num \\\n",
"0 32.469934 S8HPNTSCZA HIGH 1.0 (972) 452-8013 \n",
"1 32.715481 S8HPNTSCZA HIGH 1.0 (214) 333-3741 \n",
"2 32.926825 S8HPNTSCZA HIGH 1.0 (817) 329-2263 \n",
"3 33.573453 S8HPNTSCZA HIGH 1.0 (806) 725-7150 \n",
"4 29.170283 S8HPNTSCZA HIGH 1.0 (979) 849-5703 \n",
"\n",
" faxnum email http open_24h \\\n",
"0 NaN NaN WWW.SIMMONSINC.COM NaN \n",
"1 NaN NaN WWW.DALLASORTHO.COM NaN \n",
"2 NaN NaN WWW.DERMDFW.COM NaN \n",
"3 NaN NaN WWW.COVMEDGROUP.ORG NaN \n",
"4 NaN NaN NaN NaN \n",
"\n",
" business_line sic1 sic2 sic8 \\\n",
"0 OFFICES AND CLINICS MEDICAL DOCTORS,NSK 8011.0 NaN 80110000 \n",
"1 OFFICES AND CLINICS MEDICAL DOCTORS,NSK 8011.0 NaN 80110514 \n",
"2 OFFICES AND CLINICS MEDICAL DOCTORS,NSK 8011.0 NaN 80110503 \n",
"3 OFFICES AND CLINICS MEDICAL DOCTORS,NSK 8011.0 NaN 80110510 \n",
"4 OFFICES AND CLINICS MEDICAL DOCTORS,NSK 8011.0 NaN 80119901 \n",
"\n",
" sic8_description alt_industry_code \\\n",
"0 OFFICES AND CLINICS OF MEDICAL DOCTORS 621111.0 \n",
"1 ORTHOPEDIC PHYSICIAN 621111.0 \n",
"2 DERMATOLOGIST 621111.0 \n",
"3 INFECTIOUS DISEASE SPECIALIST, PHYSICIAN/SURGEON 621111.0 \n",
"4 GENERAL AND FAMILY PRACTICE, PHYSICIAN/SURGEON 621111.0 \n",
"\n",
" micode trade_division group \\\n",
"0 10238011 DIVISION I. - SERVICES HEALTH SERVICES \n",
"1 10942514 DIVISION I. - SERVICES HEALTH SERVICES \n",
"2 10942503 DIVISION I. - SERVICES HEALTH SERVICES \n",
"3 10942510 DIVISION I. - SERVICES HEALTH SERVICES \n",
"4 10230302 DIVISION I. - SERVICES HEALTH SERVICES \n",
"\n",
" class \\\n",
"0 OFFICES AND CLINICS OF DOCTORS OF MEDICINE \n",
"1 OFFICES AND CLINICS OF DOCTORS OF MEDICINE \n",
"2 OFFICES AND CLINICS OF DOCTORS OF MEDICINE \n",
"3 OFFICES AND CLINICS OF DOCTORS OF MEDICINE \n",
"4 OFFICES AND CLINICS OF DOCTORS OF MEDICINE \n",
"\n",
" sub_class employee_here employee_count \\\n",
"0 OFFICES AND CLINICS OF MEDICAL DOCTORS 1.0 1.0 \n",
"1 OFFICES AND CLINICS OF MEDICAL DOCTORS 6.0 6.0 \n",
"2 OFFICES AND CLINICS OF MEDICAL DOCTORS 13.0 13.0 \n",
"3 OFFICES AND CLINICS OF MEDICAL DOCTORS 22.0 22.0 \n",
"4 OFFICES AND CLINICS OF MEDICAL DOCTORS 3.0 3.0 \n",
"\n",
" year_start sales_volume_local sales_volume_us_dollars currency_code \\\n",
"0 1997.0 251657.0 251657.0 20.0 \n",
"1 1991.0 620608.0 620608.0 20.0 \n",
"2 1990.0 1345253.0 1345253.0 20.0 \n",
"3 1995.0 1058845.0 1058845.0 20.0 \n",
"4 1990.0 257133.0 257133.0 20.0 \n",
"\n",
" agent_code legal_status_code status_code subsidiary_indicator \\\n",
"0 G 3.0 0.0 0.0 \n",
"1 G 13.0 0.0 0.0 \n",
"2 G 13.0 0.0 0.0 \n",
"3 G 12.0 0.0 0.0 \n",
"4 G 13.0 0.0 0.0 \n",
"\n",
" parent_business_name parent_address parent_street_address parent_areaname3 \\\n",
"0 NaN NaN NaN NaN \n",
"1 NaN NaN NaN NaN \n",
"2 NaN NaN NaN NaN \n",
"3 NaN NaN NaN NaN \n",
"4 NaN NaN NaN NaN \n",
"\n",
" parent_areaname1 parent_country parent_postcode \\\n",
"0 NaN NaN NaN \n",
"1 NaN NaN NaN \n",
"2 NaN NaN NaN \n",
"3 NaN NaN NaN \n",
"4 NaN NaN NaN \n",
"\n",
" domestic_ultimate_business_name domestic_ultimate_address \\\n",
"0 NaN NaN \n",
"1 NaN NaN \n",
"2 NaN NaN \n",
"3 NaN NaN \n",
"4 NaN NaN \n",
"\n",
" domestic_ultimate_street_address domestic_ultimate_areaname3 \\\n",
"0 NaN NaN \n",
"1 NaN NaN \n",
"2 NaN NaN \n",
"3 NaN NaN \n",
"4 NaN NaN \n",
"\n",
" domestic_ultimate_areaname1 domestic_ultimate_postcode \\\n",
"0 NaN NaN \n",
"1 NaN NaN \n",
"2 NaN NaN \n",
"3 NaN NaN \n",
"4 NaN NaN \n",
"\n",
" global_ultimate_indicator global_ultimate_business_name \\\n",
"0 N NaN \n",
"1 N NaN \n",
"2 N NaN \n",
"3 N NaN \n",
"4 N NaN \n",
"\n",
" global_ultimate_address global_ultimate_street_address \\\n",
"0 NaN NaN \n",
"1 NaN NaN \n",
"2 NaN NaN \n",
"3 NaN NaN \n",
"4 NaN NaN \n",
"\n",
" global_ultimate_areaname3 global_ultimate_areaname1 global_ultimate_country \\\n",
"0 NaN NaN NaN \n",
"1 NaN NaN NaN \n",
"2 NaN NaN NaN \n",
"3 NaN NaN NaN \n",
"4 NaN NaN NaN \n",
"\n",
" global_ultimate_postcode family_members hierarchy_code ticker_symbol \\\n",
"0 NaN 0.0 0.0 NaN \n",
"1 NaN 0.0 0.0 NaN \n",
"2 NaN 0.0 0.0 NaN \n",
"3 NaN 0.0 0.0 NaN \n",
"4 NaN 0.0 0.0 NaN \n",
"\n",
" exchange_name geom \n",
"0 NaN POINT (-96.39854 32.46993) \n",
"1 NaN POINT (-96.85800 32.71548) \n",
"2 NaN POINT (-97.10454 32.92683) \n",
"3 NaN POINT (-101.90211 33.57345) \n",
"4 NaN POINT (-95.41950 29.17028) "
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sql_query = \"\"\"\n",
" SELECT * except(do_label) FROM $dataset$ \n",
" WHERE SUB_CLASS = 'OFFICES AND CLINICS OF MEDICAL DOCTORS' \n",
" AND STABB = 'TX'\n",
" AND CAST(do_date AS date) >= (SELECT MAX(CAST(do_date AS date)) from $dataset$)\n",
"\"\"\"\n",
"pois = poi_dataset.to_dataframe(sql_query=sql_query)\n",
"pois.columns = list(map(str.lower, pois.columns))\n",
"pois.crs = 'epsg:4326'\n",
"pois.head()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(59554, 74)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pois.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3 Visualize data"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Map([Layer(tx_boundary, geom_col='geom',\n",
" style=basic_style(opacity=0, stroke_color='#11A579', stroke_width=5),\n",
" legends=basic_legend('Texas Boundary')),\n",
" Layer(pois.sample(5000), \n",
" style=basic_style(color='#F2B701', size=2, opacity=0.9, stroke_width=0),\n",
" popup_hover=[popup_element('name', 'Client'),\n",
" popup_element('employee_here', '# Employees')],\n",
" legends=basic_legend('Client Locations'))], \n",
" basemap=basemaps.darkmatter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. Discretize space. H3 grid\n",
"\n",
"A fundamental step in territory management is to discretize space. Territory management algorithms are computationally complex and hence it is crucial to leverage the spatial component to reduce complexity. We can do this by working at an aggregated level instead of considering each client location independently.\n",
"\n",
"We first need to identify the smallest spatial aggregation that makes sense for your business, our **geographic support**. This can be census block groups, zip codes or counties, or you can be interested in using a standard grid, in which case it would ideally be a hierarchical spatial index such as [Quadkey grid](https://docs.microsoft.com/en-us/azure/azure-maps/zoom-levels-and-tile-grid?tabs=csharp) or [H3 grid](https://eng.uber.com/h3/).\n",
"\n",
"In this notebook we will use an H3 grid of resolution 4. We can easily discretize space by performing a polyfill of the Texas boundary polygon. \n",
"\n",
"*Note* a buffer has been applied because H3 will fill the polygon with all hexagons of resolution 4 whose centroid lies within the polygon to be filled and we want to make sure the whole territory is covered."
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
"
],
"text/plain": [
" hex_id geometry \\\n",
"0 8426c81ffffffff POLYGON ((-96.74717 33.11534, -96.49922 33.244... \n",
"1 8426d59ffffffff POLYGON ((-100.92381 36.33036, -100.66884 36.4... \n",
"2 8448839ffffffff POLYGON ((-99.95645 28.45344, -99.71818 28.594... \n",
"3 8448f67ffffffff POLYGON ((-104.12891 29.69693, -103.89013 29.8... \n",
"4 8448b3bffffffff POLYGON ((-98.31519 26.24470, -98.08110 26.383... \n",
"\n",
" poi_count employee_avg \n",
"0 646 5.170673 \n",
"1 0 0.000000 \n",
"2 17 5.285714 \n",
"3 0 0.000000 \n",
"4 26 3.526316 "
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pois_g = gpd.sjoin(pois, grid, how='right').groupby('hex_id').agg({'geoid':'count', 'employee_here':'mean'}).\\\n",
" reset_index().rename(columns={'geoid':'poi_count', 'employee_here':'employee_avg'})\n",
"pois_g[['poi_count', 'employee_avg']] = pois_g[['poi_count', 'employee_avg']].fillna(0)\n",
"areas = grid.merge(pois_g, on='hex_id')\n",
"areas = gpd.GeoDataFrame(areas, crs='epsg:4326')\n",
"areas.head()"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"count 402.000000\n",
"mean 148.144279\n",
"std 709.392374\n",
"min 0.000000\n",
"25% 0.000000\n",
"50% 4.000000\n",
"75% 40.500000\n",
"95% 496.950000\n",
"max 8268.000000\n",
"Name: poi_count, dtype: float64"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"areas['poi_count'].describe(percentiles=[0.25, 0.5, 0.75, 0.95])"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breaks=[1, 4, 40, 500]\n",
"\n",
"Map(Layer(areas, \n",
" style=color_bins_style('poi_count', breaks=breaks),\n",
" legends=color_bins_legend('Number of Clients')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Territory Optimization\n",
"\n",
"Once we have our data aggregated, it's time to start working on building balanced territories.\n",
"\n",
"We will explore two different techniques:\n",
"- [KMeans clustering](https://en.wikipedia.org/wiki/K-means_clustering).\n",
"- [Max-p spatial clustering algorithm](https://region.readthedocs.io/en/latest/users/max-p-regions/). "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1 Approach 1. KMeans clustering\n",
"\n",
"This is a very well known and broadly used technique. However, this technique doesn't allow you to incorporate balancing criteria and usually generates low quality results for territory management."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.1.1. Calculate clusters"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Done!\n"
]
}
],
"source": [
"no_territories = 5\n",
"kmeans = KMeans(no_territories, random_state=1111)\n",
"\n",
"kmeans.fit_predict(list(map(lambda point:[point.x, point.y], areas.to_crs('epsg:26914').centroid)), \n",
" sample_weight=areas['poi_count'])\n",
"print('Done!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.1.2. Label grid cells\n",
"\n",
"We assign each cell to the cluster it belongs to.\n",
"\n",
"In order to have comparable results with other techniques, we identify 5 representative cells, each of which being far enough from each other to make sure they are in different clusters. This way, we can compare how each cluster changes."
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"areas['kmeans_cluster'] = kmeans.labels_\n",
"areas['kmeans_cluster'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [],
"source": [
"# This dictionary contains the representative cells with the cluster they represent.\n",
"trans_dict={'8448c69ffffffff':1,\n",
" '8426d47ffffffff':2,\n",
" '8426cdbffffffff':3,\n",
" '84446edffffffff':4,\n",
" '844880dffffffff':5}"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"areas['kmeans_cluster_aux'] = -1\n",
"for hex_id in trans_dict:\n",
" areas.loc[areas['kmeans_cluster'] == areas.loc[areas['hex_id'] == hex_id, 'kmeans_cluster'].iloc[0], 'kmeans_cluster_aux'] = trans_dict[hex_id]\n",
"areas['kmeans_cluster'] = areas['kmeans_cluster_aux']\n",
"areas.drop(columns='kmeans_cluster_aux', inplace=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We create a string variable with a more descriptive name for our visualization"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"areas['kmeans_cluster_cat'] = list(map(lambda v:f'Cluster_{v}', areas['kmeans_cluster']))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.1.3. Visualize and analyze results"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"KMeans calculates nice compact clusters (see map). However, we get very unbalanced clusters with Cluster_3 having 10 times more clients than Cluster_1, as can be seen in the chart below."
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Map(Layer(areas, \n",
" style=color_category_style('kmeans_cluster_cat', cat=sorted(areas['kmeans_cluster_cat'].unique())),\n",
" legends=color_category_legend('KMeans Clustering')))"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA1gAAAEYCAYAAABBWFftAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nO3deZwdZZ3v8U9naUQIIALKkAsBgZ8R8AYCXGAGERAXVLjhsigIA14umywOI8PgVVQyE1BAQBMWZXHQKA4aBUaRRYFhRxoXlvY3gOyCBkZlzUb3/FHVzqFJ0pV0nT59Tj7v1yuvPuepqqd+J6+HE779VD3V1d/fjyRJkiRp+Ma0ugBJkiRJ6hQGLEmSJEmqiQFLkiRJkmpiwJIkSZKkmhiwJEmSJKkm41pdQKe45557+ldeeeVWlyH9xfz581lppZVaXYb0Go5LjTaOSY02jsn28fLLLz87derUtQe3G7Bq0tXVxeTJk1tdhvQXvb29jkmNOo5LjTaOSY02jsn20dPT89ji2r1EUJIkSZJqYsCSJEmSpJoYsCRJkiSpJgasmnR3d7e6hGFbuGBRq0uQJEmS2pqLXNRkzJgxnPS+f2p1GcNy6jWfaXUJkiRJUltzBkuSJEmSamLAkiRJkqSaGLAkSZIkqSYGLEmSJEmqiQFLkiRJkmpiwJIkSZKkmhiwJEmSJKkmBixJkiRJqokBS5IkSZJqYsCSJEmSpJoYsCRJkiSpJgYsSZIkSaqJAUuSJEmSamLAkiRJkqSajBuJk0TEWOA4YP/ynN3AVcDJwAXAfZl5xnL2fS2wf2Y+W1O5A/2uAfw78PHMvLvOviVJkiR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rdR2SpKH5oGFJkkqZ+YFW17AEq1M8LFeSNMr5oGFJUseJiEnAfcAXgeOBV4AvZuY5EbExcDbw18AfgfOB0zOzPyJuBL6XmTOH6P8NZd/7U1wNciVwZGbOi4jdgFOBTYHfAp/OzB+Xx/UDW2TmfeX77wH3Zebny3PfAnwIeBtwD/C3wMvAY8AbgJeADTLzuWH/JUmSmsJLBCVJnWoV4J3ARODDwOcjYg/gOuAB4K3A7sDh5Z9l8Xlge+B/AhsCGwAnR8RmFGFrBrAm8Gng8ojYomK/HwWmlTV3ASdl5h+ADwDPZeaqhitJGt0MWJKkTvbJzHwpM3uAfwFmAWtQzCrNz8zfAF8CDl7Gfj8K/HNm/i4znwcOAi4CPgJcn5lzMnNROXN1JXBAxX6/lZmPZOafgR8AmyxjXZKkFvMeLElSp5qXmU81vH8SWAd4MDMXNbQ/RjFjtCzeUvYHQGY+CRAR65T9NVqW/uc2vF6IvwiVpLbjF7ckqVO9ISLe1PB+A4qV+NaLiMZfMG4I/H4Z+34KWG/gTURsHRHHAI8Dkwbt29h/H9DdsO3Ny3heSdIo5wyWJKmTnRoRx1HcK3UgsCfFohYzIuKzFOHnBGCpi1osxmzgpIi4E5gHnAbcAXwD+HRE7AVcAbwX2AN4V3ncfwB7RsQvgPdQ3Md1U4XzzacIjN2ZuWAZa5UkjSBnsCRJnexFilml7wLHZeZNFAtebA48A/yU4t6ps5ex33+mmA37BfAQRXA6JTMfAv438BngT8DpwP6Z+fPyuGOAvYA/A0cD3654vl8D9wPPlasgSpJGKZdplyR1nHKZ9keACZn5YovLkSStQJzBkiRJkqSaeA+WJEmDRMQzwKpL2PytzDxiJOuRJLUPLxGUJEmSpJp4iaAkSZIk1cSAJUmSJEk1MWBJkiRJUk0MWJIkSZJUEwOWJEmSJNXkvwBxrJ2W+o58ZAAAAABJRU5ErkJggg==\n",
"text/plain": [
"
"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plot_clinic_balance(sorted(areas['kmeans_cluster_cat'].unique()), areas, 'kmeans_cluster_cat', poi_count='sum')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2 Approach 2. Max-p\n",
"\n",
"Let's now try to balance the number of clients per cluster while maintaining connected clusters as compact as possible.\n",
"\n",
"We will use [Pysal's implementation of the Max-p algorithm](https://github.com/pysal/spopt). Max-p is a spatial clustering algorithm that calculates spatially connected clusters, with similar properties, while balancing one criterion, or mixed or criteria."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.2.1. Weights. Adjacency matrix\n",
"\n",
"The first thing we need to do is calculate the adjacency matrix which will tell the algorithm which cells are contiguous.\n",
"\n",
"We will use [Rook weights](https://pysal.org/libpysal/generated/libpysal.weights.Rook.html) which considers two polygons to be contiguous if they share one edge."
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"wgt = Rook.from_dataframe(areas, geom_col='geometry')"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(2, 7), (3, 25), (4, 35), (5, 33), (6, 302)]"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"wgt.histogram"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.2.2 Balancing criteria\n",
"\n",
"We would like to balance clusters based on total number of clients. Normally we are not looking for a perfect balance, especially when dealing with more than one multiple criteria, and a balance tolerance is introduced. In our case, we will consider a tolerance of 20%, which means that we allow clusters to be as much as 20% below the perfect balance.\n",
"\n",
"*Note* we are only using the number of clients to balance, but this dataset also has the number of employees per client and you might even have other data you might be interested in using. The good news is Max-p allows you to do that."
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {},
"outputs": [],
"source": [
"# Trick to help the algorithm find compact areas\n",
"areas['poi_count'] += 10"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Minimum number of clients per cluster 10807\n"
]
}
],
"source": [
"balance_tolerance = 0.15 # 15%\n",
"perfect_balance = areas['poi_count'].sum()/5\n",
"threshold = int(np.floor(perfect_balance * (1-balance_tolerance)))\n",
"print('Minimum number of clients per cluster', threshold)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 3.2.3. Similarity criteria\n",
"\n",
"Max-p also allows you to set similarity criteria. These are variables that you want to have a similar behavior **within clusters**. For example, you might be interested in having clusters with similar demographic or socioeconomic characteristics.\n",
"\n",
"In this case, we don't have any specific criteria, so we will use the gris cell centroid coordinates as similarity criteria in order to get clusters as compact as possible. You can try removing these or only adding one of the coordinates to clearly see whats the effect of these similarity criteria."
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"