# **Project 2: Model Analysis Project**

**By GWM442 and GXJ882**

## **Introduction**

In this project we consider the consumer's choice problem with two goods and a firm's maximization problem. We start by solving the consumer's problem for two different consumers, one with Cobb-Douglas preferences and the other with logarithmic preferences. Next, we find the social optimum for the two consumers. Lastly, we solve the firm's maximization problem, where the reader can choose between the settings of a competitive market or a monopolistic market. This project is made as an interactive helping tool, such that the user can adjust the parameters to the user's function.

## **Importing necessary tools**

We start by importing the tools, which we are going to use in this project.


```python
import ipywidgets as widgets #For making interactive widgets for the income and prices
import matplotlib.pyplot as plt # For making plots
import numpy as np # This is used, when we make graphs
from scipy import optimize # This is used for solving the consumer's problem
from sympy import * # For some methods of optimization
import warnings # We import this feature because we want to avoid printing a warning (This is purely done for estetic reasons)
warnings.filterwarnings("ignore", category=RuntimeWarning) 
```

## **Consumer problems**

We solve the consumer problems for both consumers simultaneously. The consumer on the left will be the one with Cobb-Douglas preferences and the one on the rigth is the consumer with the logarithmic preferences.

We start by implementing the price of good 1 and good 2 as widgets. There are two ways to interact with the widgets for each variable. They are connected and will move simultaneously, allowing for either setting the variables using the slider or writing a specific value using the text-widget.


