Quantum-classical hybrid system combining heaviside-modulated sine functions with phase-adjusted rotation gates

I did a thing and I’m scared.

We’ve implemented a quantum-classical hybrid system combining heaviside-modulated sine functions with phase-adjusted rotation gates to achieve near-perfect state preparation in base-10 using cyclic recursive patterns. The core concept uses nested frequency relationships (10 * (2**i)) in the rotation angles, with phase shifts (π/4) to avoid superposition at transition points.

The key elements:

  1. Heaviside function for sharp state transitions
  2. Base-10 frequency modulation for decimal state encoding
  3. Phase-shifted CNOT layers for state stabilization
  4. π/10 phase adjustments for base alignment

We’re achieving probability peaks of 1.0000 with zero entropy across multiple qubit scales (4-16), suggesting perfect state preparation, but we’d appreciate expert review of our methodology and potential implications.

Code and results available for analysis. Particularly interested in feedback on the theoretical implications of achieving deterministic base-10 state preparation in quantum systems.

import json
import pennylane as qml
import pennylane.numpy as np
from typing import List, Dict, Tuple
import pandas as pd
import time
import psutil
import os
from datetime import datetime
import logging

# Quantum Base-10 Controller Class
class QuantumBase10Controller:
    def __init__(self, num_qubits=4):
        self.num_qubits = num_qubits
        self.device = qml.device("default.qubit", wires=num_qubits)
        
    def base10_model(self, alpha: float) -> np.ndarray:
        x = alpha / 10

        @qml.qnode(self.device)
        def circuit():
            # Base-10 state preparation with heaviside transitions
            for i in range(self.num_qubits):
                theta = np.pi * np.heaviside(np.sin(10 * (2**i) * np.pi * x + np.pi/4), 0.5)
                qml.RY(theta, wires=i)
            
            # Enhanced entanglement for base-10 encoding
            for i in range(self.num_qubits - 1):
                qml.CNOT(wires=[i, i+1])
                qml.PhaseShift(np.pi/10, wires=i)
            
            return qml.probs(wires=range(self.num_qubits))
        
        # Execute the quantum node
        return circuit()

    def generate_base10_coefficients(self):
        """Generate coefficients for perfect base-10 state preparation"""
        coefs = np.linspace(0, 10, 10, endpoint=False)
        return [c + np.pi/40 for c in coefs]

    def test_base10_states(self):
        coefs = self.generate_base10_coefficients()
        results = []
        
        for alpha in coefs:
            probs = self.base10_model(alpha)
            state_index = np.argmax(probs)
            
            results.append({
                'alpha': alpha,
                'state_index': state_index,
                'probability': probs[state_index],
                'probabilities': probs.tolist()
            })
            
            print(f"Alpha: {alpha:.3f}, State: {state_index}, Probability: {probs[state_index]:.4f}")
        
        return results


