Year in Review 2024

Past year in review posts I have made focused on showing blog stats. Writing this in early December, but total views will likely be down this year – I am projecting around 140,000 views in total for this site. But I have over 25k views for the Crime De-Coder site, so it is pretty much the same compared to 2023 combining the two sites.

I do not have a succinct elevator speech to tell people what I am working on. With the Crime De-Coder consulting gig, it can be quite eclectic. That Tukey quote being a statistician you get to play in everyone’s backyard is true. Here is a rundown of the paid work I conducted in the past year.

Evidence Based CompStat: Work with Renee Mitchell and the American Society of Evidence Based Policing on what I call Evidence Based CompStat. This mostly amounts to working directly with police departments (it is more project management than crime analysis) to help them get started with implementing evidence based practices. Reach out if that sounds like something your department would be interested in!

Estimating DV Violence: Work supported by the Council on CJ. I forget exactly the timing of events. This was an idea I had for a different topic (to figure out why stores and official reports of thefts were so misaligned). Alex approached me to help with measuring national level domestic violence trends, and I pitched this idea (use local NIBRS data and NCVS to get better local estimates).

Premises Liability: I don’t typically talk about ongoing cases, but you can see a rundown of some of the work I have done in the past. It is mostly using the same stats I used as a crime analyst, but in reference to civil litigation cases.

Patrol Workload Analysis: I would break workload analysis for PDs down into two categories, advanced stats and CALEA reports. I had one PD interested in the simpler CALEA reporting requirement (which I can do for quite a bit cheaper than the other main consulting firm that offers these services).

Kansas City Python Training: Went out to Kansas City for a few days to train their analysts up in using python for Focused Deterrence. If you think the agenda in the pic below looks cool get in touch, I would love to do more of these sessions with PDs. I make it custom for the PD based on your needs, so if you want “python and ArcGIS”, or “predictive models” or whatever, I will modify the material to go over those advanced applications. I have also been pitching the same idea (short courses) for PhD programs. (So many posers in private sector data science, I want more social science PhDs with stronger tech skills!)

Patterson Opioid Outreach: Statistical consulting with Eric Piza and Kevin Wolff on a street outreach intervention intended to reduce opioid overdose in Patterson New Jersey. I don’t have a paper to share for that at the moment, but I used some of the same synthetic control in python code I developed.

Bookstore prices: Work with Scott Jacques, supported by some internal GSU money. Involves scraping course and bookstore data to identify the courses that students spend the most on textbooks. Ultimate goal in mind is to either purchase those books as unlimited epubs (to save the students money), or encourage professors to adopt better open source materials. It is a crazy amount of money students pour into textbooks. Several courses at GSU students cumulatively spend over $100k on course materials per semester. (And since GSU has a large proportion of Pell grant recipients, it means the federal government subsidizes over half of that cost.)

General Statistical Consulting: I do smaller stat consulting contracts on occasion as well. I have an ongoing contract to help with Pam Metzger’s group at the SMU Deason center. Did some small work for AH Datalytics on behind the scenes algorithms to identify anomalous reporting for the real time crime index. I have several times in my career consulted on totally different domains as well, this year had a contract on calculating regression spline curves for some external brain measures.

Data Science Book: And last (that I remember), I published Data Science for Crime Analysis with Python. I still have not gotten my 100 sales I would consider it a success – so if you have not bought a copy go do that right now. (Coupon code APWBLOG will get you $10 off for the next few weeks, either the epub or the paperback.)

Sometimes this seems like I am more successful than I am. I have stopped counting the smaller cold pitches I make (I should be more aggressive with folks, but most of this work is people reaching out to me). But in terms of larger grant proposals or RFPs in that past year, I have submitted quite a few (7 in total) and have landed none of them to date! Submitted a big one to support surveys that myself and Gio won the NIJ competition on for place based surveys to NIJ in their follow up survey solicitation, and it was turned down for example. So it goes.

In addition to the paid work, I still on occasion publish peer reviewed articles. (I need to be careful with my time though.) I published a paper with Kim Rossmo on measuring the buffer zone in journey to crime data. I also published the work on measuring domestic violence supported by the Council on CJ with Alex Piquero.

I took the day gig in Data Science at the end of 2019. Citations are often used as a measure of a scholars influence on the field – they are crazy slow though.

I had 208 citations by the end of 2019, I now have over 1300. Of the 1100 post academia, only a very small number are from articles I wrote after I left (less than 40 total citations). A handful for the NIJ recidivism competition paper (with Gio), and a few for this Covid and shootings paper in Buffalo. The rest of the papers that have a post 2019 publishing date were entirely written before I left academia.

Always happy to chat with folks on teaming up on papers, but it is hard to take the time to work on a paper for free if I have other paid work at the moment. One of the things I need to do to grow the business is to get some more regular work. So if you have a group (academic, think tank, public sector) that is interested in part time (or fractional I guess is what the cool kids are calling it these days), I would love to chat and see if I could help your group out.

Question Sets and All Paths

I was nerd-sniped with a question at work the other day. The set up was like this, imagine a survey where all of the questions have yes-no answers. Some of the answers are terminating, so if you answer No to a particular question, the questions stop. But some if you reach that part of the tree will keep going.

The ask was a formula to articulate the total number of potential unique answer sets. Which I was not able to figure out, I did however write python code to generate all of the unique sets. So here is that function, where I create a networkx directed graph in a particular format, and then find all of the potential start to end paths in that graph. You just add a dummy begin node, and end nodes at the terminating locations and the final question. You then just search for all of the paths from the begin to end nodes.

import networkx as nx

def question_paths(totq,term):
    '''
    totq -- positive integer, total number of questions
    term -- list of integers, where ints are questions that terminate
    '''
    nodes = [f'Q{i}{r}' for i in range(totq) for r in ['N','Y']]
    edges = []
    for i in range(totq-1):
        edges.append([f'Q{i}Y',f'Q{i+1}N'])
        edges.append([f'Q{i}Y',f'Q{i+1}Y'])
        if i not in term:
            edges.append([f'Q{i}N',f'Q{i+1}N'])
            edges.append([f'Q{i}N',f'Q{i+1}Y'])
    # adding in begin/end
    nodes += ['Begin','End']
    edges += [['Begin','Q0N'],['Begin','Q0Y']]
    for t in term:
        edges.append([f'Q{t}N','End'])
    edges += [[f'Q{totq-1}N','End'],[f'Q{totq-1}Y','End']]
    # Now making graph
    G = nx.DiGraph()
    G.add_nodes_from(nodes)
    G.add_edges_from(edges)
    # Getting all paths
    paths = []
    for p in nx.all_simple_paths(G,source='Begin',target='End'):
        nicer = [v[-1] for v in p[1:-1]]
        paths.append(nicer)
    return paths

And now we can check out where all paths are terminating, you only get further up the tree if you answer all yes for prior questions.

>>> question_paths(3,[0,1,2])
[['N'],
 ['Y', 'N'],
 ['Y', 'Y', 'N'],
 ['Y', 'Y', 'Y']]

So in that scenario we have four potential answer sets. For all binary, we have the usual 2^3 number of paths:

>>> question_paths(3,[])
[['N', 'N', 'N'],
 ['N', 'N', 'Y'],
 ['N', 'Y', 'N'],
 ['N', 'Y', 'Y'],
 ['Y', 'N', 'N'],
 ['Y', 'N', 'Y'],
 ['Y', 'Y', 'N'],
 ['Y', 'Y', 'Y']]

And then you can do a mixture, here just question 2 terminates, but 1/3 are binary:

>>> question_paths(3,[1])
[['N', 'N'],
 ['N', 'Y', 'N'],
 ['N', 'Y', 'Y'],
 ['Y', 'N'],
 ['Y', 'Y', 'N'],
 ['Y', 'Y', 'Y']]

One of the things doing this exercise taught me is that it matters where the terminating nodes are in the tree. Earlier terminating nodes results in fewer potential paths.

# can different depending on where the terminators are
len(question_paths(10,[1,5])) # 274
len(question_paths(10,[6,8])) # 448
len(question_paths(10,[0,1])) # 258
len(question_paths(10,[8,9])) # 768

So the best in terms of a formula for the total number of paths I could figure out was 2^(non-terminating questions) <= paths <= 2^(questions) (which is not a very good bound!) I was trying to figure out a product formula but was unable (any suggestions let me know!)

