# Simple Economic Models

## Preface

Hammock-Mixon02.wxmx 
Edwin L. (Ted) Woollett,
http://web.csulb.edu/~woollett/
Feb. 2021
=======================================================

One goal of this series is to illustrate the use of Maxima in mathematically simple contexts,
and much of economic modelling of human behavior involves mathematically simple models.

We use the notation x ~ 11.2 to mean "x is approximately equal to 11.2".
  x ==>  y  means "x implies y"
---------------------------------------------------------------------------------------------------

"Economics studies the allocation of scarce resources among people - examining
what goods and services wind up in the hands of which people." IEA 8

"Economics proceeds by developing models of social phenomena. By a model we mean a 
   simplified representation of reality."  V9  28

"In much of economics we use a framework built on the following two simple principles.

1. The optimization principle: People try to choose the best patterns of consumption that they can afford.

2. The equilibrium principle: Prices adjust until the amount that people demand of something is equal to the 
     amount that is supplied."     V9    30
--------------------------------------------------------------------
"Realistic, successful analysis of a problem that faces a decision-maker requires that the analyst isolate 
the key aspects of reality in that problem. That is, the analyst must abstract and simplify, always taking 
care to retain those factors that are deemed crucial to the situation at hand. For example, the availability 
of iron ore is a crucial factor in the production of steel, whereas the religious affiliations of steel workers 
is probably an irrelevant factor. [We say “probably” because in some contexts this might not be true. If 
production is a team effort and if religious composition affects team performance either by  promoting 
cohesion or by providing insights from various viewpoints, then it should be taken into account. 
Witness communes like the Amana community.]" IME 19

"A model identifies the factors and influences that are important in a situation, and delineates the 
relationships among those factors and influences. A model is best thought of as a systematic presentation 
of interrelated theories." IME 20

## References

We will quote and otherwise refer to several references.

1.  MTC  The sections of this worksheet are keyed to sections in 
Microeconomic Theory and Computation: Applying the Maxima 
Open-Source Computer Algebra System, by Michael R. Hammock 
and J. Wilson Mixon, Springer, 2013 (Kindle edition). We follow closely
the examples and discussion in this useful book.  [MTC x.y.z] = Book section
-------------------------------------

2. IME  Introduction to Mathematical Economics, Wilson Mixon, Berry College, 2017

https://sites.berry.edu/wmixon/wp-content/uploads/sites/75/2017/07/Book.pdf
IME 19 refers to pdf page 19.

------------------------------
3. IEA  Introduction to Economic Analysis, v 2.1, (2009) Preston McAfee, Tracy R. Lewis, Donald J Dale,  

            https://www.kellogg.northwestern.edu/faculty/dale/ieav21.pdf.
                     Page and section numbers refer to this pdf file.
------------------------------------------------------------

[BR]    A Brief Review of Microeconomic Theory
https://www.law.berkeley.edu/php-programs/courses/fileDL.php?fID=4555
--------------------------------


--------------------------------------
4. MECON  Macroeconomics, 8th ed,  David C. Colander, McGraw-Hill, 2010

5.  SGM   Study Guide for use with Macroeconomics, 8th ed, David Colander,
McGraw-Hill 2010 (SGM)

6.  Investopedia webpage: 
                 https://www.investopedia.com  and subpages

7.   wikipedia 

             https://en.wikipedia.org/wiki/Mathematical_economics#Modern_mathematical_economics

8. 
       V9         Hal R. Varian, Intermediate Microeconomics: A Modern Approach, 9th ed, 2014, Norton

  http://candrafajriananda.lecture.ub.ac.id/files/2017/09/e-books-MICRO-INTERMDEDIATE-ed9-VARIAN.pdf
      V9   xx  refers to pdf page number xx in Varian 9th ed.

Earlier editions:
Hal R. Varian, Intermediate Microeconomics: A Modern Approach, 8th ed, 2010, Norton
https://fac.ksu.edu.sa/sites/default/files/microeco-_varian.pdf

Hal R. Varian, Intermediate Microeconomics: A Modern Approach, 7th ed, 2005, Norton
https://ugess3.files.wordpress.com/2016/02/intermediate-microeconomics-a-modern-approach_-7th-edition-hal-r-varian-w-w-norton-2005.pdf
More books:
https://people.ischool.berkeley.edu/~hal/people/hal/books.html

9. Berkeley Law Brief Review Microeconomic Theory pdf
https://www.law.berkeley.edu/php-programs/courses/fileDL.php?fID=4555
-------------------------------------------------------------------------------
MIT 14.01 FALL 2018  Principles of Microeconomics,  COURSE HOME:
https://ocw.mit.edu/courses/economics/14-01-principles-of-microeconomics-fall-2018/

VIDEOS OF LECTURES
https://ocw.mit.edu/courses/economics/14-01-principles-of-microeconomics-fall-2018/lecture-videos/
-------------------------------------------------------------------------

MIT 14.01SC, FALL 2011: Principles of Microeconomics, COURSE HOME:
https://ocw.mit.edu/courses/economics/14-01sc-principles-of-microeconomics-fall-2011/index.htm
 
youtube video series
https://www.youtube.com/watch?v=Vss3nofHpZI&list=PL61533C166E8B0028
LEC 8 PRODUCER THEORY:
https://ocw.mit.edu/courses/economics/14-01sc-principles-of-microeconomics-fall-2011/unit-3-producer-theory/introduction-to-producer-theory/
-------------------------------------------------------------------------------
10.   Khan Academy basic economics videos
https://www.khanacademy.org/economics-finance-domain/microeconomics/basic-economic-concepts-gen-micro

11.  The 5.44 version of the Maxima manual is found at:
           http://maxima.sourceforge.net/docs/manual/maxima_singlepage.html

   Inside the  wxMaxima interface, pressing the F1 function key at the top of the keyboard should bring up a
   different version of the current Maxima manual stored in your local installation (you should experiment with both versions).
   The F1 version will automatically respond to a highlighted word by showing a list of all Maxima commands, options, etc.
   which have that highlighted word as a part.

12.           The online manual index is at
http://maxima.sourceforge.net/docs/manual/maxima_singlepage.html#Function-and-Variable-Index

13.      A list of draw package functions is at
http://maxima.sourceforge.net/docs/manual/maxima_singlepage.html#Category_003a-Package-draw

## rnddp, rnd_matrix_dp, percent_inc, frac_diff, percent_diff

Some useful functions to round floating point numbers to dp decimal places:

rnddp(expr,dp):= 
    if floatnump (expr) then float((round(expr*10^dp)/10^dp)) else expr$
rnd_list_dp(alist,dp) := map (lambda([xx], rnddp(xx, dp)), alist)$
rnd_matrix_dp(%Amatrix,dp) := 
                 matrixmap (lambda([xx], rnddp(xx, dp) ), %Amatrix)$

rnddp(1.234567,  2);

rnddp(1.234567,  4);

Let Maxima display 16 digit numerical arithmetic results using 16 digits.

fpprintprec :0$

In the section on Production Possibilities Curve (PPC), we set fpprintprec to the value 4 to reduce
the eyestrain of looking at so many digits.

Two interactive methods to display 16 digits of π:

float(%pi);

%pi, numer;

percent_inc (x1,x2) calculates the percent increase going from x1 to x2.

percent_inc (%x1, %x2) :=  sconcat (100*(%x2 - %x1)/%x1, "%")$

percent_inc (1,1.5);

frac_diff (x1,x2) calculates the absolute value of the fractional difference between
x1 and x2, using the mean value in the denominator.

frac_diff (xa1,xa2) := 2*abs(xa2 - xa1)/(xa1 + xa2)$

frac_diff (1, 1.5);

percent_diff (x1,x2) calculates the absolute value of the percent difference
between x1 and x2, using the mean value (1/2)*(x1 + x2) as the denominator
instead of x1 or x2.

percent_diff (%x1, %x2) :=  sconcat (100*frac_diff (%x1,%x2), "%")$

percent_diff (1,1.5);

## Production Possibilities   [MTC 2.1]

A production possibilities curve (PPC) is a simple model of economy-wide production.
This model is perhaps the most abstract model, since it simplifies the "economy" to
the production of only two types of "goods."

The production possibilities curve shows the trade-off (or opportunity cost)
between two things (two goods). How much "y" do you have to give up to
get a desired amount of "x"?

Define a function which will relate two variables x and y, and
which depends on three parameters a, b, and n.

Assume the relation y = a + b*x^n, with a and b adjustable and
n = 2.5 hardwired in:

### Defining the PPC curve using an expression

One usually has a choice, using Maxima, to work with Maxima functions, or
else to work with Maxima expressions. The examples in the text MTC
use mainly the function approach. In this first section we mainly use expressions.

This example will assume a relation between goods x and y of the form
 y = a + b*x^n, depending on the three parameters a, b, and n.  If we
 choose n = 2.5,  then y = a + b*x^2.5 depends on two parameters, a 
and b. 

y_gen : a + b*x^2.5;

Specializing within this class of models, choose:

[a1, b1] : [500, -0.01]$

Parameters a1 and b1 then define expression y1 depending on x:

y1 : y_gen, a = a1, b = b1;

grind(%)$

Symbol bindings so far:

values;

Because b1 < 0, as x grows, y decreases, and as x shrinks
y increases. When x = 0, y = ymax = a1.

This defines a possible "Production Possibilities Curve" (PPC)
in which the x and y variables represent two "goods" in a two-goods
economy. We can think of x and y as representing the daily production rate
of two different kinds of widgets, for example, and therefore being
non-negative numbers.

We assume the variables x and y are each non-negative, and
the constraining relation we are assuming implies a maximum
positive value for both x and y (xmax and ymax) [If the PPC
proposed didn't imply maximum positive values for each of
the two goods x and y, the relation would be non-physical.]

### Finding xmax

Now  find xmax subject to these parameter values. We assume
y > 0 when x < xmax, and y = 0 when x = xmax.

In terms of notation,

(a1, b1) ==>  x1max for given n = 2.5
 

Set fpprintprec to 4 to reduce eyestrain from looking at 16 digit numerical answers.

fpprintprec : 4$

### find_root method

method 1: use numerical search via find_root.

We need to assume a range for xmax existence when
using the find_rooot method,  so  assume  0 < xmax < 1000.

Here we use the syntax 

              find_root (expr, lower-lim, upper-lim)

in which there is one free variable in expr.

x1max : find_root ( y1, 0, 1000 );

An alternative find_root syntax is: 

         find_root(expr, var, lower-limit, upper-limit)

find_root ( y1, x, 0, 1000 );

if expr has the same sign at the lower limit and at the upper limit, find_root will return an error.
For example, try find_root (2 + sin(x/30), 0, 10).

### Analytic Method

Method 2:   use analytic means.

What is x when y = 0?, or what x satisfies the equation:  a + b*x^(2.5) = 0?
We can solve algebraically to get  x = ( - a/b )^(2/5), 
since 2.5 = 5/2. Note b is negative.

(- a1/b1)^(2/5);

We can also try solve:

display2d : false$
ratprint : false$

eqn : a + b*x^2.5 = 0, a = a1, b = b1;

solve (eqn, x),  numer;

We can also rewrite the expression as:

(5.0*10^4)^(2/5);

which is the same answer. 

Note that 2.5 = 5/2, so the solution returned by solve says that x^(5/2)/100 = 500, or x^(5/2) = 5*10^4, 
or raising both sides to the (2/5) power, and using x^(5/2)^(2/5) = x^ ( (5/2) * (2/5) ) = x^1 = x, we get x = (5*10^4)^(2/5)

With the analytic  method 2, we don't have to assume ahead of time
that x1max < 1000.

We can write 5e4 for the quantity 5.0*10^4:

5*10^4;

5.0*10^4;

5e4;

(5e4)^(2/5);

(5e4)^0.4;

Likewise we can write 5e-4 for 5.0*10^(-4).

5*10^(-4);

5.0*10^(-4);

5e-4;

### ymax

Because b1 < 0, as x increases, more is subtracted from a1, and
y decreases. As x decreases, less is subtracted from a1, and
y increases, reaching a maximum value when x = 0 and y = a1.

Hence ymax = a1.

display2d : true$

values;

### Display PPC Curve Using wxdraw2d

Set the x (y) ranges for the plot to be 1.1*x1max (1.1*a1).
Set the x axis label to "Good x", y axis label to "Good y".

"   ";
print ("            y1 = ",y1, "   x1max = ",x1max, "   a1 = ", a1 );

wxdraw2d (
    title = "Production Possibilities Curve PPC ",
    grid = [2,2],
    background_color = light_gray,
    xlabel = "Good x",
    ylabel = "Good y",
    xrange = [0, 1.1*x1max],
    yrange = [0, 1.1*a1],
    line_width = 2,
    explicit (y1, x, 0, x1max ) )$

"...some levels of output cannot be attained given the resource supplies 
and technology that define this PPC. Even if all resources are used 
(no unemployment) and they are used efficiently, all points above the 
curve are ruled out." - MTC - 70

Note that in this wxdraw2d example, we used the draw package 'explicit'
function. If you look at the v. 5.44 Maxima manual (see References), the 
 syntax of explicit is given as:

Graphic object: explicit
    explicit (expr,var,minval,maxval)
    explicit (fcn,var,minval,maxval)
    explicit (expr,var1,minval1,maxval1,var2,minval2,maxval2)
    explicit (fcn,var1,minval1,maxval1,var2,minval2,maxval2)
Draws explicit functions in 2D and 3D.

The first line shows use with a Maxima expression, the second line
shows use with a Maxima function.

### Opportunity Cost  [MTC. 2.1.2]

"Opportunity cost is the basis of cost/benefit reasoning: it is the benefit
forgone, or the cost of the next-best alternative to the activity you've 
chosen. That cost should be less than the benefit you've chosen." - SGM- p. 1

In the context of a tradeoff between x and y, the opportunity cost of x is
the number of units of y given up per increased unit of x.

Pick two possible values of x, say xA and xB. Evaluate curve y1 at these
two x's and at closely adjacent values of x, producing 4 points on
the curve y1.

First, remind ourselves what y1 and x1max are bound to:

[y1, x1max];

[xA, xB, dx] : [x1max/5, x1max/2, x1max/20];
yA : y1, x = xA;
yAd : y1, x = xA+dx;
yB : y1, x = xB;
yBd : y1, x = xB + dx;

Each of the pairs of points has the same small
increase of x given by dx.

wxdraw2d (
    title = "Opportunity Cost",
    xlabel = "Good x",
    ylabel = "Good y",
    xrange = [0, 1.1*x1max],
    yrange = [0, 1.1*a1],
    line_width = 2,
    explicit (y1, x, 0, x1max ),
    point_size = 1.3,
    point_type = filled_circle,
    points ( [xA, xA+dx, xB, xB+dx],
                 [yA, yAd, yB, yBd] ) )$

