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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8c83d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d179ded1-6235-47ed-bbfb-6d72468188d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ibis\n",
    "from ibis import _\n",
    "import streamlit as st\n",
    "import ibis.expr.datatypes as dt  # Make sure to import the necessary module\n",
    "\n",
    "\n",
    "conn = ibis.duckdb.connect(extensions=[\"spatial\"])\n",
    "\n",
    "# pres = conn.read_csv(\"sources-president.csv\")\n",
    "county = conn.read_csv(\"countypres_2000-2020.csv\")\n",
    "votes = conn.read_parquet(\"vote.parquet\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "170ba045-8848-4a99-a4f6-68bde22428af",
   "metadata": {},
   "source": [
    "# Getting party affiliations for counties"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab644102-c725-4cf4-915c-8550a0a74c32",
   "metadata": {},
   "outputs": [],
   "source": [
    "filtered = county.filter((_.mode == \"TOTAL\") & (_.totalvotes > 0))\n",
    "\n",
    "# Find the winning party for each year, state, and county\n",
    "most_votes = (\n",
    "    filtered\n",
    "    .group_by(['year', 'state_po', 'county_name', 'party'])\n",
    "    .aggregate(winning_votes=_.candidatevotes.sum())\n",
    ")\n",
    "\n",
    "# For each year, state, and county, select the party with the highest total votes\n",
    "winning_party = (\n",
    "    most_votes\n",
    "    .group_by('year', 'state_po', 'county_name')\n",
    "    .aggregate(\n",
    "        max_votes=_.winning_votes.max(),  # Max votes in this group\n",
    "    )\n",
    "    .join(\n",
    "        most_votes,\n",
    "        [\"year\",\"state_po\",\"county_name\",most_votes['winning_votes'] == _.max_votes],\n",
    "        how='inner'\n",
    "    )\n",
    "    .select(\"year\",\"state_po\",\"county_name\",most_votes['party'].name('current_party')\n",
    "    )\n",
    ")\n",
    "\n",
    "# Self-join to get the previous year's winning party\n",
    "previous_year = winning_party.view()\n",
    "\n",
    "joined = (\n",
    "    winning_party\n",
    "    .join(\n",
    "        previous_year, [\"county_name\",\"state_po\",winning_party['year'] == previous_year['year'] + 4],\n",
    "        how='left'\n",
    "    )\n",
    "    .rename(state_id = \"state_po\")\n",
    "    .mutate(key = _.county_name + ibis.literal(\" COUNTY-\") + _.state_id)\n",
    "    .select(\"year\",\"key\",\"current_party\",previous_year['current_party'].name('previous_party'))\n",
    ")\n",
    "\n",
    "county_parties = joined.filter(_.year >2000).order_by(\"year\")\n",
    "\n",
    "print(county_parties.execute())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce0d80bf-3b78-4aa9-8048-5cc0dbf970d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = (votes\n",
    "        .mutate(key = _.key.upper())\n",
    "        .filter(_.jurisdiction == \"Municipal\")\n",
    "        .join(county_parties, [\"key\",\"year\"],how='inner'\n",
    "        )\n",
    "        .cast({\"geometry\": \"geometry\"})\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "87bef5e2-a40a-4aff-aa27-e7d49ec68aac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The token has not been saved to the git credentials helper. Pass `add_to_git_credential=True` in this function directly or `--add-to-git-credential` if using via `huggingface-cli` if you want to set the git credential as well.\n",
      "Token is valid (permission: write).\n",
      "Your token has been saved to /home/rstudio/.cache/huggingface/token\n",
      "Login successful\n"
     ]
    }
   ],
   "source": [
    "import subprocess\n",
    "import os\n",
    "from huggingface_hub import HfApi, login\n",
    "import streamlit as st\n",
    "\n",
    "login(st.secrets[\"HF_TOKEN\"])\n",
    "# api = HfApi(add_to_git_credential=False)\n",
    "api = HfApi()\n",
    "\n",
    "def hf_upload(file, repo_id):\n",
    "    info = api.upload_file(\n",
    "            path_or_fileobj=file,\n",
    "            path_in_repo=file,\n",
    "            repo_id=repo_id,\n",
    "            repo_type=\"dataset\",\n",
    "        )\n",
    "def generate_pmtiles(input_file, output_file, max_zoom=12):\n",
    "    # Ensure Tippecanoe is installed\n",
    "    if subprocess.call([\"which\", \"tippecanoe\"], stdout=subprocess.DEVNULL) != 0:\n",
    "        raise RuntimeError(\"Tippecanoe is not installed or not in PATH\")\n",
    "\n",
    "    # Construct the Tippecanoe command\n",
    "    command = [\n",
    "        \"tippecanoe\",\n",
    "        \"-o\", output_file,\n",
    "        \"-zg\",\n",
    "        \"--extend-zooms-if-still-dropping\",\n",
    "        \"--force\",\n",
    "        \"--projection\", \"EPSG:4326\",  \n",
    "        input_file\n",
    "    ]\n",
    "\n",
    "    # Run Tippecanoe\n",
    "    try:\n",
    "        subprocess.run(command, check=True)\n",
    "        print(f\"Successfully generated PMTiles file: {output_file}\")\n",
    "    except subprocess.CalledProcessError as e:\n",
    "        print(f\"Error running Tippecanoe: {e}\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b086e76c-4285-4036-8033-e4e45cb6966b",
   "metadata": {},
   "outputs": [],
   "source": [
    "gdf= df.execute()\n",
    "gdf = gdf.set_crs(\"EPSG:4326\")\n",
    "\n",
    "# gdf.to_parquet(\"county_parties.parquet\")\n",
    "# hf_upload(\"county_parties.parquet\", \"boettiger-lab/landvote\")\n",
    "\n",
    "# gdf.to_file(\"county_parties.geojson\")\n",
    "# hf_upload(\"county_parties.geojson\", \"boettiger-lab/landvote\")\n",
    "\n",
    "# generate_pmtiles(\"county_parties.geojson\", \"county_parties.pmtiles\")\n",
    "# hf_upload(\"county_parties.pmtiles\", \"boettiger-lab/landvote\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6193c4b9-0183-4aae-9a25-899a748fd65e",
   "metadata": {},
   "source": [
    "# Checking map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2ae8ada-c73e-4b2e-938e-70a29584f199",
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap.maplibregl as leafmap\n",
    "m = leafmap.Map(style=\"positron\")\n",
    "\n",
    "\n",
    "url_states = \"https://huggingface.co/datasets/boettiger-lab/landvote/resolve/main/county_parties.pmtiles\"\n",
    "\n",
    "outcome = [\n",
    "      'match',\n",
    "      ['get', 'Status'], \n",
    "      \"Pass\", '#2E865F',\n",
    "      \"Fail\", '#FF3300', \n",
    "      '#ccc'\n",
    "    ]\n",
    "paint_states = {\"fill-color\": outcome, \n",
    "         # \"fill-opacity\": 0.2,\n",
    "        }\n",
    "style_states = {\n",
    "    \"layers\": [\n",
    "        {\n",
    "            \"id\": \"county_parties\",\n",
    "            \"source\": \"county_parties\",\n",
    "            \"source-layer\": \"county_parties\",\n",
    "            \"type\": \"fill\",\n",
    "            \"filter\": [\n",
    "                \"==\",\n",
    "                [\"get\", \"year\"],\n",
    "                2008,\n",
    "            ],  # only show buildings with height info\n",
    "            \"paint\": paint_states\n",
    "        },\n",
    "    ],\n",
    "}\n",
    "\n",
    "m.add_pmtiles(\n",
    "    url_states,\n",
    "    style=style_states,\n",
    "    visible=True,\n",
    "    opacity=0.4,\n",
    "    tooltip=True,\n",
    "    fit_bounds=False,\n",
    ")\n",
    "\n",
    "m\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c12fd16-a953-4273-9e0f-44b50eacf633",
   "metadata": {},
   "source": [
    "# Getting Municipals "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3429fea-7c0d-4838-bcbb-6552079dc3b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "localities_boundaries = \"us_localities.parquet\"\n",
    "locality = conn.read_parquet(localities_boundaries)\n",
    "landvote = conn.read_csv(\"landvote.csv\")\n",
    "\n",
    "#needed to redo this, since I didn't save county in \"votes.parquet\". \n",
    "vote_local = (landvote\n",
    "                .filter(_[\"Jurisdiction Type\"] == \"Municipal\")\n",
    "                .rename(city = \"Jurisdiction Name\", state_id = \"State\")\n",
    "                .mutate(key = _.city + ibis.literal('-') + _.state_id)\n",
    "                .rename(amount = 'Conservation Funds at Stake', yes = '% Yes')\n",
    "                .mutate(amount_n=_.amount.replace('$', '').replace(',', '').cast('float'))\n",
    "                .mutate(log_amount=_.amount_n.log())\n",
    "                .mutate(year=_['Date'].year().cast('int32'))\n",
    "                .mutate(\n",
    "                    yes=ibis.case()\n",
    "                        .when(_.yes.isin(['Pass', 'None','Fail']), None)  # Handle non-numeric cases\n",
    "                        .when(_.yes.notnull(), (_.yes.replace('%', '').cast('float').round(2).cast(dt.float64)).cast(dt.string) + '%')  # Convert valid percentages and add %\n",
    "                        .else_(None)  # Default to None for other cases\n",
    "                        .end()\n",
    "                )\n",
    "              .mutate(log_amount = _.log_amount.round(4))\n",
    "                .select('key', 'Status', 'yes', 'year', 'amount', 'log_amount', )\n",
    "                )\n",
    "\n",
    "# getting the county parties for each municipal  \n",
    "df_municipals = (locality \n",
    "            .mutate(key_municipal = _.name + ibis.literal('-') + _.state_id) \n",
    "            .mutate(key = (_.county + ibis.literal('-') + _.state_id).upper()) \n",
    "            .select('key', 'geometry','key_municipal','name')\n",
    "            .right_join(vote_local, [_.key_municipal == vote_local[\"key\"]])\n",
    "            .mutate(jurisdiction = ibis.literal(\"Municipal\"))\n",
    "            .cast({\"geometry\": \"geometry\"})\n",
    "            .mutate(geometry = _.geometry.buffer(.07))\n",
    "            .join(county_parties, [\"key\",\"year\"],how='inner')\n",
    "            .rename(county = \"key\")\n",
    "            .rename(key = \"key_municipal\")\n",
    "            .select('key','geometry','Status','yes','year','amount','log_amount','jurisdiction','current_party','previous_party')\n",
    "           )\n",
    "\n",
    "\n",
    "gdf_municipals = df_municipals.execute()\n",
    "gdf_municipals = gdf_municipals.set_crs(\"EPSG:4326\")\n",
    "gdf_municipals\n",
    "\n",
    "\n",
    "# gdf_municipals.to_parquet(\"municipal_parties.parquet\")\n",
    "# hf_upload(\"municipal_parties.parquet\", \"boettiger-lab/landvote\")\n",
    "\n",
    "# gdf_municipals.to_file(\"municipal_parties.geojson\")\n",
    "# hf_upload(\"municipal_parties.geojson\", \"boettiger-lab/landvote\")\n",
    "\n",
    "# generate_pmtiles(\"municipal_parties.geojson\", \"municipal_parties.pmtiles\")\n",
    "# hf_upload(\"municipal_parties.pmtiles\", \"boettiger-lab/landvote\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06e24a7e-5f7f-42bc-b515-43082016d496",
   "metadata": {},
   "source": [
    "# Get States"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "217170ca-b732-4875-b4cb-f8a8cd2fc405",
   "metadata": {},
   "outputs": [],
   "source": [
    "states = (conn\n",
    "          .read_csv(\"1976-2020-president.csv\")\n",
    "          .filter(_. year >=2000)\n",
    "         )\n",
    "# states.execute()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "322b9a85-bdf9-45f9-9b19-695cc1b996e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     year key current_party previous_party\n",
      "0    2004  HI      DEMOCRAT       DEMOCRAT\n",
      "1    2004  ME      DEMOCRAT       DEMOCRAT\n",
      "2    2004  NJ      DEMOCRAT       DEMOCRAT\n",
      "3    2004  NM    REPUBLICAN       DEMOCRAT\n",
      "4    2004  ND    REPUBLICAN     REPUBLICAN\n",
      "..    ...  ..           ...            ...\n",
      "250  2020  VT      DEMOCRAT       DEMOCRAT\n",
      "251  2020  AL    REPUBLICAN     REPUBLICAN\n",
      "252  2020  IA    REPUBLICAN     REPUBLICAN\n",
      "253  2020  SD    REPUBLICAN     REPUBLICAN\n",
      "254  2020  GA      DEMOCRAT     REPUBLICAN\n",
      "\n",
      "[255 rows x 4 columns]\n"
     ]
    }
   ],
   "source": [
    "# filtered = county.filter((_.mode == \"TOTAL\") & (_.totalvotes > 0))\n",
    "\n",
    "# Find the winning party for each year, state, and county\n",
    "most_votes= (\n",
    "    states\n",
    "    .group_by(['year', 'state_po', 'party_simplified'])\n",
    "    .aggregate(winning_votes=_.candidatevotes.sum())\n",
    ")\n",
    "\n",
    "# For each year, state, and county, select the party with the highest total votes\n",
    "winning_party = (\n",
    "    most_votes\n",
    "    .group_by('year', 'state_po')\n",
    "    .aggregate(\n",
    "        max_votes=_.winning_votes.max(),  # Max votes in this group\n",
    "    )\n",
    "    .join(\n",
    "        most_votes,\n",
    "        [\"year\",\"state_po\",most_votes['winning_votes'] == _.max_votes],\n",
    "        how='inner'\n",
    "    )\n",
    "    .select(\"year\",\"state_po\",most_votes['party_simplified'].name('current_party')\n",
    "    )\n",
    ")\n",
    "\n",
    "# Self-join to get the previous year's winning party\n",
    "previous_year = winning_party.view()\n",
    "\n",
    "joined = (\n",
    "    winning_party\n",
    "    .join(\n",
    "        previous_year, [\"state_po\",winning_party['year'] == previous_year['year'] + 4],\n",
    "        how='left'\n",
    "    )\n",
    "    .rename(key = \"state_po\")\n",
    "    # .mutate(key = _.county_name + ibis.literal(\" COUNTY-\") + _.state_id)\n",
    "    .select(\"year\",\"key\",\"current_party\",previous_year['current_party'].name('previous_party'))\n",
    ")\n",
    "\n",
    "state_parties = joined.filter(_.year >2000).order_by(\"year\")\n",
    "\n",
    "print(state_parties.execute())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "2c03920e-76da-4034-8eaf-1e80a56f5b0d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3574af6546ff4cd1949e27c63cd15cd7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "states_parties.parquet:   0%|          | 0.00/2.36M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "For layer 0, using name \"states_parties\"\n",
      "12 features, 833591 bytes of geometry and attributes, 542 bytes of string pool, 0 bytes of vertices, 0 bytes of nodes\n",
      "Choosing a maxzoom of -z0 for features typically 7514540 feet (2290432 meters) apart, and at least 2073685 feet (632060 meters) apart\n",
      "Choosing a maxzoom of -z10 for resolution of about 376 feet (114 meters) within features\n",
      "  99.9%  10/271/383  \n",
      "  100.0%  10/187/380  \r"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully generated PMTiles file: states_parties.pmtiles\n"
     ]
    }
   ],
   "source": [
    "# state_boundaries = \"https://data.source.coop/cboettig/us-boundaries/us-state-territory.parquet\"\n",
    "states = conn.read_parquet(\"vote_states.parquet\")\n",
    "\n",
    "df_states = (states\n",
    "        .mutate(key = _.key.upper())\n",
    "        # .filter(_.jurisdiction == \"Municipal\")\n",
    "        .join(state_parties, [\"key\",\"year\"],how='inner'\n",
    "        )\n",
    "        .cast({\"geometry\": \"geometry\"})\n",
    ")\n",
    "\n",
    "gdf_states = df_states.execute()\n",
    "gdf_states = gdf_states.set_crs(\"EPSG:4326\")\n",
    "gdf_states\n",
    "\n",
    "\n",
    "gdf_states.to_parquet(\"states_parties.parquet\")\n",
    "hf_upload(\"states_parties.parquet\", \"boettiger-lab/landvote\")\n",
    "\n",
    "gdf_states.to_file(\"states_parties.geojson\")\n",
    "hf_upload(\"states_parties.geojson\", \"boettiger-lab/landvote\")\n",
    "\n",
    "generate_pmtiles(\"states_parties.geojson\", \"states_parties.pmtiles\")\n",
    "hf_upload(\"states_parties.pmtiles\", \"boettiger-lab/landvote\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcf5d049-68ae-4d73-be77-72d985c9ed1c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}