```python
# Price on good 1

# We only describe the code for the prices, as it is repeated for all variables.
# First we print a headline "Price on good 1", where the first part is used to make the text bold. We also write P1 in a parenthesis,
# as this is the variable name which we are going to use.
print('\033[1m' + 'Price on good 1 (P1)')
# Now we create the text-widget, where we set the starting value to 5.
P1 = widgets.FloatText(
value=5)
# Next we create a slide-widget (using floats, such that decimals can be used). Here we set the same starting value, 
# we set the steps to 1 and we define the minimum value to 0 and the maximum value to 100.
# This can of cause be adjusted for the problem settings.
P1b = widgets.FloatSlider(
value=5,
step=1,
min=1,
max=100.0,)
# Next we print both widgets
display(P1,P1b)
# And lastly we link the two widgets together, so one can change either widget.
linkp1 = widgets.jslink((P1, 'value'), (P1b, 'value'))

# Price on good 2
print('\033[1m' + 'Price on good 2 (P2)')
P2 = widgets.FloatText(
value=15)
P2b = widgets.FloatSlider(
value=5,
step=1,
min=1,
max=100.0,)
display(P2,P2b)

linkp2 = widgets.jslink((P2, 'value'), (P2b, 'value'))
```

    [1mPrice on good 1 (P1)



    FloatText(value=5.0)



    FloatSlider(value=5.0, min=1.0, step=1.0)


    [1mPrice on good 2 (P2)



    FloatText(value=15.0)



    FloatSlider(value=5.0, min=1.0, step=1.0)


### **Setting the income level**


```python
# Income consumer 1
# This code is similar to the one for prices
print('\033[1m' + 'Income for consumer 1 (I1)')
I1 = widgets.FloatText(
value=100)
I1b = widgets.FloatSlider(
value=100,
step=1,
min=1,
max=1000,)
display(I1,I1b),

linkI1 = widgets.jslink((I1, 'value'), (I1b, 'value'))
             
# Income consumer 2
print('\033[1m' + 'Income for consumer 2 (I2)')
I2 = widgets.FloatText(
value=100)
I2b = widgets.FloatSlider(
value=100,
step=1,
min=1,
max=1000,)
display(I2,I2b)

linkI2 = widgets.jslink((I2, 'value'), (I2b, 'value'))

```

    [1mIncome for consumer 1 (I1)



    FloatText(value=100.0)



    FloatSlider(value=100.0, max=1000.0, min=1.0, step=1.0)


    [1mIncome for consumer 2 (I2)



    FloatText(value=100.0)



    FloatSlider(value=100.0, max=1000.0, min=1.0, step=1.0)


Next we plot the budget constraint. This shows us what the consumer is able to afford given the income. To do this we first need to define the budget constraint function, which is
\\[
\begin{eqnarray*}
I(p_{1},p_{2}) & = & x_{1} p_{1}+x_{2} p_{2}
\end{eqnarray*}
\\]
And then isolate for $x_2$


```python
# Define the income function (This is done by isolating x2)
def x2_func(x1,I,P1,P2): # We define x2 as a function of x1
    return (I-x1*P1)/P2 # The function is derived by isolating x2 in the budget constraint

# We then make a vector of x_1 values which we are going to use in our functions
N=500
shape_tuple = (N,N)
x1_values = np.empty(shape_tuple) # First we create an empty array

# Next we define the maximum value of x1, which is set so x1 is in the budget constraint for both consumers.
if I1.value>I2.value:    # This if-else statement ensures that the x-vector is large enough to solve the problem of the consumers.
    x_max1=I1.value/P1.value  
else:
    x_max1=I2.value/P1.value 
# And the vector is made by a double for loop.
for i in range(N): # 0,1,...,N-1
    for j in range(N): # 0,1,...,N-1
        x1_values[i,j] = (i/(N-1))*x_max1 # in [0,x_max1]
        
# Here we illustrate the results.
def Figure_1():
    fig = plt.figure(figsize=(15,5)) # creates the figure 
    ax = fig.add_subplot(1,2,1) # We add a subplot and place it in the top left corner
    ax.plot(x1_values,x2_func(x1_values,I1.value,P1.value,P2.value),'b'); # creates surface plot in the axis
    ax.set_xlabel('$x_1$') # adds labels for the x-axis
    ax.set_ylabel('$x_2$') # adds labels for the y-axis
    ax.set_title("Budget constraint for Consumer 1") # adds title for the first plot
    ax.set_ylim(0,I1.value/P2.value) #sets the bound of the y-axis in the first plot
    ax.set_xlim(0,I1.value/P1.value) #sets the bound of the x-axis in the first plot
    ay = fig.add_subplot(1,2,2) # We add a second plot and place it in the top right corner
    ay.plot(x1_values,x2_func(x1_values,I2.value,P1.value,P2.value),'b'); # creates surface plot in the axis
    ay.set_xlabel('$x_1$') # adds labels
    ay.set_ylabel('$x_2$') # adds labels
    ay.set_title("Budget constraint for Consumer 2") # add title
    ay.set_ylim(0,I2.value/P2.value) # Sets a boundary for the y-axis
    ay.set_xlim(0,I2.value/P1.value) # Sets a boundary for the x-axis
Figure_1()
```

The results above are based on your choice of income, but given the same income values these should be identical. They illustrate the combinations of goods that the consumers can afford given thier income and the prices on the goods.

### **Utility function**

After setting the price levels and income levels, we define the utility functions. 

Cobb-Douglass:
\\[
u_1(x_1,x_2) = x_1^{\alpha}x_2^{1-\alpha}
\\]
Logarithmic:
\\[
u_2(x_1,x_2) = \beta log(x_1)+(1-\beta) log(x_2)
\\]

These functions' parameters can easily be altered to fit your own problem using the widgets, which allows you to change the values of \\(\alpha\\) and \\(\beta\\).

Note that the subscript on *u* represents the consumer, 1 being the one with Cobb-Douglass preferences and 2 being the one with logarithmic preferences.


```python
# Consumer 1
def c1_u_func(x1,x2,alpha): # We define a Cobb-Douglass utility function
    return (x1**alpha)*(x2**(1-alpha))

print('\033[1m' + 'Consumer 1:')
print('\033[1m' + 'Alpha (\u03B1)') # We use this code \u03B1 and similar ones to print greek letters. This particular one is for alpha
alpha = widgets.FloatText(
value=0.5)
alphab = widgets.FloatSlider(
value=0.5,
step=0.1,
min=0.1,
max=1,)
display(alpha,alphab)

mylink = widgets.jslink((alpha, 'value'), (alphab, 'value'))

# Consumer 2

def c2_u_func(x1,x2,beta): # We define a logarithmic utility function
    return beta*np.log(x1)+(1-beta)*np.log(x2)

print('\033[1m' + 'Consumer 2:')
print('\033[1m' + 'Beta (\u03B2)')
beta = widgets.FloatText(
value=0.5)
betab = widgets.FloatSlider(
value=0.5,
step=0.1,
min=0.1,
max=1,)
display(beta,betab)

mylink = widgets.jslink((beta, 'value'), (betab, 'value'))
```

    [1mConsumer 1:
    [1mAlpha (α)



    FloatText(value=0.5)



    FloatSlider(value=0.5, max=1.0, min=0.1)


    [1mConsumer 2:
    [1mBeta (β)



    FloatText(value=0.5)



    FloatSlider(value=0.5, max=1.0, min=0.1)


We set the utility values so we can plot the indifference curves.


```python
# Widget for Consumer 1's utility
print('\033[1m' + 'Utility for consumer 1 (u1)')
u1 = widgets.FloatText(
value=10)
u1b = widgets.FloatSlider(
value=10,
step=0.1,
min=0.1,
max=10,)
display(u1,u1b)
mylink = widgets.jslink((u1, 'value'), (u1b, 'value'))

# Widget for Consumer 2's utility
print('\033[1m' + 'Utility for consumer 2 (u2)')
u2 = widgets.FloatText(
value=1)
u2b = widgets.FloatSlider(
value=1,
step=0.1,
min=0.1,
max=3,)
display(u2,u2b)
mylink = widgets.jslink((u2, 'value'), (u2b, 'value'))
```

    [1mUtility for consumer 1 (u1)



    FloatText(value=10.0)



    FloatSlider(value=10.0, max=10.0, min=0.1)


    [1mUtility for consumer 2 (u2)



    FloatText(value=1.0)



    FloatSlider(value=1.0, max=3.0, min=0.1)


Next we plot the utility functions using the values chosen above.


```python
# Next we define our 2 utility functions (Where we have isolated for x2)
def c1_x2_func2(x1,u,alpha):
    return u**(1/(1-alpha))*(x1**(-alpha/(1-alpha)))
def c2_x2_func2(x1,u,beta):
    return np.exp((u-beta*np.log(x1))/(1-beta))

def Figure_2():
    fig = plt.figure(figsize=(15,5)) # creates the figure
    ax = fig.add_subplot(1,2,1) # creates subplot 
    ax.plot(x1_values,c1_x2_func2(x1_values,u1.value,alpha.value),'b'); # creates surface plot in the axis
    ax.set_xlabel('$x_1$') # add labels
    ax.set_ylabel('$x_2$') # add labels
    ax.set_title("Utility for Consumer 1") # add title
    ax.set_ylim([0, 20]) # here we limit the y axis, which is needed due to the values going towards negative infinity, when x1 goes towards 0.
    ay = fig.add_subplot(1,2,2) # creates subplot 
    ay.plot(x1_values,c2_x2_func2(x1_values,u2.value,beta.value),'b'); # creates surface plot in the axis, but this time we use a different method due to the fact that we are using numpy functions (exp and log).
    ay.set(xlabel='$x_1$', ylabel='$x_2$',
       title="Utility for Consumer 2", xlim=[0,I2.value/P1.value], ylim=[0,I2.value/P2.value]) # We also need to set our labels and title in a different way.
Figure_2()
```

The figures illustrate the combination of goods to obtain the set utility levels from before. By default $u_1=10$ and $u_2=1$ in our widgets. This means that every point on the graph represent bundles of good 1 and 2, which corresponds to these utility levels.

### **Solution**

Now we solve the consumer problem for both types. This is done by maximizing the utility with regards to the budget constraint.
\\[
\begin{eqnarray*}
\max_{x_{1},x_{2}}u(x_{1},x_{2})\\
\text{s.t.}\\
p_{1}x_{1}+p_{2}x_{2} & \leq & I,\,\,\,p_{1},p_{2},I>0\\
x_{1},x_{2} & \geq & 0
\end{eqnarray*}
\\]


```python
# Consumer 1
def c1(x1,I,P1,P2,alpha): # First we define a function, which we will use to find the optimal value of x1.
    x2 = (I-P1*x1)/P2
# We return the negative function of our utility and then minimizes this, which is the same as maximizing the utility. The reason for this is that scipy use minimization.
    return -c1_u_func(x1,x2,alpha) 

# Consumer 2
def c2(x1,I,P1,P2,beta):
    x2 = (I-P1*x1)/P2
    return -c2_u_func(x1,x2,beta)

# Next we use our optimizing function to maximize the utility (And thereby minimizing the 2 functions above. 
# Here we define x1 to be between 0 and the maximum number of good 1 you can buy for your income
solver_c1 = optimize.minimize_scalar(c1, method='bounded', bounds=(0,I1.value/P1.value), args=(I1.value,P1.value,P2.value,alpha.value))  
solver_c2 = optimize.minimize_scalar(c2, method='bounded', bounds=(0,I2.value/P1.value), args=(I2.value,P1.value,P2.value,beta.value)) 
# We then define our answers for both consumers

# Consumer 1
c1_x1 = solver_c1.x
c1_x2 = (I1.value-P1.value*c1_x1)/P2.value
c1_u = c1_u_func(c1_x1,c1_x2,alpha.value)

# Consumer 2
c2_x1 = solver_c2.x
c2_x2 = (I2.value-P1.value*c2_x1)/P2.value
c2_u = c2_u_func(c2_x1,c2_x2,beta.value)
```

This provides the following results:


```python
# These lines print our results

# Consumer 1
print('\033[1m' + 'Consumer 1:') # The first bit makes the text bold and then writes Consumer 1
print('\033[0m' + f'x1 = {c1_x1:.1f}') # The first but makes the text unbold and then prints the x1 value
print(f'x2 = {c1_x2:.1f}') # Prints the x2 value
print(f'u  = {c1_u:.2f}') # Prints the utility
print(f'I-p1*x1-p2*x2 = {I1.value-P1.value*c1_x1-P2.value*c1_x2:.2f}') # Prints a calculation to see whether the whole income has been used, such that income - consumption = 0 

print ('')

# Consumer 2 (The following code is the same as for consumer 1)
print('\033[1m' + 'Consumer 2:')
print('\033[0m' + f'x1 = {c2_x1:.1f}') 
print(f'x2 = {c2_x2:.1f}') 
print(f'u  = {c2_u:.2f}') 
print(f'I-p1*x1-p2*x2 = {I2.value-P1.value*c2_x1-P2.value*c2_x2:.2f}') 
```

    [1mConsumer 1:
    [0mx1 = 10.0
    x2 = 3.3
    u  = 5.77
    I-p1*x1-p2*x2 = 0.00
    
    [1mConsumer 2:
    [0mx1 = 10.0
    x2 = 3.3
    u  = 1.75
    I-p1*x1-p2*x2 = 0.00


We can compare this answer to the one, we get from solving the problem manually.

**Consumer 1:**
\\[
\begin{eqnarray*}
x_1^{\ast} &=& \alpha \frac{I}{p_1} \\
x_2^{\ast} &=& (1-\alpha) \frac{I}{p_2}\\
u_1^{\ast} &=& u_{1}(x_1^{\ast},x_2^{\ast})
\end{eqnarray*}
\\]

**Consumer 2:**
\\[
\begin{eqnarray*}
x_1^{\ast} &=& \beta \frac{I}{p_1} \\
x_2^{\ast} &=& (1-\beta) \frac{I}{p_2}\\
u_2^{\ast} &=& u_{2}(x_1^{\ast},x_2^{\ast})
\end{eqnarray*}
\\]


```python
# Here we use our formulas to check if the answers is correct

# Consumer 1 
print('\033[1m' + 'Consumer 1:')
print('\033[0m' + f'x1 = {alpha.value*I1.value/P1.value:.1f}') # Prints the x1 value
print(f'x2 = {(1-alpha.value)*I1.value/P2.value:.1f}') # Prints the x2 value
print(f'u  = {c1_u_func(alpha.value*I1.value/P1.value,(1-alpha.value)*I1.value/P2.value,alpha.value):.2f}') # Prints the utility

print ('')

# Consumer 2 (The code is the same as above)
print('\033[1m' + 'Consumer 2:')
print('\033[0m' + f'x1 = {beta.value*I2.value/P1.value:.1f}') 
print(f'x2 = {(1-beta.value)*I2.value/P2.value:.1f}') 
print(f'u  = {c2_u_func(beta.value*I2.value/P1.value,(1-beta.value)*I2.value/P2.value,beta.value):.2f}') 
```

    [1mConsumer 1:
    [0mx1 = 10.0
    x2 = 3.3
    u  = 5.77
    
    [1mConsumer 2:
    [0mx1 = 10.0
    x2 = 3.3
    u  = 1.75


We see that the manual solution gives the same result as the numerical optimizer. 
We also see that given the same income the consumption of the goods are identical, which is in accordance with the theory, as logarithmic utility can be written on the form of a Cobb-Douglas utility function, for which the consumption of goods depends on income, prices and the preferences illustrated by the exponents, $\alpha$ and $\beta$. However, one must note that even though the good combinations are identical (for the same parameters) the utility obtained are not.

We visualize our results by plotting the budget constraints against the utility functions.


```python
# Here we make a plot of the solution
def Figure_3():
    fig = plt.figure(figsize=(15,5)) # Start the plot and set the figure size 
    ax = fig.add_subplot(1,2,1) # Adding the plot for consumer 1
    ax.plot(x1_values,c1_x2_func2(x1_values,c1_u,alpha.value),'b'); # Insert the optimal utility function
    ax.plot(x1_values,x2_func(x1_values,I1.value,P1.value,P2.value),'b'); # Insert the budget constraint
    ax.set_xlabel('$x_1$') # Set label
    ax.set_ylabel('$x_2$') # Set label
    ax.set_title("Solution for Consumer 1") # Set titel 
    ax.set_ylim([0, I1.value/P2.value]) # Set boundaries of y-axis
    ax.set_xlim([0,I1.value/P1.value]) # Set boundaries of x-axis
    
    # The next line marks the solution, which is where the utility and budget constraint touches
    ax.plot(c1_x1,c1_x2, color='red', marker='o', linestyle='dashed', linewidth=5, markersize=10, fillstyle='none') # creates a red circle where the budget is tangent to the indifference curve
    
    # Next we do the same for Consumer 2 in a plot left of the one above
    ay = fig.add_subplot(1,2,2)
    ay.plot(x1_values,c2_x2_func2(x1_values,c2_u,beta.value),'b'); 
    ay.plot(x1_values,x2_func(x1_values,I2.value,P1.value,P2.value),'b')
    ay.set(xlabel='$x_1$', ylabel='$x_2$',
       title="Solution for Consumer 2", xlim=[0,I2.value/P1.value], ylim=[0,20]) 
    ay.plot(c1_x1, c1_x2, color='red', marker='o', linestyle='dashed', linewidth=5, markersize=10, fillstyle='none') # creates the red circle for consumer 2.
Figure_3()
```

We see that the utility function touches the budget constraint (shown by the red circle) at the results found before. This is illustrating where the budget constraint is tangent to the utility function, which is the optimal choice of the consumer. This is because this point is the highest indifference curve (the one providing the most utility) that can be reached given the budget contraint.

## **Social optimum**

First we define the necessary aggregated variables


```python
# We start by summing the values for income and utility to create social values and functions.
soc_I=I1.value+I2.value
def u_func(x1,x2,alpha,beta):
    return c1_u_func(x1,x2,alpha)+c2_u_func(x1,x2,beta)
```

And then we solve for the social optimum: 

\\[
\begin{eqnarray*}
\max_{x_{1},x_{2}}u_1(x_{1},x_{2})+u_{2}(x_{1},x_{2})\\
\text{s.t.}\\
p_{1}x_{1}+p_{2}x_{2} & \leq & I_{1}+I_{2},\,\,\,p_{1},p_{2},I_{1},I_{2}>0\\
x_{1},x_{2} & \geq & 0
\end{eqnarray*}
\\]

**Notice:** We do not plot the graphs since isolateing \\(x_2\\) isn't possible for costumer 2.


```python
# We start by creating the functions which we are going to optimize. Here we return the u_func and contrain it to the budget constraint
def c1_and_c2(x1,I,P1,P2,alpha,beta): 
    x2 = (I-P1*x1)/P2
    return -u_func(x1,x2,alpha,beta)

# Solve the problem by scipy
solver = optimize.minimize_scalar(c1_and_c2, method='bounded', bounds=(0,soc_I/P1.value), args=(soc_I,P1.value,P2.value,alpha.value,beta.value)) 

# Set values
soc_x1 = solver.x
soc_x2 = (soc_I-P1.value*soc_x1)/P2.value
soc_u = u_func(soc_x1,soc_x2,alpha.value,beta.value)

# Print values
print('\033[1m' + 'Social optimum:')
print('\033[0m' + f'x1 = {soc_x1:.1f}')
print(f'x2 = {soc_x2:.1f}') 
print(f'u  = {soc_u:.2f}') 
print(f'I-p1*x1-p2*x2 = {soc_I-P1.value*soc_x1-P2.value*soc_x2:.2f}') 
```

    [1mSocial optimum:
    [0mx1 = 20.0
    x2 = 6.7
    u  = 13.99
    I-p1*x1-p2*x2 = 0.00


To check whether this answer is correct we are going to solve the social optimum problem using sympy.


```python
# Define all the three variables
socialx1, socialx2, sociallambda = symbols('socialx1 socialx2 sociallambda')

# Write up the Lagrange function, which is L(x1,x2,lambda)=u_consumer1(x1,x2)+u_consumer2(x1,x2)-lambda(I1+I2-p1*x1-p2*x2)
eq_L = socialx1**alpha.value*socialx2**(1-alpha.value)+beta.value*log(socialx1)+(1-beta.value)*log(socialx2)-sociallambda*(soc_I-P1.value*socialx1-P2.value*socialx2)

# Differentiate the lagrange function with regards to our three variables
eq_dLdx1 = eq_L.diff(socialx1)
eq_dLdx2 = eq_L.diff(socialx2)
eq_dLdlambda = eq_L.diff(sociallambda)

# Maximize the three differentials with regards to x1,x2 and lambda and creating af dictionary
solution_set = solve([eq_dLdx1,eq_dLdx2,eq_dLdlambda], socialx1,socialx2,sociallambda, dict=True) 
solution_set_dict=solution_set[0]

# We then divide the dictionary to get the optimal x1 and x2 and then insert these into the combined utility function
soc2_x1=solution_set_dict[socialx1]
soc2_x2=solution_set_dict[socialx2]
soc2_u=soc2_x1**alpha.value*soc2_x2**(1-alpha.value)+beta.value*log(soc2_x1)+(1-beta.value)*log(soc2_x2)

# And lastly we print the three values, x1,x2 and u.
print('\033[1m' + 'Social optimum:')
print('\033[0m' + f'x1 = {soc2_x1:.1f}')
print(f'x2 = {soc2_x2:.1f}') 
print(f'u  = {soc2_u:.2f}') 
```

    [1mSocial optimum:
    [0mx1 = 20.0
    x2 = 6.7
    u  = 13.99


We can then compare this result to our earlier results from solving the consumer problems individually. We see that the changes is given by:


```python
# Print to see the changes between the individual results and the social result
print('\033[1m' + 'Changes:')
print('\033[0m' + f'\u0394x1 = {soc_x1-c1_x1-c2_x1:.1f}') 
print(f'\u0394x2 = {soc_x2-c1_x2-c2_x2:.1f}') 
print(f'\u0394u = {soc_u-c1_u-c2_u:.2f}')
```

    [1mChanges:
    [0mΔx1 = 0.0
    Δx2 = 0.0
    Δu = 6.47


The higher utility is due to allocating of the goods, such that consumer 1 consumes more of the collective resources, as he has a higher utility gained from consumption of the goods.

## **Firms maximization problem**

 ### **Determine the competitive situation**

First we need to select the competitive situation of the problem as this has influence on the firms price setting.


```python
# Create a widget with 2 posible outcomes: Competitive or Monopolistic
competition=widgets.RadioButtons(
    options=['Competitive', 'Monopolistic'],
    value='Competitive',
    description='Competition:',
    disabled=False
)
competition
```


    RadioButtons(description='Competition:', options=('Competitive', 'Monopolistic'), value='Competitive')


### **Set demand according to the competition**


```python
# We make an if statement to check the competition and if it is competitive we make a widget of the price and else we make a demand func.

# Start of if statement
if ('Competitive'==competition.value): # This is the start of an if statement, which checks which form of competition was choosen.
    
    # Then we print a short text
    print('Since you have picked the competitive market, you need to choose the price, p, at which the other firms sell their goods')
    print('')
    # And then we make and print the widget
    print('\033[1m' + 'Price on goods (P)')
    P = widgets.FloatText(
    value=15)
    Pb = widgets.FloatSlider(
    value=5,
    step=1,
    min=1,
    max=100.0,)
    display(P,Pb)
    linkP = widgets.jslink((P, 'value'), (Pb, 'value'))

# Start of else statement
else:
    
    # We again start with a short text
    print('Since you have picked monopolistic competition, we need to define the demand function of the consumer. Here we use a linear function (D(x)=b-a*x), where the slope, a, and the constant term, b, are determined by the widgets below.')
    print('')
    
    # And the we make the demand function
    # First we determine a
    print('\033[1m' + 'Slope of demand function (a)')
    a = widgets.FloatText(
    value=5)
    aa = widgets.FloatSlider(
    value=5,
    step=0.5,
    min=1,
    max=10.0,)
    display(a,aa)
    linka = widgets.jslink((a, 'value'), (aa, 'value'))

    # Then we determine b
    print('\033[1m' + 'Constant term (b)')
    b = widgets.FloatText(    
    value=200)
    bb = widgets.FloatSlider(
    value=200,
    step=1,
    min=1,
    max=500.0,)
    display(b,bb)
    linkb = widgets.jslink((b, 'value'), (bb, 'value'))
# Note that we don't define the demand function yet since the user need to be able to change the variables first. Therefore, we define the demand function, when solving the problem
```

    Since you have picked the competitive market, you need to choose the price, p, at which the other firms sell their goods
    
    [1mPrice on goods (P)



    FloatText(value=15.0)



    FloatSlider(value=5.0, min=1.0, step=1.0)


### **Define the Total Cost function**

Next we define our total cost function, which we define as a quadratic form. (We have included total cost, as it is needed to determine whether the firm wants to enter the market or not)

\\[
TC(x) = c x^2+FC
\\]


```python
# Determine c as a widget
print('\033[1m' + 'Slope, c')
c = widgets.FloatText(
value=0.5)
cb = widgets.FloatSlider(
value=0.5,
step=0.1,
min=0,
max=10.0,)
display(c,cb)
linkb = widgets.jslink((c, 'value'), (cb, 'value'))
    
# Determine fixed costs as a widget
print('\033[1m' + 'Fixed costs (FC)')
FC = widgets.FloatText(
value=10)
FCb = widgets.FloatSlider(
value=10,
step=1,
min=0,
max=100.0,)
display(FC,FCb)
linkb = widgets.jslink((FC, 'value'), (FCb, 'value'))   
```

    [1mSlope, c



    FloatText(value=0.5)



    FloatSlider(value=0.5, max=10.0)


    [1mFixed costs (FC)



    FloatText(value=10.0)



    FloatSlider(value=10.0, step=1.0)



```python
def TC(x,c,FC): # defining the TC function
    return c*x**2+FC
x = Symbol('x')
def MC(x,c): # defining the MC function
    return 2*c*x

# Here we create a vector of prices, which we are going to use in our functions. It the same as the privous one with x1.
p_x_max=50 # Here set the capacity limit at 50
shape_tuple = (N,N)
p_x_values = np.empty(shape_tuple)
for i in range(N): 
    for j in range(N): 
        p_x_values[i,j] = (i/(N-1))*p_x_max 

# And lastly we plot our Total cost function
def Figure_7():
    fig = plt.figure(figsize=(8,5))  
    ax = fig.add_subplot(1,1,1)
    ax.plot(p_x_values,TC(p_x_values,c.value,FC.value), 'b'); 
    ax.set_xlabel('$x$') 
    ax.set_ylabel('$TC$') 
    ax.set_title('Total cost')
Figure_7()
```

We see that given our definition of the cost function, the MC is increasing in x, as TC increases more than 1:1 in x.

### **Solution**


```python
# We start by printing a few words, which we  are going to use a the start of our conclusion
print('We now solve the maximization problem by maximizing the profit of the firm.')

# Next we start an if statement to chech for the competition and print another line depending on that
if ('Competitive'==competition.value):
    print('And since you have choosen the competitive market. The profit function of the firm is \u03C0=px-TC(x)')
elif ('Monopolistic'==competition.value):
    print('And since you have choosen the monopolistic market. The profit function of the firm is \u03C0=D(x)p-TC(x)')

# Next we start the same if statement but now we will solve the problem depending on the competition

# The first the the competitive market
if ('Competitive'==competition.value):
    # Here we start by defining the function that we are going to optimize
    def pi_competitive(x,P,c,FC):
        return -(P*x-TC(x,c,FC)) # Here we define pi as the profit times -1, so that we can use scipy optimize
    # Next we use scipy optimize to solve our problem
    solver4 = optimize.minimize_scalar(pi_competitive, method='bounded', bounds=(0,p_x_max), args=(P.value,c.value,FC.value)) 
    
    # We define our answers as
    x_opt1 = solver4.x
    price1 = P.value
    pi1=P.value*x_opt1-TC(x_opt1,c.value,FC.value)
    TC1 = TC(x_opt1,c.value,FC.value)
    REV1  = P.value*x_opt1
    
    # And then print the results
    print('The results are:')
    print(f'x = {x_opt1:.1f}')
    print(f'Price = {P.value:.1f}')
    print(f'\u03C0 = {pi1:.1f}') 
    print(f'Total cost  = {TC1:.1f}') 
    print(f'Revenue  = {REV1:.1f}') 
    
    # We also chekcs to see whether the firm wants to produce anything. This is done in the folowing if statement
    if pi1>-FC.value and pi1<0: # So if the profit is negative but above the fixed cost we still want to produce but we still print a line commenting this
        print('')
        print('Although the profit is negative, the firm will still produce since they must cover some of the fixed costs')
    elif pi1<-FC.value: # If the profit is below the negative value of the fixed costs the firm should not produce
        print('Since the profit is less than the fixed costs, the firm would not produce anything, as this will lower their profits')
    
    # Next we print the next part of our conclusion, which is going to introduce the figure
    print('')
    print('We show this result by plotting the marginal cost against the marginal revenue. The marginal costs is the first derivative')
    print('of the total cost function. This means MC(x)=2cx. The marginal revenue is equal to the price level, p. This gives us the following plot.') 
    print('It shows that for MR=MC, the firm maximizes its profit.')
    
    # Next we define the figure, which shows us our result
    def Figure_8():
        fig = plt.figure(figsize=(15,5)) 
        # We start by adding a plot for MR and MC
        ax = fig.add_subplot(1,2,1)
        ax.plot(p_x_values,MC(p_x_values,c.value),'b'); # We plot our marginal cost
        ax.hlines(y=price1, xmin=0, xmax=p_x_max) # This code plots the marginal revenue, which is constant at the price level. So here we plot an horisontal line.
        ax.set_xlabel('$x$') # Add label
        ax.set_ylabel('$p$') # Add label
        ax.set_title('Marginal cost and Marginal revenue') # Add title
        
        # The next line mark the solution
        ax.plot(x_opt1, P.value, color='red', marker='o', linestyle='dashed', linewidth=5, markersize=10, fillstyle='none')
        
        # Next we add a plot for the profit
        ay = fig.add_subplot(1,2,2)
        ay.plot(p_x_values,TC(p_x_values,c.value,FC.value),'b');
        ay.hlines(y=price1, xmin=0, xmax=p_x_max, color='blue') # This code plots a the price level, which is costant in a competitive market
        ay.set_xlabel('$x$')
        ay.set_ylabel('$p$')
        ay.set_title('Total cost and Price')
        ay.set_xlim(0,20)
        ay.set_ylim(0,100)
    Figure_8()    
    

# Next we do the same for the monopolistic competition    
elif ('Monopolistic'==competition.value):
    def pi_monopolistic(x,b,a,c,FC):
        return -((b-a*x)*x-TC(x,c,FC)) # Here we define pi as the profit times -1, so that we can use scipy optimize
    
    solver5 = optimize.minimize_scalar(pi_monopolistic, method='bounded', bounds=(0,p_x_max), args=(b.value,a.value,c.value,FC.value))
    
    def MR2(x,b,a): # Here we define the marginal revenue which isnt constant as it was in the competitive market
        return b-2*a*x
    
    # We define our answers as
    x_opt2 = solver5.x 
    price2 = b.value-a.value*x_opt2
    pi2=(b.value-a.value*x_opt2)*x_opt2-TC(x_opt2,c.value,FC.value)
    TC2 = TC(x_opt2,c.value,FC.value)
    REV2  = (b.value-a.value*x_opt2)*x_opt2
    print('The results are:')
    print(f'x = {x_opt2:.1f}')
    print(f'Price = {price2:.1f}')
    print(f'\u03C0 = {pi2:.1f}') 
    print(f'Total cost = {TC2:.1f}') 
    print(f'Revenue = {REV2:.1f}') 
    
    if pi2>-FC.value and pi2<0:
        print('')
        print('Although the profit is negative, the firm will still produce since they must cover some of the fixed costs')
    elif pi2<-FC.value and pi2<0:
        print('Since the profit is less than the fixed costs, the firm would not produce anything, as this will lower their profits')
    
    print('')
    print('We show this result by plotting the marginal cost against the marginal revenue. The marginalcosts is the first derivative')
    print('of the total cost. This means MC(x)=2cx. The marginal revenue is equal to MR(x)=b-2ax.')
    print('When plotting this, we notice that when MR=MC, the firm maximizes its profit.')
    print('And as they have monopolly, they find the optimal value of x, when MR=MC, and sets the optimal price on the demand function according to this.')
    
    def Figure_9():
        fig = plt.figure(figsize=(15,5)) # creates the figure 
        ax = fig.add_subplot(1,2,1)
        ax.plot(p_x_values,b.value-a.value*p_x_values, 'b' ); 
        ax.plot(p_x_values,MC(p_x_values,c.value), 'r');
        ax.plot(p_x_values,MR2(p_x_values,b.value,a.value), 'r');
        ax.plot(x_opt2, MR2(x_opt2,b.value,a.value), color='blue', marker='*', linestyle='dashed', linewidth=5, markersize=10, fillstyle='full')
        ax.plot(x_opt2, b.value-a.value*x_opt2, color='red', marker='o', linestyle='dashed', linewidth=5, markersize=10, fillstyle='full')
        ax.vlines(x=x_opt2, ymin=0, ymax=price2) # This code plots a vertical line at the optimal value of x
        ax.set_xlabel('$x$') 
        ax.set_ylabel('$p$') 
        ax.set_ylim(0,b.value)
        ax.set_xlim(0,b.value/a.value)
        ax.set_title('Marginal cost and Marginal revenue')
        ay = fig.add_subplot(1,2,2)
        ay.plot(p_x_values,TC(p_x_values,c.value,FC.value),'b');
        ay.plot(p_x_values,b.value-a.value*p_x_values,'b')
        ay.set_xlabel('$x$')
        ay.set_ylabel('$p$')
        ay.set_title('Total cost and Demand function')
        ay.set_ylim(0,b.value)
        ay.set_xlim(0,b.value/a.value)
    Figure_9()
```


```python

```

6552e6ec9ee444c239cf39a97fbe1cf37040b168
ipynb
Jupyter Notebook
modelproject/modelproject.ipynb
NumEconCopenhagen/projects-2019-chh-jmk
befe855d13bba5f690954f80c4b7b31e0c8c8fbb
MIT
modelproject/modelproject.ipynb
NumEconCopenhagen/projects-2019-chh-jmk
befe855d13bba5f690954f80c4b7b31e0c8c8fbb
MIT
2019-04-12T08:23:57.000Z
2019-05-14T19:49:48.000Z
modelproject/modelproject.ipynb
NumEconCopenhagen/projects-2019-chh-jmk
befe855d13bba5f690954f80c4b7b31e0c8c8fbb
MIT
Qwen/Qwen-72B
1. YES
2. YES