For larger x,  we must have smaller y and for larger x, a small given 
increase in x results in a greater decrease in y. Choosing the "benefit" 
of a given increase in x implies one must "pay" an increasingly 
greater cost in the value of y.

The "opportunity cost" is greater as x increases, since  the slope becomes
more negative.
 
If we let oc(x) be the opportunity cost at a given value of x,

oc (x) = - (y(x+dx) - y(x)) / dx  = - slope (x) = - dy(x)/ dx =  - diff (y(x), x)

Approximate values of the opportunity cost at xA and xB are:

[ocA, ocB] : [ - (yAd - yA) / dx,  - (yBd - yB) / dx ];

To get exact values of the opportunity cost at any value of x, we
need the first derivative of the expression y1.  Let dy1dx stand for the symbolic
first derivative of expression y1 with respect to x (the local slope):

dy1dx : diff (y1, x);

An expression which is the opportunity cost at given x for this
curve is then the negative of the local slope:

oc  : -dy1dx;

For example, the values at xA and xB are:

ocA : oc, x = xA;

ocB : oc, x = xB;

The opportunity cost at x = xB is about 4 times the opportunity cost at x = xA.

The largest opportunity cost corresponds to the largest value of x, and we let
this define ocmax to use in setting the plot yrange limits in a plot of the opportunity cost 
oc as a function of x.

ocmax : oc, x = x1max;

[xA, xB];

[xA, ocA];

wxdraw2d (
    title = "good y Opportunity Cost vs good x",
    xlabel = "Good x",
    ylabel = " oc =  - dy/dx",
    xrange = [0, x1max],
    yrange = [0, ocmax],
    line_width = 2,
    explicit (oc, x, 0, x1max ),
    point_size = 1.3,
    point_type = filled_circle,
    key_pos = top_left,
    key = sconcat (" (xA , ocA) =  (", xA, "   ",ocA, ") "),
    label (  ["A",  xA, ocA+1]  ),       
    points ([xA],[ocA]),
    color = red,
    key = sconcat (" (xB , ocB) =  (", xB, "   ",ocB, ") "),
    points ( [xB], [ocB] ),
    label ( ["B", xB, ocB + 1]) )$
  

### Shifting PPC   [MTC  2.1.3]

"A change in either the resource availability or technology shifts the PPC. 
An increased resource base or an improved technology would shift the 
PPC outward (more y for each level of x produced)." [MTC 72]

"The illustration below shows a special case. Either technology is limited 
to x production or only resources used in x production increases."

A new PPC is defined by new set of parameters (a,b). We let the value of 
a remain the same (a2 = a1), but reduce the value of b from b1  = - 0.01 to 
b2 = - 0.0075

[a2, b2] : [500, -0.0075]$

y2 will be an expression, depending on x, that reflects these new values
of the curve parameters.

y_gen;

y2 : y_gen, a = a2, b = b2;

grind(%)$

Again, both x and y are non-negative in the "real world", and x <= xmax 
which occurs when y = 0. (The most we can have of good x happens only when
we get none of good y.)  Using the analytic method here,

x2max : (- a2/b2)^(2/5);

We see the more negative value of b has shifted the PPC so that larger
values of x > 0 are now possible.

The maximum value possible for y is again the value of the parameter a = a2,
which is the value of y when x = 0.

We use wxdraw2d to show both PPC's, the "Initial" and the "New".

"  ";

print ("                   y1 = ", y1, "  y2 = ",  y2) ;


wxdraw2d (
    title = "PPC Shift to lower b value",
    xlabel = "Good x",
    ylabel = "Good y",
    xrange = [0, 1.1*x2max],
    yrange = [0, 1.1*a2],
    line_width = 2,
    key = "Initial PPC y1",
    explicit (y1, x, 0, x2max ),
    key = "New PPC y2",
    color = red,
    explicit (y2, x, 0, x2max )     )$

"In the context of a tradeoff between x and y, the opportunity cost of x is
the number of units of y given up per increased unit of x." We see that
the shifted PPC implies a smaller opportunity cost of x in general,
since the new slope is less steep.

"Chapter 12 revisits the PPC, deriving a PPC from microeconomic foundations. 
In doing so, it investigates the nature of efficiency, identifying the conditions 
that are required for an economy to reach its PPC. It also shows how the price 
system can guide an economy toward the PPC." [MTC 74]

## Competitive Markets     [MTC 2.2]

In competitive markets, supply and demand determine price and quantity of some good
(it is assumed).

### Supply and Demand Curves; Price (p) & Quantity (q) 

From ref. (6):  https://www.investopedia.com/terms/d/demand-curve.asp

"The demand curve is a graphical representation of the relationship between the price 
of a good or service and the quantity demanded for a given period of time. In a typical 
representation, THE PRICE (p) WILL APPEAR ON THE LEFT VERTICAL AXIS, THE
QUANTITY DEMANDED (q) ON THE HORIZONTAL AXIS."

"The demand curve will move downward from the left to the right, which expresses the 
"law of demand" — as the price of a given commodity decreases, the quantity demanded 
increases, all else being equal (and vice versa)."

"Note that this formulation implies that price (p) is the independent variable, and quantity (q)
 the  dependent variable. IN MOST DISCIPLINES, THE INDEPENDENT VARIABLE APPEARS ON
THE HORIZONTAL OR X-AXIS, BUT ECONOMICS IS THE EXCEPTION TO THIS RULE."

The statement "curve A lies above curve B" in a plot means curve A is vertically above curve B
and corresponds to a higher price.

"As an example of the "law of demand", if the price of corn rises, consumers will have an 
incentive to buy less corn and  will replace corn with other foods, so the total quantity of 
corn consumers demand will fall."

"Economists call a person’s maximum willingness to pay for something that person’s "reservation price." 
The reservation price is the highest price that a given person will accept and still purchase the good. 
In other words, a person’s reservation price is the price at which he or she is just indifferent between 
purchasing or not purchasing the good." V9  31

"In economics, supply is the amount of a resource that firms, producers, labourers, providers of financial assets, 
or other economic agents are willing and able to provide to the marketplace or directly to another agent in the marketplace."
(Wikipedia)

From Ref (6):

"On most supply curves, as the price of a good increases, the quantity of supplies increases.
Emerging technology that increases efficiency lowers the labor cost and therefore price of a good.
Supply curves can often show if a commodity will experience a price increase or decrease based on demand, and vice versa."

"The supply curve will move upward from left to right, which expresses the law of supply: As the price of a given commodity 
increases, the quantity supplied increases (all else being equal)."


For "elastic goods" sellers and buyers quickly adjust their demand for that good or service if the price changes.

For "inelastic goods" demand does not change for that particular good or service when the price goes up or down.

### Exogenous and Endogenous Variables

Reference:
https://en.wikipedia.org/wiki/Exogenous_and_endogenous_variables

"In an economic model, an exogenous variable is one whose value is determined outside the model and is imposed 
on the model, and an exogenous change is a change in an exogenous variable."

"In contrast, an endogenous variable is a variable whose value is determined by the model. An endogenous change is 
a change in an endogenous variable in response to an exogenous change that is imposed upon the model."

"In the simple supply and demand model, a change in consumer tastes is unexplained by the model and imposes an 
exogenous change in demand that leads to a change in the endogenous equilibrium price and the endogenous equilibrium 
quantity transacted. Here the exogenous variable is a parameter conveying consumer tastes. Similarly, a change in the 
consumer's income is exogenously given, outside the model, and appears in the model as an exogenous change in demand."

"An economic variable can be exogenous in some models and endogenous in others. In particular this can happen when 
one model also serves as a component of a broader model."
---------------------------------------------
"The magnitude of endogenous variables is explicitly examined and determined by the model. A supply-and-demand model 
determines the price of goods and services. Price is endogenous variable in such a case. If, however, government mandates 
a price for the good, then price becomes an exogenous variable in the model." IME 22
 

" We write the inverse demand curve as P = a - b*Qd (demand), with P = price and Qd = quantity demanded and we write the
inverse supply curve as P = c + d*Qs   (supply), with again P = price and Qs = quantity supplied, and a, b, c, d are parameters."

"The parameters a, b, c, d depend on many factors in the economic environment, such as consumer preferences and income
(demand side) and technology and input prices (supply side). These parameters (and the underlying economic factors that
determine them) are exogenous to our model because we do not explicitly model their determination or derivation. Similarly,
we do not model the choice-making processes by consumers or firms; we simply assume that the optimal results of those
processes are captured in the demand and supply schedules. In contrast, [equilibrium] price and quantity will be determined
within the solution to our model. These variables are therefore endogenous." ME 3

In equilibrium Qs = Qd = q0 say and q0 is determined from equating the two expressions for price:
    a - b*q = c + d*q

solve (a - b*q = c + d*q, q);

q0 : rhs (%[1]);

Change sign in numerator by the following trick:

q0 : num(q0)/denom(q0);

Solve for equilibrium price by substituting q0 for q in one of the two price equations.

p0 :  a - b*q0, ratsimp;

These solutions for q0 and p0 are expressions for two endogenous variables in terms of four exogenous variables,
the four model parameters a, b, c, d.

As a numerical example of this linear demand and linear supply model, we can choose values for the
four exogenous parameters.

kill(a,b,c,d);

Creating a parameter list in this way doesn't bind the symbols a,b,c,d to anything.
The result is a list of replacement rules.

parameters : map ("=", [a,b,c,d], [10,3,2,2] );

Define DP (the inverse demand curve) as an expression depending on q. DP is the price buyers are willing
and able to pay for quantity q.

DP : a - b*q, parameters;

Define SP (the inverse supply curve) as an expression depending on q. SP is the price producers require
to supply quantity q.

SP : c + d*q, parameters;

Here is a way you can create a small table of these definitions in the process of binding DP and SP to
specific expressions (instead of doing one at a time as above).

matrix ( ["DP", "SP"],
           ev( [DP : a - b*q,  SP : c + d*q], parameters ) );

Solve for the equilibrium q, call this q0. Since this is a linear demand curve model, the Maxima function
solve has no problem.

solve (DP = SP,q);

q0 : rhs (%[1]), numer;

Then find the equilibrium price p0 using either DP or SP.

[DP, SP], q = q0;

Here we actually bind p0 to a number.

p0 : DP, q = q0;

Use wxdraw2d to make a plot of the inverse demand curve DP and the inverse supply curve SP 
with price on the vertical axis and quantity on the horizontal axis (following Economics conventions).
In this example, we are using expressions (rather than functions) as the first argument of explicit.
Blue is the default color.

The vertical axis is labelled "$ per unit".  Remember that the unit can be any size. For example, one "unit"
might refer to one million widgets per year.

"   ";

print ("           DP = ", DP, "    SP = ", SP );

wxdraw2d (    
    grid = [2,2],
    background_color = light_gray,
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 5],
    yrange = [0, 15],
    line_width = 2,
    key_pos = top_center,
    key = "DEMAND",
    explicit ( DP, q, 0, 5),    
    color = red,
    key = "SUPPLY",
    explicit ( SP, q, 0, 5) )$

We can add information about the equilibrium point (p0, q0). The added information can be as
elaborate as you have time for. We will even add a simple label. In this example, we are using
expressions (rather than functions) as the first argument of explicit. If dashes doesn't work
on your system, use dots. We omit the gray background and grid so the other information
is easier to see on the default white background.

"   ";

print ("                    DP = ", DP, "    SP = ", SP );


wxdraw2d (    
    title = "Demand and Supply Curves",
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 5],
    yrange = [0, 15],
    line_width = 2,
    key_pos = top_center,
    key = "DEMAND",
    explicit ( DP, q, 0, 5),    
    color = red,
    key = "SUPPLY",
    explicit ( SP, q, 0, 5),
    color = black,
    point_type = filled_circle,
    point_size = 1.3,
    key = "",
    points ([q0], [p0] ),
    color = brown,
    line_type = dashes,
    key = sconcat (" p0 = ", p0),
    explicit (p0,q,0,q0),
    color = green,
    key = sconcat (" q0 = ",q0 ),
    parametric (q0, t, t, 0, p0),
    color = black,
    label ( [ " <--  EQUILIBRIUM POINT ", 3, p0] ))$

### DQ, DP, SQ, SP  Definitions for Nonlinear Demand Curve:  model 0

The "demand curve" model now will be a nonlinear expression/function: DQ = a*p^E  is the quantity demanded by buyers as a 
function of price p.   We also use the notation q(demand) and demand curve, quantity. a and E are exogenous parameters.
The quantity E turns out to be the (constant) elasticity of the demand curve; we discuss this aspect in the section
Elasticities. The general form we are assuming for DQ defines a class of "constant elasticity demand curves". We later
consider a linear demand curve in which the elasticity E changes with price/quantity.

The "inverse demand curve" DP = (q/a)^(1/E) (inverting the above assumed demand curve) is the price buyers 
are willing and able to pay as a function of quantity q, and we also use the notation p(demand) and demand curve, price.

The "supply curve" SQ is assumed to be a linear function of price, and is defined here to be SQ  = b + c*p.  
We can use the notation q(supply) for this. Also called the "supply curve, quantity", SQ is the quantity 
producers will supply as a function of price p. b and c are exogenous model parameters.

The "inverse supply curve" SP = (q - b)/c  is a function of quantity q, and we use the notation p(supply). 
Also called the "supply curve, price", SP is the price required to achieve a needed supply (quantity).

We define four Maxima expressions which are based on our model assumptions:

matrix ( ["DQ", "DP", "SQ", "SP"],
    [ DQ : a*p^E,   DP : (q/a)^(1/E), SQ : b + c*p,  SP : (q - b)/c ] );

As an example we consider the demand curve q(demand) = 1200/p^2.5 and the
supply curve q(supply) = -5 + 10*p. These particular parameter choices are fixed with the
binding of symbols a0, E0, b0, c0 (we will call this model 0):

fpprintprec : 4$

[a0, E0, b0, c0] : [1200, -2.5,-5, 10]$

model0 : map ("=", [a, E, b, c], [a0, E0, b0, c0] );

DQ0, DP0, SQ0, SP0 are the form of the expressions DQ, DP, SQ, SP for model 0.
Here is the fastest way to bind these symbols for model0 parameters:

[DQ0 : DQ, DP0 : DP], model0;

[SQ0 : SQ, SP0 : SP], model0;

A fancier way to do the same job is to add a row of symbol names above the expressions
the names are bound to; we can use matrix to automatically worry about spacing of the result.

