#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""《资本论》三卷研究：明确条件下的教学例复算。
用法：python recalculate_examples.py
仅核算术，不验证现实假设；不用网络，不读写用户数据。
所有条件及原典/自拟身份见报告正文及附录 C。率以比值输出，乘100才是百分数。
"""
from fractions import Fraction as F
import json

out = {}
def keep(name, **values):
    out[name] = {k: {'exact': str(v), 'decimal': float(v)} if isinstance(v, F) else v
                 for k, v in values.items()}

# 纱线：12h，每h新增0.5s，劳动力3s，生产资料耗费24s。
new = 12 * F(1, 2)
surplus = new - 3
assert surplus == 3 and (24 + new) - (24 + 3) == 3
keep('11 纱线（先令）', new_value=new, product=24+new, surplus=surplus, e=surplus/3)

# 价值加权等效周转，不是固定资产物理更新次数。
turn = F(80000, 10) + 20000 * 5
keep('30 加权周转', annual_value_return=turn, equivalent_turnovers=turn/100000)
assert turn/100000 == F(27,25)

# 零启动批次模型，生产每周100，K=900，无剩余、折旧、信用。
def batch(W,C,H):
    W,C,H=F(W),F(C),F(H)
    complete=100*W*(H//W)
    returned=100*W*max(0,(H-C)//W)
    spent=100*H
    cash=900+returned-spent
    finished=complete-returned
    wip=spent-complete
    assert cash+finished+wip==900
    assert min(cash,finished,wip)>=0
    return dict(completed=complete,returned=returned,cash=cash,finished=finished,wip=wip)
for W,C,H in [(F(9,2),F(9,2),51),(6,3,51),(3,6,51),(6,3,50)]:
    keep(f'32 批次 W={W},C={C},H={H}',**batch(W,C,H))
assert batch(6,3,50)['returned']==4200
keep('33 年剩余价值率', A=F(5000,500),B=F(5000,5000),long_batch_produced_not_cash=F(5000,5500))

# 两部类：本期剩余分为追加c、追加v、消费g，再推下一期。
def reproduce(I,II,alloc_I,alloc_II):
    c1,v1,s1=map(F,I);c2,v2,s2=map(F,II)
    dc1,dv1,g1=map(F,alloc_I);dc2,dv2,g2=map(F,alloc_II)
    assert dc1+dv1+g1==s1 and dc2+dv2+g2==s2
    assert v1+dv1+g1==c2+dc2
    assert c1+v1+s1 == c1+dc1+c2+dc2
    assert c2+v2+s2 == v1+dv1+g1+v2+dv2+g2
    nextI=(c1+dc1,v1+dv1,v1+dv1)
    nextII=(c2+dc2,v2+dv2,v2+dv2)
    return nextI,nextII,v1+dv1+g1
I,II,cross1=reproduce((4000,1000,1000),(1500,750,750),(400,100,500),(100,50,600))
J,JJ,cross2=reproduce(I,II,(440,110,550),(160,80,560))
assert sum(I)+sum(II)==9800 and sum(J)+sum(JJ)==10780
keep('38 两轮再生产',cross1=cross1,total1=sum(I)+sum(II),cross2=cross2,total2=sum(J)+sum(JJ),growth1=F(800,9000),growth2=F(980,9800))

keep('40 分母', markup=F(100,500),return_on_advance=F(100,1680))
costs=[70,81,91,55,15];sv=[20,30,40,15,5]
value=[k+s for k,s in zip(costs,sv)]
price=[k+22 for k in costs]
assert sum(value)==sum(price)==422 and sum(sv)==110
keep('42 五资本',total_cost=sum(costs),total_surplus=sum(sv),total_value=sum(value),total_price=sum(price),r=F(110,500))

# Bortkiewicz：三部类一年周转，z=1；统一缩放另列。
x,y,z,r=F(32,25),F(16,15),F(1),F(1,4)
rows=[(225,90,375),(100,120,300),(50,90,200)]
prices=[];profits=[]
for (c,v,total),factor in zip(rows,(x,y,z)):
    cost=c*x+v*y
    sales=total*factor
    assert (1+r)*cost==sales
    prices.append(sales);profits.append(sales-cost)
assert sum(prices)==1000 and sum(profits)==200
keep('44 Bort z=1',x=x,y=y,r=r,total_price=sum(prices),total_profit=sum(profits))
keep('44 统一缩放7/8',total_price=sum(prices)*F(7,8),total_profit=sum(profits)*F(7,8))

# 一商品：预付实物工资，无固定资本，技术量给定。
def one(a,l,b):
    a,l,b=F(a),F(l),F(b)
    lam=l/(1-a);wage_value=lam*b
    return dict(labour_value=lam,e=(1-wage_value)/wage_value,cost=a+b*l,r=1/(a+b*l)-1)
old=one('0.4','0.6','0.5');fixed_b=one('0.48','0.4','0.5');fixed_e=one('0.48','0.4','0.65')
assert old['r']==F(3,7) and fixed_b['r']==F(8,17) and fixed_e['r']==F(13,37)
for name,data in [('旧',old),('固定实薪',fixed_b),('固定剥削率',fixed_e)]:keep('47 一商品 '+name,**data)
keep('47 新工资下旧技术成本',old_tech_new_wage=F('0.4')+F('0.6')*F('0.65'))
# 仅按正文提供的四舍五入系数验代数，不是重估原回归。
keep('47 动态系数代数',conditional_log_slope=F('-0.002'),lag=F('0.843'),long_run_log_slope=F('-0.002')/(1-F('0.843')))

# 商业纯费用50先从总剩余180扣除，预付K=900+150。
r=F(130,1050);industry_profit=900*r;merchant_profit=150*r
sale_to_merchant=900+industry_profit
assert sale_to_merchant==F(7080,7)
assert 1080-sale_to_merchant-50==merchant_profit
keep('48 商业纯费用',r=r,industry_sale=sale_to_merchant,industry_profit=industry_profit,merchant_profit=merchant_profit)
net=F(6)-90*F('0.03')
keep('50 银行',net_income=net,net_return_on_assets=net/100,return_on_equity=net/10)
assert net==F('3.3')

rate=F(1,20);cashflow=F(10)
keep('52 资本化',perpetuity=cashflow/rate,annuity20=cashflow*(1-(1+rate)**-20)/rate,perpetuity_at4=cashflow/F('0.04'))

# 两状态地租反例：初期各地最多一份投入，后期B-E两份；正常利润20%。
q0=[10,12,13,14,15];p0=F(6);cost0=60
rent0=[p0*q-cost0 for q in q0]
q1=[24,26,28,30];p1=F(5);cost1=120
rent1=[p1*q-cost1 for q in q1]
assert rent0==[0,12,18,24,30] and rent1==[0,10,20,30]
assert sum(rent0)==84 and sum(rent1)==60
assert 328-44*p0==sum(q0) and 328-44*p1==sum(q1)
keep('58 地租自拟反例',initial_rent=sum(rent0),later_rent=sum(rent1),initial_output=sum(q0),later_output=sum(q1))

# 绝对租示意：总S40，两个K100；农业销售125外给。
R=F(10);r=(40-R)/200
P_ind=100+100*r;P_ag=100+100*r+R
assert P_ind==115 and P_ag==125 and P_ind+P_ag==240
keep('59 绝对租分配闭合',rent=R,r=r,industrial_price=P_ind,agricultural_price=P_ag)

print('仅为给定假设下的算术复算；不是经验验证、原典无误保证或投资建议。')
print(json.dumps(out,ensure_ascii=False,indent=2))
