For weeks this winter, Pennsylvania flirted with a full-blown constitutional crisis.

In January, the Democrat-controlled state Supreme Court sided with activists from the League of Women Voters and ordered state legislators to redraw the state's congressional district map. GOP lawmakers, who had created the boundaries in 2011 during the once-per-decade reapportionment process, had engaged in a heavy dose of gerrymandering—the practice of drawing district lines intentionally to favor one party over another. Not surprisingly, Republicans objected to the court order, even threatening to impeach some of the state high court's justices. The two branches of government appeared to be deadlocked, with each determined to check what it saw as partisan opportunism on the part of the other.

Republican lawmakers in the General Assembly blinked first, offering a new set of district lines on February 9. It was promptly rejected by Gov. Tom Wolf, a Democrat. A week later, the state Supreme Court produced its own map, drawn by Stanford Law School's Nathaniel Persily. Republicans howled that the court had unconstitutionally usurped a legislative power and asked the U.S. Supreme Court to intervene.

For now, uncertainty reigns.

Even when the crisis in Pennsylvania is eventually resolved, deeper issues regarding electoral district lines are likely to persist. Around the country, courts and independent redistricting commissions have been called upon. But so far, the big questions that haunt every such dispute—What makes a district gerrymandered? How do you draw a truly neutral map?—have proven surprisingly difficult to answer.

At least, that is, by human beings.

Some researchers, armed with powerful new electoral data, have begun asking what might happen if human decisions were entirely removed from the equation. If regular citizens, state lawmakers, and Supreme Court justices can't figure out redistricting, perhaps an algorithm can.

Anatomy of a Crisis

The roots of Pennsylvania's crisis lie in the 2010 midterm election. After winning huge electoral victories, Republicans set about the regularly scheduled task of redrawing the commonwealth's congressional district lines. In a state with about 1 million more registered Democrats than registered Republicans, it's not easy to carve out districts that virtually ensure GOP victories. But they managed it.

In 2012, thanks to the new maps, Republicans won 13 out of 18 races—even though Democratic candidates received more total votes. The 13–5 split in the state's congressional delegation persisted in the 2014 and 2016 elections, and the GOP-drawn districts made a Democratic takeover in 2018 seem nearly impossible to imagine.

Then in January, the Supreme Court of Pennsylvania ruled that the districts were "plainly, clearly, and palpably" unconstitutional because counties were unfairly fractured to give Republicans an advantage. In a 5–2 decision, the Court ordered the old maps scrapped. It then instructed the state legislature to draw new ones in less than a month. If lawmakers failed to do so on time, the Court said, the justices would do it themselves.

Pennsylvania's congressional districts before the most recent legal challenge. Source: Supreme Court of Pennsylvania.Pennsylvania Republicans accused the state Supreme Court of judicial imprudence. Although Pennsylvania judges are technically nonpartisan, they noted that all five justices who voted against the GOP's map had been elected as Democrats. One of them, Justice David Wecht, was elected in 2015, and had called gerrymandering "an absolute abomination" during his campaign. Republicans called that an implicit promise to strike down the 2011-era maps.

Wecht's comments, the party-line ruling in the League of Women Voters case, and the state Supreme Court's declaration that it had the authority to redraw the map without legislative input—a pretty clear violation of the rules found in both the state and the federal constitutions—looked to GOP lawmakers like a political coup from the bench. A bill to impeach several of the justices was introduced in the General Assembly, and all hell broke loose.

Amid the grumbling and the threats against sitting judges, GOP lawmakers did indeed draw a new map and passed it through both chambers of the legislature. Although it removed some of the most egregious elements of the old map, several analysts condemned it for maintaining a Republican tilt. "A prettier map can still conceal ill-intent," said Sam Wang, a neuroscientist who runs the Princeton Election Consortium site.