matrix (  [ "DQ0", "DP0", "SQ0", "SP0" ],
            ev (  [DQ0 : DQ, DP0 : DP, SQ0 : SQ, SP0 : SP ], model0 ) );

### Using wxdraw2d for the Demand and Supply Curves

We want the independent variable prices (p) on the vertical axis and dependent variable quantities (q) on the 
horizontal axis to agree with Economics practice. 

So for the demand curve, we use the inverse demand curve DP0 expression as a function of q, and start the curve 
at q = 0.001 to stay away from a singular point at q = 0. 

For the supply curve we use the inverse supply curve expression SP0 which also depends on q, and there is no 
singularity problem  so we start at q = 0.

wxdraw2d (    
    grid = [2,2],
    background_color =  light_gray,
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 100],
    yrange = [0, 10],
    line_width = 2,
    key_pos = bottom_right,
    key = "DEMAND",
    explicit ( DP0, q, 0.001, 100),    
    color = red,
    key = "SUPPLY",
    explicit ( SP0, q, 0, 100) )$

If you use draw2d, instead of wxdraw2d with the same inputs, you will get a separate gnuplot window in which
the coordinates of the cursor are printed out in the lower left hand corner. By placing the
cursor over the point where the curves cross, you can get an approximate location of the equilibrium point:
qE0 ~ 36, pE0 ~ 4.2. You then need to close the gnuplot window to continue with your wxMaxima
session. (the qE0 notation reminds us  it stands for "equilibrium model 0 quantity"; when we consider
a shifted model  with parameters a1, E1, etc, we will have a new equilibrium quantity qE1, etc.)

### Quick Survey of Plots Using plot2d

Prior to using wxdraw2d, you can get a quicker idea of suitable ranges on the x-axis (horizontal axis) and
the y-axis (vertical axis) by using plot2d, which opens a gnuplot window displaying a plot using default
options of plot2d.

Thus you could first just enter the minimal command to just see DP0

        plot2d (DP0, [q, 0.01,100])$

and  to just see SP0:

       plot2d (SP0, [q, 0.01,100])$

or to see both DP0 and SP0 in a minimal plot
   
       plot2d ( [DP0, SP0], [q, 0.01, 100] )$

since both of the expressions depend on the symbol q, and this is then taken as the x-axis variable.
You will see that gnuplot has included all y (p) values from 0 to 120 and most of the action (curves
crossing) takes place near the bottom of the plot. If you put the cursor where the curves cross,
in the bottom left corner of the gnuplot window will be the coordinates of the cursor, and you
will see that the curves cross somewhere around (q = 35, p = 3.5).

So add a vertical (y) range option, and shrink the horizontal (x) range, with 
                
      plot2d ([DP0,SP0], [q, 0.01,50], [y, 0, 20] )$

This will give you a better look at where the curves cross. Note that plot2d
automatically changes the color (by default) for the second expression.
The automatic legend appears if you have two or more expressions, and the
actual formula used is what the legend shows.

To eliminate the legend completely, add [legend, false] as in
    
      plot2d ([DP0,SP0], [q, 0.01,50], [y, 0, 20], [legend, false] )$

To instead have the names of the expressions used for the legend, use

      plot2d ([DP0,SP0], [q, 0.01,50], [y, 0, 20], [legend, "DP0", "SP0"] )$

To thicken the lines, use the [style , [lines, nwidth] ] option, as in

      plot2d ([DP0,SP0], [q, 0.01,50], [y, 0, 20], [legend, "DP0", "SP0"],  [style, [lines, 2] ] )$

Chapter 2 of Maxima by Example has more plot2d examples you can look at.

One warning about plot2d use: if wxMaxima is not responding to your next command,
you have probably not closed the gnuplot window. Shrink your wxMaxima window to
the task bar and you should see an open gnuplot window which was not closed.

### Equilibrium  [MTC 2.2.2]

Reference:
https://pressbooks.bccampus.ca/uvicecon103/chapter/3-6-equilibrium-and-market-surplus/

"A market in equilibrium is said to be operating efficiently as its quantity supplied equals its 
quantity demanded at an equilibrium price or a market clearing price. In an equilibrium market, 
there are neither surpluses nor shortages for a good or service."  Ref 6

"The equilibrium principle: Prices adjust until the amount that people
demand of something is equal to the amount that is supplied."  V9  30

For our example of  the price per order of hamburger plus french fries, and the number of orders 
purchased or produced per hour, at what point does the demand price equal the supply price?

Equivalently, at what point does the demand quantity equal the supply quantity?

Given the demand quantity curve q(demand) = 250/p, and also the supply quantity curve q(supply) = -5 + 10*p, 
we can first show both curves on the same plot and see visually at what quantity they cross.

### Equilibrium Model 0 Quantity qE0 and Price pE0

At the point of intersection, q = qE0 > 0 and p = pE0 > 0 and we can use the equation DP0 = SP0 with
the unknown being q.  solve can deal with a polynomial and to_poly_solve can deal with more
difficult cases, but neither works here. 

For example, solve returns an equation which is a restatement of the equation which needs to be solved; 
note it is not a polynomial.

ratprint : false$

solve (DP0 = SP0, q);

Using find_root (expr, var, varmin, varmax) is a more direct route to the numerical value of qE0, but
you have to provide a range in which to look. Start the find_root interation function at q  = 0.001
to stay away from q = 0  (where expr blows up and find_root returns the request unevaluated).

We can't use find_root (A = B, q,q1,q2) using an equation, but need to convert the equation into
an expression which is zero at the solution point; so use A - B.

After finding qE0 = 35.77 (displaying only four digits) we plug qE0 into the inverse demand curve and the
inverse supply curve and find both predict the same number for the equilibrium price pE0 = $4.08.

In the previous section we drew DP and SP vs q on the same plot and we know the rough location of
the intersection of the demand and supply curves already (at what quantity does the demand price
equal the supply price?) so we expect one root between q = 10 and q = 50.

[qE0 : find_root (DP0 - SP0, q, 10, 50), subst (q = qE0,[ Prices, DP0,  SP0 ] )  ];

Remember L[j] returns element j  of list L. Using this twice, we can extract pE0:

%[2] [2];

but we can also just evaluate DP0 at q = qE0

pE0 : DP0, q = qE0;

Maxima internally holds the values of qE0 and pE0 to 16 digit accuracy for any later numerical use.

fpprintprec:0;

[qE0, pE0];

fpprintprec : 4;

[qE0, pE0];

Solving for the equilibrium quantity instead of the equilibrium price was an arbitrary decision. We can equally well
start by solving for the price at which the demand price equals the supply price.

[pE0 : find_root (DQ0 - SQ0, p, 1, 10), subst (p = pE0, [Quantities, DQ0, SQ0] ) ];

### Create an Excess Demand Table with Discrete Price Points

First create a list of prices pL0 based on the equilibrium value pE0, using the expression
pE0*k/5, letting k run from 1 to 8, when k = 5 we get pE0, when k = 1, pE0/5, etc.

pE0;

pL0 : makelist (pE0*k/5, k, 1, 8);

pL0[5];

The fifth element of the list pL0 is pE0 = 4.077 = the equilibrium price.

We next turn the list of prices pL0 into a list of quantities demanded (qdL0) in model 0
by mapping a lambda function onto list pL0, which converts prices into quantity demanded
using q(demand) = DQ0.

As the argument to the lambda function, we need to precede DQ0 with two single quotes ('') which
replaces DQ0 with its binding 1200/p^2.5 before the lambda function affects the list pL0.

qdL0 : map ( lambda ([p], ''DQ0), pL0);

qdL0[5];

We see that the fifth element of the list qdL0 is 35.77, which is the equilibrium
quantity q0.

An alternative approach to obtaining a list of quantities demanded at the
various prices included in the list pL0, is to define a formal Maxima
function of p, with some name, say foo:

foo (p) := ''DQ0$

We then either map foo onto the list pL0.

