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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import random
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# Embedded data
|
| 9 |
+
gdp_data = {
|
| 10 |
+
'Year': [2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022],
|
| 11 |
+
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4'],
|
| 12 |
+
'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]
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
population_data = {
|
| 16 |
+
'Year': [2020, 2021, 2022],
|
| 17 |
+
'Population': [331, 332, 333] # In millions
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# Load data
|
| 21 |
+
def load_gdp_data():
|
| 22 |
+
gdp_df = pd.DataFrame(gdp_data)
|
| 23 |
+
gdp_df['TimePeriod'] = gdp_df['Year'].astype(str) + '-' + gdp_df['Quarter']
|
| 24 |
+
gdp_df.set_index('TimePeriod', inplace=True)
|
| 25 |
+
return gdp_df
|
| 26 |
+
|
| 27 |
+
def load_population_data():
|
| 28 |
+
population_df = pd.DataFrame(population_data)
|
| 29 |
+
total_population = population_df['Population'].sum() * 1e6 # Convert to individual count
|
| 30 |
+
return total_population
|
| 31 |
+
|
| 32 |
+
# Neural Network for Predictive Analytics
|
| 33 |
+
def train_neural_network(X, y):
|
| 34 |
+
model = tf.keras.Sequential([
|
| 35 |
+
tf.keras.layers.Dense(64, activation='relu', input_shape=(X.shape[1],)),
|
| 36 |
+
tf.keras.layers.Dense(1)
|
| 37 |
+
])
|
| 38 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 39 |
+
model.fit(X, y, epochs=100)
|
| 40 |
+
return model
|
| 41 |
+
|
| 42 |
+
# Agent class
|
| 43 |
+
class Agent:
|
| 44 |
+
def __init__(self, income, wealth, consumption_rate):
|
| 45 |
+
self.income = income
|
| 46 |
+
self.wealth = wealth
|
| 47 |
+
self.consumption_rate = consumption_rate
|
| 48 |
+
|
| 49 |
+
def fitness(self):
|
| 50 |
+
return self.wealth + self.income
|
| 51 |
+
|
| 52 |
+
def reproduce(self, other):
|
| 53 |
+
income = (self.income + other.income) / 2
|
| 54 |
+
wealth = (self.wealth + other.wealth) / 2
|
| 55 |
+
consumption_rate = (self.consumption_rate + other.consumption_rate) / 2
|
| 56 |
+
|
| 57 |
+
if random.random() < 0.1:
|
| 58 |
+
income += random.uniform(-10, 10)
|
| 59 |
+
if random.random() < 0.1:
|
| 60 |
+
wealth += random.uniform(-1000, 1000)
|
| 61 |
+
if random.random() < 0.1:
|
| 62 |
+
consumption_rate += random.uniform(-0.1, 0.1)
|
| 63 |
+
|
| 64 |
+
return Agent(income, wealth, consumption_rate)
|
| 65 |
+
|
| 66 |
+
def interact(self, other):
|
| 67 |
+
trade_amount = min(self.wealth, other.wealth) * 0.1
|
| 68 |
+
self.wealth -= trade_amount
|
| 69 |
+
other.wealth += trade_amount
|
| 70 |
+
|
| 71 |
+
def initialize_population(size):
|
| 72 |
+
return [Agent(random.uniform(1000, 5000), random.uniform(10000, 50000), random.uniform(0.1, 0.5)) for _ in range(size)]
|
| 73 |
+
|
| 74 |
+
# Genetic Algorithm
|
| 75 |
+
def genetic_algorithm(population, generations, mutation_rate):
|
| 76 |
+
for generation in range(generations):
|
| 77 |
+
population.sort(key=lambda agent: agent.fitness(), reverse=True)
|
| 78 |
+
top_agents = population[:len(population) // 2]
|
| 79 |
+
|
| 80 |
+
new_population = []
|
| 81 |
+
while len(new_population) < len(population):
|
| 82 |
+
parent1, parent2 = random.sample(top_agents, 2)
|
| 83 |
+
child = parent1.reproduce(parent2)
|
| 84 |
+
new_population.append(child)
|
| 85 |
+
|
| 86 |
+
population = new_population
|
| 87 |
+
|
| 88 |
+
return population
|
| 89 |
+
|
| 90 |
+
# Agent-Based Modeling
|
| 91 |
+
def simulate_abm(population, steps):
|
| 92 |
+
for step in range(steps):
|
| 93 |
+
for agent in population:
|
| 94 |
+
other = random.choice(population)
|
| 95 |
+
agent.interact(other)
|
| 96 |
+
|
| 97 |
+
return population
|
| 98 |
+
|
| 99 |
+
# Simulation class with AI integration
|
| 100 |
+
class Simulation:
|
| 101 |
+
def __init__(self, gdp_df, total_population, ml_model, generator):
|
| 102 |
+
self.gdp_df = gdp_df
|
| 103 |
+
self.total_population = total_population
|
| 104 |
+
self.ml_model = ml_model
|
| 105 |
+
self.generator = generator
|
| 106 |
+
|
| 107 |
+
def simulate_ubi(self, ubi_amount):
|
| 108 |
+
total_ubi = self.total_population * ubi_amount
|
| 109 |
+
new_gdp_df = self.gdp_df.copy()
|
| 110 |
+
new_gdp_df['GDP'] += total_ubi / 1e9
|
| 111 |
+
return new_gdp_df
|
| 112 |
+
|
| 113 |
+
def predict_future_gdp(self, year):
|
| 114 |
+
prediction = self.ml_model.predict(np.array([year]).reshape(-1, 1))
|
| 115 |
+
return prediction[0]
|
| 116 |
+
|
| 117 |
+
def generate_insight(self, prompt):
|
| 118 |
+
return self.generator(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
|
| 119 |
+
|
| 120 |
+
def generative_loop(self, initial_prompt, max_iterations=10, threshold=0.01):
|
| 121 |
+
prompt = initial_prompt
|
| 122 |
+
previous_evaluation = None
|
| 123 |
+
for _ in range(max_iterations):
|
| 124 |
+
generated_text = self.generate_insight(prompt)
|
| 125 |
+
evaluation = self.evaluate(generated_text)
|
| 126 |
+
if previous_evaluation and abs(evaluation - previous_evaluation) < threshold:
|
| 127 |
+
break
|
| 128 |
+
previous_evaluation = evaluation
|
| 129 |
+
prompt = generated_text
|
| 130 |
+
return generated_text
|
| 131 |
+
|
| 132 |
+
def evaluate(self, text):
|
| 133 |
+
# Simplified evaluation function
|
| 134 |
+
return len(text)
|
| 135 |
+
|
| 136 |
+
def run_simulation(ubi_amount, steps, generations, mutation_rate):
|
| 137 |
+
# Load data
|
| 138 |
+
gdp_df = load_gdp_data()
|
| 139 |
+
total_population = load_population_data()
|
| 140 |
+
|
| 141 |
+
# Initialize population
|
| 142 |
+
population_size = 100
|
| 143 |
+
population = initialize_population(population_size)
|
| 144 |
+
|
| 145 |
+
# Train machine learning model
|
| 146 |
+
X = np.array(gdp_df.index.str.extract('(\d+)', expand=False).astype(int)).reshape(-1, 1)
|
| 147 |
+
y = np.array(gdp_df['GDP'])
|
| 148 |
+
ml_model = train_neural_network(X, y)
|
| 149 |
+
|
| 150 |
+
# Initialize GPT-2 generator
|
| 151 |
+
generator = pipeline('text-generation', model='gpt2')
|
| 152 |
+
|
| 153 |
+
# Run genetic algorithm
|
| 154 |
+
evolved_population = genetic_algorithm(population, generations, mutation_rate)
|
| 155 |
+
|
| 156 |
+
# Simulate agent-based interactions
|
| 157 |
+
final_population = simulate_abm(evolved_population, steps)
|
| 158 |
+
|
| 159 |
+
# Create simulation object
|
| 160 |
+
simulation = Simulation(gdp_df, total_population, ml_model, generator)
|
| 161 |
+
new_gdp_df = simulation.simulate_ubi(ubi_amount)
|
| 162 |
+
|
| 163 |
+
# Generate insights using GPT-2 with generative loop
|
| 164 |
+
insight_prompt = f"Given an annual UBI of {ubi_amount} dollars, the expected impact on GDP is"
|
| 165 |
+
final_insight = simulation.generative_loop(insight_prompt)
|
| 166 |
+
|
| 167 |
+
# Prepare data for visualization
|
| 168 |
+
original_gdp = gdp_df['GDP']
|
| 169 |
+
new_gdp = new_gdp_df['GDP']
|
| 170 |
+
|
| 171 |
+
return original_gdp.values.tolist(), new_gdp.values.tolist(), final_insight
|
| 172 |
+
|
| 173 |
+
# Gradio interface
|
| 174 |
+
def create_gradio_interface():
|
| 175 |
+
interface = gr.Interface(
|
| 176 |
+
fn=run_simulation,
|
| 177 |
+
inputs=[
|
| 178 |
+
gr.Slider(0, 50000, step=1000, label="Annual UBI Amount"),
|
| 179 |
+
gr.Slider(1, 1000, step=1, label="Simulation Steps"),
|
| 180 |
+
gr.Slider(1, 100, step=1, label="Generations"),
|
| 181 |
+
gr.Slider(0.0, 1.0, step=0.01, label="Mutation Rate")
|
| 182 |
+
],
|
| 183 |
+
outputs=[
|
| 184 |
+
gr.Plot(label="Original GDP"),
|
| 185 |
+
gr.Plot(label="GDP with UBI"),
|
| 186 |
+
gr.Textbox(label="Generated Insight")
|
| 187 |
+
],
|
| 188 |
+
title="UBI Impact Simulation with Generative Loop",
|
| 189 |
+
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.",
|
| 190 |
+
live=True
|
| 191 |
+
)
|
| 192 |
+
interface.launch()
|
| 193 |
+
|
| 194 |
+
if __name__ == "__MAIN__":
|
| 195 |
+
create_gradio_interface()
|