After Wolf vetoed the new districts, Speaker of the House Mike Turzai (R–Allegheny) and Senate President Joe Scarnati (R–Jefferson) wrote a joint letter accusing him of setting forth a "nonsensical approach to governance." Among other things, the governor had taken issue with the placement of Erie in a primarily rural district. But Erie is located in the state's sparsely populated northwest corner, near no other population centers. Where else, the GOP leaders asked, were they supposed to put it, given that "there are no voters in Lake Erie, and we are not allowed to go into Ohio, New York, or Toronto"? According to Turzai and Scarnati, the Democratic governor and Democrats on the state Supreme Court were conspiring to "divest the General Assembly of its constitutional authority to enact congressional districts."

If that was the justices' intent, they accomplished the mission on February 19 by releasing their own congressional district map and ordering the Department of State to use it for the upcoming midterm elections.

Pennsylvania's congressional districts as redrawn by the state Supreme Court. Source: Supreme Court of Pennsylvania.At first glance, the Supreme Court's districts appear less gerrymandered than either the 2011 map or the proposed Republican replacement. But a prettier map can still conceal ill-intent, and observers say Democrats stand to gain.

"This is the PA map Dems wanted," tweeted Dave Wasserman, the U.S. House editor for The Cook Political Report. "The PA Supreme Court's map doesn't just undo the GOP's gerrymander. It goes further, actively helping Dems compensate for their natural geographic disadvantage in PA."

Democrats could win between eight and 11 seats with the new map, Wasserman said. Other analyses came to similar conclusions, with Democrats favored in at least seven districts and having a good chance to win 10 or more—a big change from the previous 13–5 GOP edge.

Pennsylvania Republicans have petitioned the U.S. Supreme Court, asking the justices in Washington to rule that their state-level counterparts are usurping a power explicitly given to legislators in Article I, Section 4 of the U.S. Constitution.* "Pennsylvania will be the future in every state if the Justices decide that judges should be redistricting kings," warned a Wall Street Journal editorial. Even President Donald Trump waded into the controversy. "Your original [map] was correct!" he tweeted. "Don't let the Dems take elections away from you so that they can raise taxes & waste money!"

'Destructive to Representative Democracy'