map ('foo, pL0);

or use f(L) (since user defined functions automatically distribute over lists):

foo (pL0);

This latter method avoids use of the obscure looking anonymous lambda
function, but has the defect of introducing unneeded function definitions into
your Maxima session.

kill(foo);

Likewise create list qsL0, a list of quantities supplied at the various prices, by 
using q(supply) = SQ0 as an expression depending on p.

qsL0 : map ( lambda ([p], ''SQ0 ), pL0);

qsL0[5];

Again, the 5th element is 35.77, the equilibrium quantity qE0.

Now add titles to the lists pL0, qdL0, qsL0 using append.

pL0 : append ([Price], pL0);

qdL0 : append ( ["DQ"],  qdL0);

qsL0 : append ( ["SQ"], qsL0);

Create an excess demand list edL0 by subtracting list qsL0 from list qdL0.
(This uses "list arithmetic".)

edL0 : qdL0 - qsL0;

Finally we produce a summary table with prices in the first
column and "excess demand" in the fourth column.

"EXCESS DEMAND TABLE";
"  ";
print ("         DQ = ", DQ0, "    SQ =", SQ0 )$
"  ";
transpose (matrix (pL0, qdL0, qsL0, edL0) );

"The table shows that for low prices, a quite large excess demand results. 
This reflects the fact that the demand curve of model 0 is quite price elastic 
over its range." MTC 77

At price 4.08 the excess demand is 0. This becomes more obvious if we round off the floating
point numbers in the matrix using our rnd_matrix_dp(MM, dp) function defined in Section 3.

rnd_matrix_dp (transpose (matrix (pL0, qdL0, qsL0, edL0) ), 2);

### Plot of Excess Demand Using a List of Values

We can use the lists pL0 and edL0, removing the first title element
using rest, to make a simple plot of excess demand, with prices on the vertical
axis and excess demand on the horizontal axis.

rest (pL0);

First with excess demand on the vertical axis, prices on the horizontal axis:

wxdraw2d (
    xlabel = "Prices",
    ylabel = "excess demand", 
    point_type = filled_circle, 
     points_joined = true,  
    points (rest (pL0), rest (edL0) ) )$

Secondly with prices on the vertical axis and excess demand
on the horizontal axis:

wxdraw2d (
    xlabel = "excess demand",
    ylabel = "Prices", 
    point_type = filled_circle, 
     points_joined = true,  
    points (rest (edL0), rest (pL0) ) )$

### Use Lagrange Interpolation on Discrete Point Sample

We can "smooth out" this curve using Lagrange interpolation.

load (interpol);

If you look up lagrange in the index of the Maxima html manual (see Section 1, References),
you find the required syntax:

Function: lagrange
    lagrange (points)
    lagrange (points, option)
Computes the polynomial interpolation by the Lagrangian method. Argument points must be either:

a two column matrix, p:matrix([2,4],[5,6],[9,3]), ie., matrix ([x1, y1], [x2, y2], [x3, y3]), etc
a list of pairs, p: [[2,4],[5,6],[9,3]],
a list of numbers, p: [4,6,3], in which case the abscissas will be assigned automatically to 1, 2, 3, etc.
In the first two cases the pairs are ordered with respect to the first coordinate before making computations.

With the option argument it is possible to select the name for the independent variable, which is 'x by default; 
    to define another one, write something like varname='z.

So let pts0 be a two column matrix. We want excess demand on the horizontal x axis and prices
on the vertical y axis, and we need to remove list titles.

[y1,y2];

kill(y1,y2);

We are going to use the two column matrix version of points for lagrange.

Here is the basic idea of what we are doing:

matrix ([x1, x2, x3],[y1,y2,y3]);

transpose(%);

pts0 : transpose (matrix ( rest(edL0), rest(pL0) ));

Let ed_lagrange0 be the return expression (with default variable x) from lagrange which is
the smoothed excess demand curve inferred from the sample points provided, as provided by
the lagrange function. (Don't worry about this being a large and lengthy expression!)

ed_lagrange0 : lagrange (pts0);

We want to see a plot of excess demand (the dependent variable) vs price (the independent variable)
using the Economics convention that the independent variable is on the vertical axis.
Remember that x is the independent variable here and, as usual in mathematics, the
independent variable is on the horizontal axis and we have arranged this to be excess demand by the
way we defined pts0.

If dashes doesn't work on your system, use dots.

wxdraw2d ( title = "EXCESS DEMAND: Lagrange Interpolation",
                  xlabel = "Excess Demand",
                  ylabel = "Prices",
                  line_width = 2,
                  line_type = dashes,
                  color = black,
                  explicit (pE0, x, -50, 0),
                  parametric (0,t,t,3, pE0),
                   label ( [sconcat ("pE0 =  ", pE0), 15, 4.2] ),
                  color = blue,  
                  line_type = solid,
                  explicit (ed_lagrange0, x, -50, 50) )$

### Disequilibrium

We again show both the demand curve and the  supply curve for our model on the same plot.
(If dashes doesn't work on your system, use dots.)

"   ";
print ("                               DP = ", DP0,"     SP = ",SP0 )$



wxdraw2d (    
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 100],
    yrange = [0, 10],
    line_width = 2,
    key_pos = bottom_right,
    key = "DEMAND",
    explicit ( DP0, q, 0.001, 100),    
    color = red,
    key = "SUPPLY",
    explicit ( SP0, q, 0, 100),
    color = dark_turquoise,
    line_type = dashes,
    key = "(pE0, qE0)",
    explicit ( pE0, q, 0, qE0),
    key = "",
    parametric (qE0, t, t, 0, pE0),
    color = black,
    label ( [sconcat ("pE0 = ", pE0,"  qE0 = ",qE0 ), 40, 9]))$

It is clear from the plot that if q > qE0 then  price(supply) > price(demand),
equivalent to the statement: the "supply curve lies above the demand curve."
The price producers would have to be paid to supply quantity q is greater
than the price consumers would be able and willing to pay for this quantity,
which implies a shortage.

For a numerical example, choose q = 1.1*q0, and evaluate DP and SP for our model 0 parameters.

[1.1*qE0,  subst (q = 1.1*qE0, [DP0, SP0] ) ];

This says that for q = 39.34 , price(supply) = $4.43  and  price(demand) = $3.92,  
and  "...the price that producers would have to be paid in order to produce the
quantity 39.34 exceeds the price that buyers are willing and able to pay for that 
quantity."  MTC  79

In contrast, for quantity 0.9*qE0 < qE0, the "demand curve lies above the
supply curve" and the price that buyers are willing and able to pay exceeds the price
producers would need to be paid to produce that quantity.

[0.9*qE0,  subst (q = 0.9*qE0, [DP0, SP0] ) ];

### Mandated Price Ceilings and Black Market Price

A "price floor" is a minimum price that can be charged for a product or service.
A "price ceiling" is a maximum price that can be charged for a product or service.
A price ceiling that is larger than the equilibrium price has no effect.
A price ceiling that is lower than the equilibrium price means too few units are supplied
leading to a shortage (producers are unwilling to produce the quantity demanded by
consumers at the price ceiling mandated).

"Markets tend to drive the price toward the equilibrium price. Market tendencies can be overcome, 
however, by government policies that mandate a price other than the one that clears the market." MTC 79

Suppose the government mandates that the price cannot rise above 0.8*p0. In this context, 0.8 is called
the "multiple" of the equilibrium price p0. Call this price ceiling pNE and let qNED be q(demand) = DQ at this price
and qNES be q(supply) = SQ at this price, with maxq the maximum of these two quantities. The "multiple" is included
as a variable in this calculation cell to allow for easy changes.

pE0;

multiple : 0.8$
[pNE : multiple*pE0,   [qNED, qNES] :  subst ( p = pNE, [DQ0, SQ0] )];
maxq : max (qNED, qNES) ;

This says that the mandated price ceiling is $3.26  (whereas the free-market price is $4.08 ), 
and the quantity demanded for the mandated price is ~ 62, and  the quantity that would be
supplied at the government mandated price is only ~ 28.

We show these two points (pNE, qNED) and (pNE, qNES) on our plot, and use a multiple of maxq to govern the 
upper end of the q range (the x range) in case the multiple is changed, and use a multiple of the equilibrium price
to set the upper end of the price range (the y range). 

If the dashes option for line_type doesn't work on your system, use dots.

wxdraw2d (
    title =  sconcat("Model 0 with a Mandated Price Ceiling pNE = ", pNE),
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [0, 1.25*maxq],
    yrange = [0, 2.5*pE0],
    line_width = 2,    
    key_pos = top_center,
    key = "DEMAND",
    explicit ( DP0, q, 0.01, 1.25*maxq),    
    color = red,
    key = "SUPPLY",
    explicit  (SP0, q, 0.01, 1.25*maxq),    
    line_type = dashes,    
    color = black,
    point_type = filled_circle,
    point_size = 1.3,
    key = "",
    points ( [qNES, qNED], [pNE, pNE] ),
    label ([" <---- Excess Demand ----> ", 45, 2.8]),
    key = sconcat ("pNE = ", pNE),
    explicit (pNE, q, 0.01, 1.25*maxq),
    color = green,
    key = sconcat ( "qNES = ", qNES),
    parametric (qNES,t,t,0,pNE),
    color = brown,
    key = sconcat ( "qNED = ", qNED),
    parametric (qNED,t,t,0,pNE ) )$

Suppose black marketeers can buy all qNES = 28 units available from suppliers at this price ceiling
($3.26 per unit) and auction them to the highest bidder. The black market price offered by the highest 
bidder would  then be predicted by the point on the demand curve corresponding to q = qNES = 28, 
which we call  pBM for "black market price."

pBM  : DP0, q = qNES;

Thus the price ceiling of $3.26 per unit causes a smaller supply being produced than a free market 
would cause, and hence excess demand: at the mandated price of $3.26 the demand curve lies above 
the supply curve.  The predicted black market price in the above scenario is $4.52 per unit.

### Demand Curve Shift: model 1

We define model 1 by changing E0 = -2.5 to E1 = -1.5, and leaving the other three exogenous parameters alone.

E1 : -1.5;

model1 : map ("=", [a, E, b, c], [a0, E1, b0, c0] );

DQ1, DP1, SQ1, SP1 are the form of the expressions DQ, DP, SQ, SP for model 1. There are no changes to the
supply curve. "...the demand curve becomes less responsive to price (elasticity falls)" ( MTC p 81) by changing E
from -2.5 to -1.5.

[DQ1 : DQ, DP1 : DP], model1;

[SQ1 : SQ, SP1 : SP], model1;

DP0;

Find the new equilibrium quantity qE1 and equilibrium price pE1, and compare with model 0 values.

qE1 : find_root (DP1 - SP1, q, .001, 500)$
pE1 : DP1, q = qE1$
matrix ( ["qE0", "qE1", "pE0", "pE1" ],  [qE0,qE1,pE0,pE1] );

Both the equilibrium quantity and price have shifted to larger values.

maxq : max(qE0, qE1)$
maxp : max (pE0, pE1)$
"  ";
print ("         MODEL 1:       DEMAND CURVE SHIFT ")$
print ("             DP0 = ",DP0,"    DP1 = ",DP1)$
" ";


wxdraw2d (    
    xlabel = "Quantity",
    ylabel = "$ per unit",
    yrange = [0, 1.5*maxp],    
    key_pos = bottom_center,
    key = " INITIAL DEMAND",
    explicit ( DP0, q, 0.01, 1.5*maxq),    
    line_width = 2,
    key = " NEW DEMAND",
    explicit ( DP1, q, 0.01, 1.5*maxq),    
    color = red,
    key = "SUPPLY",
    explicit ( SP1, q, 0.01, 1.5*maxq) )$

### Supply Curve Shift: model 2

We define model 2 by changing c0 = 10 to c2 = 15 , and leaving the other three exogenous parameters as in model 0.

c2 : 15;

model2 : map ("=", [a, E, b, c], [a0, E0, b0, c2] );

DQ2, DP2, SQ2, SP2 are the form of the expressions DQ, DP, SQ, SP for model 2. There are no changes to the
demand curve from model 0. Model 2 contains an increasing supply shift rather than an increasing demand
shift (as in model 1).

[DQ2 : DQ, DP2 : DP], model2;

[SQ2 : SQ, SP2 : SP], model2;

q(supply) rises faster with increasing price p, with a slope of 15 instead of 10. At a given price there is
a larger supply available.

We can solve (using find_root) for the new equilibrium values qE2 and pE2 as above.

qE2 : find_root (DP2 - SP2, q, .001, 500)$
pE2 : DP2, q = qE2$
matrix ( ["qE0", "qE2", "pE0", "pE2" ],  [qE0,qE2,pE0,pE2] );

As a result of the increased supply, the equilibrium price has fallen and the equilibrium quantity has risen.

maxq : max(qE0, qE2)$
maxp : max (pE0, pE2)$
"  ";
print ("     MODEL 2:       SUPPLY CURVE SHIFT ")$
print ("             SP0 = ",SP0,"    SP2 = ", SP2)$
" ";


wxdraw2d (    
    xlabel = "Quantity",
    ylabel = "$ per unit",
    yrange = [0, 1.5*maxp],    
    key_pos = bottom_center,
    color = red,
    key = " INITIAL SUPPLY",
    explicit ( SP0, q, 0.01, 1.5*maxq),    
    line_width = 2,
    key = " NEW SUPPLY",
    explicit ( SP2, q, 0.01, 1.5*maxq),    
    color = blue,
    key = "DEMAND",
    explicit ( DP2, q, 0.01, 1.5*maxq) )$

Of course we can have models with both demand and supply shifts (model 3). We leave as an exercise constructing
excess demand tables and plots for models 1 and 2 and 3, as well as the effects of mandated price ceilings. 

For changes in both E and c, how does the direction (larger or smaller) and size (how much larger or how much smaller)
 of the shifts in the values of E and c affect equilibrium quantity and price?

## Elasticities   [MTC  2.3]

Two possible measures of change in quantity demanded are 1. the local slope d(DQ)/dx, and
2. the local dimensionless point elasticity (x/DQ)* d(DQ)/dx, which can either be described as
the local fractional increase in DQ divided by the corresponding local fractional increase in x, 
or (since we can multiply top and bottom by 100% whichout changing the numerical value of 
the ratio), the local percent increase in DQ divided by the local percent increase in x.

Let's review the local slope measure first. The change in quantity demanded with changes in 
price can  be described by the local slope of the demand curve DQ, the first derivative of demand 
quantity DQ with respect to price (p).

(local slope of demand curve, quantity with respect to the variable price) = diff (DQ, p)

Let slope0 =  d (DQ0) / dp and slope1 = d (DQ1) / dp.

matrix(["DQ0","slope0","DQ1","slope1"],
           [DQ0, slope0 : diff(DQ0,p), DQ1, slope1 : diff (DQ1,p)]);

For example, the numerical values of the slopes at price p = 8, shows that
model 1 slope has a larger absolute value by a factor of about 5.

[slope0, slope1], p = 8;

There is a difference of a factor of 10 in the slope denominators at p = 8:

[p^3.5, p^2.5], p = 8;

Demand quantity is falling faster with increasing price with model 1, as compared with model 0.

### Own-Price Elasticity of Demand

In addition to the local slope, another measure of quantity dependence on price is the price elasticity 
of demand. The quotes here are from MTC:

"The 'price elasticity of demand' is the percentage change in quantity demanded per 1% change in price."

"Each measure has its merits. For a given product in a given setting, the slope is quite informative. 
For more general statements, elasticity becomes more useful, for two main reasons."

"First, it is free of units, so elasticities of demand for various products can be compared. Second, the 
elasticity is closely related to how total expenditures for a good change in response to a price change. 
This is particularly important for analyzing the behavior of price-searching firms (e.g., monopoly, 
monopolistic competition)."

"Be aware that many textbooks, by tradition, use the absolute value of own-price elasticity of demand, 
so that it is reported as a positive number" [whereas we are calling the negative number E the own-price
elasticity of demand].

An additional reference is:
https://www.economicshelp.org/blog/6260/economics/difference-between-point-and-arc-elasticity-of-demand/

### Arc Elasticity of Demand

The so-called arc-Elasticity is defined by two  values of price p1 and p2, with p2 > p1, and
by a model which relates demand quantity DQ to price p:

arc_Elasticity = (fractional_increase_in_Q) / (fractional_increase_in_p)
                  = (Q2 - Q1)  / ((Q1+Q2)/2) / (p2 - p1) / (  (p1+p1)/2) )
                  = [ (p1 + p2) / (Q1 + Q2) ] * [ (Q2 - Q1) / (p2 - p1),

which uses the mean value of (x1,x2): (x1+x2)/2, in the denominator of our formula for a fractional change.

As an example for model 0 with a = 1200, E = -2.5,  q(demand) = DQ0,
we choose p1 = 9.9 and p2 = 10.1.  If we temporarily let fracp be Δp/p = 
(p2-p1)/ ( (p1+p2)/2 ), the dimensionless fractional increase in price p,
and use our function frac_diff (x1, x2) defined in section 3.

matrix ( ["p1", "p2", " (p1 + p2)/2 ", "fracp"],
    [p1 : 9.9,  p2 : 10.1, (p1 + p2)/2, fracp :  frac_diff (p1,p2) ]);

Now let's do a hand calculation of the corresponding fracq = Δq/q for the dimensionless
fractional change in DQ0 induced by the change in price.

DQ0;

Note that our function frac_diff (x1,x2) returns the absolute value of the fractional difference
of x1 and x2. The fracq we need to define the arc-elasticity includes the correct sign, which
we need to put in by hand here.

matrix ( ["q1", "q2", "fracq"],
    [q1 : ev ( DQ0, p = p1), q2 : ev (DQ0, p = p2) , fracq : -frac_diff (q1, q2) ]);

We see that the quantity demanded has decreased since q2 < q1.

Now we calculate the arc elasticity of demand, Ed, using Ed = (Δq/q) / (Δp/p), with
Δp/p = fracp = 0.02 from above and fracq = -0.04999.

fracq / fracp;

Now let's define a function which calculates the arc elasticity of demand, given a model called DQv, 
and two closely spaced prices, p1v and p2v with p2v > p1v. This calculation returns a dimensionless number.

This function assumes the model expression DQv depends on only a single symbolic variable 
(representing price) and returns an error otherwise. (The user of this function is free to use any
desired symbol for price in the model DQv.) In order to always get the correct sign, we don't use
the function frac_diff here.

Elast_arc (DQv, p1v,p2v) :=
  block ([q1v,q2v, pv],
       if length ( listofvars (DQv)) > 1 then error ("DQv should only depend on one symbol"),
       if p2v <= p1v then error ("p2v should be greater than p1v"),
       pv : listofvars (DQv) [1],
      q1v : subst (p1v, pv, DQv),
      q2v : subst (p2v, pv, DQv),
      (p1v + p2v)*(q2v - q1v) / (p2v - p1v) / (q1v + q2v) )$

Now let's try out this new function:

Elast_arc (DQ0, p1, p2);

which agrees with our hand calculation.

What does the error return look like?  Try:
Elast_arc (1200*r/p^2.5, p1, p2) and you'll find out!

### Point Elasticity of Demand PED, Total Spending TS, Marginal Revenue MR

Main reference: IEA, Sec. 3.1: Elasticity

The dimensionless point elasticity of demand PED is (p/Q) * dQ/dp. We use the symbol E 
for the point elasticity of demand, and contrary to most textbooks,  E < 0. 

                    E =  (p/Q) * dQ/dp < 0.

If a consumer buys q(p) units at price per unit p, the "total expenditure" or "total spending" (by the consumer),
 "total revenue" (for the seller) TS is 

                    TS = p*q(p). 

The first derivative of TS with respect to price p is

       d(TS)/dp = q(p) + p*(dq/dp) = q(p) * [ 1 + (p/q(p)) * (dq/dp) ]  = q(p)* [ 1 + E ]

A finite change in total spending is then approximately

       Δ(TS) ~ d(TS)/dp * Δp = q(p)* (1 + E) * Δp = (TS/p)* (1 + E) * Δp using the definition of TS.

Then we have approximately,

               Δ(TS)/(TS) ~ (1 + E) * (Δp/p)

In words, the percent increase in total spending TS equals the percent increase of price
times the dimensionless  number (1 + E).

If  -1 < E < 0 (  ie., abs(E) < 1 ) then a price increase is accompanied by a increase of total
spending, and we call this an inelastic demand curve.

If E = -1, then there is no change in total spending (total revenue) when price changes; this
is called a unitary elasticity of demand.

If E < -1  ( abs(E) > 1) then total spending TS decreases as price increases; this is called an
elastic demand curve.

The "marginal revenue" MR is the change in total spending per unit change in quantity 
purchased. More precisely,

     MR = d(TS)/dq =  (dp/dq)* d(TS)/dp, using the chain rule, and using the result above,
                         MR  =  (dp/dq) * q(p) * [ 1 + E ] = - abs (dp/dq) * q(p) * (1 + E)

Note that dp/dq = d(DP)/dq < 0, since the inverse demand curve DP slopes down. Also
q(p) > 0.

If the demand curve is elastic, E <  -1, (1 + E) < 0,  MR > 0 and there is an increase in 
total spending as the quantity purchased increases.

If the demand curve is inelastic, -1 < E < 0, (1 + E) > 0, MR < 0 and there is a decrease
in total spending as the quantity purchased increases.

In the point elasticity function PED below, DQv is the demand quantity as a function of price. 
Our function PED figures out what symbol is being used for price in DQv and binds the local 
variable %px to that price symbol.  The  symbolic first derivative diff (DQv, %px) is calculated 
first, and then the specific input price value %pv is substituted for %px. 

PED (DQv, %pv) :=
 block ([%px, %qv],
    if length ( listofvars (DQv)) > 1 then error ("DQv should only depend on one symbol"),
    %px : listofvars (DQv) [1],
    %qv : subst (%pv, %px, DQv),
    (%pv/%qv)*subst (%pv, %px, diff (DQv, %px) ) )$

Our model 0 demand curve is DQ0 (demand quantity as a function of price p). The inverse
demand curve is DP0 (demand price as a function of quantity q).

[DQ0, DP0];

Here is an example of using the function PED (the point elasticity of demand) for model 0
at a price equal to 10.

PED (DQ0, 10);

Our model DQ = a*p^E is a constant elasticity of demand model.
For prices (6, 8, 10) model 0 has the same numerical point elasticity of demand (PED).

Our function PED (DQ, pa) takes two arguments, the first an expression for quantity
demanded depending on price p, the second a particular numerical value of price at which the  
point elasticity of demand is desired. 

In the following map of a lambda function on to a list of prices, the local variable pa successively 
takes on each of the values in the list, but (since it is a local variable) is not permanently bound to anything.

map (lambda ([pa],PED (DQ0, pa)), [6,8,10] );

pa;

If we consider a model such that DQ = 1200/p we get what we call a "unit elasticity demand curve".
The inverse demand curve DP is then 1200/q.

map (lambda ([pa],PED (1200/p, pa)), [6,8,10] );

If we consider a model such that DQ = 1200/p^0.25 we get an example of an "inelastic demand curve".
From q = 1200/p^(1/4), raising both sides to the fourth power gives q^4 = 1200^4/p or p = 1200^4/q^4
so DP = 1200^4/q^4 is the corresponding inverse demand curve (price as a function of quantity).

map (lambda ([pa],PED (1200/p^0.25, pa)), [6,8,10] );

We can draw these examples on one plot by choosing the ranges suitably.

wxdraw2d (    
    yrange = [0, 3],
    xrange = [0,1500],
    xlabel = "Quantity",
    ylabel = "$ per unit",   
    key_pos = bottom_left,
    line_width = 2,
    key = " ELASTIC",
    explicit ( DP0, q, 1, 1500),    
    key = " UNIT ELASTICITY",
    color = red,
    explicit ( 1200/q, q, 1, 1500),    
    color = green,
    key = "INELASTIC",
    explicit ( (1200/q)^4, q, 1, 1500) )$

If we had started with the question, what is the relation between quantity
and price if the price elasticity of demand is equal to -A, where A is any constant,
 we could solve the  differential equation (p/q)*dq/dp = -A

Check first that A is an unbound symbol.

A;

We can use the Maxima function ode2 (differential_eqn, dependent_var,  independent_var).

soln : ode2('diff(q, p) = - A*q/p, q, p);

The solution returned by ode2 includes the symbol %c which is some arbitrary constant which
remains to be chosen to determine an actual solution.

In Maxima, log(p) is the natural logarithm, so %e^log(p) = p. Since %e^(B*log(p)) = (%e^log(p))^B
= p^B, and here B = -A,  the solution returned by ode2 is equivalent to q = %c/p^A, in which the
elasticity E = -A.

If radexpand is set to true, then the function radcan will simplify expressions containing logs, exponentials
and radicals. (See section of the Maxima manual on functions which are available for simplification of
expressions.

radexpand;

radcan (soln);

Here we simply confirm well known properties (acually definitions) of the natural log and exponential functions.

[%e^log(p), log (%e^p)];

Now check the point elasticity of demand of a couple of examples:

PED (3/p^2.5, 10);

PED (10/p^5, 3);

map (lambda ([pa], PED (10/p^5, pa)), [3,5,7,9] );

Thus all of our models of the form DQ = a*p^E, with E < 0 are "constant elasticity of demand" models.
The price elasticity is the same number for any price.

### Elasticity, Price, Total Spending and Marginal Revenue MR

The total spending TS on the product (total revenue for the seller) is the product of 
the quantity demanded at a given price times the price per unit.  

               TS = q(p) * p.

Then  for our model, TS = DQ*p = (a*p^E)*p = a*p^(E+1). If we set E = -A, with A > 0, then
   TS = a*p^(1-A), and the first derivative of TS with respect to price p is
          d(TS)/dp  = a*(1-A)*p^(-A) = a*(1-A)/ p^A.

TS : a*p^(1-A);     /* total spending with E = -A  */

dTSbydp : diff (TS, p);       /*  d(TS)/dp   */

If the demand curve is elastic, A > 1 (for example, A = 2.5),  TS = a/p^(A-1) with (A-1) > 0, so 
total spending decreases as price p increases, and since (1-A) < 0, the first derivative of TS with respect to
price p is negative.

If the demand curve has unit elasticity, E = -1, A = 1, TS = a is independent of price p, d(TS)/dp = 0,
and there is no change in total spending as price changes.

If the demand curve is inelastic, A < 1 (for example, E = -0.25, A = 0.25 < 1), then TS = a*p^(1-A) 
with (1 - A) > 0 and as price increases, total spending increases and the first derivative of TS
with respect to p is positive.

The "marginal revenue" MR is the change in total spending  (or revenue) per one unit increase in
quantity.

To find a convenient expression for MR = marginal revenue  = d (TS)/dq = (dp/dq)*d(TS)/dp 
(using the chain rule from calculus).  We want to show by a specific example that we can
use dp/dq = 1/ dq/dp, which implies that the product (dp/dq)* (dq/dp) = 1.  

The case we are using is DQ = q = a*p^E, which implies that p = (q/a)^(1/E) = DP. 
Let diff_prod be bound to the product of derivatives: (dq/dp) * (dp/dq).

diff_prod : diff (a*p^E, p) * diff ( (q/a)^(1/E), q);

Now eliminate the variable q from this expression:

diff_prod : diff_prod, q = a*p^E;

Clearly, (p^E)^(1/E) = p^(E*(1/E)) = p^1 = p, which cancels the p in the denominator.
For some reason, this expression is hard to get Maxima to simplify (to unity) without making it numerical.

In the lambda function we need to preceed the symbol diff_prod with two single quotes (not one double
quote!) to get the symbol replaced by the expression the symbol is bound to (from the previous line).

The variable E takes on the values in the list in succession and diff_product is evaluated leaving the
symbol p untouched.

map (lambda ([E], ''diff_prod), [-2.5, -1.5, -0.5]);

radcan(%);

which justifies our assertion that  the product (dq/dp)*(dp/dq) = 1, and hence  dp/dq = 1/ dq/dp.

The marginal revenue (MR) is the change in total spending (TS) per one unit change in q, or
MR  = d (TS)/ dq = dp/dq * d (TS)/dp (using the chain rule) = d (TS)/dp / dq/dp.

With E = -A  and A > 0 (as above) we have DQ = a*p^E = a/p^A. Let dqbydp be the first
derivative of DQ in this form (with respect to p).

dqbydp : diff (a/p^A, p);

From above:

dTSbydp;

Then

MR : dTSbydp / dqbydp;

We can get the form (A-1) using ratsubst:

MR : ratsubst (-(A-1), (1-A), MR);

So our final expressions (one in terms of A, one in terms of E = -A) for marginal revenue are:

  MR = (A-1)*p/A  = (1+E)*p/E.

The marginal revenue MR is thus a constant times the price, and the sign of the constant is the
same as the sign of (A-1). If A > 1, then we have the elastic case and marginal revenue is a positive
number. If A = 1 we have the unit elasticity case, and the marginal revenue is zero.  If A < 1 we have
the inelastic case and the marginal revenue is a negative number.

Case A > 1 example: E = -2.5; If a = 1200, this is the elastic model 0 case for the demand curve, and
DQ0 and DP0 are already defined.

MR_case1 : MR, A = 2.5;

[DQ0, DP0];

For this elastic case (E = -2.5) we let MR1 be the marginal revenue ($$) expressed as a function of
quantity q; ie., we replace the symbol p with DP0.

MR1 : MR_case1, p = DP0;

Case A < 1 example: E = -0.5; call this (inelastic case) case 3. We again use a = 1200, and let [DQ3, DP3] hold the
appropriate factors.

MR_case3 : MR, A = 0.5;

Define case 3 replacement rules for a and E:

case3 : [a = 1200, E = -0.5]$
[DQ3 : DQ, DP3 : DP], case3;

MR3 : MR_case3, p = DP3;

We now make a plot which shows both the demand curve and the marginal revenue curve
for each case. First for the elastic case.

wxdraw2d (    
    title = "ELASTIC CASE:  a = 1200,  E = -2.5",
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 1, 50],
    yrange = [0, 15],
    line_width = 2,  
    key = "DEMAND",
    explicit ( DP0, q, 1, 50),    
    color = red,
    key = "MARGINAL REVENUE",
    explicit ( MR1, q, 1, 50) )$

And now for the inelastic example.

 wxdraw2d (    
    title = "INELASTIC CASE:  a = 1200,  E = -0.5",
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 1, 1500],
    yrange = [-100, 50],
    color = black,
    explicit (0,q, 1, 1500),
    line_width = 2,  
    color = blue,
    key = "DEMAND",
    explicit ( DP3, q, 1, 1500),
    color = red,
    key = "MARGINAL REVENUE",
    explicit ( MR3, q, 1, 1500) )$

### Linear Demand Curve

We now assume a linear relation between price and quantity demanded of the form p = a - b*q, with
a and b undefined model parameters so far, except a > 0 and b > 0 so that the quantity demanded
decreases as price increases.

Check that a and b are unbound.

[a,b];

The total spending = total revenue = TR = price per unit * number of units = p*q(p),
the marginal revenue MR is the increase of total revenue per unit increase of q,
ie., d(TR)/dq, and the point elasticity E = (p/q)*(dq/dp) = (p/q)/ (dp/dq).

matrix ( ["p", "TR", "MR", "E"],
    [p : a - b*q, TR : expand (q*p),  MR : diff (TR, q), E : (p/q) / diff (p, q) ]);

Since q = (a - p)/b, q increases as price decreases (less is subtracted from a in the numerator), 
and q reaches a maximum  value qmax = a/b when p = 0 ( price p cannot be negative, we assume).

With qmax = a/b, we can write the elasticity as

   E = - (a - b*q) / (b*q) = - (a/ (b*q)  -  1) = (1  -  (a/b)*(1/q) ) =  1 - qmax/q.

When q = (1/2)*qmax, E = - 1 and we have "unit elasticity".  Thus for q > (1/2)*qmax
the demand curve in inelastic, and for q < (1/2)*qmax, the demand curve is elastic.

For q = qmax, E = 0, and for q > qmax, E > 0, approaching 1 as q becomes very large.

We choose a and b for a specific example and call the replacement rules for a and b
modelL.

[p,TR,MR,E];

modelL : [a = 400, b = 2.5];

For this choice of a and b we want to draw the (inverse) demand curve pL and the marginal revenue
MRL on one plot, and draw the elasticity EL on a separate plot.

matrix ( ["pL", "MRL", "EL"],
  ev ( [pL : p, MRL : MR, EL : E], modelL) );

For this case (a = 400, b = 2.5), qmax = 160, qmax/2 = 80.

a/b, modelL;

D_MR : gr2d (xlabel = "Quantity", ylabel = "$ per unit", color = black,explicit (0,q, 0, 160),
                       line_width = 2, color = blue, key_pos = bottom_left, key = "Demand", explicit (pL, q, 0, 160),
                      color = red, key = "MR", explicit (MRL, q, 0, 160), ytics = {-200, 0, 200},  xtics = {0, 80, 160})$
Elasticity : gr2d (key_pos = bottom_right, xlabel = "Quantity", ylabel = "No units", yrange = [-5, 0], 
                          ytics = {-5, -1, 0}, color = black, explicit (-1, q, 0, 160), line_width = 2, key = "Elasticity", 
                          color = dark_green, explicit (EL, q, 0, 160), xtics = {0, 80, 160})$
wxdraw (D_MR, Elasticity, dimensions = [360, 360])$

The elasticity becomes positive for q > qmax = 160, and approaches 1 for large q.

map (lambda ([q], ''EL), [40, 80, 160, 200, 400,1000]);

limit (EL, q, inf);

### Other Elasticities

The dimensionless elasticity is a general concept used by economists to describe the response of some variable 
to some change in conditions. We describe an "income elasticity of demand" EDY, a "cross-price elasticity of 
demand" EDR, and a "price elasticity of supply" ES in the following. 

If we let p be the price of a primary product, ED a constant price elasticity of demand of that primary product, pr be the 
price of some other related product, EDR a constant price elasticity of demand of that other related product, y be income, 
and EDY be the constant income elasticity of demand for the primary product, a constant elasticity model of demand 
which includes all these variables is

                     DQ = a*p^ED*pr^EDR*y^EDY

If we solve this equation for price p, we get

                    DP = (q / (a*pr^EDR*y^EDY) )^(1/ED)

We want to use p as an unbound variable; check its current binding:

p;

kill (p);

Here we are redefining the symbols DQ and DP.

matrix (  ["DQ", "DP"],
    [DQ : a*p^ED*pr^EDR*y^EDY,  DP : (q / (a*pr^EDR*y^EDY) )^(1/ED) ]);

### Income Elasticity of Demand EDY

The (point) "income elasticity of demand" EDY is defined as the fractional increase in quantity demanded 
divided by the corresponding fractional increase in income, or (y/DQ)*d(DQ)/dy, where we let  DQ represent 
quantity demanded and let y represent income, and we let the change in y, Δy, become infinitesimally small,
which causes the change in demand, Δ(DQ) to also become infinitesimally small, thus

                    EDY =  (y/DQ)*d(DQ)/dy

(y/DQ)*diff(DQ, y);

For "normal goods", EDY > 0. For "inferior goods", EDY < 0.  As income increases, consumers can afford 
better than inferior goods and the demand for better quality goods will increase.

Within normal goods, those goods for which EDY > 1 are sometimes called "luxury goods."  
The share of income spent on luxury goods varies directly with income.

For those goods for which EDY < 1,  including inferior goods, the share of income spent on such goods 
varies inversely with income

We first choose values for the exogenous parameters a, ED, EDR, and EDY and call the chosen
list of replacement rules model0_y_pr.

model0_y_pr : map ("=", [a, ED, EDR, EDY], [10, -0.8,-0.2, 0.4] );

Here we are redefining the symbols DQ0 and DP0.

matrix ( [ "DQ0", "DP0" ],
   ev( [ DQ0 : DQ,  DP0 : DP ],  model0_y_pr) );

We now set pr = 2 and consider a 50% increase in income, from y = 1000 to y = 1500, with the former
income demand curve represented by DQ00 and DP00, and the latter (higher) income represented by
DQ01 and DP01.

matrix ( ["DQ00", "DP00" ],
    ev ([DQ00 : DQ0, DP00 : DP0], [pr = 2, y = 1000]) );

matrix ( [ "DQ01", "DP01" ],
   ev ( [DQ01 : DQ0, DP01 : DP0], [pr = 2, y = 1500]) );

For a given fixed price level, DQ01 is 17.6% larger than DQ00:

percent_inc (DQ00, DQ01);

due to a 50% increase in income (1000 --> 1500).

From the definition of the (point) elasticity of income demand EDY,
at a given income y, (y/DQ) * d(DQ)/dy = EDY , we expect that roughly we can
say, for a finite change Δy, we would have Δ(DQ)/DQ ~ EDY * Δy/y = 0.4 * 0.5 = 0.2,
or roughly a 20% increase in DQ,  which roughly agrees with the 17.6% increase 
in quantity demanded we actually get.

wxdraw2d (    
    title = " a = 10, ED = -0.8, EDR = -0.2, EDY = 0.4, pr = 2",
    grid = [2,2],
    background_color = light_gray,
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 1, 25],
    yrange = [0, 50],
    line_width = 2,  
    key = "y = 1000",
    explicit ( DP00, q, 1, 100),    
    color = red,
    key = "y = 1500",
    explicit ( DP01, q, 1, 100) )$

