---
title: "Applications"
output: 
  bookdown::html_document2:
    toc: true
bibliography: library.bib   
vignette: >
  %\VignetteIndexEntry{Applications}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Quantum Game Theory

HIV-1 (Human Immunodeficiency Virus) is a highly mutable virus that causes AIDS (Acquired Immunodeficiency Syndrome) by weakening the immune system. Current antiretroviral treatments focus on inhibiting viral maturation, but the virus's rapid mutation leads to treatment resistance. To address this challenge, a quantum game theory approach is proposed to model the competition and evolution of HIV-1 phenotypes [@Ozluer_Baser2022-nh].

  * Classical Approaches: Historically, research on HIV-1 evolution has utilized classical physics-based models, such as agent-based modeling, differential equations, Markov models, and classical game theory.

  * Quantum Perspective: Recognizing that molecular-level interactions follow quantum mechanics rules, this study employs quantum computation to analyze HIV-1 phenotypes' behaviors.

## Implementation of Quantum Game Theory Simulator

The `QGameTheory` package facilitates simulations of quantum game theory models. It utilizes a quantum circuit model, allowing computations with up to six qubits [@QGameTheory2020]. Key functionalities include:

  * Quantum State Initialization: Users can define quantum states and perform measurements, visualized through probability distribution plots.
  
  * Quantum Logic Gates: The package supports various quantum logic gates like the Hadamard gate, Pauli gates, CNOT, and more, enabling the simulation of quantum algorithms.
  
  * Game Theory Models: It includes simulations for classical game theory models like the Penny Flip Game, Prisoner’s Dilemma, Battle of the Sexes, and others, offering insights into quantum strategies and outcomes.

    Advanced Analysis: Functions like Iterated Deletion of Strictly Dominated Strategies (IDSDS) and Nash equilibrium calculations enhance strategic analysis within quantum game contexts.

## HIV-1 Phenotypes

  * Phenotype Competition: The study analyzes four HIV-1 phenotypes, each representing stages of replication, mutation, and selection. Evolutionary game theory principles are applied to understand their competitive dynamics.
  
  * Quantum Game Analysis: By integrating quantum perspectives, stable states and competitive scenarios among HIV-1 phenotypes are examined. This approach provides deeper insights into evolutionary strategies and potential treatment vulnerabilities.

Quantum game theory offers a novel lens for studying HIV-1 evolution and treatment strategies. By combining quantum computation with evolutionary game theory, this research aims to uncover new patterns, strategies, and potential interventions against HIV-1 infection and treatment resistance.

Th study of HIV-1's game of phenotypes, focuses on four key types: two infectious ones, V and v, with different production rates, and two defective ones, D and d, also with varying production rates. When HIV-1 tries to infect CD4+T cells, it uses a molecule called gp120. Sometimes, this molecule mutates, leading to defective viruses d and D that can't infect cells. Interest lies in the infectious viruses, V and v, because they can infect and transform into different types through mutations.

The phenotype game can be imagined as having viruses V and v in a competition. When V meets another V, they share resources (CD4+T cells) equally, resulting in a balanced outcome. Same goes for v. However, V reproduces faster, so it depletes resources quicker, making its life span shorter in evolutionary terms. When V meets v, V gains more because it reproduces faster and grabs more CD4+T cells.

Using  game matrices these outcomes are represented. For example, when V meets V, it's (alpha, alpha), meaning they share equally. When V meets v, it's (gamma, beta), indicating V gains more. Similar setups exist for v meeting V and v meeting v.

So, in the survival hierarchy, it's $gamma > alpha > theta > beta$, showcasing how the faster-reproducing viruses gain an edge in resource utilization and evolutionary continuity.

Evolutionary game theory peeks into a world where players play games for survival as a a mix of Darwin's evolution and a strategic match.

Evolutionary game theory  looks at how strategies evolve over time and see who comes out on top in a population. Genes can be pictured as determinants of which strategy wins and which fades into obscurity. It's less about decision making and more about what works best in terms of survival.

In regular game theory, players stick to strategies that give them the best payoff, like winning a game of cards. In evolutionary game theory, it's about what strategy survives the longest and spreads through the population. For this type of games the winning strategy keeps playing, while the losing one gets replaced.

The concept of evolutionarily stable strategy (ESS) is an strategy that stands the test of time. It's the one that, even if a mutant strategy tries to take its place, holds its ground and continues to dominate.

An evolutionarily stable phenotype is the virus that outlasts the others, even though it might not be the absolute best in terms of payoff. This highlights the necessity of prioritizing V when developing treatments because it's the survivor in this game.

Quantum game theory takes the perspective that these biological games are already happening at a molecular level, guided by quantum mechanics, where the rules are set by particles and waves. It's a whole new perspective that takes these games to a quantum level.

By looking at how quantum strategies could disrupt classical evolutionary stable strategies in populations, a quantum game model for the evolutionary trajectory of HIV-1 phenotypes applies quantum game strategies to understand how the virus evolves and competes within populations.

To obtain an implementation of the described process

  * Define the initial state as $|00⟩$ using the ket function.
  
  * Define the unitary operators $U_v$ and $U_V$ for phenotypes $v$ and $V$. In this case, both operators are identity matrices since the description mentions no specific transformation.
  
  * Apply the unitary operators to the initial state to simulate the moves of the phenotypes.
    
  * Calculate the inverse of the unitary operator $U$ and apply it to bring the game to the final state after measurement.
    
  * Print the final state after measurement.
  
