Contents
Socio-physical Modeling of Spanish Electoral Dynamics
Context & Motivation
This project explores a provocative and interdisciplinary question: Can we use mathematical tools from physics to understand political behavior? In particular, it investigates how Spanish electoral dynamics can be modeled using the principles of sociophysics, a growing field that applies statistical mechanics to social phenomena such as opinion formation, polarization, and voting.
The core idea of sociophysics is not to describe every nuance of human behavior, but to ask whether large-scale patterns—emerging from the interaction of thousands or millions of individuals—can be captured with simplified mathematical models. This approach is inspired by the success of statistical physics in explaining how local interactions among particles give rise to collective macroscopic properties in physical systems.
In democratic elections, voters influence each other through conversations, media, family, and social networks. This influence can lead to emergent phenomena: political polarization, sudden shifts in public opinion, or persistent partisan alignment. In this work, I explore whether such phenomena can be explained and even predicted using techniques borrowed from physics—specifically, Markov models, Ising-like systems, and agent-based simulations.
I focused on three guiding research questions:
- Do voting patterns in Spain exhibit universal features that are independent of context, as has been shown in other countries?
- Does the Spanish political system have “memory”? That is, do past election results statistically influence future outcomes in a quantifiable way?
- Can we build a mathematical model that realistically simulates how voters, parties, and leaders interact across multiple elections, incorporating both local influence and historical feedback?
By answering these questions, the goal is not only to understand Spanish politics better, but also to demonstrate how physical modeling can shed light on social dynamics. The project ultimately serves as an example of how skills in physics, computation, and data analysis can be applied in novel domains outside traditional scientific disciplines.
Theoretical Framework
To describe the collective behavior of voters, I built on two main mathematical tools from physics and probability theory: Ising-like interaction models (adapted to simulate social influence), and Markov chains (used to represent transitions between political states across elections).
The Ising Model & Social Influence
The Ising model is a classical framework in statistical physics designed to study how local interactions between particles can give rise to global order. In its original version, each “particle” (or spin) can be in one of two states: +1 or –1. These spins sit on a grid and interact with their neighbors, trying to align with them. When many spins align, we get magnetization—a collective phenomenon.
In social systems, we can reinterpret this idea: instead of particles, we have voters; instead of spin states, we have opinions or voting choices (e.g., vote for Party A or Party B). People tend to align with their peers, especially if there's strong social cohesion. The analogy is remarkably powerful: polarization and consensus can be modeled as “phase transitions,” just like in physical materials.
In this project, I used a specific extension of the Ising model called the Sznajd model, which simulates opinion dynamics. Its core rule is: “United we stand, divided we fall.” In this setup:
- If two neighboring agents agree, they influence their neighbors to adopt the same opinion.
- If they disagree, their neighbors tend to adopt opposite views—leading to polarization.
This model captures essential aspects of social contagion, peer pressure, and opinion formation. It allows for the simulation of clusters of opinion, consensus emergence, and even stable alternation between two choices—just like in real elections.
Markov Chains & Electoral Memory
The second key tool is a discrete-time Markov chain, a model from probability theory that describes systems that evolve over time via transitions between states. The defining feature is the Markov property: the future state depends only on the present, not on the full history.
In this project, I used a 3-state Markov model to simulate the career of political leaders:
- State 1: A newly elected leader
- State 2: A leader who has been re-elected once
- State 3: A leader re-elected more than once
Transitions between these states represent what happens in each election. For example, a newly elected leader might be re-elected (transition from state 1 to 2), or replaced (back to state 1). The transition probabilities are estimated from historical data, forming a matrix P. Over time, the model reaches a stationary distribution that tells us how likely each scenario is in the long run.
This framework allows us to ask: Does past political dominance increase the chances of future success? If so, it means the system has “memory.” Validating this with real data helps connect physical models with empirical political behavior.
Universal Voting Patterns in Spanish Senate Elections
As a first empirical exploration, I analyzed over 40 years of individual voting data from the Spanish Senate elections (1977–2023) to test a hypothesis proposed by Fortunato & Castellano (2007): that the distribution of relative votes received by candidates follows a universal statistical law, independent of country or historical context.
The Variable vQ/N
In Spain's Senate elections, voters choose individual candidates, not party lists. This enables the study of personal popularity relative to collective voting behavior. For each candidate, I computed the dimensionless ratio:
This normalization allows for fair comparison across parties, regions, and years. A value of vQ/N ≈ 1 means the candidate received the “expected” number of votes given their party. Values above or below reflect individual popularity or rejection.
Empirical Findings
After collecting and cleaning the Senate election data (using Python's pandas and numpy), I plotted the histogram of vQ/N values for all elections combined. The result was a right-skewed bell-shaped distribution, consistent with a log-normal model:
Fitting the parameters (μ, σ) via maximum likelihood estimation yielded good agreement with the observed data (see figure below). The peak of the distribution was near v = 1, suggesting that in most cases, candidates attract votes proportionally to their party's average—a sign of strong party identity.

Fitted log-normal distribution for vQ/N. Most values cluster near 1.
This result supports the idea of universality in electoral behavior: despite cultural and historical differences, voters tend to evaluate candidates in statistically predictable ways. It also validates the use of dimensionless variables (like vQ/N) in sociophysics.
These findings set the stage for more dynamic modeling: if voter behavior has stable statistical features, then perhaps its evolution over time can also be modeled systematically.
Modeling Political Memory with Markov Chains
Having observed statistical regularity in voter behavior, I turned to a deeper question: Does political power in Spain follow a memoryless process, or are future leadership outcomes influenced by past incumbency? To test this, I modeled the evolution of political leadership as a discrete-time Markov chain, using real electoral data from 1977 to 2023.
States and Transitions
I defined a simplified model of political career stages based on the outcome of general elections. Each state represents a phase in the leadership lifecycle:
- S₁: Newly elected leader (first term)
- S₂: Re-elected leader (second term)
- S₃: Long-term incumbent (third or more term)
At each general election, transitions occur: a new leader may win re-election, lose power, or continue holding office. These transitions define a Markov chain with state space {S₁, S₂, S₃}, and probabilities estimated from historical successions in Spain’s government.
The resulting transition matrix P was:
Each entry represents the probability of moving from state to state in one election cycle. For instance, a new leader () has a 71% chance of being re-elected once ().
Long-Term Behavior
A key property of finite Markov chains is that, under mild assumptions, they converge to a stationary distribution , which satisfies:
Solving this system yielded:
Interpretation: in the long term, we expect 16% of governments to be newcomers, 27% to be serving a second term, and 57% to be long-term incumbents. This indicates a strong tendency for power retention in the Spanish system—not a memoryless process, but one favoring continuity.
Statistical Validation
To evaluate the validity of the model, I compared the expected frequency of transitions with the observed sequence of electoral outcomes using a Chi-square goodness-of-fit test. The result:
Since the p-value is well above any common significance threshold (e.g., 0.05), we cannot reject the null hypothesis that the model fits the data. In other words, the Markov chain provides a statistically plausible descriptionof Spain’s electoral leadership dynamics.
Insight
This analysis shows that past incumbency plays a role in future re-election probabilities. It quantifies how political systems exhibit statistical “memory” — a finding with implications for political modeling, election forecasting, and the broader application of stochastic processes in social science.
Sznajd-Ising Voting Model with Feedback Dynamics
To go beyond empirical analysis, I developed a computational model of voting inspired by interacting particle systems in statistical physics. The model combines ideas from the Sznajd model of opinion dynamics, the Ising model of spin alignment, and feedback loops based on political success or failure.
Model Architecture
The model operates on three interconnected layers, each representing a different scale of political dynamics:
- Micro Level: A 2D grid of agents (voters), each with an opinion , updated based on their neighbors and external signals.
- Meso Level: Representatives are chosen by local majority; they form a “parliament” where a leader is selected via Gaussian-distributed reputation scores.
- Macro Level: The leader is evaluated as successful or not based on a probabilistic threshold. This perception affects future voter alignment via an external field .
Micro-Level Interactions
At the micro level, agents follow a modified Sznajd rule: if two neighbors agree, they attempt to convince adjacent agents. If they disagree, they may promote the opposite opinion. The probability of changing state is governed by a local “tension function” analogous to the Hamiltonian in the Ising model:
where:
- controls the strength of local peer influence.
- represents the external field (political climate, media, leadership feedback).
- is the opinion of agent .
The agents update their state using a probabilistic rule based on the Boltzmann distribution:
where is the energy difference if the agent flips state, and reflects how strongly success or failure influences opinion formation. There are two values of :
- — applied when the leader was perceived as successful
- — applied otherwise
Meso & Macro Dynamics
After voters stabilize, each region elects a representative based on majority rule. Each representative receives aleadership score sampled from a Gaussian distribution. The one with the highest score becomes the leader.
This leader is evaluated based on whether their score exceeds a threshold (e.g., 0.7). The outcome affects the value of for the next iteration, simulating how perceived political success or failure influences the public mood and future elections.
Interpretation of Parameters
- — peer pressure strength. Higher J leads to faster consensus or polarization.
- — reinforces opinion when a leader is successful.
- — creates destabilization when a leader fails.
- — global field; models sentiment trends, propaganda, legacy.
By tuning these parameters and observing the macroscopic behavior of the system (e.g. reelection rate, opinion clusters, polarization), I could simulate and analyze long-term political trends under controlled synthetic conditions.
Simulation Results & Parameter Analysis
After implementing the model, I ran simulations varying key parameters to observe how the system evolves under different conditions of social cohesion, leadership perception, and external feedback. Each simulation represents a multi-election cycle, where voters interact, form opinions, elect leaders, and update their beliefs based on the leader’s performance.
Metric: Re-election Rate
A central output of the model is the reelection probability of political leaders over time. I ran simulations for 10,000 iterations with varying and , while keeping peer influence fixed at .
The model correctly reproduced the empirical reelection rate observed in Spain (~58%) when using:
This indicates that voters are more sensitive to failure than to success, reflecting a real-world bias where disappointment has greater influence than approval.
Metric: Social Magnetization
The system’s global opinion alignment is measured by the average opinion:
When , society is fragmented. When , the population is highly polarized or reaches consensus.
Increasing led to faster polarization, while biases the direction depending on the recent perception of leadership.
Parameter Sweep
To understand the stability and sensitivity of the model, I performed a parameter sweep over and , observing how reelection probability evolves. Results showed:
- Re-election rate increases with , but plateaus quickly.
- Re-election rate decreases steeply with , showing voters punish failure more aggressively.
- There exists a critical balance point where positive and negative feedback cancel out.
Analytical Approximation
In the mean-field limit, the system satisfies the self-consistent equation:
This expression captures the non-linear feedback loop between individual alignment and collective field effects. No bifurcation threshold was observed in , but solutions became more sharply peaked as increased.
Interpretation & Comparison
The model successfully reproduces macro-observables like reelection rates and opinion shifts seen in Spanish elections. It also captures asymmetries in social response: citizens react more strongly to political failure than to success.
The simulation confirms that local interactions and historical feedback are sufficient to explain certain features of electoral systems without requiring complex psychological assumptions.
(Simulation visualizations available in the blog section and dataset repository)
Conclusions & Reflections
This project is a concrete demonstration of how tools from statistical physics and probabilistic modeling can be meaningfully applied to social systems. Through a combination of data analysis, stochastic processes and simulation techniques, I explored the dynamics of Spanish electoral behavior over nearly five decades.
Empirically, the study confirmed universal patterns in individual voting behavior via the analysis of normalized Senate votes, and showed that the Spanish political system exhibits statistical memory, captured effectively through a Markov chain model validated against historical data.
On the theoretical side, I developed an agent-based model inspired by Ising and Sznajd dynamics, incorporating feedback from leadership success. The model integrates micro-level peer influence and macro-level opinion shifts through a minimal yet expressive parameter set, capable of reproducing real-world patterns like reelection bias and polarization.
Beyond its scientific contributions, this project reflects my ability to learn independently and rigorously about unfamiliar fields, to transfer mathematical and computational tools to new contexts, and to build formal models from real-world questions. I had no prior background in sociophysics or political science, yet I was able to critically engage with research literature, adapt methods from physics, and produce simulations grounded in both theoretical reasoning and empirical data.
Technically, the project strengthened my skills in:
- Extracting and transforming large real-world datasets for statistical modeling
- Formalizing complex social dynamics through physical and probabilistic frameworks
- Designing agent-based simulations with multi-scale dynamics and feedback mechanisms
- Validating computational models with empirical benchmarks and statistical tests
- Communicating interdisciplinary research with clarity, rigor, and attention to mathematical precision
In short, this work illustrates what I value most in science and engineering: the ability to combine critical thinking, mathematical modeling, and computational experimentation to explore complex systems, even outside traditional disciplinary boundaries.
(This project originated as my undergraduate thesis in physics. If you're interested in the full thesis or would like to discuss the model in more depth, feel free to reach out — I'm happy to share it.)