We can verify that as income increases, more of that income is spent on the
product, but the share of income spent on the product decreases.

Recall that the total spending TS on a product is the price per unit times
the number of units or p*DQ(p). We compare the total spending in
the above cases, where initial income y0 = 1000, and final income
is y1 = 1500.

We first do the calculation for price p = 3. For arbitrary price p, pr = 2,
and the two comparison income cases y0 = 1000, and y1 = 1500,
we have DQ(p) expressions given by:

[DQ00, DQ01];

Calculate total spending TS for the two cases, for the fixed
price p = 3:

matrix ( ["TS0", "TS1"],
          ev ([TS0 : p*DQ00,  TS1 : p*DQ01], p = 3) );

Bind y0 and y1 to the initial and final incomes respectively.

matrix ( ["income y0", "income y1"],
    [y0 : 1000, y1 : 1500] );

Now calculate the share of income for case y0 and case y1.

matrix ( [ "Income", "Spending", "Share"],
             [y0, TS0, TS0/y0],
             [y1, TS1, TS1/y1] );

which shows that total spending increases but the share of income decreases.

If we repeat the calculation for p = 30:

matrix ( ["TS0", "TS1"],
          ev ([TS0 : p*DQ00,  TS1 : p*DQ01], p = 30) );

matrix ( [ "Income", "Spending", "Share"],
             [y0, TS0, TS0/y0],
             [y1, TS1, TS1/y1] );

