File size: 7,973 Bytes
ca59565
 
 
 
 
 
 
 
 
 
 
 
 
 
8f974ee
ca59565
feffd43
 
 
 
 
 
 
8f974ee
ebb3e5c
 
 
8f974ee
 
 
 
ca59565
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import subprocess

# 🔹 Clear Hugging Face Pip Cache Before Installing
subprocess.run("rm -rf /home/user/.cache/pip/*", shell=True)

import streamlit as st
import numpy as np

import os
os.system("pip install --no-cache-dir matplotlib")
import matplotlib.pyplot as plt
import pandas as pd

import subprocess

# Ensure SpaCy is installed
try:
    import spacy
except ModuleNotFoundError:
    subprocess.run(["pip", "install", "spacy"])
    import spacy

# Ensure the model is installed
try:
    nlp = spacy.load("en_core_web_sm")
except OSError:
    subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"])
    nlp = spacy.load("en_core_web_sm")



def extract_equation_params(text):
    """
    Extracts demand and supply equation parameters from a structured natural language query.
    """
    doc = nlp(text.lower())
    numbers = [float(token.text) for token in doc if token.like_num]

    if len(numbers) < 14:
        return None

    demand_intercept_corn, demand_slope_corn, supply_intercept_corn, supply_slope_corn, \
    supply_intercept_prod_pay, supply_slope_prod_pay, \
    demand_intercept_cleaned, demand_slope_cleaned, supply_intercept_cleaned, supply_slope_cleaned, \
    demand_intercept_no_loading, demand_slope_no_loading, supply_intercept_no_loading, supply_slope_no_loading = numbers[:14]

    demand_slope_corn = -abs(demand_slope_corn)
    demand_slope_cleaned = -abs(demand_slope_cleaned)
    demand_slope_no_loading = -abs(demand_slope_no_loading)

    return demand_intercept_corn, demand_slope_corn, supply_intercept_corn, supply_slope_corn, \
           supply_intercept_prod_pay, supply_slope_prod_pay, \
           demand_intercept_cleaned, demand_slope_cleaned, supply_intercept_cleaned, supply_slope_cleaned, \
           demand_intercept_no_loading, demand_slope_no_loading, supply_intercept_no_loading, supply_slope_no_loading

def calculate_equilibrium(demand_intercept, demand_slope, supply_intercept, supply_slope):
    """
    Computes Competitive Equilibrium: Quantity and Price.
    Also calculates CS, PS, and SW for the competitive market.
    """
    quantity_eq = (demand_intercept - supply_intercept) / (supply_slope - demand_slope)
    price_eq = demand_intercept + demand_slope * quantity_eq

    cs_eq = (demand_intercept - price_eq) * quantity_eq / 2
    ps_eq = (price_eq - supply_intercept) * quantity_eq / 2
    sw_eq = cs_eq + ps_eq

    return round(quantity_eq, 2), round(price_eq, 2), round(cs_eq, 2), round(ps_eq, 2), round(sw_eq, 2)

def plot_market(demand_intercept, demand_slope, supply_intercept, supply_slope, quantity_eq, price_eq, market_name,
                supply_intercept_alt=None, supply_slope_alt=None):
    """
    Plots the supply and demand curves for a given market.
    """
    q_range = np.linspace(0, quantity_eq * 1.5, 100)
    demand_curve = demand_intercept + demand_slope * q_range
    supply_curve_primary = supply_intercept + supply_slope * q_range
    supply_curve_alt = supply_intercept_alt + supply_slope_alt * q_range if supply_intercept_alt is not None else None

    plt.figure(figsize=(8, 6))
    plt.plot(q_range, demand_curve, label="Demand Curve", color="blue")
    plt.plot(q_range, supply_curve_primary, label="Supply Curve (Original)", color="green")
    if supply_curve_alt is not None:
        plt.plot(q_range, supply_curve_alt, label="Supply Curve (Alternative)", color="red", linestyle="dashed")

    plt.xlabel("Quantity")
    plt.ylabel("Price")
    plt.title(f"Market Equilibrium: {market_name}")
    plt.legend()
    st.pyplot(plt)

# Streamlit Interface
st.title("Market Equilibrium Solver")

st.write("Enter a question describing supply and demand equations for corn and water.")
user_query = st.text_area(
    "Type your question here:", 
    value="Corn market demand: intercept 100, slope -2. Original Corn supply (water consumers pay): intercept 20, slope 3. Intervene Corn supply (corn producer pays): intercept 30, slope 3.\n"
          "Original Sceanrio (water consumer pays): Water Demand has intercept 200, slope -4. Water Supply has intercept 64.38, slope 2.1.\n"
          "Intervene Scenario (corn producer pays): Water demand has intercept 200, slope -4. Water supply has intercept 44.91, slope 2.1."
)