This reminds me of a bit of product advice from Jennifer Pahlka, you should have eliminating questions earlier in the form. So instead of filling out 100 questions and at the end being denied for TANF, you ask questions that are the most likely to eliminate people first.

It works the same for total complexity of your application. So asking the terminating questions earlier reduces the potential number of permutations you ultimately have in your data as well. Good for the user and good for the developers.

Suits, Money Laundering, and Linear Programming

Currently watching Suits with the family, and an interesting little puzzle came up in the show. In Season 1, episode 8, there is a situation with money laundering from one account to many smaller accounts.

So the set up is something like “transfer out 100 million”, and then you have some number of smaller accounts that sum to 100 million.

When Lewis brought this up in the show, and Mike had a stack of papers to go through to identify the smaller accounts that summed up to the larger account, my son pointed out it would be too difficult to go through all of the permutations to figure it out. The total number of permutations would be something like:

N = Sum(b(A choose k) for 1 to k)

Where A is the total number of accounts to look over, and k is the max number of potential accounts the money was spread around. b(A choose k) is my cheeky text format for binomial coefficients.

So this will be a very large number. 10,000 choose 4 for example is 416 416 712 497 500 – over 416 trillion. You still need to add in b(10,000 choose 2) + b(10,000 choose 3) + ….. b(10,000 choose k). With even a small number of accounts, the number of potential combinations will be very large.

But, I said in response to my son I could write a linear program to find them. And this is what this post shows, but doing so made me realize there are likely too many permutations in real data to make this a feasible approach in conducting fraud investigations. You will have many random permutations that add up to the same amount. (I figured some would happen, but it appears to me many happen in random data.)

(Note I have not been involved with any financial fraud examinations in my time as an analyst, I would like to get a CFA time permitting, and if you want to work on projects let me know! So all that said, I cannot speak to the veracity of whether this is a real thing people do in fraud examinations.)

So here I use python and the pulp library (and its default open source CBC solver) to show how to write a linear program to pick bundles of accounts that add up to the right amount. First I simulate some lognormal data, and choose 4 accounts at random.

import pulp
import numpy as np

# random values
np.random.seed(10)
simn = 10000
x = np.round(np.exp(np.random.normal(loc=5.8,scale=1.2,size=simn)),2)

# randomly pick 4
slot = np.arange(0,simn)
choice = np.random.choice(slot,size=4,replace=False)
tot = x[choice].sum()
print(tot,choice)

So we are expecting the answer to be accounts 2756 5623 5255 873, and the solution adds up to 1604.51. So the linear program is pretty simple.

# make a linear program
P = pulp.LpProblem("Bundle",pulp.LpMinimize)
D = pulp.LpVariable.dicts("D",slot,cat='Binary')

# objective selects smallest group
P += pulp.lpSum(D)

# Constraint, equals the total
P += pulp.lpSum(D[i]*x[i] for i in range(simn)) == tot

# Solving with CBC
P.solve()

# Getting the solution
res = []
for i in range(simn):
    if D[i].varValue == 1:
        res.append(i)

In practice you will want to be careful with floating point (later I convert the account values to ints, another way though is instead of the equal constraint, make it <= tot + eps and >= tot - eps, where eps = 0.001. But for the CBC solver this ups the time to solve by quite a large amount.)

You could have an empty objective function (and I don’t know the SAT solvers as much, I am sure you could use them to find feasible solutions). But here I have the solution by the minimal number of accounts to look for.

So here is the solution, as you can see it does not find our expected four accounts, but two accounts that also add up to 1604.51.

You can see it solved it quite fast though, so maybe we can just go through all the potential feasible solutions. I like making a python class for this, that contains the “elimination” constraints to prevent that same solution from coming up again.

# Doing elimination to see if we ever get the right set
class Bundle:
    def __init__(self,x,tot,max_bundle=10):
        self.values = (x*100).astype('int')
        self.totn = len(x)
        self.tot = int(round(tot*100))
        self.pool = []
        self.max_bundle = max_bundle
        self.prob_init()
    def prob_init(self):
        P = pulp.LpProblem("Bundle",pulp.LpMinimize)
        D = pulp.LpVariable.dicts("D",list(range(self.totn)),cat='Binary')
        # objective selects smallest group
        P += pulp.lpSum(D)
        # Constraint, equals the total
        P += pulp.lpSum(D[i]*self.values[i] for i in range(simn)) == self.tot
        # Max bundle size constraint
        P += pulp.lpSum(D) <= self.max_bundle
        self.prob = P
        self.d = D
    def getsol(self,solver=pulp.PULP_CBC_CMD,solv_kwargs={'msg':False}):
        self.prob.solve(solver(**solv_kwargs))
        if self.prob.sol_status != -1:
            res = []
            for i in range(self.totn):
                if self.d[i].varValue == 1:
                    res.append(i)
            res.sort()
            self.pool.append(res)
            # add in elimination constraints
            self.prob += pulp.lpSum(self.d[r] for r in res) <= len(res)-1
            return res
        else:
            return -1
    def loop_sol(self,n,solver=pulp.PULP_CBC_CMD,solv_kwargs={'msg':False}):
        for i in range(n):
            rf = self.getsol(solver,solv_kwargs)
            if rf != 1:
                print(f'Solution {i}:{rf} sum: {self.values[rf].sum()}')
            if rf == -1:
                print(f'No more solutions at {i}')
                break

And now we can run through and see if the correct solution comes up:

be = Bundle(x=x,tot=tot)
be.loop_sol(n=10)

Uh oh – I do not feel like seeing how many potential two solutions there are in the data (it is small enough I could just enumerate those directly). So lets put a constraint in that makes it so it needs to be four specific accounts that add up to the correct amount.

# add in constraint it needs to be 4 selected
choice.sort()
be.prob += pulp.lpSum(be.d) == 4
print(f'Should be {choice}')
be.loop_sol(n=10)

And still no dice. I could let this chug away all night and probably come up with the set I expected at some point. But if you have so many false positives, this will not be very useful from an investigative standpoint. So you would ultimately need more constraints.

Lets say our example the cumulative total will be quite large. Will that help limit the potential feasible solutions?

# Select out a sample of high
sel2 = np.random.choice(x[x > 5000],size=4,replace=False)
tot2 = sel2.sum()
ch2 = np.arange(simn)[np.isin(x,sel2)]
ch2.sort()
print(tot2,ch2)

be2 = Bundle(x=x,tot=tot2)
be2.loop_sol(n=20)

There are still too many potential feasible solutions. I thought maybe a problem with real data is that you will have fixed numbers, say you are looking at transactions, and you have specific $9.99 transactions. If one of those common transactions results in a total sum, it will just be replicated in the solution over and over again. I figured with random data the sum would still be quite unique, but I was wrong for that.

So I was right in that I could write a linear program to find the solution. I was wrong that there would only be one solution!

Some things work

A lawyer and economist Megan Stevenson last year released an essay that was essentially “Nothing Works” 2.0. For those non-criminologists, “nothing works” was a report by Robert Martinson in the 1970’s that was critical of the literature on prisoner rehabilitation, and said to date that essentially all attempts at rehabilitation were ineffective.

Martinson was justified. With the benefit of hindsight, most of the studies Martinson critiques were poorly run (in terms of randomization, they almost all were observational self selected into treatment) and had very low statistical power to detect any benefits. (For people based experiments in CJ, think you typically need 1000+ participants, not a few dozen.)

Field experiments are hard and messy, and typically we are talking about “reducing crime by 20%” or “reducing recidivism by 10%” – they are not miracles. You can only actually know if they work using more rigorous designs that were not used at that point in social sciences.

Stevenson does not deny those minor benefits exist, but moves the goalposts to say CJ experiments to date have failed because they do not generate wide spread sweeping change in CJ systems. This is an impossible standard, and is an example of the perfect being the enemy of the good fallacy.

A recent piece by Brandon del Pozo and colleagues critiques Stevenson, which I agree with the majority of what Brandon says. Stevenson’s main critique are not actually with experiments, but more broadly organizational change (which del Pozo is doing various work in now).

Stevenson’s critique is broader than just policing, but I actually would argue that the proactive policing ideals of hotspots and focused deterrence have diffused into the field broadly enough that her points about systematic change are false (at least in those two examples). Those started out as individual projects though, and only diffused through repeated application in a slow process.

As I get older, am I actually more of the engineer mindset that Stevenson is critical of. As a single person, I cannot change the whole world. As a police officer or crime analyst or professor, you cannot change the larger organization you are a part of. You can however do one good thing at a time.

