<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Modeling the Russian Mir
Land and labor allocations on a commune
Step1:  This notebooks extends the general equilibrium farm distribution models found in the geqfarm module o also include the possibility that the 'smallholder' sector is represented by a commune, which we model with the historical Russian Mir in mind.
THIS NOTEBOOK IS WORK IN PROGRESS...
Preliminaries
As a benchmark we start with a simplified statement of the problem with just two types of household group -- landlords and `peasants' and a very simple discrete distribution of farming skills.  We later generalize.
The economy has $\overline{T}$ units of cultivable land and $\overline{L}$ households with one unit of labor each. The economy-wide land to labor ratio is therefore $\overline{t}=\overline{T}/\overline{L}$. 
Household are indexed $i=1..$ $\overline{L}$ and each household has a non-traded farming skill level $s_{i}$ drawn from a known distribution $Z$. There is also an initial distribution of property rights over land. We'll make more flexible assumptions later but for now suffice to say that there is a group of "landlord" households (fraction $\lambda $ of the total) who together own fraction $\theta $ of the land endowment. The remaining fraction  $1-\theta$ is controlled by the smallholder sector (possibly organized into a commune). 
In some scenarios below landlords will distort allocations by colluding to coordinate their factor market demands and supplies as if they were a single landlord monopoly `cartel'.   
Depending on the scenario the commune also may or may not create its own distortions, principally by enforcing land allocationsto households in the commune based on an egalitarian norm (e.g. proportionate to demographic characteristics) rather than based on each smallholder's skill or productivity.
As the $\lambda \overline{L}$ landlord households own $\theta \overline{T}$ units of land, peasant households own the remaining $(1-\theta )\overline{T}$ units. The average non-landlord household therefore owns $\frac{(1-\theta )\overline{t}}{(1-\lambda )}$ units and, for the moment, all peasant households have the same initial land endowment. Under these assumptions it can be shown that the land Gini coefficient is exactly $\left[ \theta -\lambda \right] .$
A single tradable good such as corn is produced and consumed in the economy at a unity price fixed by trade with the world market. \ Households maximize utility from consumption subject to household income from farm production plus net factor sales.  
All peasant households have access to the same production technology represented by a standard concave production function $\widehat{F}(T,L,s)$ assumed for now to be linearly homogenous in its three arguments
Step2:  Model Scenarios
We classify the scenarios we want to analyze into four possible scenarios depending on whether there are distortions in the way the landlord and/or the smallholder class allcates resources. On the landlord side we first consider market power distortions while on the smallholder side we mainly consider distortions due to the possible presence of a commune authority that allocates land to smallholder households according to an egalitarian norm, for example according to the demographic characteristics rather than on farming skill/productivity of the household.
EE
Step3:  Useful math preliminaries
In an efficient equilibrium the first order necessary conditions for a maximum are that shadow prices are equalized across farms, and hence between landlord farms and all other farms. For any given smallholder farm $i$ we have
Step4:  The Economy has default resource endowment
Step5:  So as expected the efficient (competitive) resource allocation has every farmer operating a farm of equal unit size.  The smallhold_eq method gives the competitive (efficient) allocation for a subeconomy with XE = (TE,LE) endowments and skill distribution s. It returns a named tuple with equilibrium facor prices and X=[T,L] allocations.
If XE and s are those of the entire economy then we've found the economywide competitive allocation.
Step6:  Since everyone started out with the same skill $z_i$ and DRS production function and land and labor are assumed perfectly tradable then it makes sense that in equilibrium everyone would operate a farm of the same size.
The ED scenario (egalitarian commune in otherwise efficient)
In this scenario the MIR assigns every household member an equal allocation of land and that there are no factor markets inside the MIR.   
Define the average skill level inside the MIR
Step7:  Let's create a little heterogeneity in the commune
Step8:  The DE scenario (Latifundia)
Step9:  Thus far we've said nothing of the ownership of land or labor.  Let's assume every household has one unit of labor but that the 'landlord' class (which WLOG we index to be the last skill group s[-1]) owns fraction $\theta$ of the land.  Assuming a uniform distribution of households across skills every skill group has Lbar/N households, and so there are that many landlords who act as a single cartel.
The following code is useful for printing and plotting out equilibria as a function of initial landlords' land ownership share.
We pass our economy instance to the scenarios function and it solves for competitive and market-power equilibria (at different levels of theta) and prints out the results.
Let's plot the results.. THis is the classic diagram from Latifundia Economics..
Step10:  In the example above the 'landlord' farmer was in every way the same as the other farmers, the only difference being he had more land ownership (fraction $\theta$ of the total). He had the same skill parameter as every other farmer. In an efficient equilibrium his operational farm size should therefore be the same size as every other farmer. The plot above shows how monopoly power (which rises with $\theta$ allows the monopolist to distort the economy -- he withholds land from the lease market to drive up the land rental rate and, since this deprives the 'fringe' of farmers of land, lowers the marginal product of labor on each smallholder farm, increasing the smallholder labor supply to the market which pushes down the labor wage.  Hence we see how at higher levels of $\theta$ the landlord expands the size of his estate and establish monopsony power wages.
A key force keeping the landlord from becoming too large is the fact that their are diseconomies of scale in production.  THe landlord is expanding the scale of his operation (raising the land to labor ration on his farm in this example) earn more via distorted factor prices, but he balances off the increase in extraction from disorted wages against the cost of operating an inefficiently large farm (i.e. the cost of being too big). 
Now let's see the effect of making the landlord just a little bit more 'skilled' than the others.  This lowers the cost of being big.  But note that it also makes him bigger at lower theta and makes what I call the 'size monopsony or 'Feenstra' effect matter more..
So let's raise the landlord farmer's productivity 10% relative to the rest of the farmers.
Step11:  Let's recalculate the new equilibria under the different scenarios.
Step12:  Given that he is more skilled than before the landlord's efficient scale of production has increased. This lowers the cost of being big.  Interestingly at low $\theta$ this leads the landlord to hire less land and labor ...
Step14:  NEXT STEPS
<ASSISTANT_TASK:>
Python Code:
%reload_ext watermark
%watermark -u -n -t 
Explanation: Modeling the Russian Mir
Land and labor allocations on a commune:a general equilibrium framework
Jonathan Conning (Hunter College and The Graduate Center, CUNY) and Aleksandr Michuda (University of California, Davis)
End of explanation
import sys
sys.path.append('../')
from geqfarm import *
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = (10, 8)
np.set_printoptions(precision=4)
%matplotlib inline
%load_ext autoreload
%autoreload 2
Explanation: This notebooks extends the general equilibrium farm distribution models found in the geqfarm module o also include the possibility that the 'smallholder' sector is represented by a commune, which we model with the historical Russian Mir in mind.
THIS NOTEBOOK IS WORK IN PROGRESS...
Preliminaries
As a benchmark we start with a simplified statement of the problem with just two types of household group -- landlords and `peasants' and a very simple discrete distribution of farming skills.  We later generalize.
The economy has $\overline{T}$ units of cultivable land and $\overline{L}$ households with one unit of labor each. The economy-wide land to labor ratio is therefore $\overline{t}=\overline{T}/\overline{L}$. 
Household are indexed $i=1..$ $\overline{L}$ and each household has a non-traded farming skill level $s_{i}$ drawn from a known distribution $Z$. There is also an initial distribution of property rights over land. We'll make more flexible assumptions later but for now suffice to say that there is a group of "landlord" households (fraction $\lambda $ of the total) who together own fraction $\theta $ of the land endowment. The remaining fraction  $1-\theta$ is controlled by the smallholder sector (possibly organized into a commune). 
In some scenarios below landlords will distort allocations by colluding to coordinate their factor market demands and supplies as if they were a single landlord monopoly `cartel'.   
Depending on the scenario the commune also may or may not create its own distortions, principally by enforcing land allocationsto households in the commune based on an egalitarian norm (e.g. proportionate to demographic characteristics) rather than based on each smallholder's skill or productivity.
As the $\lambda \overline{L}$ landlord households own $\theta \overline{T}$ units of land, peasant households own the remaining $(1-\theta )\overline{T}$ units. The average non-landlord household therefore owns $\frac{(1-\theta )\overline{t}}{(1-\lambda )}$ units and, for the moment, all peasant households have the same initial land endowment. Under these assumptions it can be shown that the land Gini coefficient is exactly $\left[ \theta -\lambda \right] .$
A single tradable good such as corn is produced and consumed in the economy at a unity price fixed by trade with the world market. \ Households maximize utility from consumption subject to household income from farm production plus net factor sales.  
All peasant households have access to the same production technology represented by a standard concave production function $\widehat{F}(T,L,s)$ assumed for now to be linearly homogenous in its three arguments: land $T,$labor $L$, and a third factor which we label $s.$This last factor is assumed to be a non-traded factor that captures farming skill or labor supervision ability$.$  
In the illustrative simulations below we assume a Cobb-Douglas form
$$\widehat{F}(T,L,s)=s^{1-\gamma }\cdot \left[ T^{\alpha }L^{1-\alpha }\right] ^{\gamma }$$
The Economy Class
The python code relies on object oriented programming ideas.  We first define an Economy class. An instance of an Economy is an object with atributes describing the technology as well as an initial distribution of land and non-traded skills. The Economy class also includes methods for solving for and describing equilibrium allocations under different scenarios.  
Most of the code for this project is in the geqfarm module which includes these definitions. 
When the module is in a parent folder we need to add that folder to the pythonpath so the import works.
End of explanation
N = 5
Explanation: Model Scenarios
We classify the scenarios we want to analyze into four possible scenarios depending on whether there are distortions in the way the landlord and/or the smallholder class allcates resources. On the landlord side we first consider market power distortions while on the smallholder side we mainly consider distortions due to the possible presence of a commune authority that allocates land to smallholder households according to an egalitarian norm, for example according to the demographic characteristics rather than on farming skill/productivity of the household.
EE: Landlord and smallholder groups allocate resources efficiently, so marginal products will be equalized across farms. This scenario would include perfect competition with no market imperfections as well as the 'efficient exploitation' scenario described below. 
DE:  Here the landlord faces a competitive fringe (who allocate resources efficiently within their subeconomy) but the landlord is able to exercise some monopoly-cum-monoposony power through land and labor markets due to their concentrated ownership of land and/or farming skill. This is the 'Latifundia Economics' equilibrium.  It's possible to interpret the smallholder sector as a commune under the assumption that the commune allocates resources efficiently.  We do not consider bilateral monopoly (where the commune acts as a syndicate in strategic competition with the landlord) although this would be an interesting extension.
ED: In this scenario we imagine a commune embedded in an otherwise competitive economy. There distortions with...
DD: ...
To start simple assume that there just N=5 farmers.  By convention the code will treat the first (N-1) skill groups as belonging to the smallholder category and the last group as the landlord group.  
We'll start with an assumed equal distribution of farming skill across all N groups.
End of explanation
E = Economy(N)    # an instance takes N length as parameter
s = np.ones(N)    # skill distribution in the economy
E.ALPHA = 0.5
E.GAMMA = 0.90
Explanation: Useful math preliminaries
In an efficient equilibrium the first order necessary conditions for a maximum are that shadow prices are equalized across farms, and hence between landlord farms and all other farms. For any given smallholder farm $i$ we have:
$$
\begin{eqnarray}
z_{R}F_{T}(T_{R},L_{R}) &=&z_{i}F_{T}(T_{i},L_{i}) \
z_{R}F_{L}(T_{R},L_{R}) &=&z_{i}F_{L}(T_{i},L_{i})
\end{eqnarray}
$$
A farmer with skill $z_{i}$ will use fraction $\tau {i}$ of the land and labor input used by the landlord farm. Since $F$ is homogenous of degree $\gamma ,$ Euler's theorem implies that $F{T}$ will be homogenous of degree $\gamma -1$, so we can rewrite the first FOC as 
$$ 
\begin{eqnarray}
z_{R}F_{T}(T_{R},L_{R}) &=&z_{i}F_{T}(\tau {i}T{R},\tau {i}L{R}) \
z_{R}F_{T}(T_{R},L_{R}) &=&z_{i}\cdot \tau ^{\gamma -1}\cdot
F_{T}(T_{R},L_{R})
\end{eqnarray}
$$
to find that
$$
\begin{equation}
\tau {i}=\left( \frac{z{i}}{z_{R}}\right) ^{\frac{1}{1-\gamma }}
\end{equation}
$$
This implies that efficient equilibrium land and labor use by a farmer of skill $z_{i}$ can be expressed as being $\tau_{i}$ as large as that of the landlord:  $T_{i}=\tau_{i}T_{R}$ and $L_{i}=\tau {i}L{R}$
That also means that we can write:
$$
\bar L = L_{R} \left({\sum_{i=1}^{N-1}\tau _{i} + 1}\right) 
$$
$$
\bar T = T_{R} \left({\sum_{i=1}^{N-1}\tau _{i} + 1}\right) 
$$
If the $z_i$ happen to be all the same, and hence the $\tau_i = \tau$ then equilibrium landlord factor use can be written:
$$ T_R = \frac{\bar T}{(N-1)\tau+1} $$
$$ L_R = \frac{\bar L}{(N-1)\tau+1} $$
We'll also use formulas like these in the ED case below where we'll equalize marginal products on the landlord farm and the MIR as a corporation.
The EE scenario (e.g. perfect competition)
The following contrived example helps to starkly highlight the mechanisms behind the factor-market power distorted equilibrium.
Now create an economy and change a few parameters from their default.  The $\gamma$ parameter which measures the degree of homogeneity in production is purposefully set very high.. We are very close to assuming constant returns to scale (but setting it just below 1 is needed to make sure the size-distribution remains determinate).
End of explanation
E.TBAR,E.LBAR
Explanation: The Economy has default resource endowment:
End of explanation
Xc = E.smallhold_eq([E.TBAR,E.LBAR],s)
Xc
Explanation: So as expected the efficient (competitive) resource allocation has every farmer operating a farm of equal unit size.  The smallhold_eq method gives the competitive (efficient) allocation for a subeconomy with XE = (TE,LE) endowments and skill distribution s. It returns a named tuple with equilibrium facor prices and X=[T,L] allocations.
If XE and s are those of the entire economy then we've found the economywide competitive allocation.
End of explanation
N = 5
mir = Economy(N)
mir.s
Explanation: Since everyone started out with the same skill $z_i$ and DRS production function and land and labor are assumed perfectly tradable then it makes sense that in equilibrium everyone would operate a farm of the same size.
The ED scenario (egalitarian commune in otherwise efficient)
In this scenario the MIR assigns every household member an equal allocation of land and that there are no factor markets inside the MIR.   
Define the average skill level inside the MIR:
$$ \hat{z}=\frac{1}{(N-1)} \sum\limits_{i=1}^{N-1}z_{i} $$
When the MIR as a whole gets an allocation $T^M$ and $L^M$:
$$ T_{i}^{M}=\frac{T^{m}}{(N-1)(\overline{L}/N)}$$
$$ L_{i}^{M}=\frac{L^{m}}{(N-1)(\overline{L}/N)}$$
Then total output from an egalitarian MIR can be written:
$$
\begin{eqnarray}
H(T_{i}^{m},L_{i}^{m}) &=&\sum_{i=1}^{N-1}\frac{\overline{L}}{N}\cdot
z_{i}\cdot F(T_{i}^{m},L_{i}^{m}) \
&=&\widehat{z}(N-1)\frac{\overline{L}}{N}F(T_{i}^{m},L_{i}^{m})
\end{eqnarray}
$$
Note that since $F$ is homogenous of degree $\gamma $, $H$ is also
homogenous of degree $\gamma $, but $only$ under the institutional
constraint that all households employ the same production technique,
regardless of $z_{i}$.
TO ADD/EXPLORE:  We should investigate how heterogeneity in z inside the MIR lowers output.  For example:
MIR A has skill distribution [1 , 1, 1, 1]
MIR B has skill distribution [0 , 0, 0, 4]
Both have average skill level of 1 and same total output (since F is CRS in T, L and S). However an egalitarian distribution has no efficiency effect in MIR A but disastrous output consequences in MIR B 
There are distortions within the MIR but we would expect the equalization of shadow prices between the landlord farm and the Mir as a corporation. 
It's as if in equilibrium there are just two types of firm in a competitive economy: landlord firms and egalitarian communes where each commune has an (average) productivity level $\hat z$ as defined above.
Working with our earlier trick involving a proportionality factor $\tau$ we find:
$$T_R = \frac{N\overline{t}}{(N-1)\tau +1} $$
$$L_R = \frac{N}{(N-1)\tau +1} $$
where as before 
$$\tau =\left( \frac{\widehat{z}}{z_{R}}\right) ^{\frac{1}{1-\gamma }}$$
Shadow prices in the MIR are simply the 
$$
\begin{eqnarray}
r^{ed} &=&z_{R}\cdot F_{T}\left( \frac{N\overline{t}}{(N-1)\tau +1},
\frac{N}{(N-1)\tau +1}\right) \
w^{ed} &=&z_{R}\cdot F_{L}\left( \frac{N\overline{t}}{(N-1)\tau +1},
\frac{N}{(N-1)\tau +1}\right)
\end{eqnarray}
$$
End of explanation
mir.s = np.array([0.85, 0.85, 0.95, 0.95, 1.0])
zhat = mir.s[0:N-1].sum()/(N-1)
zR = mir.s[-1]
zhat, zR
tau = (zhat/zR)**(1/(1-mir.GAMMA))
tau
mir.GAMMA 
Explanation: Let's create a little heterogeneity in the commune:
End of explanation
(Xrc,Xr,wc,wr) = scene_print(E,10, detail=True)
Explanation: The DE scenario (Latifundia)
End of explanation
factor_plot(E,Xrc,Xr)
Explanation: Thus far we've said nothing of the ownership of land or labor.  Let's assume every household has one unit of labor but that the 'landlord' class (which WLOG we index to be the last skill group s[-1]) owns fraction $\theta$ of the land.  Assuming a uniform distribution of households across skills every skill group has Lbar/N households, and so there are that many landlords who act as a single cartel.
The following code is useful for printing and plotting out equilibria as a function of initial landlords' land ownership share.
We pass our economy instance to the scenarios function and it solves for competitive and market-power equilibria (at different levels of theta) and prints out the results.
Let's plot the results.. THis is the classic diagram from Latifundia Economics..
End of explanation
TLratio_plot(E,Xrc,Xr)
E.s[-1]=1.10
Explanation: In the example above the 'landlord' farmer was in every way the same as the other farmers, the only difference being he had more land ownership (fraction $\theta$ of the total). He had the same skill parameter as every other farmer. In an efficient equilibrium his operational farm size should therefore be the same size as every other farmer. The plot above shows how monopoly power (which rises with $\theta$ allows the monopolist to distort the economy -- he withholds land from the lease market to drive up the land rental rate and, since this deprives the 'fringe' of farmers of land, lowers the marginal product of labor on each smallholder farm, increasing the smallholder labor supply to the market which pushes down the labor wage.  Hence we see how at higher levels of $\theta$ the landlord expands the size of his estate and establish monopsony power wages.
A key force keeping the landlord from becoming too large is the fact that their are diseconomies of scale in production.  THe landlord is expanding the scale of his operation (raising the land to labor ration on his farm in this example) earn more via distorted factor prices, but he balances off the increase in extraction from disorted wages against the cost of operating an inefficiently large farm (i.e. the cost of being too big). 
Now let's see the effect of making the landlord just a little bit more 'skilled' than the others.  This lowers the cost of being big.  But note that it also makes him bigger at lower theta and makes what I call the 'size monopsony or 'Feenstra' effect matter more..
So let's raise the landlord farmer's productivity 10% relative to the rest of the farmers.
End of explanation
(Xrc,Xr,wc,wr) = scene_print(E,10,detail=True)
factor_plot(E,Xrc,Xr)
Explanation: Let's recalculate the new equilibria under the different scenarios.
End of explanation
TLratio_plot(E,Xrc,Xr)
Explanation: Given that he is more skilled than before the landlord's efficient scale of production has increased. This lowers the cost of being big.  Interestingly at low $\theta$ this leads the landlord to hire less land and labor ...
End of explanation
class MirEconomy(Economy):
     sub class of Economy class but with Mir rules in subeconomy
    
    def __init__(self, N):  # constructor to set initial parameters.
        super(MirEconomy, self).__init__(N)  # inherit properties
        # if None supplied use defaults
mir = MirEconomy(N)
mir.print_params()
DE = Economy(5)
DE.smallhold_eq([E.TBAR, E.LBAR], s, analytic=True)
(Xrc, Xr, wc, wr) = scene_print(DE, 10, detail=True)
factor_plot(E, Xrc, Xr)
DD = MirEconomy(5)
print(DD.prodn(np.array([10, 10]), np.array([1, 1.05])))
Explanation: NEXT STEPS:
Make the plot routines flexible to take multiple arguments to plot lines side by side e.g. factor_plot(Xrc0,Xr0,Xrc1,Xr1) would plot two scenarios on same figure.
The Russian Mir
THis is not finished...
EE(Competitive) and the ED (Latifundia) cases.  For example to find the competitive economy equilibrium we would use:
EE= Economy(5)
res = EE.smallhold_eq([EE.TBAR, EE.LBAR], s, analytic=True)
EE is an instance of this economy which initializes various things to defaults and the smallhold_eq is a method in this class that solves for a competitive equilibrium (it can solve analytically for homothetic case or numerically more generally). If the skill vector s is for the entire economy then the above call gives a competitive equilibrium outcome when landlords have no market power.  The returned result res will be a named tuple that holds equilibrium factor prices (res.w) and equilibrium factor d...(line truncated)...
now there is also a MirEconomy class that inherits from Economy.  These are economies where the smallholder sector are described by 
To instead find cartel 'Latifundia' equilibria for a theta of 0,8 we'd instead call on the cartel_eq method within the same Economy class:
3/23/15 Have set up a new Class called MirEconomy that inherits all its attributes.  The idea is to just change the methods that describe the smallholder 'subeconomy'.  Rather than assuming a competitive smallholder sector (as in the Economy class) these methods will have same name but the subeconomy will now be a MIR. With that we should then have working ED and DD cases.  I haven't yet rewritten the code but we'd want to rewrite demands(), excessD and smallhold_eq.  cartel_income and **car...(line truncated)...
End of explanation
<END_TASK>