Thesimai / app.py
Unfaithful's picture
Create app.py
c25ceaa verified
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()