Even if that singular good thing you did is fleeting, it does not make it in vain.

References

GenAI is not a serious solution to California’s homeless problem

This is a rejected op-ed (or at least none of the major papers in California I sent it to bothered to respond and say no-thanks, it could be none of them even looked at it). Might as well post it on personal blog and have a few hundred folks read it.


Recently Gov. Newsom released a letter of interest (LOI) for different tech companies to propose how the state could use GenAI (generative artificial intelligence) to help with California’s homeless problem. The rise in homelessness is a major concern, not only for Californian’s but individuals across the US. That said, the proposal is superficial and likely to be a waste of time.

A simple description of GenAI, for those not aware, are tools to ask the machine questions in text and get a response. So you can ask ChatGPT (a currently popular GenAI tool) something like “how can I write a python function to add two numbers together” and it will dutifully respond with computer code (python is a computer programming language) that answers your question.

As someone who writes code for a living, this is useful, but not magic. Think of it more akin to auto-complete on your phone than something truly intelligent. The stated goals of Newsom’s LOI are either mostly trivial without the help of GenAI, or are hopeless and could never be addressed with GenAI.

For the first stated goal, “connecting people to treatment by better identifying available shelter and treatment beds, with GenAI solutions for a portable tool that the local jurisdictions can use for real-time access to treatment and shelter bed availability”. This is simply describing a database — one could mandate state funded treatment providers to provide this information on a daily basis. The technology infrastructure to accomplish this is not much more complex than making a website. Mandating treatment providers report that information accurately and on a timely basis is the hardest part.

For the second stated goal, “Creating housing with more data and accountability by creating clearer insights into local permitting and development decisions”. Permitting decisions are dictated by the state as well as local ordinances. GenAI solutions will not uncover any suggested solution that most Californian’s don’t already know — housing is too expensive and not enough is being built. This is in part due to the regulatory structure, as well as local zoning opposition for particular projects. GenAI cannot change the state laws.

For the last stated goal of the program, “Supporting the state budget by helping state budget analysts with faster and more efficient policy”. Helping analysts generate results faster is potentially something GenAI can help with, more efficient policy is not. I do not doubt the state analysts can use GenAI solutions to help them write code (the same as I do now). But getting that budget analysis one day quicker will not solve any substantive homeless problem.

I hate to be the bearer of bad news, but there are no easy answers to solve California’s homeless crisis. If a machine could spit out trivial solutions to solve homelessness in a text message, like the Wizard of Oz gifting the Scarecrow brains, it would not be a problem to begin with.

Instead of asking for ambiguous GenAI solutions, the state would be better off thinking more seriously about how they can accomplish those specific tasks mentioned in the LOI. If California actually wants to make a database of treatment availability, that is something they could do right now with their own internal capacity.

Solutions to homelessness are not going to miraculously spew from a GenAI oracle, they are going to come from real people accomplishing specific goals.


If folks are reading this, check out my personal consulting firm, Crime De-Coder. I have experience building real applications. Most of the AI stuff on the market now is pure snake oil, so better to articulate what you specifically want and see if someone can help build that.

Crime De-Coder consulting

Types of websites and trade-offs

For some minor updates on different fronts. I have a new blog post on Crime De-Coder about how to figure out the proper ODBC connection string to query your record management system. I have done this song and dance with maybe a dozen different PDs at this point (and happened to do it twice in the prior week), so figured a post would make sense.

Two, article with Kim Rossmo has been published, The journey-to-crime buffer zone: Measurement issues and methodological challenges. Can check out the github repo and CrimRXiv version for free.

Main reason I wanted to make a post today about the types of websites. I have seen several influencers discuss using GenAI to create simple apps. These tools are nice, but many seem to make bad architecture decisions from the start (many people should not be making python served websites). So I will break down a few of the different options for creating a website in this post.

The most basic is a static html site – this just requires you create the HTML and place it somewhere on a server. A free option is github pages. You can still use javascript apps, but they are run client side and there is no real ability to limit who can see the site (e.g. you cannot make it password protected to log in). These can handle as much traffic as you want. If you have data objects in the site (such as a dashboard) the objects just need to be stored directly on the server (e.g. in json files or csv if you want to parse them). You can build data dashboards using D3 or other WASM apps.

The other types of websites you can do anything you can in HTML, so I focus more on what makes them different.