we find the same trends.

If your calculations should show that the income share spent on a product is greater
or equal to 1,  the model parameter 'a' has been set to too large a value from the start.
Smaller values of the parameter 'a' should better reflect reality, and the entire model
calculation should be re-run.

### Cross-Price Elasticity of Demand EDR

A reference is
https://www.investopedia.com/terms/c/cross-elasticity-demand.asp

The cross elasticity of demand is an economic concept that measures the responsiveness in the 
quantity demanded of one good when the price for another good changes. Also called cross-price 
elasticity of demand, this measurement is calculated by taking the percentage change in the quantity 
demanded of one good and dividing it by the percentage change in the price of the other good.

Our model for the quantity demanded as a function of price p for the primary good, the price
of a related good pr, and income y is defined by DQ, and the cross elasticity of demand is the
dimensionless constant EDR.

[DQ,  (pr/DQ)*diff(DQ,pr)];

We next consider a change in the price pr of a competing related good, keeping "other things
equal" (ie., keeping income and the exogenous parameters a, ED, EDY constant).
 
From our work above, DQ00 and DP00 were the values of DQ0 and DP0 for y = y0 
= 1000, and for pr = pr0 = 2.

We redefine DQ01 and DP01 to be the values of DQ0 and DP0 for y = y0 and pr = pr1 = 5.

Recall that we defined DQ0  to be the quantity demanded at a given price p, and  DP0
the price buyers are willing and able to pay as a function of quantity q, as a function of
the buyer's income y, and the price pr of a related product.

[DQ0, DP0];

We now redefine DQ01 and DP01:

matrix ( [ "DQ01", "DP01" ],
   ev ( [DQ01 : DQ0, DP01 : DP0], [pr = 5, y = 1000]) );

The value of q(demand) = DQ is proportional to pr^EDR where the cross-price elasticity
of demand EDR = -0.2 in our model. (Look at our expression for DQ0 above.)

This implies that as the price of the competing product pr increases, other things being
equal, the value of DQ at a given price should decrease. The demand curve should shift
to the left in this model (ie., less quantity demanded of the primary product at a given price).

We can see how the factor 1/pr^(.2) influences DQ as we increase pr:

map ( lambda([pr], (pr)^(-0.2) ), [ 10, 30, 60 ] );

Clearly, DQ decreases at a fixed price (and at a fixed income), as pr increases.

wxdraw2d (    
    title = " a = 10, ED = -0.8, EDR = -0.2, EDY = 0.4, y = 1000",
    grid = [2,2],
    background_color = light_gray,
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0.1, 5],
    yrange = [0, 500],
    line_width = 2,  
    key = "pr = 2",
    explicit ( DP00, q, 0.1, 5),    
    color = red,
    key = "pr = 5",
    explicit ( DP01, q, 0.1, 5) )$

Evidently, the model value of EDR = -0.2 implies that as the price per unit (pr) of the competing product 
increases (at fixed income), the buyer must decrease purchases of the primary product and DQ
decreases.

### Price Elasticity of Supply ES

Price elasticity of supply measures the responsiveness of the supply of a good or service after a 
change in its market price. According to basic economic theory, the supply of a good will increase 
when the price offfered per unit rises. Conversely, the supply of a good will decrease when the price 
offered per unit decreases.

With ES the constant (point) price elasticity of supply, we assume producers will supply the quantity
SQ = b*p^ES given the price p (b is another exogenous parameter), and solving for price as
a function of quantity supplied, SP = (q/b)^(1/ES) is the price required by producers to supply
a quantity q.

matrix ( ["SQ", "SP"],
              [SQ : b*p^ES,  SP : (q/b)^(1/ES)] );

Here we verify that ES is the point price elasticity of supply for arbitrary values of b.

(p/SQ)*diff(SQ,p);

ES is the ratio of the fractional increase in quantity supplied divided by the corresponding fractional
increase in price, or, equivalently, the percent difference in quantity supplied divided by the percent
difference in price.

As a numerical example we take b = 40, thus defining SQ0 and SP0:

matrix ( ["SQ0", "SP0"],
             ev ([SQ0 : SQ, SP0 : SP], b = 40) );

A "perfect inelastic supply" curve has ES = 0, so SQ = b is independent of price, and
producers supply units at the same rate irregardless of the price offered. Examples include 
products that have limited quantities, such as land or painting from deceased artists.

A "relatively inelastic supply" curve has 0 < ES < 1. That means (Δq)/q < (Δp/p) 
Inelastic goods include nuclear power, which has a long lead time given the construction, 
technical know-how, and long ramp-up process for plants.

Unit elastic supply has ES = 1, so SQ = b*p, and  (Δq)/q = (Δp/p).

"Relatively elastic supply" has ES > 1, where (Δq)/q > (Δp/p).  An example would be a product 
that’s easy to make and distribute, such as a fidget spinner. The resources to make additional 
spinners are readily available and the total cost would be minimal to ramp production up or down.

Let's compare the supply curves at three diffferent values of price elasticity of
supply: ES = 1 (unit elasticity), ES = 1/2 (inelastic), and ES = 3/2 (elastic),
defining SP00, SP01, and SP02 to be the corresponding values of SP0.  This is
easy to do using the lambda function.

matrix (  ["SP00", "SP01", "SP02"],
    ev (  [SP00, SP01, SP02] :  map (lambda ([ES], ''SP0), [1,0.5, 1.5]) ) );

print ("  ")$
print ("                                 SQ = b*p^ES    SP = (q/b)^(1/ES) ")$

wxdraw2d (    
    title = " SUPPLY CURVES, ES = Supply Elasticity, b = 40",
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 75],
    yrange = [0, 2],
    line_width = 2,  
    key_pos = bottom_right,
    key = "ES = 1",
    explicit ( SP00, q, 0, 75),    
    color = red,
    key = "ES = 0.5 inelastic",
    explicit ( SP01, q, 0, 75),
    color = dark_green,
    key = "ES = 1.5  elastic",
    explicit (SP02, q, 0, 75) )$

Let's take a specific example of price increase: p1 = 0.3 --> p2 = 0.6.

[ [p1,p2] : [0.3, 0.6], frac_diff (p1,p2)];

For three different values of ES (1, 0.5, 1.5) what are the values of SQ as a function of p?

 [SQ00, SQ01, SQ02] :  map (lambda ([ES], ''SQ0), [1,0.5, 1.5]) ;

For each value of ES, and for the given values of prices p1 and p2 > p1, what are the
corresponding quantities, fractional difference in quantity, and ratio of the fractional
difference in quantity to the fractional difference in price?  The latter should be in the
neighborhood of the selected (point) supply elasticity ES.

Since in all three cases here, q2 > q1, we can use frac_diff (q2,q1) which always results
in a positive number by definition.

fundef (frac_diff);

grind(%)$

Case unit supply elasticity ES = 1.

[ [q01, q02] : map (lambda ([p], ''SQ00), [p1,p2]), frac_diff (q01,q02), frac_diff(q01,q02)/frac_diff(p1,p2)];

Case inelastic, ES = 1/2.

[ [q11, q12] : map (lambda ([p], ''SQ01), [p1,p2]), frac_diff (q11,q12), frac_diff(q11,q12)/frac_diff(p1,p2)];

Case elastic, ES = 3/2.

[ [q21, q22] : map (lambda ([p], ''SQ02), [p1,p2]), frac_diff (q21,q22), frac_diff(q21,q22)/frac_diff(p1,p2)];

Consider the more general linear supply curve q = a + b*p, which implies p = (q-a)/b, and dq/dp = b
so ES = (p/q)*(dq/dp) = (p/q)*b = (q - a)/q. The quantity q >= 0.

For a > 0, ES < 0 for 0 < q < a, ES = 0 for q = a, ES > 0 for g > a, and when price p = 0, q = a > 0.
For a > 0, the supply curve intersects the line p = 0 at q = a > 0 and intersects the line q = 0 at
p = - a/b < 0.

For a < 0 the supply curve intersects the line p = 0 at q = a < 0 and intersects the line q = 0 at
p = -a/b > 0.

For either sign of a, the supply elasticity ES approaches 1 as q (and p) become large.

limit ((q-a)/q, q, inf);

Here is an example for a > 0: a = 5, b = 2.

wxdraw2d (    
    title = " SQ = 5 + 2*p, SP = (q-5)/2, ES = (q-5)/q",
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0, 10],
    yrange = [-4, 4],
    color = black,
    explicit (0, q, 0, 10),
    line_width = 2,  
    key_pos = bottom_right,
    key = "Supply",
    color = blue,
    explicit ( (q - 5)/2, q, 0, 10),    
    color = red,
    key = "Supply Elasticity",
    explicit ( (q - 5)/q, q, 0, 10),
    color = black,
    label ( [" q = a + b*p, case a = 5 > 0, b = 2", 4, 2.5 ]))$

## Taxes and Efficiency  [MTC 2.4]

### Excise  and Sales Tax Shift of Equilibrium

[MTC]  "An important implication of the demand/supply model is that a tax imposed on the sale or purchase of the product 
will be born in part by sellers and in part by buyers. Furthermore, the effects of the tax on buyers and sellers are independent 
of whether the tax is nominally placed on the seller or on the buyer."

Let's assume a constant elasticity demand curve and a constant elasticity supply curve model of supply and demand,
with all other variables held constant and their effects accounted for by the numerical values chosen for the model
parameters.  We first define the supply/demand model in the absence of taxes) and calculate the equilibrium price
and quantity.

matrix ( ["DQ", "DP", "SQ", "SP"],
    [ DQ : a*p^ED,   DP : (q/a)^(1/ED), SQ : b*p^ES,  SP : (q/b)^(1/ES) ] );

Select some plausible model parameters, call it model0.

[a0, ED0, b0, ES0] : [1200,  - 4, 40, 0.75]$

model0 : map ("=", [a, ED, b, ES], [a0, ED0, b0, ES0] );

Let DQ0, DP0, SQ0, SP0 be the resulting model 0 expressions.

matrix (  [ "DQ0", "DP0", "SQ0", "SP0" ],
            ev (  [DQ0 : DQ, DP0 : DP, SQ0 : SQ, SP0 : SP ], model0, numer ) );

Find the equilibrium quantity qE (in the absence of taxes) in model 0.

qE : find_root (DP0 - SP0, q, 0.01, 500);

Find the equilibrium price pE (in the absence of taxes) in model 0.

pE : DP0, q = qE, numer;

Make a plot of the (pre-tax) demand and supply curves, showing the equilibrium point.

wxdraw2d (  
    title =  "a = 1200, ED = -4,   b = 40, ES = 0.75, qE = 68.4, pE = 2.05",
    grid = [2,2],
    background_color =  light_gray,
    xlabel = "Quantity",
    ylabel = "$ per unit",
    xrange = [ 0.1, 100],
    yrange = [0, 6],
    line_width = 2,
    key_pos = bottom_right,
    key = "DEMAND",
    explicit ( DP0, q, 0.1, 100),    
    color = red,
    key = "SUPPLY",
    explicit ( SP0, q, 0.1, 100),
    point_size = 1.3,
    point_type = filled_circle,
    color = dark_green,
    key = "EQUILIBRIUM",
    points ([qE],[pE]))$
    

GENERAL COMMENTS ON EXCISE AND SALES TAXES

From 
https://www.freshbooks.com/hub/taxes/an-excise-tax

"Excise taxes are internal taxes that are levied on the sale of specific goods and services, such as alcohol, fuel and tobacco. 
An excise tax is an indirect tax that is not paid by the customers directly — instead, the excise tax is imposed on the supplier or
the producer, who then includes it in the product price."

"Excise taxes are imposed by the federal, state, and local governments. Excise taxes can either be applied as a percentage of the 
total cost of a product or service or as a fixed amount independent of base price. For example, the excise tax on a vehicle is a 
percentage of the total cost  while the excise tax on a tobacco and gasoline is a fixed amount."