if st.button("Solve"):
    params = extract_equation_params(user_query)

    if params:
        demand_intercept_corn, demand_slope_corn, supply_intercept_corn, supply_slope_corn, \
        supply_intercept_prod_pay, supply_slope_prod_pay, \
        demand_intercept_cleaned, demand_slope_cleaned, supply_intercept_cleaned, supply_slope_cleaned, \
        demand_intercept_no_loading, demand_slope_no_loading, supply_intercept_no_loading, supply_slope_no_loading = params

        # Compute Equilibria for Corn
        quantity_eq_corn, price_eq_corn, cs_eq_corn, ps_eq_corn, sw_eq_corn = \
            calculate_equilibrium(demand_intercept_corn, demand_slope_corn, supply_intercept_corn, supply_slope_corn)

        quantity_eq_corn_prod_pay, price_eq_corn_prod_pay, cs_eq_corn_prod_pay, ps_eq_corn_prod_pay, sw_eq_corn_prod_pay = \
            calculate_equilibrium(demand_intercept_corn, demand_slope_corn, supply_intercept_prod_pay, supply_slope_prod_pay)

        # Compute Equilibria for Water
        quantity_eq_cleaned, price_eq_cleaned, cs_eq_cleaned, ps_eq_cleaned, sw_eq_cleaned = \
            calculate_equilibrium(demand_intercept_cleaned, demand_slope_cleaned, supply_intercept_cleaned, supply_slope_cleaned)

        quantity_eq_no_loading, price_eq_no_loading, cs_eq_no_loading, ps_eq_no_loading, sw_eq_no_loading = \
            calculate_equilibrium(demand_intercept_no_loading, demand_slope_no_loading, supply_intercept_no_loading, supply_slope_no_loading)

        # Display Equilibrium Prices and Quantities
        st.write("\n**Equilibrium Prices and Quantities:**")
        st.write(f"- **Corn Mkt(Original:Water Consumer Pay):** Price: ${price_eq_corn}, Quantity: {quantity_eq_corn} units")
        st.write(f"- **Corn Mkt(Intervene:Corn Producer Pays):** Price: ${price_eq_corn_prod_pay}, Quantity: {quantity_eq_corn_prod_pay} units")
        st.write(f"- **Water Market(Original:Water Consumer Pays):** Price: ${price_eq_cleaned}, Quantity: {quantity_eq_cleaned} units")
        st.write(f"- **Water Mkt:(intervene:Corn Producer Pays):** Price: ${price_eq_no_loading}, Quantity: {quantity_eq_no_loading} units")

        # Plot Graphs for Corn with both supply curves
        plot_market(demand_intercept_corn, demand_slope_corn, supply_intercept_corn, supply_slope_corn,
                    quantity_eq_corn, price_eq_corn, "Corn Market", supply_intercept_prod_pay, supply_slope_prod_pay)

        # Plot Graphs for Water with both supply curves
        plot_market(demand_intercept_cleaned, demand_slope_cleaned, supply_intercept_cleaned, supply_slope_cleaned,
                    quantity_eq_cleaned, price_eq_cleaned, "Water Market", supply_intercept_no_loading, supply_slope_no_loading)

        # Display Surplus Tables
        st.write("\n**Surplus Tables:**")
        st.table(pd.DataFrame({
            "Scenario": ["Orig Corn Mkt:Water Cons Pay", "Intervene Corn Mkt:Corn Prod Pay)", "Difference"],
            "Consumer Surplus": [cs_eq_corn, cs_eq_corn_prod_pay, cs_eq_corn_prod_pay - cs_eq_corn],
            "Producer Surplus": [ps_eq_corn, ps_eq_corn_prod_pay, ps_eq_corn_prod_pay - ps_eq_corn],
            "Total Social Welfare": [sw_eq_corn, sw_eq_corn_prod_pay, sw_eq_corn_prod_pay - sw_eq_corn]
        }))

        st.table(pd.DataFrame({
            "Scenario": ["Orig Water Mkt:Water Cons Pay", "Intervene Water Mkt:Corn Prod Pay", "Difference"],
            "Consumer Surplus": [cs_eq_cleaned, cs_eq_no_loading, cs_eq_no_loading - cs_eq_cleaned],
            "Producer Surplus": [ps_eq_cleaned, ps_eq_no_loading, ps_eq_no_loading - ps_eq_cleaned],
            "Total Social Welfare": [sw_eq_cleaned, sw_eq_no_loading, sw_eq_no_loading - sw_eq_cleaned]
        }))