PHP sites – this probably requires you to purchase an online server (ignoring self hosting in your closet). There are many low cost vendors (my Crime De-Coder site is PHP on Hostinger. But they are pretty low price, think $5 per month. These do have the ability to create password protected content and have server side functions hidden. My $5 a month website has a service level agreement to handle 20k responses per day, it also has a built in MySQL database that can hold 2 gig of data for my plan. (These cheap sites are not bad if all you want is a smallish database.) WordPress is PHP under the hood (although if you want a custom site, I would just start from scratch and not modify WordPress. WordPress is good to use a GUI to style the site with basic templates.)

IMO if you need to protect stuff behind a server, and have fairly low traffic requirements, using a PHP site is a very good and cheap option. (For higher traffic I could pay under $20 a month for a beefier machine as well, we are talking crazy site traffic like well over 100k visits per day before you need to worry about it.)

Node.js – this is a server technology, popular for various apps. It is javascript under the hood, but you can have stuff run server side (so can be hidden from end user, same as PHP). The tech to host a site is a bit more involved than the PHP hosting sites. You can either get a VPS (for typically less than $10 a month, and can probably handle close to the same amount of traffic as the cheap PHP), and write some code to host it yourself. Think of a VPS as renting a machine (so can be used for various things, not just webhosting.) Or use some more off the shelf platform (like FlyIO, which has variable pricing). You typically need to think about a separate database hosting as well with these tools though. (I like Supabase.)

Python – python has several libraries, e.g. django, flask, as well as many different dashboard libraries. Similar to Node, you will need to either host this on a VPS (Hostinger has VPS’s as well, and I know DigitalOcean is popular), or some other service. Which is more expensive than the cheaper PHP options. It is possible to have authentication in python apps, but I do not tend to see many examples of that. Most python websites/dashboards I am familiar with are self-hosted, and so limit who can seem them intrinsically to the companies network (e.g. not online in a public website for everyone to see).

Personal story, at one point my Dallas crime dashboard (which is WASM + python) on my Crime De-Coder site (which is served on the PHP site, so takes a few extra seconds to install), was broken due to different library upgrades. So I hosted the python panel dashboard on Google cloud app while I worked on fixing the WASM. I needed one up from the smallest machine due to RAM usage (maybe 2 gigs of RAM). Google cloud app was slower than WASM on start up, sometimes would fail, and cost more than $100 per month with very little traffic. I was glad I was able to get the WASM version fixed.

Dallas Crime Dashboard

It is all about trade-offs though in the architecture. So the WASM app you can right click and see how I wrote the code to do that. Even though it is on a PHP site, it is rendered client side. So there is no way to protect that content from someone seeing it. So imagine I wanted you to pay $5 a month to access the dashboard – someone could right click and copy the code and cancel the subscription (or worse create their own clone for $4 per month). For another example, if I was querying a private database (that you don’t want people to be able to see), someone could right click and see that as well. So the WASM app only makes sense for things that don’t need to be private. Google cloud app though that is not a limitation.

The mistake I see many people make is often picking Node/Python where PHP would probably be a better choice. Besides costs, you need to think about what is exposed to the end user and the level of effort to create/manage the site. So if you say to GenAI “I want to build a dashboard website” it may pop out a python example, but many of the examples I am seeing it would have been better to use PHP and say “I have a php website, build a function to query my database and return an array of crimes by month”, and then as a follow up question say, “ok I have that array, create a line chart in PHP and javascript using D3.js”.

So to me GenAI does not obviate the need to understand the technology, which can be complicated. You need a basic understanding of what you want, the constraints, and then ask the machine for help writing that code.

Stacking and clustering matplotlib bar charts

Just a quick post – recently was trying to see examples of both stacking and clustering matplotlib + pandas bar charts. The few examples that come up online do not use what I consider to be one of the simpler approaches. The idea is that clustering is the hard part, and you can replicate the stacked bars fairly easily by superimposing multiple bars on top of each other. For just a quick example, here is a set of similar data to a project I am working on, cases cleared by different units over several years:

import pandas as pd
import matplotlib.pyplot as plt

# data of cases and cleared over time
years = [20,21,22]
acases = [180,190,200]
aclosed = [90,90,90]
bcases = [220,200,220]
bclosed = [165,150,165]
ccases = [90,110,100]
cclosed = [70,100,90]

df = pd.DataFrame(zip(years,acases,aclosed,bcases,bclosed,ccases,cclosed),
                  columns=['Year','Cases_A','Closed_A','Cases_B','Closed_B',
                           'Cases_C','Closed_C'])
print(df)


# Transpose
dfT = df.set_index('Year').T
dfT.index = dfT.index.str.split("_",expand=True) # multi-index

The biggest pain in doing these bar charts is figuring out how to shape the data. My data initially came in the top format, where each row is a year. For this plot though, we want years to be the columns and rows to be the different units. So you can see the format after I transposed the data. And this is pretty much the first time in my life a multi-index in pandas was useful.

To superimpose multiple pandas plots, you can have the first (which is the full bar in the background) return its ax object. Then if you pass that to the subsequent bar calls in superimposes on the plot. Then to finish I need to redo the legend.

# Now can plot
ax = dfT.loc['Cases',:].plot.bar(legend=False,color='#a6611a',edgecolor='black')
dfT.loc['Closed',:].plot.bar(ax=ax,legend=False,color='#018571',edgecolor='black')

# Redo legend
handler, labeler = ax.get_legend_handles_labels()
hd = [handler[0],handler[-1]]
lab = ['Not Closed','Closed']
ax.legend(hd, lab)
ax.set_title('Cases Assigned by Unit 21-23')

plt.show()

To make this a percentage filled bar plot, you just need to change the input data. So something like:

den = dfT.loc['Cases',:]
ax = (den/den).plot.bar(legend=False,color='#a6611a',edgecolor='black')
(dfT.loc['Closed',:]/den).plot.bar(ax=ax,legend=False,color='#018571',edgecolor='black')

# Redo legend
handler, labeler = ax.get_legend_handles_labels()
hd = [handler[0],handler[-1]]
lab = ['Not Closed','Closed']
ax.legend(hd, lab,loc='lower left')
ax.set_title('Proportion Cases Closed by Unit 21-23')

plt.show()

This does not have any way to signal that each subsequent bar in the clustered subsequent is a new year. So I just put that in the title. But I think the part is pretty simple to interpret even absent that info.

Crime De-Coder Updates

For other Crime De-Coder updates. I was interviewed by Jason Elder on his law enforcement analysts podcast.

Also I am still doing the newsletter, most recent talks about my social media strategy (small, regular posts), an interesting research job analyzing administrative datasets at Chase, and some resources I have made for Quarto (which I much prefer over Jupyter notebooks).

Hillbilly Lament

I recently read JD Vance’s Hillbilly Elegy. I grew up in very rural Pennsylvania in the Appalachian mountains, and I am the same age as Vance. So I was interested in hearing his story. My background was different, of course not all rural people are a monolith, but I commiserated with many of his experiences and feelings.

I think it is a good representation of rural life, more so than reading any sociology book. The struggles of rural people are in many ways the same as individuals living in poverty in urban areas. Vance highly empathized with Wilson’s Truly Disadvantaged, and in the end he focuses on cultural behaviors (erosion of core family, domestic violence, drug use). These are not unique to rural culture. Personally I view much of the current state of rural America through Murray’s Bell Curve, which Vance also discusses.

This is not a book review. I will tell some of my stories, and relate them to a bit of what Vance says. I think Murray’s demographic segregation (brain drain) is a better way to frame why rural America looks the way it does than Vance’s focus on cultural norms. This is not a critique of Vance’s perspective though, it is just a different emphasis. I hope you enjoy my story, the same way I enjoyed reading Vance’s story. I think they give a peak into rural life, but they aren’t a magic pill to really understand rural people. I do not even really understand rural people, I can only relate some of my personal experiences and feelings at the time.

It also is not any sort of political endorsement. I do endorse people to read his book – even if you do not like Vance’s current politics the book has what I would consider zero political commentary.

Farming

Where I grew up is more akin to Jackson Kentucky than Middletown Ohio – I grew up in Bradford county Pennsylvania. The town I went to school in has a population of under 2,000 individuals, and my class size was around 80 students. A Subway opened in town when I was a teenager and it was a big deal (the only fast food place in town at the time).

My grandfather on my mother’s side had a small dairy farm. One of the major cultural perspectives I have on rural people is somewhat contra to Vance – farmers have an incredible work ethic. Again this is not a critique of Vance’s book, I could find lazy people like Vance discusses as well. I just knew more farmers.

Farming is Sisyphean – you get up and you milk the cows. It does not matter if you are sick, does not matter if it is raining, does not matter if you are tired. It would be like you not feeding your pets in the morning, and you do not get paid.

There was always an expectation of working. I was doing farm work at an early age. I always remember being in the barn, but even before I was 10 years old I was taught to operate heavy machinery (skidsteer, tractors). So I was doing what I would consider “real work” at that young, not just busy work you give a child to keep them preoccupied.

My grandfather retired and sold his farm when I was 11, but I went and worked for a neighbors farm shortly there after. We had a four-wheeler that I would drive up the road in the wee hours of the morning to go work. I was not an outlier among other kids my age. The modal kid in my school was not a farmer, but there were more than a dozen of my classmates who had the same schedule.

Farming, and manual labor in general, is brutal. When Vance talked about the floor tile company not being able to fill positions (despite the reasonable pay), I can hardly blame people for not taking those jobs. They are quite literally backbreaking.

Farming has become more consolidated/automated over time. The dairy farms I worked on were very small, having less than 100 cows. One of my memories is being exhausted stacking small square bales of hay. There is a machine that bundles up the hay and shoots it onto a wagon. I would be in the wagon stacking the bales. Then we would have to load the bales up a conveyor belt and stack them in the barn. The bales weighed around 50 pounds, it was crazy hard work.

Round bales were only starting to become more common in the area when I was a teenager. You can only move the larger round bales using farm equipment. I believe almost no one does the small square bales like I am describing anymore. The smaller square bales were also a much larger fire hazard. If the hay was wet when baled it would go through a fermentation process and potentially get hot enough in the center of the stack to catch fire.

This is one of the reasons I do not have much worry about automation taking jobs. A farmer not needing to hire extra labor to stack hay and instead use a tractor to do the same work is a good thing. This will apply to many manual labor jobs.

The Culture of Danger

One thing I had always been skeptical of when reading in sociological texts was the southern culture of violence. Saying southern people have an honor culture and then showing homicide rates in the south are higher is very weak evidence supporting that theory.

The first person who had told me of that hypothesis in my PhD program at Albany was a professor named Colin Loftin. I think I laughed when he said it in class and I straight up asked “is this a real thing.” He was from Alabama and assured me it is, and told some story of a student fighting after bumping into another person walking in a hallway as an example. For those who do not know Colin, imagine a nerdy grandpa accountant with a well groomed white beard stepped out of a Hallmark movie. And he tells you southern people are prone to violence over trivial matters of honor – I was not convinced. As I said I grew up in a very rural area; Pennsylvania is sometimes described as Philadelphia, Pittsburgh, and Alabama in between. But I did not experience that type of violence at all.

Vance’s book is the first confirmation of the southern culture of violence that I believed. The area I grew up in was substantively less violent. I would consider it more northeastern vibes than what Vance describes as southern honor culture. I am sure I could find some apocryphal violent stories similar to what Vance describes if I prodded my relatives enough, but I did not take that to be a core part of our identity the same way Vance does.

Culture is hard to define. The ideal of “you work at all costs” I take as part of farming culture. It was not an ideal more generally held among the broader population though. I definitely was familiar with adults who were lazy, or adults who had the volatile lifestyle of Vance’s mother he describes in his book. But I was personally familiar with more people who day in and day out performed incredibly hard manual labor.

Another aspect of growing up, which I have coined the culture of danger, is harder to associate specific behaviors with. But it is something that I now recognize was constantly in the background, something we all took for granted as a given, but is not something that is more broadly accepted in other parts of society.

Farming is incredibly dangerous. There are steel pipes that transport the milk from the cow to the bulk tank. After you are done with a round of milking, the interior of the pipeline gets washed with a round of acid. Then the pipes are rinsed with a second round of a much more concentrated caustic solution to get rid of the residual acid. When I was around 6 years old, me and my older sister were playing in the barn and I spilled the more caustic solution on myself. They were housed in large plastic containers that had a squirt top on them (no different than the pump on your liquid hand soap). All it took was a push, and it melted my nipple off (through the shirt I was wearing at the time). Slightly different trajectory and I would be missing half of my face.

Like I said previously, I learned to operate heavy machinery before I was 10. I distinctly remember doing things in both the skidsteer and the tractor when I was young that scared me. Driving them in areas and in situations where I was concerned I would roll the machines. Skidsteers are like mini tanks with a bucket on the front. I do not think it had a seat belt, but if I rolled the skidsteer I think my chances were better than 50/50 to make it out (it had a roll cage, but if ejected and it rolled over you, you are going to be a pancake). If I rolled a tractor (these are very old tractors, no cab), I think your chances are less than 50% you get out without serious injury.

Learn to operate here meant I was given a short lesson and then expected to go do work, by myself without supervision. Looking back it was crazy, but of course when I was a kid it did not seem crazy.

Another example was climbing up silos. At the farm that I worked on, he did not have a machine to empty out the silo. So I would need to climb the silo, and fork out the silage for the cows feed. Imagine you took your lawn mower over a corn field, the clippings (both the cobs and the stalks) are what silage is.

I would climb up a ladder, around 50 feet, carrying a pitchfork. When I was 12. This was not a rare occurrence; this was one of my main responsibilities as a farmhand, I did this twice a day at least.

The cows were also fed a grain like mixture (that is similar to cereal, it did not taste bad). I have mixed feelings about the grass fed craze now, since the cows really enjoyed the grain and the silage (although I do not doubt a grass fed diet could be better for their overall health). And I do not know if feeding them just baled hay counts as grass fed, or if they need to be entirely fed with fresh grass from the field.

Some may read this and think the child labor was the issue. I do not think that that was a problem at all. To me there is no bright line between doing chores around the house and doing chores in the barn. I was paid when I worked on the neighbors farm, and it was voluntary. It was hard work, but it did not directly impact my schooling in any obvious way. No more than when a kid does sports or scouts. The operating heavy machinery when I was a child was crazy though, and the working conditions were equally dangerous for everyone.

Even more broadly, just driving around the area I lived was dangerous. There were six males I went to high school with that died in traffic accidents. So in a group of less than 300 males nearby me in age (+/- two years), six of them died. I can not remember what the roads MPH was graded at, but they were winding. I am not sure it matters what the MPH is, there is no way reasonable way to enforce driving standards on all those back roads.

Death and danger was just part of life. Johnny died in a car accident, Mary is having a yard sale, and Bobby rolled the tractor, his femur broke the skin but he was able to crawl to the road where Donny happened to be driving by, so he will be ok. So it goes.

The culture of danger as I remember it does not have as many direct manifest negative behaviors as does “honor culture” or “I am too lazy and too high on drugs to keep a job”. So maybe some real ethnographers would quibble with my description of it as a culture.

I do think this is distinct from how individuals in certain areas have a constant specter of interpersonal violence. I do not have any PTSD type symptoms from my experience, like Vance describes based on his experience with child abuse. In the end I suspect the area I grew up had worse early death rates than many urban areas with violence on a per capita basis, but the nature of it doesn’t have quite the same effect on the psyche. Ignorance is bliss I suppose, you get used to driving tractors on steep hills.

Steaks are for rich people

One of the places I remember eating at growing up was Hoss’s Steakhouse in Williamsport. So if we went to get clothes for school at the Lycoming Mall as a family, we would often eat there on the way home. It is a place with a nice salad bar. You could load up a salad with a pound of bacon bits, and have a soft serve ice cream on the side if you wanted.

Walking into the restaurant before you are seated are pictures on the walls of the meals. I was maybe 14 at the time, and waiting to be seated I pointed to one of the steak meals and said “I would like to get that”. The immediate response from my mother was “No you are not. You are getting the salad bar like always.” One of the ironic parts of this story to me is that, because I was working as an independent farmhand, I had my own money. I could have certainly paid for a steak dinner with my own cash.

After I was 16 and could drive, I did end up doing the majority of my own clothes shopping. I remember splurging on some really ugly yellow and green Puma sneakers one year (totally worth it, they were $80 and did get the “whoa nice shoes” comments at school as intended).

I have only recently developed a palette for steak. My son likes it and requests we go to the local steak house on occasion. I have for awhile actively encouraged him to buy whatever expensive steak is on the menu when we go out to eat (Waygu beef at the sushi place, that sounds interesting you should try that). Makes me feel like the god damn king of the world.

Soda and Beer

When I was young (less than 10 years old), during summers I would spend most of my time on the farm, but once a week visit my other grandparents. I would do two activities with my grandfather: either golf or go fishing. For golf we had a par three 9 hole course in my town. I cannot hit a driver straight to save my life, but my iron game is at the level where I would not embarrass myself.

Fishing was just in little ponds in the area, mostly sunfish and bass. We would bring a sandwich, two Pepsis for myself, and two beers for Grandpa.

I tell this story both because it is a fond memory, as well as it highlights one of the stark differences in my lifestyle now (in terms of healthy eating) vs back then. I am pretty sure I drank more soda than water growing up. Our well water was sulfurous, so it was quite unpleasant to drink. Soda was just a regular thing I remember everyone having, including kids.

Charles Murray in his Bell Curve proactively addresses most of the negative commentary you hear about right in the writing. But one thing I thought was slightly cringe at the time I read the book (sometime while getting my PhD) was his “middle class values index”. To be clear these were not things about healthy eating, but were more basic “received a high school diploma” and “have a job”. The items I did not object to, but the moniker of “middle class” I thought was an unnecessary jab for something that was so subjective.

In retrospect though, “feeding kids soda like it is water” and “driving around with open containers of beer” is the most apropos “not middle class values” I can think of. So now I do not hold that name against Murray. These are not idiosyncratic to rural areas, you can identify people in poor urban areas who behave like this as well. But you definitely do not need to worry about being pulled over for an open container while driving where I grew up.

In Pennsylvania at this time, to buy beer you needed to go to a distributor. You could not get a six pack at the gas station. You needed to get at least a 24 pack. I figure this limited the number of people purchasing beer, but I do wonder for those who did buy beer if it increased the amount of binge drinking.

Role Models and Choices

For a crazy dichotomy with how I grew up versus what I know now, one of the only role model career choices I remember individuals talking about growing up were teachers. Getting a job as a teacher at the school district was a well respected (and well paying) career option in my town.

An aspect of this that can only be understood when you are outside of it is how insular this perspective is. A kid wants to be a teacher, because that is pretty much the only career they are exposed to. This is from the perspective “I may need to go to school, but I will come back here and get a job as a teacher”.

I personally did not have much respect for my teachers in high school, so I never seriously considered that as a career option. I was an incredibly snarky and sarcastic kid. My older sister (and then later my younger sister) were salutatorians of their classes. I (quite intentionally) did not try very hard.

For one story, my physics teacher (who was friends with my father) called home to ask if I was doing ok since I slept in class. My mother asked what my grade was, and since it was an A, she did not care. For another, which I am embarrassed about now, I would intentionally give wrong answers (it was history or civics I believe) because the teacher would get upset. I found it hilarious at the time, but I realize this is incredibly churlish now (he cared that we were learning, which I cannot say for all of my teachers). Sorry Mr. Kirby.

So, I was not a super engaged student.

Vance talks about it seeming like the choices you make do not matter. I can understand that, it did not seem to me I was making any choices at all when I think back on it. My parents did always have an expectation that I would go to college for myself and my siblings. Working as a farmhand (for other peoples farms at that point) was never a serious option.

Both my parents had associates degrees, and my sister (who was two years older than me) went to Penn State for accounting. That was about the extent of college advice I got – you should go. I never had a serious conversation about where I should go or what I should go for. Choose your own adventure.

I remember signing myself up for the SAT. I took the test on a Saturday morning in a testing center a few towns over. I finished each of the sections very fast, and I scored decently for not practicing at all (a 1200 I believe, out of a possible 1600). I have consistently done excellent on math and poorly on the English portions of tests in my life; I think I had 700 in math and 500 in English for the SAT.

One funny part of this is that, until graduate school, I actually did not understand algebra. Given my area of expertise (statistical analysis and optimization now), many people think I am quite a math geek. I did have good teachers in high school, but I was able to score this high on the SAT through memorization. For example I knew the rule for derivatives for polynomials, but if you asked me to do a simple proof at that point I would not have had any clue how to do that.

When I say I did not understand algebra, I mean when I was given a word problem that I needed to use mathematical concepts to solve, I just figured it out in my head. It was not until graduate school that at some point I realized you can take words and translate them into mathematical equations.

I know now that this is somewhat common for intelligent people when learning math. I home school my son, and I noticed the same thing for him. So it took active engagement (forcing him to write down the algebraic equivalent, even when he could figure out the answer in his head). But just rote memorization can get you quite a good score on the SAT.

Individuals who want to get rid of standardized testing because poor people score worse on average is the wrong way to think about it. You should want to improve the opportunities for individuals to get better education, not stick your head in the sand and pretend those inequalities do not exist.

SAT results in hand, I remember asking the guidance counselor about school information for Bloomsburg University (I chose Bloomsburg because it was not Mansfield and not Penn State, and was cheaper). And her response was simply to hand me a single page flier.

I can understand my parents not giving decent college advice; they did not know about scholarships or what opportunities were available. The high school guidance counselor in her sloth though makes me angry in retrospect. Our grade had less than 80 kids – she could have spent a few minutes reviewing each of those kids backgrounds, and provided more tailored advice.

I am positive none of the kids in my class went to undergrad at any more advance school than Penn State (and even that may have only been one student in my class). Cornell (an ivy league school in Ithaca, New York) is actually closer than Penn State to where I lived – I did not know it existed when I was in high school. To be fair, I do not know if the guidance counselor knew my SAT score, but she could have asked. She certainly had access to my grades, could see I did well in STEM courses, and could have easily given suggestions like “you can apply for partial scholarships to many different places.”

This goes both ways, I knew several of my classmates that should not have gone to college. My best friend in high school was a solid B/C student, went to Mansfield for journalism, and stopped going in his junior year. He is doing fine now as a foreman for a natural gas company. Going to get a four year BA degree for him was a bad idea and waste of money. And it was doubly bad going for journalism.

The brain drain had not happened yet in my high school. The level of discourse in my high school classes was excellent. I noticed a significant regression in the level of discussion in my first classes at Bloomsburg relative to those in my high school. (Bloomsburg had an average SAT score for entrants of 1000.)

I am intelligent, but I was not the most intelligent in my class. There were easily 10 other people in my class that had comparable intelligence to me. All of whom would have likely qualified for at least partial Pell grant assistance.

For those in my class that did go to college, pretty much everyone went to one of the PASSHE schools (these are state schools in Pennsylvania, originally founded as normal schools that were intentionally spread out in rural areas). Most went to the closest nearby (Mansfield), but a few spread out to various institutions across the state (Lock Haven, Shippensburg, Indiana, etc.).

I have hobnobbed with ivy league individuals (professors and students) since getting my PhD. There is no fundamental difference between kids who go to ivy league schools and the kids I went to high school with. With a semester of SAT test prep, and a not lazy guidance counselor helping apply to scholarships, we could have had double digit number of kids accepted to prestigious institutions for zero cost.

Do Not Talk About Money

I remember asking my grandfather why barns were red. He said it was because red paint was cheaper. That was the only conversation I can remember in my childhood that discussed money in any form.

When going to college I was filling out my FAFSA form, and asked my father how much money he made. His response was “enough”. Vance brings up the idea that, ironically, going to nicer colleges is cheaper for poor people. But they have no clue about that. I am fairly sure I would have qualified for partial Pell grant assistance – I just left the section on your parents income blank on the FAFSA form.

Besides inept counsel on college, even though I had worked all these different jobs I only remember actively thinking about pay when I was working different jobs in college. The floor board factory was over $8 per hour. The ribbon factory was $11 per hour. Later when I worked as a security guard for Bloomsburg University I made $13 per hour.

Similar to Vance’s experience in Middletown, $13 per hour is quite decent to get an apartment and put food on a table for a family in that area of PA (at least at that time, 2004-2008). You are not saving up for retirement, but you shouldn’t need to live in the dregs and go hungry either.

In retrospect the advice I needed at the time (but never received) was real talk about pursuing careers. This is wrapped up in college, you go to college to prepare yourself for a career (the expectation I go to college was certainly not only to obtain a liberal arts education!)

I ended up choosing Bloomsburg University because I knew many of my classmates were going to a closer school (Mansfield) and just wanted to be different. There was no thought into choosing criminal justice as a major either. When folks ask me the question “what did you want to be when you grew up”, I can not remember actively thinking about any specific career. Even when I was young and hitting baseballs in the back yard, I knew that I was not going to be a professional baseball player.

I remember at one point in the middle of undergrad at Bloomsburg realizing that a criminal justice degree is not really vocational, and I could quit if I really wanted to just go and be a police officer (the only vocation I likely associated with the major). Which I did not really want to do. So I was debating on transferring to Bucknell for sociology, or some community college for whatever degree you get to work on HVAC systems. (I do not know where the Bucknell idea came from, I must of thought “it was fancy” or something relative to Bloomsburg.)

I could have used other advice, like “you can negotiate your wage”, but likely understanding my career options was the one thing that negatively effected my long term career progression. I do not mean to denigrate the HVAC job (given my background and what I know now, I am pretty sure that would have been a better return on investment than sociology at Bucknell!)

Not that I would go back in time and change anything (I received an excellent education at Bloomsburg in criminal justice, and ditto at SUNY Albany). But if someone somewhere said “hey Andy, you are pretty good at math, you should look into engineering”, my life trajectory would likely be very different.

Factory Jobs Suck

After I was able to drive at 16 I started to take other jobs outside of being a farmhand. These included being a line cook and dishwasher at a local restaurant where my aunt-in-law was a chef, and working for a company that did paving and seal-coating before I was 18. Cooking wasn’t bad. The restaurant was actually a mildly fancy steak and seafood place you needed a membership to eat. Thinking back, I am honestly confused how that many people where I grew up could afford a membership that would make that business model work.

Paving and seal-coating was comparable to the level of effort of farming. It was safer in the short term than farming (in a “I probably will not be maimed way”), but breathing in the fumes I am guessing would be worse long term. I do not remember my hourly wage (it may have just been the minimum wage), but I did get a bunch of overtime in summer which was nice.

When I went to college I then did various jobs as well. I worked at Kentucky Fried Chicken at the cash register at one point. On campus, jobs intended for undergraduate college students through the university, I worked as a carpenter building theater sets and as a tutor for the stats classes in the criminal justice department.

The last time I moved home though over summer break (after sophomore year at Bloomsburg) I got a job stacking uncut floorboards in a factory. This was my first factory job – we would stand on a conveyor belt down the machine that cut the boards. Our palettes would be stacked with a single size and we would rotate sizes after a while. So sometimes I am stacking 4 inch wide boards, another time I am stacking 12 inch wide boards, etc.

This was monotonous and hard work, but not crazy bad and I enjoyed my coworkers. Stacking hay bales was harder. Many of the people I worked with were on work release from the county jail. I got paid $8 an hour, they only got $4. But they were happy to do the work and not be sitting in jail. It is absurd that they did not receive the same pay. Most of them were in jail for DUIs.

After about a month of doing this job I had inflammation in my elbow. My elbow only had minor pain, but my arm would fall asleep when I slept and I would wake up in quite a lot of pain from that (so lack of sleep was really the bigger issue than my arm hurting). I asked to take the day off to go to the doctor (one of my coworkers said he had the same issue, but still worth working rather than sitting in jail). The owner mistakenly thought I was trying to get workers compensation, so told me no to the day off and I would be fired if I went to the doctor. (That was not my intention, I just wanted to get some pain medication.) So I just ended up quitting. Doctor said it was “tennis elbow,” and that it would only go away with rest, so I would have needed to quit anyway.

I then moved back to Bloomsburg for the summer (the town I grew up in was incredibly boring, hanging out in an empty college town was certainly a step up for a 20 year old). I got a job at a ribbon factory in Berwick (a neighboring town) for $11 dollars an hour. You could consider Berwick a doppelganger for Middletown as Vance describes it.

Working at the ribbon factory was barely manual labor. I would sit on a conveyor belt and either count bags to fill in boxes, or look at ribbons as they rolled by only to throw away malformed ones. This was soul sucking work. There was only one other younger person I befriended while working there, most everyone else was middle aged. I wondered to myself how these people survived this existence. Of all the jobs I have had in my lifetime this was easily the worst.

Despite having the “work every day” mentality from when I was young, I just stopped going to this job alittle over a month after I started worked there. I did not tell my boss I quit, just literally stopped going. It wasn’t a hard job, the opposite, it was easy. A second grader could do the job.

So this is often what I think about when people say “the factory jobs are going away,” or Vance’s example that the tile company that cannot get people to work for them. You have a choice, break your back or watch ribbons go by on a conveyor belt. I recognize that having people just take a paycheck from the government is not good for people long term. I think people need something to work to strive for and take pride in. Working in a factory is not that.

It was at this point (in between being a sophomore and junior) I went from just doing the bare minimum to get by for my classes at Bloomsburg to being actively engaged in my course work and putting in real effort. Working at the ribbon factory was the nadir. Having the more advanced upper level classes did make me more engaged. It was around this time I began working as a security guard for the university. I made the most for that position of any job I had at that point in my life, $13 per hour.

I worked night shift for the security guard job. There was one point in my schedule where I needed to stay awake for over 48 hours. I would get off at 4AM, and if I went to sleep I would not wake back up (even with an alarm) for a 9AM class. So I would have to stay up, go to class, and then sleep for an extended period of time.

By my senior year of college, I was back in the working crazy all the time stage. At one point I had three jobs (college tutor for statistics classes, working as a security guard, and even had work to help with statistical analysis for the local school). This is in addition to being a full time student.

Trailers and Going to Grad School

In the summer between junior and senior year at Bloomsburg University, I had an internship with state parole. The officer I shadowed had an area that covered the counties around Scranton, so a mix of rundown rust belt towns (like Berwick) but also more rural areas. There were more people living in trailers on single lots than trailers in trailer parks.

The first house call I shadowed was an individual who only had a few more weeks on his sentence. He was very nervous and sweaty (which was my first house call I witnessed, so I did not think much of it at the time). The parole officer had the individual do a urine sample. I found out later that he failed (heroin), and the parole officer said the reason he was nervous is that they take multiple officers to arrest individuals, so he likely thought he was being taken back to prison. It probably was not the failed drug test, which him being that close to finished would just result in a warning.

Shadowing parole was an eye opening experience. I had lived in rural areas, but I had been mostly sheltered from the decrepit lifestyle some people lived. Some houses the parole officer would make his parolees meet us outside, as he would refuse to go inside the house. People would not let their animals out (so the house smelled of the strong ammonia scent from the urine, much worse than the barn). Houses with kids sleeping on mattresses in the living room and fleas. I knew people like this existed, but seeing them firsthand was different.

Matthew Desmond’s book, Evicted, in which he follows the lifestyle of various individuals trying to scrape by in Milwaukee, reminded me quite a bit of my time with parole. A bunch of people who could not make two good decisions in a row if their life depended on it. I presume getting drunk before your scheduled parole visit or not cleaning your sink and getting evicted are consequences of the same inability to make good long term decisions.

All of those individuals had no fundamental reason they needed to live in filthy conditions. You can take the cat litter out. People dig on trailers and trailer parks, but living in a trailer is not fundamentally bad. It is no different than living in a small apartment.

So I had planned on applying to be a parole officer after this experience. It was likely I would not be assigned the field area I did my internship, but either assigned a position in a prison (they have officers inside state prison help with offenders release plans). Or maybe be assigned in the field in the Philadelphia area. So I took the civil service exam to be a parole officer in the fall semester of my senior year.

I had made a mistake though, I had taken the exam too early. They called and asked if I could go to training in the spring. I said I could not do that, as I wanted to finish my degree. (The parole officer I shadowed had quit one semester early, and he did say he regretted that.) The civil service exams in Pennsylvania had a rule that you could not re-take them within a certain time frame, so I did not have the ability to take them again when the timing would have worked out better.

So at this point in the fall semester I decided to apply to graduate school, not really knowing what I was getting into. The other option was applying to different police departments in the spring (I remembered Allentown and Baltimore had come to classes to recruit). I did well on the GREs, and was accepted into SUNY Albany (my top choice) quite early. I had also applied to Delaware. SUNY was somewhat unique, in that you could apply straight into the PhD program from undergrad. I did not realize this at the time, but this was very fortunate, as PhD programs were funded. I would have racked up a bill for the masters degree at Delaware.

When I ended up getting into grad school at SUNY Albany, Julie Horney called me in the afternoon of one of my binge sleep sessions in my night security guard schedule to say I was invited for orientation. I do not remember what I said on the phone call, I remember getting up later and not being sure if that was a dream or it had really happened.

Later that spring when I visited Albany I headed straight up from my night shift to the orientation day. I remember being confused, thinking this was an interview and still not 100% guaranteed I was in. I said something to Dana Peterson and her response was along the lines of “you do not have to worry Andy, you have gotten in”.

Going to Albany ended up being one of the greatest decisions of my life. The academic atmosphere of a PhD program was totally different and fundamentally changed me. It would be a lie though if I said it was something I intentionally pursued, as opposed to a series of random happenstance factors in my life that pushed me to do that. I really had no clue what I was getting into.

Drugs

Growing up in Bradford county I had very little exposure to drugs. My friends and I would pinch beer and liquor from our parents on occasion, but in the grand scheme of things I was a pretty square kid. I knew some individuals smoked pot, but I did not know anyone in high school who did heroin or other opiates. Unlike Vance, serious drug or alcohol abuse was not something I personally witnessed in my family.

It was around the beginning of 2000’s that the gradual increase in opioid overdose deaths started to happen across the US. In the town with the ribbon factory, Berwick, heroin usage was an issue. My sister in law (who grew up in Bloomsburg) ultimately died due to long term heroin usage. I worked on a grant to help Columbia county analyze the Monitoring the Future survey (a behavioral health survey that all students in Pennsylvania took). There were a few students in each grade cohort (as young as seventh grade) who stated they used heroin.

If you look at maps of drug overdose deaths in this time period, you can see a cluster start to form around the Scranton area by around 2005. This area in western Pennsylvania is close enough to commute to New York City. It is possible the supply networks for heroin from more urban areas were established that way.

I suspect it is also related to working labor jobs though. One reason my grandfather retired from farming was because he had chronic shoulder pain. I would drive him to his visits to the VA hospital in Harrisburg on occasion, in a full size van, when I was a teenager. He was prescribed oxycodone, but knew that it was addictive, so he would take them one week and then abstain the following week.

I do not know how you work these labor jobs and not have some type of chronic pain. It is hard for me to imagine working these jobs for thirty years without them killing you. I recently had a kidney stone, and I was stuck waiting for several hours in the ER before I was able to get a fentanyl drip. Went from pulsating pain and throwing up to relief almost instantly. I was prescribed oxycodone to use at home before I passed the stone. I did not take it.

When I was a professor at the University of Texas at Dallas, a well respected qualitative criminologist came to give a talk. He discussed his recent work, an ethnography of methamphetamine users in rural Alabama. His main thesis in the talk, which is something I think only an academic sociologist could come up with, is that women were influenced by their boyfriends to begin taking meth. (This is true, but you could do the same talk and say men were introduced to drugs by their female partners.) I asked at the end of his talk whether he thought his findings extended to heroin users, and his response was that heroin is an urban drug problem.

Another main point of his talk was to take pictures of his subjects in realistic settings. The idea being that most drug users are depicted in the media in a negative light. So we should take pictures of them so people do not think they are monsters. The lecture was mostly pictures of peoples trailers, and pillow talk his interviews discussed that resulted in snickers from the audience at various points.

Taking pictures of trailers does not humanize poor people. It makes you look like you are Steve Irwin describing wildlife in the outback – I personally thought it was incredibly degrading.

The idea that you shouldn’t show the negative impacts of hard drug use is such a comically white knight perspective I am not sure whether it makes me want to laugh or cry. I did not take that oxycodone because I have seen, with my own eyes, what happens to people who are addicted to opioids. The most recent wave of fentanyl laced with xylazine can result in open sores and losing phalanges. I do not believe those people are monsters (does anyone?) but it is grotesque what drug addiction can do to people.

I suggest to read Vance’s discussion of his life growing up, over any sociologist, because of this. When what we have to offer is “some people think people who take drugs are monsters” and “you should take nice pictures of them”, people are well justified to ignore academics as out of touch and absurd.

Lament

If I had the chance to sit down with Vance, one thing I would ask him is his choice of elegy in the title of his book. I name my blogpost lament. I have moved on with my life, my work focuses on working with police departments on public safety. This work entirely focuses on urban areas.

I do not think anything my research relates to could, even at the margins, help materially improve the lives of people I grew up with. There are things I think could marginally improve individuals outcomes, such as getting better advice about colleges. But there is nothing reasonable to be done to prevent traffic accidents or improve farm safety. I mean you could attempt stricter safety regulations but realistically enforcing them is another matter.

Vance in his book does not really talk about politics, but towards the end gives some examples of policies he thinks could on the margins help – such as restricting the number of section 8 vouchers in a neighborhood (to prevent segregation). He is right that you cannot magically subsidize factory jobs and all will be well – it will not. These jobs, as I said above, suck.

I view the current state of rural America, as I experienced it, via Murray’s Bell Curve. Specifically the idea of brain drain, and more broadly intellectual segregation. One of Murray’s theses was that, historically, rural communities had a mix of intelligent (and not so intelligent) individuals. Gradually over time, the world has become more globalized, so it is easier to move from the farm to industrialized areas.

This results in intelligent people – those who can go to college and keep a job – to move away. What is left over is a higher proportion of the types of people Vance more focuses on in his book – individuals with persistent life problems. Criminologists will recognize this process as fundamentally the same with urban blight areas described by the Chicago school of crime. Vance focuses on the culture that is the end result of this demographic process – the only people who don’t move away are the ones who live hard lives that Vance describes in his book.

Automation is the long term progression of farming in America. Farming in rural areas will eventually be just the minimal number of humans needed to oversee the automated machinery. I am not sure the town I grew up in will exist in 100 years.

And this to me is not a bad thing. I left to pursue opportunities that were not available to me if I stayed in Bradford county. I am not sad that I do not need to sling square bales of hay. My suggestion, to help give better advice to students about pursuing college and careers, will only hasten the demise of rural areas, not save them. This is the lament.

Politics aside, I found Vance’s biography of his life growing up worth reading. If you find my stories interesting, I suspect you will find his as well.

Aoristic analysis, ebooks vs paperback, website footer design, and social media

For a few minor updates, I have created a new Twitter/X account to advertise Crime De-Coder. I do not know if there is some setting that people ignore all unverified accounts, but would appreciate the follow and reshare if you are still on the platform.

I also have an account on LinkedIn, and sometimes comment on the Crime Analysis Reddit.

I try to share cool data visualizations and technical posts. I know LinkedIn in particular can be quite vapid self-help guru type advice, which I avoid. I know being more technical limits the audience but that is ok. So appreciate the follow if you are on those platforms and resharing the work.

Ebooks vs Paperbacks

Part of the reason to start X account back up is to just try more advertising. I have sold not quite 80 to date (including pre-sales). My baseline goal was 100.

For the not pre-sales, I have sold 35% ebooks and 65% paperbacks. So spending some time to distribute your book paperback seems to me to be worth it.

Again feel like most academics who publish technical books self-publishing is a very good idea. So read the above linked post about some of the logistics of self-publishing.

Aoristic analysis in python

On the CRIME De-Coder blog, check out my post on Aoristic analysis. It has links to python code on github for those who just want the end result. It has several methods though to do hour of day and hour by day of week breakdowns. With the ability to do it by categories in data. And post hoc generate a few graphs. I like the line graphs the best:

But the more common heatmap I can understand why people like it

Website Design

I have a few minor website design updates. The homepage is more svelte. Wife suggested that it should be easier to see what I do right when you are on homepage, so put the jumbotron box at the bottom and the services tiles (with no pictures) at the top.

It does not look bad on mobile either (I only recently figured out that in Chrome’s DevTools they have a button to do turn on mobile view, very helpful!)

Final part is that I made a footer for my pages:

I am not real happy with this. One of the things you notice when you start doing web-design is everyone’s web-page looks the same. There are some basic templates for WordPress or Wix (and probably other CMS generators). Here is Supabases’s footer for example:

And now that I have shown you, you will see quite a few websites have that design. So I did the svg links to social media, but I may change that. (And go with no footer again, there is not a real obvious need for it.) So open to suggestions!

In intentionally made many of the decisions for the way the Crime De-Coder site looks not only to make it usable but to make it at least somewhat different. Avoid super long scrolls, sticky header (that still works quite well on phones). The header is quite dense with many sub-pages (I like it though).

I think alot of public sector agencies that are doing data dashboards now do not look very nice. Many are just iframed Tableau dashboards. If you want help with those data visualizations embedded in a more organic way in your site, that is something Crime De-Coder can help with.

Reducing folium map sizes

Recently for a crimede-coder project I have been building out a custom library to make nice leaflet maps using the python folium library. See the example I have posted on my website. Below is a screenshot:

This map ended up having around 3000 elements in it, and was a total of 8mb. 8mb is not crazy to put on a website, but is at the stage where you can actually notice latency when first rendering the map.

Looking at the rendered html code though it was verbose in a few ways for every element. One is that lat/lon are in crazy precision by default, e.g. [-78.83229390597961, 35.94592660794455]. So a single polygon can have many of those. Six digits of precision for lat/lon is still under 1 meter of precision, which is plenty sufficient for my mapping applications. So you can reduce 8+ characters per lat/lon and not really make a difference to the map (you can technically have invalid polygons doing this, but this is really pedantic and should be fine).

A second part of the rendered folium html map for every object is given a full uuid, e.g. geo_json_a19eff2648beb3d74760dc0ddb58a73d.addTo(feature_group_2e2c6295a3a1c7d4c8d57d001c782482);. This again is not necessary. I end up reducing the 32 length uuids to the first 8 alphanumeric characters.

A final part is that the javascript is not minified – it has quite a bit of extra lines/spaces that are not needed. So here are my notes on using python code to take care of some of those pieces.

To clean up the precision for geometry objects, I do something like this.

import re

# geo is the geopandas dataframe
redg = geo.geometry.set_precision(10**-6).to_json()
# redg still has floats, below regex clips values
rs = r'(\d{2}\.|-\d{2}\.)(\d{6})(\d+)'
re.sub(rs,r'\1\2',redg)

As most of my functions add the geojson objects to the map one at a time (for custom actions/colors), this is sufficient to deal with that step (for markers, can round lat/lon directly). It may make more sense for the set precision to be 10**-5 and then clip the regex. (For these regex’s I am showing there is some risk they will replace something they should not, I think it will be pretty safe though.)

Then to clean up the UUID’s and extra whitespace, what I do is render the final HTML and then use regex’s:

# fol is the folium object
html = fol.get_root()
res = html.script.get_root().render()
# replace UUID with first 8
ru = r'([0-9a-f]{8})[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{12}'
res = re.sub(ru,r'\1',res)
# clean up whitespace
rl = []
for s in res.split('\n'):
    ss = s.strip()
    if len(ss) > 0:
        rl.append(ss)
rlc = '\n'.join(rl)

There is probably a smarter way to do this directly with the folium object for the UUID’s. For whitespace though it would need to be after the HTML is written. You want to be careful with the cleaning up the whitespace step – it is possible you wanted blank lines in say a leaflet popup or tooltip. But for my purposes this is not really necessary.

Doing these two steps in the Durham map reduces the size of the rendered HTML from 8mb to 4mb. So reduced the size of the file by around 4 million characters! The savings will be even higher for maps with more elements.

One last part is my map has redundant svg inserted for the map markers. I may be able to use css to insert the svg, e.g. something like in css .mysvg {background-image: url("vector.svg");}, and then in the python code for the marker svg insert <div class="mysvg"></div>. For dense point maps this will also save quite a few characters. Or you could add in javascript to insert the svg as well (although that would be a bit sluggish I think relative to the css approach, although sluggish after first render if the markers are turned off).

I have not done this yet, as I need to tinker with getting the background svg to look how I want, but could save another 200-300 characters per marker icon. So will save a megabyte in the map for every 3000-5000 markers I am guessing.

The main reason I post webdemo’s on the crimede-coder site is that there a quite a few grifters in the tech space. Not just for data analysis, but for front-end development as well. I post stuff like that so you can go and actually see the work I do and its quality. There are quite a few people now claiming to be “data viz experts” who just embed mediocre Tableau or PowerBI apps. These apps in particular tend to produce very bad maps, so here you can see what I think a good map should look like.

If you want to check out all the interactions in the map, I posted a YouTube video walking through them

Durham hotspot map walkthrough of interactions