"Most customers don’t realize that they are paying excise taxes. This is because the taxes are generally factored into the product 
cost, rather than being listed separately like a sales tax." 

"If you run a business that’s required to collect excise taxes, it’s your responsibility to collect the tax from the customer and pay it 
to the government every quarter. To do that, business owners must file Form 720, Quarterly Federal Excise Tax Return which lists 
the various types of federal excise taxes. In the form, business owners must list the types of taxes that they’ve collected and reported 
to the government. In addition, states may have their own filing requirements." 

"There are certain exemptions to paying excise taxes. Non-profit organizations, government organizations and emergency service 
providers are exempt from certain excise taxes in some situations."

"A sales tax is the tax that businesses usually collect from the consumer at the point of purchase, and pay to the government due to the sale 
of certain goods and services. There are two basic differences between a sales tax and an excise tax." 

"While excise taxes are levied only on certain goods and services that are considered harmful or linked to specific health issues, sales tax 
is applied to a broad range of products."

"Also, sales tax is calculated as a percentage of the sale price. For example, if you buy a more expensive luxury vehicle as opposed to a 
cheaper utility vehicle, you would need to pay more sales tax. The sales tax percentage is set by the local and state governments 
in the United States." 

"On the other hand, an excise tax is often a per unit  tax imposed (before the purchase price) for specific items by the state, local and federal 
governments. For example, in 2019 a tax of $4.35 was imposed on each 20 cigarette package by New York State regardless of the base 
price of the pack."

From  https://www.investopedia.com/terms/e/excisetax.asp:

"An excise tax is a legislated tax on specific goods or services at purchase such as fuel, tobacco, and alcohol. Excise taxes 
are intranational taxes imposed within a government infrastructure rather than international taxes imposed across country borders. 
A federal excise tax is usually collected from motor fuel sales, airline tickets, tobacco, and other goods and services."

"Excise taxes are primarily for businesses. Consumers may or may not see the cost of excise taxes directly. Many excise taxes 
are paid by merchants who then pass the tax on to consumers through higher prices. Merchants pay excise taxes to wholesalers 
and consider excise taxes in product pricing which increases the retail price overall. There are some excise taxes however that 
are paid directly by a consumer including property taxes and excise taxes on certain retirement account activities."
------------------------------------------------------------

We impose an excise tax of amount X0 = $0.5 per unit sold in the above before tax model (DQ0, DP0,SQ0,SP0, qE, pE).

DP0 is the price buyers are willing and able to pay for a given quantity in the absence of any sales tax.
SP0 is the amount sellers are willing to receive for a given quantity in the absence of any excise tax.

matrix (["DQ0","DP0","SQ0", "SP0","qE", "pE"],
    [DQ0, DP0, SQ0, SP0, qE, pE] );

In the presence of an excise tax required from the seller, a new equilibrium quantity (qX0 < qE) occurs for the number of units 
 such that DP0 = SP0 + X0, as the seller passes on the excise tax to the buyer, and the effective Supply curve is (SP0 + X0). 
(The seller must increase the asking  price by X0 to compensate for the later remission of the excise tax to the government.) 
The new and increased price paid per unit by the buyer is called pDX0 > pE,  and the new decreased  price retained by the seller 
per unit (after subtracting the excise tax) is called pSX0 < pE.

X0 : 0.5;
qX0 : find_root (DP0 - (SP0 + X0), q, 0.01, 500 );
pDX0 : DP0, q = qX0;
pSX0 : SP0, q = qX0;
[pDX0 - pE, pSX0 - pE];

The new equilibrium quantity of units sold (per unit time) has decreased (from 68.4 to 57.8). The amount paid per
unit by the buyer has risen (from 2.05 to 2.13). The price received by the seller per unit has fallen from 2.05 to 1.63.
In other words, the amount paid by the buyer per unit (2.13), minus the excise tax per unit (0.5), is the amount (1.63)
the seller will actually retain, after paying the required excise tax to the government.

Given our particular demand and supply models, the excise tax  disproportionately affects the seller.

wxdraw2d (  
 title =  " X0 = 0.5, qE = 68.4, qX0 = 57.8, pE = 2.05,  pDX0 = 2.13 ",
    xlabel = "Quantity",
    ylabel = "$ per unit",    
    yrange = [0, 1.25*pDX0],
    line_width = 2,
    color = black,
    line_type = dots,
    explicit (pDX0, q, 0, qX0),
    parametric (qX0, t, t, 0, pDX0),    
    color = blue,
    line_type = solid,
    key_pos = bottom_right,
    key = "DEMAND DP0",
    explicit ( DP0, q, 0.1, 1.25*qE),    
    color = dark_green,
    key = "Pre-Tax Supply SP0",
    explicit ( SP0, q, 0, 1.25*qE), 
    color = red,
    key = "Excise Tax Laden Supply",
  explicit ( SP0 + X0, q, 0, 1.25*qE))$

We next consider  the implications (for this model) if the tax is imposed on the buyer, rather than the
seller, (for example as a sales tax based on the amount of the purchase price).

If the tax is placed on the buyer of the good, the price that buyers would be willing and able to
pay to sellers at each quantity value q would be the original willingness to pay LESS the tax on the purchase,
since the sales tax will be added to the sales price, and go to a local government entity instead of to
the seller.

The effective demand curve shifts so that (DP0 - X0) = SP0, which is the same equation as DP0 = SP0 + X0 solved
above for the excise tax case.

The value of pSX0 (price received by seller per unit) remains the same (1.63) as we got before using SP0, q = qX0,
but we can also calculate it as:

DP0 - X0, q = qX0;

SP0, q = qX0;

wxdraw2d (  
 title =  " X0 = 0.5, qE = 68.4, qX0 = 57.8, pE = 2.05,  pSX0 = 1.63 ",
    xlabel = "Quantity",
    ylabel = "$ per unit",    
    yrange = [0, 1.25*pDX0],
    line_width = 2,
    color = black,
    line_type = dots,   
    parametric (qX0, t, t, 0, pSX0),    
    explicit (pSX0, q, 0, qX0),
    color = red,
    line_type = solid,
    key_pos = bottom_right,
    key = "Sales Tax Laden Demand",
    explicit ( DP0 - X0, q, 0.1, 1.25*qE),    
    color = dark_green,
    key = "Supply SP0",
    explicit ( SP0, q, 0, 1.25*qE), 
    color = blue,
    key = "Pre-Tax Demand DP0",
  explicit ( DP0, q, 0, 1.25*qE))$

### Marginal Value and Consumer Surplus [MTC 2.4.2]

Main ref: IEA, Sec. 2.1
-------------------------
Ref: https://www.danieldollinger.com/what-is-marginal-value/

"Marginal value is marginal benefit minus marginal cost. It is simply how much benefit you get per each additional 
unit of measure (marginal benefit) minus how much it costs you per each additional unit of measure (marginal cost)."

"Let’s say that you’re the owner of a company that produces widgets. Each widget is sold for 10 dollars (marginal benefit) 
and it costs you 5 dollars to make (marginal cost). Marginal value is thus 5 dollars per unit."
-----------------------------------------------------------
Ref: https://www.economics.utoronto.ca/jfloyd/modules/csrpa2.html

"It is sometimes thought paradoxical that water, which is essential to life, is of little value in the market whereas diamonds, 
which are useless decorative baubles, are valued very highly. The reason for this seeming paradox is that  price is equal to 
marginal value, and price is not equal to total value."

"The consumer will purchase each commodity to the point where the marginal benefit to her is just equal to its price---price 
therefore equates with marginal value. It follows that if the supply of a commodity is very large relative to the demand, as is the 
case with water, its price and the marginal valuation of it by consumers will be very low. In the case of diamonds, the supply 
is very small in relation to the demand so the price, and the marginal valuation, is high. When we say that water is essential to 
life and diamonds are not we mean that the total benefit from water, given by the area under the demand curve to the left of the 
quantity consumed is very large, while the corresponding area under the demand curve for diamonds is small."

We consider a very simple demand curve model.

matrix (["DQ", "DP" ],
    [ DQ : p^ED, DP : q^(1/ED)] );

matrix ( ["DQ0", "DP0" ],
    ev ([DQ0 : DQ, DP0 : DP], ED = -1.5) );

wxdraw2d ( xlabel = "Quantity",  ylabel = "$ per unit",
    yrange = [0, 10],
    line_width = 2,
    explicit ( DP0, q, 0, 1.5) )$

The range on the vertical price axis is restricted to (0 < p <= 10), so one does not see the prices
of the first few units. For a quantity q = 10^(-7), the price per unit is $46, 420. If the supply is limited,
(for diamonds, say) the equilibrium price per unit is large, and the quantity supplied at that equilibrium
price is small. Remember the units used for quantity q can be any size, for example, one million per year.

DP0, q = 1e-7;

"The marginal willingness to pay for the first few units might not be meaningful. Consider, for example, water. A single 
liter per week would not be enough to keep even one consumer alive, so any statement about how much consumers 
would pay for the first liter makes no sense. Fortunately, we seldom seek the total value of a good. Rather, we typically 
analyze a change that results in an increase or decrease in the quantity without reference to the first few units." 

"A related problem is that some goods may not be available in continuously divisible units. We follow convention and 
assume goods are continuously divisible."

"This convention is more reasonable that it might appear. Individuals who consume commodities like automobiles make 
two decisions, how many units to own and how often to buy new models. If prices rise slightly and many individuals 
adjust by keeping their units a bit longer, then the market quantity demanded will decrease slightly, perhaps by a few hundred 
units in a market in which millions of units are sold." [MTC]

We simplify the market for a good into consumers (demand) and producers (supply). For each quantity q, the height of the 
(inverse) demand  curve is the amount (price) that some consumer is willing and able to pay per unit for that quantity.  Given 
a quantity q1, the demand curve implies a price per unit p1 (the height of the (inverse) demand curve for q = q1), and then the 
cost to the  consumer (for q1 units at price p1) is q1*p1.

