File size: 6,907 Bytes
c25ceaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import pandas as pd
import numpy as np
import tensorflow as tf
import random
import gradio as gr
from transformers import pipeline

# Embedded data
gdp_data = {
    'Year': [2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022],
    'Quarter': ['Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4'],
    'GDP': [21433.2, 19477.6, 21042.5, 21428.5, 22038.2, 22696.3, 22994.6, 23400.0, 24025.7, 24483.7, 24988.5, 25387.7]
}

population_data = {
    'Year': [2020, 2021, 2022],
    'Population': [331, 332, 333]  # In millions
}

# Load data
def load_gdp_data():
    gdp_df = pd.DataFrame(gdp_data)
    gdp_df['TimePeriod'] = gdp_df['Year'].astype(str) + '-' + gdp_df['Quarter']
    gdp_df.set_index('TimePeriod', inplace=True)
    return gdp_df

def load_population_data():
    population_df = pd.DataFrame(population_data)
    total_population = population_df['Population'].sum() * 1e6  # Convert to individual count
    return total_population

# Neural Network for Predictive Analytics
def train_neural_network(X, y):
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(64, activation='relu', input_shape=(X.shape[1],)),
        tf.keras.layers.Dense(1)
    ])
    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(X, y, epochs=100)
    return model

# Agent class
class Agent:
    def __init__(self, income, wealth, consumption_rate):
        self.income = income
        self.wealth = wealth
        self.consumption_rate = consumption_rate

    def fitness(self):
        return self.wealth + self.income

    def reproduce(self, other):
        income = (self.income + other.income) / 2
        wealth = (self.wealth + other.wealth) / 2
        consumption_rate = (self.consumption_rate + other.consumption_rate) / 2

        if random.random() < 0.1:
            income += random.uniform(-10, 10)
        if random.random() < 0.1:
            wealth += random.uniform(-1000, 1000)
        if random.random() < 0.1:
            consumption_rate += random.uniform(-0.1, 0.1)

        return Agent(income, wealth, consumption_rate)

    def interact(self, other):
        trade_amount = min(self.wealth, other.wealth) * 0.1
        self.wealth -= trade_amount
        other.wealth += trade_amount

def initialize_population(size):
    return [Agent(random.uniform(1000, 5000), random.uniform(10000, 50000), random.uniform(0.1, 0.5)) for _ in range(size)]

# Genetic Algorithm
def genetic_algorithm(population, generations, mutation_rate):
    for generation in range(generations):
        population.sort(key=lambda agent: agent.fitness(), reverse=True)
        top_agents = population[:len(population) // 2]

        new_population = []
        while len(new_population) < len(population):
            parent1, parent2 = random.sample(top_agents, 2)
            child = parent1.reproduce(parent2)
            new_population.append(child)

        population = new_population

    return population

# Agent-Based Modeling
def simulate_abm(population, steps):
    for step in range(steps):
        for agent in population:
            other = random.choice(population)
            agent.interact(other)

    return population

# Simulation class with AI integration
class Simulation:
    def __init__(self, gdp_df, total_population, ml_model, generator):
        self.gdp_df = gdp_df
        self.total_population = total_population
        self.ml_model = ml_model
        self.generator = generator

    def simulate_ubi(self, ubi_amount):
        total_ubi = self.total_population * ubi_amount
        new_gdp_df = self.gdp_df.copy()
        new_gdp_df['GDP'] += total_ubi / 1e9
        return new_gdp_df

    def predict_future_gdp(self, year):
        prediction = self.ml_model.predict(np.array([year]).reshape(-1, 1))
        return prediction[0]

    def generate_insight(self, prompt):
        return self.generator(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']

    def generative_loop(self, initial_prompt, max_iterations=10, threshold=0.01):
        prompt = initial_prompt
        previous_evaluation = None
        for _ in range(max_iterations):
            generated_text = self.generate_insight(prompt)
            evaluation = self.evaluate(generated_text)
            if previous_evaluation and abs(evaluation - previous_evaluation) < threshold:
                break
            previous_evaluation = evaluation
            prompt = generated_text
        return generated_text

    def evaluate(self, text):
        # Simplified evaluation function
        return len(text)

def run_simulation(ubi_amount, steps, generations, mutation_rate):
    # Load data
    gdp_df = load_gdp_data()
    total_population = load_population_data()
    
    # Initialize population
    population_size = 100
    population = initialize_population(population_size)
    
    # Train machine learning model
    X = np.array(gdp_df.index.str.extract('(\d+)', expand=False).astype(int)).reshape(-1, 1)
    y = np.array(gdp_df['GDP'])
    ml_model = train_neural_network(X, y)
    
    # Initialize GPT-2 generator
    generator = pipeline('text-generation', model='gpt2')
    
    # Run genetic algorithm
    evolved_population = genetic_algorithm(population, generations, mutation_rate)
    
    # Simulate agent-based interactions
    final_population = simulate_abm(evolved_population, steps)
    
    # Create simulation object
    simulation = Simulation(gdp_df, total_population, ml_model, generator)
    new_gdp_df = simulation.simulate_ubi(ubi_amount)
    
    # Generate insights using GPT-2 with generative loop
    insight_prompt = f"Given an annual UBI of {ubi_amount} dollars, the expected impact on GDP is"
    final_insight = simulation.generative_loop(insight_prompt)
    
    # Prepare data for visualization
    original_gdp = gdp_df['GDP']
    new_gdp = new_gdp_df['GDP']
    
    return original_gdp.values.tolist(), new_gdp.values.tolist(), final_insight

# Gradio interface
def create_gradio_interface():
    interface = gr.Interface(
        fn=run_simulation,
        inputs=[
            gr.Slider(0, 50000, step=1000, label="Annual UBI Amount"),
            gr.Slider(1, 1000, step=1, label="Simulation Steps"),
            gr.Slider(1, 100, step=1, label="Generations"),
            gr.Slider(0.0, 1.0, step=0.01, label="Mutation Rate")
        ],
        outputs=[
            gr.Plot(label="Original GDP"),
            gr.Plot(label="GDP with UBI"),
            gr.Textbox(label="Generated Insight")
        ],
        title="UBI Impact Simulation with Generative Loop",
        description="Simulate the impact of Universal Basic Income (UBI) on GDP using genetic algorithms, agent-based modeling, machine learning, and GPT-2 for generating insights with a generative loop.",
        live=True
    )
    interface.launch()

if __name__ == "__MAIN__":
    create_gradio_interface()