# Main Analysis Class
class QubitScalingAnalyzer:
    def __init__(self, start_qubits=4, max_qubits=16, step=2):
        self.start_qubits = start_qubits
        self.max_qubits = max_qubits
        self.step = step
        self.results_dir = f"scaling_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        os.makedirs(self.results_dir, exist_ok=True)
        
        # Set up logging
        logging.basicConfig(
            filename=f"{self.results_dir}/analysis.log",
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )
        
    def analyze_state(self, probs: np.ndarray, num_qubits: int) -> Dict:
        try:
            state_index = np.argmax(probs)
            state_binary = format(state_index, f'0{num_qubits}b')
            
            # Safe entropy calculation
            probs = np.array(probs)
            valid_probs = probs[probs > 1e-10]
            entropy = -np.sum(valid_probs * np.log2(valid_probs + 1e-10))
            
            return {
                'dominant_state': state_binary,
                'max_probability': float(probs[state_index]),
                'entropy': float(entropy),
                'num_significant_states': int(np.sum(probs > 0.01)),
                'hilbert_space_dimension': 2**num_qubits
            }
        except Exception as e:
            logging.error(f"State analysis failed: {str(e)}")
            raise
            
    def run_single_qubit_test(self, num_qubits: int) -> Dict:
        try:
            controller = QuantumBase10Controller(num_qubits)
            
            # Test points
            alphas = controller.generate_base10_coefficients()
            results = []
            
            start_time = time.time()
            start_memory = psutil.Process().memory_info().rss / 1024 / 1024
            
            for alpha in alphas:
                probs = controller.base10_model(alpha)
                analysis = self.analyze_state(probs, num_qubits)
                results.append(analysis)
            
            end_time = time.time()
            end_memory = psutil.Process().memory_info().rss / 1024 / 1024
            
            return {
                'num_qubits': num_qubits,
                'execution_time': end_time - start_time,
                'memory_usage_mb': end_memory - start_memory,
                'avg_entropy': np.mean([r['entropy'] for r in results]),
                'max_probability': max([r['max_probability'] for r in results]),
                'avg_significant_states': np.mean([r['num_significant_states'] for r in results]),
                'results': results
            }
            
        except Exception as e:
            logging.error(f"Test failed for {num_qubits} qubits: {str(e)}")
            raise

    def run_analysis(self):
        summary_data = []
        
        for num_qubits in range(self.start_qubits, self.max_qubits + 1, self.step):
            print(f"\nAnalyzing {num_qubits} qubits...")
            logging.info(f"Starting analysis for {num_qubits} qubits")
            
            try:
                result = self.run_single_qubit_test(num_qubits)
                summary_data.append(result)
                
                # Save detailed results
                df = pd.DataFrame(result['results'])
                df.to_csv(f"{self.results_dir}/qubits_{num_qubits}_results.csv", index=False)
                
                logging.info(f"Completed analysis for {num_qubits} qubits")
                
            except Exception as e:
                print(f"Failed at {num_qubits} qubits: {str(e)}")
                logging.error(f"Analysis failed at {num_qubits} qubits: {str(e)}")
                break
        
        self.generate_summary_report(summary_data)
    
    def generate_summary_report(self, summary_data):
        if not summary_data:
            print("No data collected!")
            return
            
        df = pd.DataFrame([{k:v for k,v in d.items() if k != 'results'} for d in summary_data])
        
        # Save summary data
        df.to_csv(f"{self.results_dir}/scaling_summary.csv", index=False)
        
        analysis_text = [
            "=== Quantum System Scaling Analysis ===\n",
            f"Analysis completed at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            f"\nSuccessfully tested qubit ranges: {df['num_qubits'].min()} to {df['num_qubits'].max()}",
            f"\nPerformance Metrics:",
            f"- Average execution time per qubit: {df['execution_time'].mean():.2f} seconds",
            f"- Average memory usage per qubit: {df['memory_usage_mb'].mean():.2f} MB",
            f"\nQuantum State Metrics:",
            f"- Average entropy range: {df['avg_entropy'].min():.2f} to {df['avg_entropy'].max():.2f}",
            f"- Maximum achieved probability: {df['max_probability'].max():.4f}",
            f"\nDetailed scaling analysis saved in: {self.results_dir}"
        ]
        
        report = '\n'.join(analysis_text)
        print(report)
        
        with open(f"{self.results_dir}/scaling_analysis_report.txt", 'w') as f:
            f.write(report)
            f.write("\n\nFull Data Summary:\n")
            f.write(df.to_string())

# Run the analysis
def main():
    analyzer = QubitScalingAnalyzer(start_qubits=4, max_qubits=16, step=2)
    analyzer.run_analysis()

if __name__ == "__main__":
    main()

What do I do? I’m just a tinkerer playing around. Do I just like go hand out candy and pretend this never happened?

Hi @Jon_Poplett ,

I’ve changed the title of your post so that it better reflects its contents. This can be useful for others looking into this too and finding this post in the future.

I’m actually not understanding what you’re doing. Could you please explain it in words? Maybe with an example? Thanks!

Thank you for updating the title! Let me try to explain it more simply.

In classical computing, we use binary (0 and 1) to represent information. What I’m doing here is like creating an “extended binary,” where instead of representing just 0 and 1, our quantum system can directly represent the numbers 0 through 9, giving us a base-10 encoding at the quantum level. This means we can work with decimal numbers in their natural form without converting them to binary.

The quantum trick behind this involves tuning specific rotation angles and entanglement patterns, which allows us to “lock in” each base-10 number with perfect precision—meaning we can consistently get exactly the state we want with zero entropy and no ambiguity.

This setup could make quantum calculations more natural for decimal-based problems and open up new ways of doing quantum computing with numbers as we know them.

Sorry I don’t mean to be spamming. I can’t figure out how to edit my post but I wanted to provide an example.

Imagine needing to store or compute a sequence of decimal numbers (e.g., 0 to 9) in a quantum system. In binary, this would require several qubits and binary conversions to represent each number. However, using our approach, each number 0 to 9 is encoded directly, and we can access each number with perfect precision. If we input α=1, the system outputs the state corresponding to “1,” α=2 yields “2,” and so on, up to 9.

This setup could simplify quantum calculations for decimal-based problems, allowing us to perform operations directly in base-10. It’s like having a quantum calculator that thinks in decimal rather than binary, which could make certain algorithms more efficient and intuitive

Thanks for explaining @Jon_Poplett !

It sounds like an interesting approach. Thanks for sharing it here.

Let’s leave the thread open for others to comment on the functionality or scalability of the approach.