To calculate the expected payoffs using unitary matrix $U$ and its inverse $U^{-1}$, along with the final state $|\psi_f⟩$ obtained from the previous implementation, leveraged by using the `six_state` function from `qvirus`.

 * We load the required libraries `qvirus` and `qsimulatR`.
 
 * Define the unitary matrix $U$ and its inverse $U^{-1}$ using the tensor and Pauli-X functions.
 
 * Define the initial state $\Lambda$ as $|00⟩$ and calculate the final state $|\psi_f⟩$ after applying $U$ and $U^{-1}$.
 
 * Use the `phen_hiv` function from `qvirus` to calculate the expected payoffs $\pi_v$ and $\pi_V$ based on the final state and the possible outcomes from Table 2.
    
 * Print the calculated expected payoffs.
 
First, let's define the unitary matrix $U$ and its inverse $U^{-1}$ as given:

$$
\begin{equation}
 U = \frac{1}{\sqrt{2}} (I^{\otimes 2} + i \sigma_x^{\otimes 2}) 
    (\#eq:phe1)
\end{equation}
$$


$$
\begin{equation}
 U^{-1} = \frac{1}{\sqrt{2}} (I^{\otimes 2} - i \sigma_x^{\otimes 2}) 
    (\#eq:phe2)
\end{equation}
$$

Here, $\otimes 2$ denotes the tensor product 2 times, and $I$ is the identity matrix, and $\sigma_x$ is the Pauli-X matrix (also known as the bit-flip or NOT gate in quantum computing). The term $i \sigma_x^{\otimes 2}$ represents a strategy that involves flipping the qubit's state using the Pauli-X gate.

When combined, $U$ creates a superposition of these strategies, giving each strategy an equal chance to be chosen. This represents a fair and unbiased approach to selecting strategies in the game.

The inverse unitary operator $U^{-1}$ is used to revert the effects of $U$ after the game has progressed. It allows the players to undo their chosen strategies and observe the final outcome.

The Kronecker product $\otimes$ combines two matrices or quantum states into a larger composite state. In the context of quantum games, it allows us to represent complex strategies that involve multiple qubits or actions.
    
For example, $I \otimes 2$ combines the identity matrix $I$ with a $2 \times 2$ identity matrix, effectively creating a larger $4 \times 4$ identity matrix that acts on two qubits simultaneously.

In this implementation:

  * Define the initial state $|00⟩$.
  
  * Define the Pauli-X gate (bit-flip gate) using a $2 \times 2$ matrix.

  * Define the unitary matrix $U$ and its inverse $U^{-1}$ to create the tensor products and combining them with scalar multiplication.

  * Apply the unitary matrix $U$ to the initial state $\Lambda$ to obtain the final state.

  * Apply the inverse unitary matrix $U^{-1}$ to the final state to obtain the final state of the system.

  * Calculate the probabilities of each outcome.
  
In quantum game theory, strategies are represented by unitary operators. Unitary operators are essentially transformations that can be applied to quantum states without changing their length or causing information loss. In the context of the Quantum Penny Flip game, the unitary operators $U$ and $U^{-1}$ represent the strategies available to the players (Alice and Bob).

The unitary matrix $U$ is designed to give equal probability to each quantum move, ensuring fairness in the game.

## Implementation in qvirus

```{r setup}
library(qvirus)
```

The `phen_hiv` function returns the final stage and payoffs of a quantum game of HIV phenotype.

```{r qgame}
library(qsimulatR)
phen_hiv <- function(strategy1, strategy2, alpha, beta, gamma, theta) {
  # Define the quantum gates
  I <- diag(2)
  X <- matrix(c(0, 1, 1, 0), nrow=2)
  H <- 1/sqrt(2) * matrix(c(1, 1, 1, -1), nrow=2)
  
  # Define the initial state |00>
  initial_state <- qsimulatR::qstate(nbits = 2, coefs = c(1, 0, 0, 0), basis = c("|00>", "|01>", "|10>", "|11>"))@coefs
  
  # Define the unitary transformation for mutant H gate
  U <- 1/sqrt(2) * (kronecker(I, I) - 1i * kronecker(X, X))
  V <- 1/sqrt(2) * (kronecker(I, I) + 1i * kronecker(X, X))
  
  # Apply the sequence of operations to the initial state
  state_after_U <- U %*% initial_state
  state_after_strategy <- kronecker(strategy1, strategy2) %*% state_after_U
  state_after_V <- V %*% state_after_strategy
  final_state <- U %*% state_after_V
  
  # Apply the inverse unitary transformation
  U_inverse <- Conj(t(U))
  psi_f <- U_inverse %*% final_state
  
  # Calculate the probabilities for each basis state
  prob_00 <- Mod(psi_f[1])^2
  prob_01 <- Mod(psi_f[2])^2
  prob_10 <- Mod(psi_f[3])^2
  prob_11 <- Mod(psi_f[4])^2
  
  # Calculate the expected payoffs for players v and V
  pi_v <- alpha * prob_00 + beta * prob_01 + gamma * prob_10 + theta * prob_11
  pi_V <- alpha * prob_00 + gamma * prob_01 + beta * prob_10 + theta * prob_11
  
  # Return the final state and the payoffs
  list(
    final_state = psi_f,
    payoffs = c("|00> alpha" = prob_00, "|01> beta" = prob_01, "|10> gamma" = prob_10, "|11> theta" = prob_11),
    pi_v = pi_v,
    pi_V = pi_V
  )
}
```

Implemented on the equilibrium and optimum, is given by strategy 1 and strategy 2 of both phenotype playing a mutant $\sigma_Z$ gate.

```{r qgame2}
strategy1 <- Z(2)@M # Identity matrix for strategy 1
strategy2 <- Z(2)@M # Identity matrix for strategy 2
alpha <- 1
beta <- 0.5
gamma <- 2
theta <- 0.1
phen_hiv(strategy1, strategy2, alpha, beta, gamma, theta)
```