Pennsylvania faced the most acute gerrymandering crisis of the decade. But it is not the only place where an egregiously partisan map has been drawn. In 2011, North Carolina was carefully redistricted to give Republicans a significant electoral advantage. (A year later, the GOP won 10 of the state's 13 districts despite losing the aggregate vote.) The U.S. Supreme Court is currently weighing a challenge to Wisconsin's Republican-drawn districts, which critics say disenfranchise minorities in Milwaukee and other cities.

Democrats have increasingly seized on redistricting as an explanation for their electoral shortcomings. Gerrymandering is "destructive to the representative democracy that our founders envisioned," former Attorney General Eric Holder wrote in The Washington Post last year. He's now heading a campaign organization aimed at helping Democrats retake state legislative seats before the 2021 reapportionment happens.

But Democrats have drawn maps designed to confer partisan advantage as well. In Illinois, the 4th district looks like a pair of earphones; its two halves are connected at one point by a strip only as wide as Interstate 294. Maryland's 3rd district bobs and weaves its way from Annapolis to Baltimore on a snaking path that in some places is no more than a few hundred yards wide.

Gerrymandering has been blamed for a lack of competitive congressional elections, for growing levels of extremism in both major parties, and for a perceived breakdown in trust between citizens and government. Opponents say it allows elected officials to choose their voters, rather than the other way around.

The practice is not singularly responsible for any of the ills attributed to it, and Democratic efforts to highlight the importance of fair districts are also fueled by partisan motivations. Yet as the showdown in Pennsylvania proves, battles over redistricting have the potential to become true constitutional crises.

Of Packing and Cracking

Fights over the "best" way to set district boundaries can seem like petty partisan distractions—just another way in which America's two major parties insulate themselves from meaningful competition in the political market.

But there's more to redistricting than simple partisan jockeying, says Walter Olson, a senior fellow at the libertarian Cato Institute. Redistricting also offers a glimpse into the hidden ways in which politicians exert and preserve their power.

"You miss a lot of it if you look just at the Republican vs. Democratic stuff," says Olson, who sat on a commission** that proposed alternative redistricting methods for Maryland in 2015.

That experience gave Olson a new perspective on how redistricting manipulates the political fortunes of individual politicians and shapes the membership of Congress. District lines are sometimes drawn for intensely personal reasons—to remove a prospective challenger from an incumbent's turf, for example, or to put two opposition lawmakers in the same district so that only one can win the seat.

"A lot of it is the ability of leadership to punish backbenchers. A lot of it is the alteration of districts in a way that benefits people with access to inside political resources," Olson says. "I realized that the system allowed manipulation of a much more varied and subtle type than I'd expected."

None of this is new. The word gerrymandering was coined in the 1810s to describe a particularly lizardy-looking district carved out of rural Massachusetts by Gov. Elbridge Gerry, who wanted a favorable constituency for a run at Congress. The practice stretches back into at least the early 18th century, when leaders of the counties surrounding Philadelphia conspired to limit the city's influence in the colonial assembly, according to historian Elmer Griffiths. Pennsylvania, it seems, has always been a leader when it comes to tilting the scales of representative democracy.

The U.S. Constitution gives few requirements for how districts are to be drawn. Article 1 puts state legislatures in charge of the process but says little else about it. The 14th Amendment, and later court rulings based on it, require that each district have roughly the same population. Beyond that, legislators have been able to get away with almost anything. The motivation is the same as it was in Gerry's day: Friendly district lines can be the difference between an early retirement and years of easy re-election campaigns.

The word gerrymandering was coined in the 1810s to describe a particularly lizardy-looking district carved out of rural Massachusetts by Gov. Elbridge Gerry, who wanted a favorable constituency for a run at Congress.

What is new is the level of sophistication available to the lawmakers charged with creating the maps. Over the past two decades, political campaigns have steadily evolved in their ability to use demographic data to target individual voters. That same technology has helped political mapmakers draw ever more exact district lines. The adage about politicians getting to pick their voters has never been more accurate.

Joanna AndreassonThere are two basic strategies used for crafting a partisan map: "packing" and "cracking." Packing involves crowding as many of your opponent's voters into a single district as possible. North Carolina's 12th district—which winds from Charlotte to Winston-Salem and Greensboro—is a perfect example of packing Democratic voters into one weird-looking district, thus excluding them from the districts nearby. The packed district becomes, effectively, a single-party domain, while neighboring districts become more favorable for the other side.

Cracking is exactly the opposite. Pockets of demographically similar voters are separated into different congressional districts to eliminate their potential influence. This may explain why the famously liberal city of Austin, Texas, is split between three districts, all controlled by Republicans. Or why the relatively liberal enclave of Salt Lake City and its suburbs fall into four different districts, effectively leaving Utah's only significant population center without a representative in the U.S. House.

In Pennsylvania, Republican mapmakers packed as many of the state's Democratic voters as they could into just five districts: two in Philadelphia, another in a bluish part of the Philly suburbs, one in Pittsburgh, and a fifth that winds between several Democrat-heavy cities in the state's northeastern corner but excludes the redder areas outside them. Democratic leaders did not object much because party bosses in the state's two major cities got the districts they wanted. The 2011 vote to approve the map was a bipartisan one.

The biggest beneficiaries of redistricting are not the members of one party or the other but sitting office holders on both sides. "It's a multidimensional thing, but I think it all comes back to incumbents," says Olson. A party can safeguard key players and rising stars, and it can end the political careers of outsiders who buck the party line—all by shifting the map one way or another. Since state lawmakers draw the lines for members of Congress, redistricting is also a way to keep federal lawmakers beholden to their state-level party bosses. "Cross the leadership and you just might get cut into a tough new district next time," Olson says.

No Clear Line

The 2017–18 term is not the first time the country's high court has confronted this issue. In 2004, a group of Pennsylvania voters challenged an earlier set of Republican-drawn district boundaries on the theory that they unfairly disenfranchised Democrats. (Sound familiar?) In the end, the Court ruled in Vieth v. Jubelirer that it could not adjudicate claims of political gerrymandering for lack of a "workable standard" for identifying it. In a dissenting opinion, then–Justice David Souter proposed a multistep process to determine whether districts exhibited an "extremity of unfairness" toward one party or another. But the other justices were not convinced.

Each step in Souter's proposal, then–Justice Antonin Scalia wrote in his plurality opinion, required "a quantifying judgment that is unguided and ill-suited to the development of judicial standards." There is no clear line to indicate how much packing and cracking is too much, he observed, and courts should not be in the business of trying to sort out the motivations of partisan legislators. "The devil lurks precisely in such detail," Scalia wrote. "The central problem is determining when political gerrymandering has gone too far. It does not solve that problem to break down the original unanswerable question into four more discrete but equally unanswerable questions."

The current debate involves the same tensions highlighted 14 years ago by Souter and Scalia. Smart people often come down on different sides of the central question: Is it possible to apply objective, measurable standards to determine whether a district has been unlawfully gerrymandered?

Since 2011, Pennsylvania's 7th district has been cartoonishly shaped. David Daley, author of 2016's Ratf**ked: The True Story Behind the Secret Plan to Steal America's Democracy (Liveright/W.W. Norton), described it as looking like "Goofy kicking Donald Duck." It wound through parts of five counties, from the rural Amish farmlands around Lancaster to the heavily urbanized western edge of Philadelphia. In its January ruling, the state Supreme Court pointed specifically to that odd shape as an example of a district that is not compact.

Compactness is a term that gets thrown around a lot in redistricting debates. It can mean different things in different contexts, and there's probably not a single gold standard for measuring it, according to Daniel McGlone, a senior analyst for the Philadelphia-based mapping software firm Azavea. Yet it's a generally accepted principle among redistricting reformers that more compact districts are usually better than weirdly stretched or branched ones.

Math to the Rescue?

Various methods for calculating compactness have been proposed. The Polsby-Popper system, invented by two lawyers in the 1990s, compares the ratio of a district's area against a theoretical circle with the same circumference as the district's perimeter. That ratio indicates how much the district is indented on a scale of zero to one. The national average for a district is about 0.223, but the infamous Pennsylvania 7th scored just a 0.041, making it one of the least compact districts in the country.

There are other methods for measuring compactness as well. The Schwartzberg score is similar to Polsby-Popper, except it's the ratio of a district's perimeter measured against the circumference a circle whose area is equal to the district's. The Reock score requires drawing the smallest possible circle that would encompass all points of a district, then comparing the area of the circle to the area of the district.

These systems allow anyone with a map, a few basic drafting tools, and a calculator to score any district in the country. But looking only at the shapes can miss an important part of diagnosing a partisan political map: the outcome of elections held within it.

When a computer can spit out 100 different relatively fair and compact options, a map full of conspicuously partisan districts becomes harder to rationalize.

That's why another metric has gained currency in redistricting circles in recent years. Devised by Nicholas Stephanopoulos, a law professor at the University of Chicago, and Eric McGhee, a researcher at the Public Policy Institute of California, the "Efficiency Gap" is at the center of the Wisconsin redistricting case that is currently before the U.S. Supreme Court. To catch "packing" and "cracking" in action, it looks at whether districts are overloaded with voters from one party in order to boost the political fortunes of the other party in other places. Unlike purely geographical measurements, it attempts to quantify the partisan intent behind district lines.

The Efficiency Gap measure the number of "wasted" votes in each congressional district, defined as any vote for a losing candidate at all and any vote for a winning candidate above and beyond the number needed to secure a victory. The formula attempts to highlight partisan imbalance among all the districts in a state, with the underlying assumption being that districts should be as competitive as possible to reduce the number of "wasted" votes.

Working in its favor is this system's simplicity: No software is needed, just election results and basic math. But there are gaps in the Efficiency Gap. For one, it requires that elections be held before it can be employed. That makes it useful for determining whether districts are fair after they've been drawn and put to use, but it doesn't offer much help for how to go about drawing boundaries to avoid such problems in the first place. For another, the Efficiency Gap relies entirely on election results, which can be misleading. A blowout win in one district means lots of "wasted" votes for the victorious party under the Efficiency Gap model, but that doesn't necessarily mean the map was designed to bring about that outcome. A particularly bad opponent, a national electoral wave, or any number of other factors could give a false positive if the Efficiency Gap is the only metric you're using to decide whether a district is unfair.

Measures that seem more objective, such as Polsby-Popper, have shortcomings too. A congressional district that follows lines already on the map—geographic dividers such as rivers, or political boundaries such as municipal borders—is more likely to respect already-recognized communities and less likely to unnecessarily split up constituencies. But this salutary outcome may come at the expense of a better Polsby-Popper score. "Statistical compactness measures can have a problem because they don't look at the underlying geography," says McGlone. A perfectly round district would score a 1 in this system, but that doesn't make it ideal.

We have yet to discover a perfect method for deciding whether a district is "compact" or "fair," but the tools now available to judges, lawmakers, and activists at least offer a few ways to get at that question. Which is important, because as Scalia pointed out in 2004, gerrymandering will remain an "unanswerable problem" until courts have a way to define what it is and what it isn't.

'Redistricting Should Be Boring'

In their attempts to prevent partisan redistricting, many states have created "independent commissions" that empower supposedly disinterested members of the general public to craft maps, or at least to give input to the legislature.

Those efforts have had mixed results, with biases often managing to infiltrate a supposedly nonpartisan process. In California, for example, a highly touted "citizens commission" redrew congressional district lines in 2011, but a ProPublica investigation revealed that Democratic activists and labor unions had secretly packed the body to influence the outcome.

​Azavea, 'Measuring District Compactness in PostGIS,' 2016​Even when they are not consciously sabotaged, citizens commissions don't do a very good job of un-gerrymandering districts. Researchers from Yale and the University of California, Los Angeles compared a set of 1,473 proposed district maps from 13 states where citizen input is part of the process against a set of maps created by computer simulations. After comparing simulated and actual election results using the different maps, researchers concluded that 77 percent of maps drawn by state lawmakers were less competitive than the computer-drawn alternatives—not very surprising, given the incentives for legislatures to create "safe" districts for incumbents. But the maps drawn by members of the general public were just as bad, with 75 percent of them being less competitive than their simulated counterparts.

So what if we took human beings out of the equation entirely?

"Redistricting should be a bureaucratic, boring process where you get the census data, you turn the crank, and you get new maps for the next decade," says Brian Olson (no relation to Walter), a Boston software engineer who has designed a computer algorithm to do exactly that. Olson's model uses numbers collected by the U.S. Census Bureau to ensure each district has the same number of voters and produces districts that are as compact as possible—garnering high scores on measures like Polsby-Popper and Reock—without regard for party registration or demographic information. Partnering with the website FiveThirtyEight, Olson then tweaked the model to show greater respect for existing political boundaries, such as county borders.

In his simulated map, there are few tendrils reaching out to snare extra pockets of desirable voters and, by design, no cities split three or four ways in order to eliminate their political influence. Any set of arbitrary lines on a map can be criticized for being drawn here instead of there, but Olson's algorithmic congressional maps are more compact and, according to a FiveThirtyEight analysis of likely election results, more competitive than what most states have now as well.

McGlone believes technology will play an important role in holding mapmakers accountable in 2021, when the next nationwide redistricting occurs. Azavea, where he works, is developing a program called District Tracker that will allow anyone to plug in freely available census data and draw their own congressional district maps. It's set to launch nationally later this year.

If the U.S. Supreme Court doesn't accept the Efficiency Gap as a bright line for ruling certain districts out of bounds, people will have to look for other ways to challenge maps they believe were drawn in bad faith. By giving average citizens and reform-minded organizations access to the same mapmaking tech that experts already use, Azavea and others make it easier for petitioners to provide courts and legislative bodies with alternatives to consider. When a computer can spit out 100 different relatively fair and compact options, a map full of conspicuously partisan districts becomes harder to rationalize.

Checking Our Worst Impulses

Stopping politicians and parties from using redistricting to preserve their power probably requires settling on an objective standard for determining gerrymandering. Fourteen years ago, the Supreme Court said such a standard did not exist. Now perhaps it does.

But even if the justices come to the same conclusion when they rule in the Wisconsin case that they came to in '04, lawmakers in any given state could take the initiative and create a gerrymandering standard on their own—forbidding districts with a Polsby-Popper score of less than 0.25, for instance. In comparison, the 2011 Pennsylvania districts averaged 0.16 on the Polsby-Popper and 0.28 on the Reock. The new Supreme Court–drawn map averages 0.30 and 0.43, respectively.

Setting a lower bound "would provide something like a fence," says Cato's Olson. "Gerrymandering could be as politically motivated as they want as long as they stay within the fence."

The Arizona Reapportionment Commission, overseen by a bipartisan collection of county commissioners, officially uses Polsby-Popper to evaluate proposed districts. Currently, there are no hard rules about what constitutes an acceptable score. If the commission did draw a line, critics would surely complain that its exact placement was arbitrary—and they'd have a point. But at least it would give both sides a clear understanding of where, to use Olson's term, the "fences" are.

Both parties should want to erect those fences now. Republicans took advantage of the opportunity afforded them in 2011 on the heels of the Tea Party wave. But who holds the reins of power could look different in 2021 and beyond.

It seems inevitable, especially in a hyperpartisan environment, that political parties will want to use every tool at their disposal to gain a redistricting advantage. That prospect should be worrying enough to convince lawmakers to place some limits on the process. Even if the five Democratic justices on Pennsylvania's high court had nothing but good intentions in tossing the 2011 map (which was, after all, plainly political), the appearance of partisan motivation is unfortunate in a case that's already entirely about competing political interests.

Will every subsequent change in the balance of the state Supreme Court mean congressional districts must be redrawn again to the majority of the bench's liking? If so, judicial elections in Pennsylvania just gained a new level of partisan significance—and the same thing could soon play out in other states. On the other hand, rules that a legislature sets for itself are less likely to create future constitutional crises.

One defining feature of American democracy is the intentional inclusion of elements meant to check politicians' (and factions' or parties') worst impulses. When those limitations do not exist, abuses like gerrymandering occur, inverting the all-important relationship between voter and representative. Removing self-interest from redistricting is probably impossible—too many people are too invested in the outcome of the process—but if we can finally get to a definition of gerrymandering, courts and citizens can start to do something about it.

"I don't think we're ever going to be able to take humans out of the process completely," says McGlone. But with technology, at least we can "shame politicians, or just show that it can be done better, done in a more collaborative way, rather than just by politicians behind closed doors." And with any luck, by limiting the nastiest abuses, we'll prevent a repeat of the current conflagration in Pennsylvania.

*Since this story went to press, the U.S. Supreme Court decided against reviewing the new district map drawn by the Pennsylvania Supreme Court. The federal court offered no comment on the map or the process used to draw them, issuing only a one sentence statement by Justice Samuel Alito denying the Republican-backed bid to have the new map reviewed. In the wake the decision, some Republican lawmakers in Harrisburg have again discussed a longshot bid for the impeachment of state Supreme Court justices.

**CORRECTION: The original version of this story erroneously claimed that Walter Olson was a member of Maryland's redistricting commission in 2011. He was a member of the Maryland Redistricting Reform Commission, which met in 2015 to review the 2011 commission's work and to propose alternative methods of redistricting to Gov. Larry Hogan.