In the usual case quantity will have dimensions (number of units)/(unit of time), for example #units/yr.
Consider the case that q1 = 1 unit/yr, the corresponding price p1 is $1  per (unit per year), with purchase cost $1/yr;
(1$/(unit/yr) * (1unit/yr) = 1$.

DP0, q = 1;

The "total value" TV(q1) defined by a particular q1 and this (inverse) demand curve p(q), is the sum of the infinitesimal costs 
p(q)*dq  (thin rectangles extending vertically from p = 0 to p(q) with width dq), summing from q = 0 to quantity q1. This is visually 
the  "area beneath the demand curve." In the limit that the width dq of the rectangles goes to zero, the sum becomes an integral.

This scenario envisions paying for qa units at the price per unit pa, plus paying for qb units at the price per unit pb, etc., from 
q = 0 out to q = q1, and adding up the total cost.

For this example p(q) = DP0 = 1/q^(2/3). If we compute the "total value" TV(q1) out to q = q1, we get 3*q1^(1/3), so TV(q) = 3*q^(1/3),
and the "marginal value" v(q) = d (TV(q) )/dq = p(q) = DP0 equals the price defined by the inverse demand curve for this quantity q.
The "marginal value" v(q) is the first derivative of the total value with respect to quantity q.

[DP0, q1];

kill (q1);

assume (q1 > 0)$
integrate (1/q^(2/3), q, 0, q1);

Let TV be the total value out to some arbitrary quantity q.

TV : %, q1 = q;

The marginal value v(q) associated with this demand curve, for arbitrary q, is the rate of change of TV with respect to 
quantity q; ie., the first derivative ( so v(q) is just the price the consumer is willing and able to pay for the quantity q).

diff (TV, q);

We can confirm that this expression v(q) = d(TV)/dq  = q^(-2/3) = DP0 =  p(q) = demand price for this model.

[DP0, ev (%, numer)];

We can illustrate the area beneath the demand curve out to quantity q = 1.
Since the total value, as a function of q, is 3*q^(1/3), the area under the demand
curve out to q = 1 is 3.

TV, q = 1;

wxdraw2d ( xlabel = "Quantity",  ylabel = "$ per unit",
    title = "Total Value = area beneath demand curve",
    yrange = [0, 10],
    fill_color   = blue,
     fill_density = 0.2,
    bars ( [0.1, subst (q = 0.1, DP0), 0.04]),
    line_width = 2,
    explicit ( DP0, q, 0, 1.5),
    color = black,
    parametric (1,t,t,0,1),
    label (["<------------AREA = TOTAL VALUE------------>", 0.5, 0.7],
        ["total value out to q = 1 case", 0.8, 9] ) )$

    

Another way to illustrate this case is to use fill_color together
with filled_func  = true.

wxdraw2d ( xrange = [0, 1.5], yrange = [0, 10],
           xlabel = "Quantity",  ylabel = "$ per unit",
          color = red,
           line_width = 5,
           explicit ( DP0, q, 0.01, 1.5),       
            fill_color = blue,
            filled_func = true,
            explicit ( DP0 , q, 0.01, 1) )$

The presumed large group of consumers of the good in question can attach a total value u(q) (in some sense) to
the purchase (by discrete subgroups) of amounts qa at price per unit qb, amount qb at price per unit pb, etc all the 
way from q = 0 out to some finite q > 0, since our simplified model assumes there exists some subgroup of consumers
who will pay any amount for the corresponding quantity implied by our demand curve.

Faced with a price per unit p for a quantity q, the consumers as a whole are faced with a cost = p*q and the benefit of
u(q) = total value. The benefit minus the cost is called the "consumer  surplus" CS(q) associated with that
point on the demand curve. 

    CS(q) = u(q) - p*q = benefit  -  cost.

To maximize the welfare of the group of consumers, we look for the value of q such that CS takes on its maximum
value for a fixed price p, ie., we solve the equation

    d(CS)/dq = 0,  or d(u)/dq - p = 0, which just says  p = v(q) = marginal value of purchasing quantity q units.

Suppose the solution is q0, and the corresponding price per unit is p0, so p0 = v(q0). Then the (maximum) 
consumer surplus is  u(q0) - p0*q0  = total area under the demand curve (and to the left of q0) minus the 
rectangular area p0*q0 = cost of q0 units at price per unit p0.

In more detail, u(q0) = integrate ( diff(u,x),x,0,q0 ) since u(0) = 0. Also q0 = integrate (1,x,0,q0). Use v(q) = diff(u,q).
Hence CS(q0) = integrate(v(x) - p0, x, 0, q0) = area under the inverse demand curve v(q) and above price per unit p0,
and to the left of q = q0. Then u(q0) = CS(q0) + p0*q0 = total area under the marginal value curve v(q) and to the
left of q = q0.

q0 is already bound to a number, so use qf instead for this sidebar (u is not bound).

[q0, qf];

assume( qf > 0 )$
integrate ( diff (u(x), x), x, 0, qf );

%, u(0) = 0;

wxdraw2d ( xlabel = "Quantity",  ylabel = "$ per unit",
    yrange = [0, 10],
    fill_color = dark_green,
    filled_func = 1,
    key = "Consumer Surplus",
    explicit ( DP0, q, 0.0001, 1),
    fill_color = light_green,
    filled_func = 0,
    key = " Cost = p1*q1 = $1",
    explicit (1, q, 0, 1),
    color = black,
    label ([" Total Value u(q1) = CS + Cost ", 0.6, 6] ) )$

   

We can write a simple Maxima function to compute the consumer surplus CS, given the price as a function
of q, the quantity purchased qv and the price paid per unit pv. Since economists often use demand curves
which can't be taken seriously close to q = 0 and even diverge as q --> 0, we include qstart as the minimum
value of q in the summation (integration). By the way, we are assuming the expression price_func depends
on the variable q inside this function.

CS (price_func, qstart, qv, pv) :=
 float (integrate (price_func,q, qstart, qv) - pv * (qv - qstart) )$

CS (DP0, 0, 1, 1);

We  know CS = 2, cost = 1, so total value = 3.

DP0;

Total value is the area under the marginal value curve DP0 to the left of q = 1.

integrate (DP0, q, 0, 1);

### Value of Additional Units Related to Elasticity

Consider three demand curves, each with a different elasticity, all passing through the demand curve
point (p = 1, q = 1).

Define three elasticities ED0 (Median elasticity), ED1 (less elastic than ED0), ED2 (more elastic than ED0).
ED2  = 2*ED1

matrix (["ED0", "ED1", "ED2"],
[ED0 : - 0.75, ED1 : 0.75*ED0, ED2 : 1.5*ED0] );

Recall our definitions of DQ and DP.

[DQ, DP];

Define DQ0 and DP0 to correspond to ED = ED0 (this is a redefinition of DQ0 and DP0).

matrix (["DQ0", "DP0"],
      ev ([DQ0 : DQ, DP0 : DP], ED = ED0) );

Define DQ1 and DP1 to correspond to ED = ED1.

matrix (["DQ1", "DP1"],
      ev ([DQ1 : DQ, DP1 : DP], ED = ED1) );

Define DQ2 and DP2 to correspond to ED = ED2.

matrix (["DQ2", "DP2"],
      ev ([DQ2 : DQ, DP2 : DP], ED = ED2) );

If we had retained fractions as exponents, ED0 = - 3/4, DQ0 = 1/p^(3/4), DP0 = 1/q^(4/3).
ED1 = (3/4)*ED0 = -9/16, DQ0 = 1/p^(9/16),  DP0 = 1/q^(16/9).
ED2 = (3/2)*ED0 = -9/8, DQ0 = 1/p^(9/8), DP0 = 1/q^(8/9).

Let q1 = 0.8 and p1 be the corresponding value of DP0.

matrix (["q1", "p1"],
           [q1 : 0.8, p1 : ev (DP0,q = q1)] );

matrix (["phigh", "pmax"],
           [phigh :  apply ('max, ev ([DP1,DP2], q = q1)), pmax : max (1, phigh)] );

[DP1,DP2];

[DP1, DP2], q = q1;

[DP1, DP2], q = 1;

Show these three demand curves corresponding to three different values of elasticity.

wxdraw2d (xlabel = "Quantity", ylabel = "$ per unit", yrange = [0, 1.2*pmax],
    color = black, parametric (1,t,t,0,1), parametric (q1,t,t,0,phigh),
    explicit (1, q, 0.001, 1), label (["Consumer Surplus", 0.35,1.3]),
    key_pos = bottom_left, color = blue, key = "DP0 Median E", 
    explicit (DP0, q, 0.001, 1.5*max (1, q1)),
    color = red, key = "DP1 Less Elastic", line_width = 2,
    explicit (DP1, q, 0.001, 1.5*max (1, q1)),
    color = dark_green, key = "DP2 More Elastic", line_width = 3,
    explicit (DP2, q, 0.001, 1.5*max (1, q1)) )$

We see that the demand curve with the greatest "Consumer Surplus" (associated with a purchase of
q = 1 units at price p = 1) is the least elastic demand curve DP1 (in red).

[q1,DP0,DP1,DP2];

Let delvk be the change in "value" (with demand curve DPk) due to a change of q from q = 1 to q = q1 = 0.8.
For k = 0, 1, 2, this will be the area under the corresponding demand curves between q = 0.8 and q = 1.

[ [delv0, delv1, delv2] : float ( [integrate (DP0,q,1,q1), integrate (DP1,q,1,q1), integrate (DP2,q,1,q1) ] ), delv1/delv2 ];

It is visually clear from our plot of these three demand curves, that if we compare the area under each of
the three curves, from q = 0.8 to q = 1, that the area under the red curve (least elastic curve DP1) is larger
than the area under the blue curve (median elastic curve DP0), and the latter area is larger than the area
under the green curve (greatest elasticity DP2). The greatest loss of value occurs for the least elastic
demand curve DP1 (red).

### Prices and Consumer Surplus

Given the three demand curves considered above, consider the effects of charging a higher price for units ultimately
purchased. We assume the price paid per unit is p1 = $1.347 per unit instead of  $1 per unit. The consequence is
that a smaller quantity of units are purchased (no matter which demand curve is considered here) and the quantity
purchased (q) will be less than q = 1 unit per unit period.

Recall that p1 is the price corresponding to q = q1 for demand curve DP0.

[q1,p1];

DP0, q = q1;

q10, q11, q12 will be the smaller quantity purchased (at price p1) corresponding to the demand curves
DQ0 (Median elasticity), DQ1 (least elasticity), DQ2 (greatest elasticity).

[DQ0, DQ1, DQ2];

[ q10, q11, q12  ] : [DQ0, DQ1, DQ2],  p = p1;

The changes is quantity purchased with this price increase are then:

[delq0, delq1, delq2] : % -1;

The shift in quantity purchased (for a given price increase) is greatest for the demand curve with the 
greatest elasticity (DQ2) and the least for the demand curve with the least elasticity (DQ1).

We can illustrate this with a plot.

wxdraw2d (xlabel = "Quantity", ylabel = "$ per unit", yrange = [0, 1.2*pmax],
    color = black, explicit (p1,q,0.001, max (q10,q11,q12)),
    explicit (1, q, 0.001, 1), label (["Consumer Surplus", 0.35,1.5]),
    key_pos = bottom_left, color = blue, key = "DP0 Median E", 
    explicit (DP0, q, 0.001, 1.5*max (1, q1)),
    color = red, key = "DP1 Less Elastic", line_width = 2,
    explicit (DP1, q, 0.001, 1.5*max (1, q1)),
    color = dark_green, key = "DP2 More Elastic", line_width = 3,
    explicit (DP2, q, 0.001, 1.5*max (1, q1)) )$

Just looking at the shrunken regions under the demand curves, to the left of (q10, q11, q12), and above p = p1 = 1.35,
we see visually the reduced consumer surplus area.

The calculation of the consumer surplus out to q = 1 for the case DP0 presents the difficulty (for example) that the integral
integrate (DP0, q, 0,1) is divergent and returns an error.

DP0;

Here we do the integration of DP0 with the starting point close to q = 0. Note that 1e-3 is a quick and easy way
to enter 10^(-3).

1e-3;

integrate (DP0,q, 1e-3,1);

integrate (DP0,q, 1e-10,1);

We see that we are getting a larger and larger number as we start the integration closer and closer to q = 0.

Let's try integrating from some small positive number a out to q = 1, and then take the limit as a --> 0. Let's 
also use 1/q^(4/3) instead of the floating point approximation.

a;

assume (a > 0, a < 1)$
Ia : integrate (1/q^(4/3),q, a, 1);

limit (Ia, a, 0, plus);

So the integrand 1/q^(4/3) is not integrable at q = 0, and the "area under the demand curve DP0" is
not definable if we insist on starting at q = 0. 

Likewise for curve DP1.

Ia : integrate (1/q^(16/9),q, a, 1);

limit (Ia, a, 0, plus);

However, the area under the curve DP2 is finite.

Ia : integrate (1/q^(8/9),q, a, 1);

limit (Ia, a, 0, plus);

integrate (DP2,q,0,1);

Since consumer surplus CS(q) is defined as

       CS(q0) = u(q0) - p0*q0

where q0 is the quantity purchased at price p0, and u(q0) is the area under the demand curve and to the left of q0, 
 there are two ways that increased prices decrease the consumer surplus.
 
"As textbooks show, a price increase reduces Consumer Surplus in two ways: It increases 
the price that buyers must pay for the units that they still purchase at the higher price, and it reduces the quantity 
consumed so that buyers lose the Consumer Surplus on the marginal units." [MTC]

If we want to compare the change in consumer surplus for three demand curve with different elasticities, we need
to first establish a safe way (a non-divergent way!) to compute the consumer surplus. If any one of the demand
curves is divergent at q = 0, then we need to simply choose a common small positive value of qstart  for the calculation.

Let's choose qstart = qs = 10^(-10). We first calculate two values of the consumer suplus for demand curve DP0,
one (CS0A) for qfinal = 1, and one (CS0B) for qfinal = q10 = 0.8 ( with pfinal = p1 ~ 1.347).

[qs : 1e-10, CS0A : CS (DP0, qs, 1, 1), CS0B : CS (DP0, qs, q10, p1), CS0B - CS0A];

Let's write a Maxima function to compute the shift in consumer surplus, given an expression for p(q),
a minimum value of q to use for integration (qmin), the case A  quantity and price (qA, pA) and the
case B quantity and price (qB, pB).

CS_shift (pricef, qmin, qA, pA, qB, pB) :=
    (CS (pricef, qmin, qB, pB) - CS (pricef, qmin, qA, pA) )$

Let's try this function out.

CS_shift (DP0, qs, 1, 1, q10, p1);

which agrees. Now we want to compare the shift in "consumer surplus" for the three demand curves with
different elasticity, each going through the point (p = 1, 1 = 1).

matrix ( ["DP0", "DP1", "DP2"],
    [ CS_shift (DP0, qs, 1, 1, q10, p1), CS_shift (DP1, qs, 1, 1, q11, p1), CS_shift (DP2, qs, 1, 1, q12, p1) ] );

The least elastic demand curve DP1 has the largest decrease in consumer surplus and the smallest decrease 
in quantity purchased. The most elastic demand curve DP2 has the smallest decrease in consumer surplus
and the largest decrease in quantity purchased.

A much easier way to compute the shift in consumer surplus is to compute the sum of the numbers q(p)*dp from pA to pB
(and put in the minus sign by hand). QuantityF is an expression depending on p and is the demand curve (not the
inverse demand curve).

del_CS (quantityF, pA,pB) := - float (integrate (quantityF, p, pA, pB))$

[DQ0, DQ1, DQ2];

matrix ( ["DQ0", "DQ1", "DQ2"],
    [ del_CS (DQ0, 1, p1), del_CS (DQ1, 1, p1), del_CS (DQ2, 1, p1) ]);

which, of course, produces the same consumer surplus shifts as before, and leads to the same conclusions.

### Producer Surplus [MTC 2.4.3]

Reference: IEA, Sec 2.2, Supply and Profit

We first draw an example of an upward sloping supply curve, labeling areas as producer cost and
producer surplus (profit), and then justify the terminology.

matrix ( ["SQ", "SP" ],
         [SQ : b*p^ES, SP : (q/b)^(1/ES)] );

matrix (["SQ0", "SP0"],
      ev ([SQ0 : SQ, SP0 : SP], [b = 1.5, ES = 0.5]) );

ptemp : SP0, q = 1;

For this example, SP0(q) is the "inverse supply curve"  and SQ0(p) is the "supply curve", and
producers are willing and able to supply q = 1 unit per unit time when offered a price of $0.444 per unit
(per unit time).

wxdraw2d ( xlabel = "Quantity",  ylabel = "$ per unit",
    yrange = [0, 1.5*ptemp],
    line_width = 2,
    explicit ( SP0, q, 0, 1.5*max (1, q1)),
    color = black,
    line_width = 1,
    explicit (ptemp,q,0,1),
    parametric (1,t,t,0,ptemp),
    label ( ["Producer Cost", 0.8, 0.2*ptemp],
               ["Producer Surplus", 0.4, 0.8*ptemp] ),
    label_alignment = left,
    label ( ["Revenue = Producer Surplus + Producer Cost",0.05, 1.4*ptemp]) )$

Where does the supply curve come from?  A desire of producers to maximize profit.

Assume there exists a function c(q) which is the "producer cost" to produce q units (per unit time). Given
a price p offered for quantity q, the "producer surplus" PS (profit) equals the revenue p*q minus the cost.
        
         profit = benefit - cost,          PS(q) = p*q  - c(q)

Producers seek to maximize profit, and look for that quantity q = q0 such that d(PS)/dq = 0 for given p, which 
implies the equation

          p - dc/dq = 0,  or p = SP(q)
   
where SP(q) = d (c(q))/dq = marginal cost of production = supply curve as a function of quantity. Let q0 and p0
solve this equation, so p0 = SP(q0).  Then the maximum profit (given p = p0) is PS(q0) = p0*q0 - c(q0). 

Now c(0) = 0 [it costs nothing to produce nothing]. So c(q0) = integrate (diff(c(x),x), x, 0, q0), and 
q0 = integrate (1,x,0,q0), and PS(q0) = p0*integrate (1,x,0,q0) - integrate (SP(x), x, 0, q0) = integrate (p0 - SP(x), x, 0, q0) 
= area shown above in the figure labeled Producer Surplus, in the example with q0 = 1, p0 = 0.444. 

The revenue is the area of the rectangle p0*q0, and the producer cost is the area of the revenue minus 
the area of the profit (producer surplus) and justifies calling the area under the supply curve (to the left of q0) 
as the producer cost of quantity q0.

The area under the supply curve from q = 0 to q = 1 is the "Producer Cost" (for quantity q = 1 unit) for the case 
of an industry of  "price-taking firms." For such firms the height of the supply curve defines the minimum 
price per unit required to  bring a specified quantity to market. 

"Price-taking behavior" characterizes industries in which there are so many firms, most of them small, that the 
actions of no single firm can affect the market price of the good or service. An example might be farming. There 
are so many suppliers of wheat that the decision of one farmer to double or triple output or cut it in half
will have no impact on its market price. (Of course, if all farms decide to double output, there will be a substantial 
impact on market price.) Such an industry is said to be “perfectly competitive.”