You are on page 1of 123

GAMS 软件培训材料

——基本语法及案例分析

(内部使用)
第一章 GAMS 的基本操作方法: ....................................... 4

1.0 进入 GAMS 系统:............................................. 4


1.1.1 File | New:.............................................. 5
1.2 Edit Menu(其功能和 Microsoft Words 编辑的功能一样):........ 14
1.3 Search Menu:.............................................. 15
1.4 Window Menu:.............................................. 16
1.5 Help Menu:可查询 GAMS 语法及其操作方法..................... 17

第二章 GAMS 的程序语法: .......................................... 19

一 、集合和索引 .............................................. 20
二、数据输入:参数、标量和表格................................. 25
三 带参数的基本运算........................................... 28
四. 变量...................................................... 33
五. 方程...................................................... 36
六. 模型...................................................... 37
七. 结果输出(display)....................................... 38
八. GAMS 模型库 ............................................... 39

第三章 GAMS 特殊符号与命令 ........................................ 40

一、条件$符号.................................................. 40
二、options 命令 ............................................... 41
三、程序控制命令(loop 语句、if-else 语句)..................... 42
四. GAMS 的其它语法及注意事项: ............................... 46
五. GAMS 软件与 EXCEL 软件的联合应用 ........................... 48

第四章 案例分析 ................................................. 50

案例一:简单的种植水平模型..................................... 50
案例二:家庭效用最大化......................................... 55
案例三:非线性回归问题......................................... 57
案例四:经济最优增长 Ramsey 模型 ............................... 58
案例五:OPEC 最佳定价和开采量模型 .............................. 61
案例六:工业污染控制问题....................................... 63
案例七:简单投资组合模型....................................... 66
案例八:贷款偿还因素问题....................................... 68
案例九:最优增长模型........................................... 71
案例十:Ajax 纸业公司生产计划 .................................. 73
案例十一:基本生产和库存模型................................... 75
案例十二:Robust 最优化问题 .................................... 78
案例十三、$title MathOptimizer Example 1 (MATHOPT1,SEQ=255).... 79
案例十四、$title MathOptimizer Example 2 (MATHOPT2,SEQ=256).... 81
案例十五、 $title MathOptimizer Example 3 (MATHOPT3,SEQ=257)... 82
案例十六、$title Stochastic Programming Example (PRODSP,SEQ=186)
............................................................... 83
案例十八、简单 CGE 模型......................................... 86

THE FIFTH CHAPTER THE SIMPLE CGE MODEL ......................... 90

5.1 Household behavior......................................... 90


5.2 Firm behavior.............................................. 91
5.3 Market-clearing conditions................................. 93
5.4 The Social Accounting Matrix............................... 93
5.5 Value, price and quantity.................................. 95
5.6 The basic concept of Calibration........................... 95
5.7 Calibration procedure –the case without indirect taxes.... 96
5.8 GAMS programming........................................... 98

THE SIXTH CHAPTER THE STANDARD CGE MODEL ........................ 99

6.1 Firm behavior (including Intermediate inputs)............. 100


6.2 Investment and savings.................................... 102
6.3 Modification of household and government behavior......... 102
6.4 Armington’s assumption................................... 103
6.5 Substitution between imports and domestic goods........... 104
6.6 Transformation between exports and domestic goods......... 105
6.7 Market-clearing conditions................................ 106
6.8 Model system.............................................. 106
6.9 Calibration............................................... 108
6.10 Calibration of the CES function.......................... 108
6.11 Calibration of the CET function.......................... 109
6.12 Estimation of savings rates.............................. 109
6.13 GAMS programming......................................... 110
A.5 Communicating with spreadsheet software.................. 110

第七章 实用的 CGE 模型构建及应用(静态) ........................ 113

1.部门划分.................................................... 113
2.生产要素.................................................... 113
3.经济行为主体................................................ 113
7.1 社会核算矩阵:............................................. 120
7.2 模型方程:................................................. 121
7.3 The program:.............................................. 122

第八章 实用的 CGE 模型构建及应用(动态) ........................ 122

8.1 The SAM Table:............................................ 122


8.2 The model:................................................ 122
8.3 The program:.............................................. 122

参考文献:........................................................ 123

第一章 GAMS 的基本操作方法1:


1. Menus and Windows
1.0 进入GAMS系统
1.1 File Menu
1.2 Edit Menu
1.3 Search Menu
1.4 Windows Menu
1.5 Help Menu

1.0 进入 GAMS 系统:

1
选自台湾国立清华大学黄宗煌教授“GAMS 基础篇——中文操作手册及程序式语法”
当 GAMS 软件安装好之后,在电脑桌面上会出现 GAMS-IDE 之图像 Gams.lnk ,

点击此按钮进入 GAMS 系统,出现画面如下图所示:

1.1 File Menu:


1.1.1 File | New:
打开新的编辑视窗,请选择 File | New 指令或按键盘 Ctrl+N,即可编写新

GAMS 程式,出现画面如下图所示:
1.1.2 File | Open:

打开一个或者多个已存在档案,请点选 File | Open 指令、或按键盘


Ctrl+O、或在 GAMS 介面中点击 按钮,会出现开启档案的视窗,然后
按照档案存储的路径开启档案,按 Shift+Ctrl+↓可选择多个 GAMS 档案,
出现画面如下图所示:
1.1.3 File | Open in New Window:
打开一个或多个已存在档案在新的编辑视窗,其操作方法同 1.1.2。
1.1.4 File | View in Explorer:
先开启一个已存在的 GAMS 档案,再选择 File | View in Explorer 指令,
会出现其档案的储存视窗,出现画面如下图所示:

1.1.5 File | Run:

执行 GAMS 程式,请选择 File | Run 指令、或直接按键盘的 F9、或在 GAMS

介面中点击 按钮。

1.1.6 File | Save:

原档名存储 GAMS 档案,请选择 File | Save 指令、或按键盘 Ctrl+S、或在

GAMS 介面中点击 按钮。

1.1.7 File | Save as:

更改档名存储 GAMS 档案,请选择 File | Save as。


1.1.8 File | Close:

关闭 GAMS 档案,请选择 File | Close 指令或点击编辑视窗右上角 。

1.1.9 File | Print:

列印 GAMS 档案,请选择 File | Print 指令、或在 GAMS 介面中点击 按

钮,出现画面如下图。列印之前可选择列印內容,如档案路径及页数(Header

& page number)、每列程式的编号(Line Numbers)、程式格式列印(Syntax print,

如粗体字和斜体字)、彩色列印(Color print)、双面列印(Two pages)、预览列

印(Preview)、及字型大小和样式(Printer font)等。

1.1.10 File | Preview:


打开之前曾经开启过的档案,请选择 File | Preview 指令,出现画面如下图
所示:
曾经开启过的档案
案。

1.1.11 File | Exit:

点选 File | Exit 指令,或点击 GAMS 系统视窗右上角 ,可离开 GAMS


系统。
1.1.12 File | Model Library:
点选 File | Model Library 指令,可打开 GAMS 标准模型图书馆(Open
GAMS Model Library)里的范例档案(著重于 Model Type,如 LP 或 NLP 等),出
现画面如下图所示:
或可打开样式模型图书馆(Open User Model Library)里的范例档案(著重
于语法格式,例如变数、方程式、及模型的宣告),其档名为 modlib.glb,
路径如下:C:\Program
Files\GAMS22.6\docs\bigdocs\gams2002\modlib.glb。
File | Project:
(1) New Project:
点选 File | Project | New Project 后,再决定 New Project 的档名(例如:Harry
Potter)及路径,其功能在使所有跟 Harry Potter.gpr 有关的档案都会储存在相
同的路径底下,gpr 为 Project 的副档名,出现画面如下图所示:
创造新的 Project 档名。

在 Harry Potter.gpr 下打开


math1.gms 档案(储存在 F 盘),
然后执行程式,其所产生的输
出档会跟 Harry Potter.gpr 储存
在相同的路径。

(2) Open Project:


打开一个已存在的 Project,則 GAMS 系统会要求你储存正在修改中的档案,
且会自动关闭。
File | Options:
Options 的功能如同 GAMS 系统的管家一般,总管 GAMS 系统的设定,包
括 Editor、Execute、Output、Solvers、Licenses、Colors、File Extensions、
Charts/GDX、及 Execute2。
(1) Options | Editor:
可设定字型及其样式和大小、Tab 键的型式及大小、页边空白、段落标记、
及语法颜色等,Options | Editor 出现画面如下图所示:

(2) Options | Execute:


设定 GAMS 系统执行程式时的环境,显示执行过程的视窗、及执行
完成后显示 lst 档的视窗等,Options | Execute 出现画面如下图所示:

(3) Options | Output:


设定输出档页面宽度和高度、日期和时间的型式,通常页面宽度的
范围介于 72~255,页面高度为 0 或 99999,Options | Output 出现画
面如下图所示:
(4) Options | Solvers:
显示可使用的 Solvers 和 Model 的型态,以便解决问题。第一行显示
可使用的 Solvers,第二行显示 Solvers 的 license 状态。Full 表示可
完全使用其 Solvers 的功能,Demo 表示试用版本,可部分使用其
Solvers 的功能。小长方形表示对某个 Model 型态来说,此 Solvers
选择了 GAMS 系统的隐含值;X 表示对某个 Model 型态来说,现行
所使用的 Solvers;-(a dash)表示对某个 Model 型态来说,无法使用
的 Solvers。
例如:CPLEX 适用于 LP、MIP、MIQCP、QCP 等模型。

(5) Options | Licenses:


在安装 GAMS 系统时,即可上传 license 档案,或在 Options | Licenses
选择替代的 license 档案,出现画面如下图所示:
(6) Options | Colors:
设定 GAMS 程式语法的颜色(分为前景(Foreground)及背景
(Background)及字体(包括粗体(Bold)、斜体(Italics)、及底线(Underline))。
例如保留字(Reserved words),前景为蓝色,背景为 Default 值,粗体字。
Options | Colors 出现画面如下图所示:

1.2 Edit Menu(其功能和 Microsoft Words 编辑的功能一样):


1.2.1 Edit | Undo(Ctrl + Z):
回复至上一次更改程式的画面。
1.2.2 Edit | Redo(Shift + Ctrl + Z):
再次回复至上一次更改程式的画面。
1.2.3 Edit | Cut(Ctrl + X):
刪除某一段程式內容,并复制到你想要贴上的地方。
1.2.4 Edit | Copy(Ctrl + C):
复制所选择的程式內容。
1.2.5 Edit | Paste(Ctrl + V):
贴上所选择的程式內容。
1.2.6 Edit | Delete:
刪除所选择的程式內容。
1.2.7 Edit | Select All(Ctrl + A):
选择档案全部的內容。

1.3 Search Menu:


1.3.1 Search | Find(Ctrl + F):

寻找程式里的指令或语法。
1.3.2 Search | Replace(Ctrl + R):
寻找程序里错误的语法,并用正确的语法来取代,1.3.1 和 1.3.2 的画面视
窗如下图所示:

1.3.1 画面视窗 1.3.2 画面视窗

1.3.3 Search | Goto line(Ctrl + G):


输入某列错误程序的号码列数(可由输出档得知此号码列数),并修改其程
式,出現的画面视图如下图所示:

程式中第七行发生
打字错误。

1.4 Window Menu:

1.4.1 Windows | Cascade:


多个编辑视窗呈阶梯式排列,出现的画面视窗如下图所示:

1.4.2 Windows | Tile Horizontal:


多个编辑视窗呈水平排列,出现的画面视窗如下图所示:
1.4.3 Windows | Tile Vertical:
多个编辑视窗呈垂直排列,出现的画面视窗如下图所示:

1.5 Help Menu:可查询 GAMS 语法及其操作方法


1.5.1 点选 Help | GAMSIDE Help Topics,出现的画面视窗如下图所示:
1.5.2 可供查询的 GAMS 文件:
(1) Help | GAMS Users Guide:

(2) Help | Solver Manual:

(3) Help | Expanded GAMS Guide(McCarl):


第二章 GAMS 的程序语法:
GAMS 程式基本结构,GAMS 基本成员的语法格式大至如下所述:
一、集合的声明/宣告(Declaration of sets):
set set_name optional descriptive text / first element, second element, ... /;
二、数据的声明/宣告(Declaration of data):包括直接参数赋值(scalar)、集合
参数赋值(parameter)、表格赋值(table)三种类型:
● scalar scalar_name optional descriptive text / numerical value /;
● parameter parameter_name (set_dependency) optional descriptive text
/first element with respect to the associated value,second ele
ment with respect to the associated value, ... /;
● table table_name (set_1, set_2…) optional descriptive text
set_2_element_1
set_2_element_2
set_1_element_1 value_11 value_12
set_1_element_2 value_21 value_22;

三、变量的声明/宣告(Declaration of variables):
● variable type variable_name (set_dependency) optional descriptive
text;

四、方程式的声明/宣告(Declaration of equations):
● equation equation_name (set_dependency) optional descriptive text;
● Equation_name.. definition of equation;

五、模型的陈述(Model statement):
● model model_name /all/;

六、求解方法的陈述(Solve statement):
● solve model_name maximizing objective_function_name using model
type;
● solve model_name minimizing objective_function_name using model
type;

一 、集合和索引
任何 GAMS 程序中,集合是基本的组成部分,它可以使模型程序变得清晰易懂。
集合语句以关键字 set (或 sets)开始,后面跟集合名称,最后是集合元素。其
中可以用〝text〞在集合名称或集合元素后加上解释性文字用来进一步描述前面
的集合或元素。

GAMS 程序的集合基本读法规则:
Set set_name ["text"] [/element1 ["text"] ,element2 ["text"] ,…/];

例 1:包含 a、b、c、d 四个元素的集合 S,用数学符号表示为:


S={a, b, c, d}
在 GAMS 程序中,可以写成:

Set G1 /a, b, c, d / ; 或者:


Set G1 "the first group " /a "the element1 ", b "the element2 " ,c "the element3 " ,
d "the element4 " / ; 或者:
Set G1 "the first group " / a "the element1 "
b "the element2 "
c "the element3 "
d "the element4 " / ;
1.集合名称
集合名称是一个必须以字母开始的最多有 63 个字母数字字符(alphanumeric
characters)构成的标识符(集合名称又称为索引)。例如:
ii15
28
Countries
¥210
$currency in USA
t003
Food&drink
T003

2.集合元素
每一个集合元素名称由最多 63 个字符长度构成,分为加引号和不加引号两种形
式。
不加引号的集合元素名称必须以字母或者数字的形式开始,后面只能跟字母、数
字或者”_”符号。例如:
Pho-acid
1987
2009-march
Novenmer
H2s04
K2_4329
Line+1
加引号的集合元素名称可以以任何字符开始,后面可以跟任何字符,但两边必须
用引号(单引号,或双引号)。例如:
“*TOTAL*”
“Month”
“2846”
“27sy’
‘10%increase’
‘Line 1’
值得注意的是:加引号的集合元素没有值,元素不是数值得概念。
例如,“2846”不是数值 2846; 集合元素“010” 与集合元素“10”不同。
(对于集合元素名称,采用不加引号的形式使用时更为方面,最常用;加引号的
形式相对繁琐,容易出错,通常仅仅对于特殊的集合元素,比如 no、ne 或者 sum
这样的名称加以使用)

集合中,元素名称和元素名称之间必须以逗号或者行结束等形式分开;例如:
Set cq /N210,P304/; 或者
Set cq /N210
P304/;
注意:GAMS 程序中集合元素两边用斜杠“/”而不是大括号。

3.关联文本
解释性的文本可以放在集合名称或者集合元素名称后面,起进一步说明和解释
的作用。关联文本不能超过 254 个字符,并且放在双引号“ ”之中。集合中,元
素名称和解释文本之间,集合名称与解释文本之间必须以空格来分开。例如:
Set fp “final products” /yncrude “refined crude(million barrels)”, lpg “liquefied
petroleum gas(million barrals)”, amm “ammonia(million tons)”, sulf “sulfer(million
tons)”/;

注意:双括号中的关联文本可以由任何字符组成,包括空格、斜线、逗号,货币
符号等等,只要不超过最长限度即可。

4.星号(*)的特殊作用
在 GAMS 程序中,星号(*)在集合定义中起着特殊的作用。对于连续排列的
集合元素,使用星号(*)可以使得集合元素输入简洁,例如:
Set t “time”
/1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,
2006,2007,2008,2009/;或者
Set t “time”
/1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009/;
以上例子可以写成为:
Set t “time” /1991*2009/;

值得注意的是,对于非数字的集合元素,若集合元素之间的差别仅仅在于某个位
置的数字不同,并且前一个集合元素中的数字小于后面集合元素中的数字,而且
连续,则也可以使用星号(*)进行简化输入。例如:
Set g /a1bc*a30bc/;
Set w /qw201tons*qw400tons/;
Set t1 /a20na*a10na/;
Set qy /a1x1*a9x9/;
Set r /a1*b9/;
Set g /a01bc*a30bc/;

“set g / a1bc * a20bc /;


Note that this is not the same as
set g / a01bc * a20bc /; ”——“GAMS —A User's Guide ,p37”

5.多重集合的声明
当 GAMS 程序中有两个或两个以上的集合时,一种方法是使用多个 set;另一种
方法是使用一个 sets,例如:
Set s “sector’ /Industry, Agriculture, Servers , Residence, Government, Foreign/;
Set p “province” /Jiangsu, Anhui, Zhejiang, Beijing , Shanghai , Xinjiang /;

或者
Sets
s “sector’ /Industry, Agriculture,Servers, Residence, Government, Foreign/
p “province” /Jiangsu, Anhui, Zhejiang, Beijing , Shanghai , Xinjiang /;
注意,set 或 sets 必须以“;”结束。

6.alias 语句:集合的多重命名
有时,需要对同一集合使用两个以上的名字。例如,投入产出表行于列,SAM
表中的行于列等,a(i,j)。 例如:

set c “commodities” /food , clothing, drinking, tobacco, vegetable /;


alias(c, cp);或者
alias(cp, c);

7.子集
在现实经济活动中,比如出口和进口,由于对外贸易的行业仅仅是全部行业的一
部分,因此,对外贸易部门相对全部行业就是一个子集。当一个较大集合的子集
需要单独突出时,就需要用子集定义进行声明。子集定义的基本语法是:
Set name1 / element1 , element2, element3, element4, element5,… /
name2(name1) / elementi, … /
name3(name1) /elementj,… /

例如:
Set i “all sectors” /light-ind, food+agr, heavy-ind, services/
t(i) “traded sectors” / light-ind, food+agr, heavy-ind/
nt(i) “non-traded sectors” /services/;

例如:
SETS
I SECTORS
/
agric Agriculture
imini Coal mining and Metal ore mining and Non-ferrous mineral mining
ifood Manufacture of food products and tobacco processing
itext Textile goods and Wearing apparel leather furs products
iopro the other productions in industry
ielec Electricity steam and hot water production and supply
icook Petroleum processing and cooking and Gas product and supply
ichem Chemicals productions
ibuil the building materiala and Nonmetal mineral products
imetl Metals smelting and pressing and Metal products
imach Machinery and equipment
icons Construction
stran Transport and warehousing and post
swhol Wholesale and retail and Eating and drinking places and lodge
sesta Real estate and rent and business serves
sbank Finance and insurance
sothe other social services
/
IE(I) EXPORT SECTORS

/ agric,imini,ifood,itext,iopro,ielec,icook,ichem,ibuil,imetl,
imach,icons,stran,swhol,sesta,sbank,sothe/

IA(I) AGRICULTURE SECTOR

/agric/

II(I) INDUSTRY AND CONSTRUCTION SECTORS

/ imini,ifood,itext,iopro,ielec,icook,ichem,ibuil,imetl,imach,icons /

IS(I) SERVICE SECTORS

/stran,swhol,sesta,sbank,sothe/

ALIAS(I,J);

补充知识:
1.动态集合:集合元素可以改变的集合称之为动态集合。
动态集合元素赋值的语法为:
Set_name(domain_name/domain_label)=yes/no;
Set_name 是集合名称;yes 和 no 是关键词,分别表示来自被赋值集合的全体成
员或缺少的成员。
例如:
set item all items / dish, ink, lipstick, pen, pencil, perfume /
subitem1(item) first subset of item / pen, pencil /
subitem2(item) second subset of item;
subitem1('ink') = yes ; subitem1('lipstick') = yes ;
subitem2(item) = yes ; subitem2('perfume') = no ;
Display subitem1, subitem2;

二、数据输入:参数、标量和表格
GAMS 的数据包括直接参数赋值(scalar)、集合参数赋值(parameter)、表格
赋值(table)三种类型。
1.直接参数赋值。直接参数赋值用 Scalar(标量)语句,适用于单一(标量)
数据输入。这个语句给标量参数赋值,即一个参数名称对应一个具体的数值。
应用 Scalar 语句用来声明和初始化一个,意味着该参数没有相关的集合,因
此只有一个与参数有关的数字。
一般来讲,scalar 的 GAMS 语法为:
scalar[s] scalar_name [text] [/signed_num/]
{ scalar_name [text] [/signed_num/]} ;

Scalar scalar_name [text] / scalar_number/;或者


Scalars scalar_name1 [text] / scalar_number1/
scalar_name2 [text] / scalar_number2/
scalar_name3 [text] / scalar_number3/;
同集合名称一样,scalar_name 也必须以字母开始,后面跟最长不超过 63 个字符
长度的字母或数字。说明性文本同样不能超过 254 个字符。
例如:
Scalars rho “discount rate” /0.15/
alpha “rate of investment profit” /0.7/
beta “lifetime of products ” /30/
gamma “the number of liquid capital ”;

以上语句初始化了参数 rho,alpha 和 beta。以后可以使用一个赋值语句直接赋值:


gamma=5000;
注意,这个赋值语句只有在参数 gamma 经过 scalar 定义以后才有效。

2.集合参数赋值。集合参数赋值用 parameter(参数)语句,适用于一维的列或
行数据输入。一个集合参数可以被一个或者多个索引序列检索,集合中的元
素应该是属于那些已经声明过的索引,元素值与数值之间用空格或等号分
开。parameter 的 GAMS 语法为:

parameter[s] param_name [text] [/ element [=] signed_num


{,element [=] signed num} /]
{,param_name [text] [/ element [=] signed_num
{,element [=] signed num} /]} ;

例如:
Set i “market” /beijing, shanghai, tianjing/;
Parameter dd(i) the price of the real estate
/beijing 30000, tianjing 8500 /;
集合参数 dd 中的每个元素值都与索引序列中的每一个元素对应,由于对应
i=shanghai 的元素,没有赋值,说明参数 dd(shanghai)暂时定为 0。

集合参数的默认值为零。
Parameter 也可以进行多个一维数列赋值,如:
Parameters a(i) /settle=350, san-diego=600/
b(i) /seattle 2000, san-diego 4500/;

※ parameter 也可以进行简单的二维或多维数据赋值。例如:
Set i /row1*row10/
J /column1*column6/;
Parameter a(i,j);
a(i,j)=2.5;

3.表格赋值。表格赋值用 table 语句,适用于二维及二维以上的集合参数赋值。


表格赋值语句是 GAMS 中唯一的一个格式限定的语句。即表格中的每个元素
顺序一定,并且必须与相对应的索引的交叉点位置一致,也即固定的行、列
位置。在用表格语句 table 之前,必须用 set 语句来为表格元素确定其在集合
中的位置。例如:
Table beta (h,j) share parameter in production function
BRD MLK
CAP 0.32 0.66435 Under both of BRD and
MLK column label
LAB 0.68 0.33765 Error
Under no column label
No Error
Under
exclusively
either BRD or
MLK label
例如:
Sets i commodities” /food , clothing, drinking, tobacco, vegetable /
j companies /company1*company3/;
table p(i,j) initial productive units(1000 tons per yr)
company1 company2 company3
food 3702 12910 9875
clothing 23 517 1207
drinking 181 148
tobacco 207 235 579
vegetable 93719 122 ;

其中的行坐标由“i”确定,列坐标由“j”确定。注意是由“i”“j”在 p(i,j)中的位置确定。
如果一行不足以输入所有列数据的话,则可以用“+”号继续,上例一也可以写成:
table p(i,j) initial productive units(1000 tons per yr)
company1 company2
food 3702 12910
clothing 23 517
drinking 181
tobacco 207 235
vegetable 93719 ;
+ company3
food 9875
clothing 1207
drinking 148
tobacco 579
vegetable 122 ;
注意“+”号的位置。
表格也可以是多维的,三维的表格例子如:
Sets i commodities” /food , clothing, drinking, tobacco, vegetable /
j companies /company1*company3/
c cities /Beijing , shanghai /;

table p(i,c,j) initial productive units(1000 tons per yr)


company1 company2 company3
food. Beijing 2202 8910 6375
food. Shanghai 1500 4000 3500
clothing. Beijing 15 317 947
clothing. Shanghai 7 200 360
drinking. Beijing 131 28
drinking. Shanghai 0 60 120
tobacco. Beijing 162 115 279
tobacco. Shanghai 45 120 300
vegetable. Beijing 70719 72
vegetable. Shanghai 23000 50;
注意 i,c,j 的位置。
Exercise : table p(j,i,c)

三 带参数的基本运算
1.用索引赋值
例如:
Scalar x /1.5/;
x=1.2;
x=x+2;
第一条语句是通过 scalar 语句给 x 赋予初始值 1.5;
第二条语句将 x 的值改为 1.2;
第三条语句是将 x 的值改为 3.2。
第二句和第三句都用新值代替了旧值,这样做的前提是标量 x 已经被声明过。
注意所有的赋值语句前需要用分号作为分隔符。

例如:对参数 a 中的 60 个数据元素进行赋值。
Set row /r1*r10/
col /c1*c6/;
Parameter a(row,col);
a(row,col)=13.2;
也可用索引为集合中的某个元素直接赋值(用双引号或单引号)。如:
a("r7","c2")=6;
a(row,"c5")=20;
a("r6",col)=-15;

向量/矩阵的求和运算:
例如:已知 B 矩阵为 B=[1 3 5;9 4 8;7 12 16 ] ,C 矩阵每个元素都是 B 元素
的 2.5 倍,则 C 的矩阵定义如下:
Set i /i1, i2, i3/
J /j1,j2,j3/;
table b(i,j)
i1 i2 i3
j1 1 3 5
j2 9 4 8
j3 7 12 16 ; (√or×)

parameter c(i,j);
c(i,j)=2.5*b(i,j);

注意:b 矩阵的行与列的顺序。

例:已知 B 矩阵为 B=[1 3 5;9 4 8;7 12 16 ];C 矩阵为 C=[-2 1;22 20;19 75],
求 D=B+C;
Sets i /i1, i2, i3/
j /j1,j2,j3/
g /g1,g2/
h /j1,j2,j3,g1,g2/;

table b(i,j)
j1 j2 j3
i1 1 3 5
i2 9 4 8
i3 7 12 16 ;

table c(i,g)
g1 g2
i1 -2 1
i2 22 20
i3 19 75;

parameter d(i,h);
d(i,"j1")=b(i,"j1");
d(i,"j2")=b(i,"j2");
d(i,"j3")=b(i,"j3");
d(i,"g1")=c(i,"g1");
d(i,"g2")=c(i,"g2");
或者
sets i /i1, i2, i3/
h /j1,j2,j3,g1,g2/
j(h) /j1,j2,j3/
g(h) /g1,g2/ ;

table b(i,j)
j1 j2 j3
i1 1 3 5
i2 9 4 8
i3 7 12 16 ;
table c(i,g)
g1 g2
i1 -2 1
i2 22 20
i3 19 75;

parameter d(i,h);
d(i,j)=b(i,j);
d(i,g)=c(i,g);

GAMS 程序中的字母不分大小写,即 P 与 p 完全一样。

2.利用数学表达式
2.1 标准数学运算。同其他计算软件一样,在 GAMS 程序中,“+”、“-”表示加、
减运算;“*”、“/”表示乘、除运算;“**”求幂运算;运算的优先级别与此序相反。
可以用括号改变优先级,一般在表达式中使用圆括号。
例如,数学式“x=(5+7)÷2×92”,可以写成
“x=(5+7)/2*9**2”
例如:一个数学中的求和计算:
TC i   C i , j
j
用 GAMS 语言表达如下:
Sets I products /food, clothes, drinking, tobacco/
J provinces / jiangsu, anhui, zhejiang /
Parameter C(i,j) productive capacity in tons per day for each province
TC(i) total productive capacity in tons per day ;
TC(i)=sum(j, C(i,j));

又如:计算公式为 count   a i , j 和 mp   lt  mt  ,对应的 GAMS 程序分


i j t
别为:
Count= sum((i,j),a(i,j));
Mp=sum(t,l(t)*m(t));

另外,还可以利用索引寻找集合中的最大或者最小值或者求积,如
“f=smax((i,h),d(i,h));”就是在二维集合 d 中寻找最大值并赋值给参数 f;如,
“f=smin((i,h),d(i,h))” 就是在二维集合 d 中寻找最小值并赋值给参数 f;如,
“f(j)=prod(i,b(i,j))”;“f=prod((i,j),b(i,j))”,含义?

2.2 函数。GAMS 提供了一些常用的标准函数,下表给出了 GAMS 中所有的可


用函数。
表1 GAMS 常用函数及其含义
函数 功能描述
errorf(x) 标准正态分布的积分(-∞,x)
exp(x) 指数 ex
log(x) 自然对数 loge(x)
log10(x) 常用对数 log10(x)
normal(x,y) 均值为 x,方差为 y 的随机正态分布函数
uniform(x,y) 均匀分布在 x 与 y 之间的随机数
abs(x) x 的绝对值
ceil(x) x 的上限值,大于等于 x 的最小整数
floor(x) x 的下限值,小于等于 x 的最大整数
mapval(x) 映射函数
max(x,y,…) 求序列中的最大值
min(x,y,…) 求序列中的最小值
mod(x,y) 求模 x-y*trunc(x/y)
power(x,y) 整数幂 xy
round(x) 取整,求最接近 x 的整数
sign(x) 符号 1(x>0); -1(x<0) ; 0(x=0)
sqrt(x) x 的平方根
sqr(x) x 的平方
trunc(x) Sign(x)*floor(abs(x))
arctan(x) 反正切
cos(x) 余弦
sin(x) 正弦

2.3 逻辑运算
表 2 GAMS 的逻辑运算符
操作符 说明 操作符 说明
lt,< 小于 ne,<> 不等于
gt,> 大于 not 非
le,<= 小于或等于 and 与
ge,>= 大于或等于 or 或
eq,= 等于 xor 非或
四. 变量
变量同参数一样,在使用之前必须定义(声明),变量同参数的一个重要区别在
于它可以设置类型和属性。
1.变量的类型。变量有 5 种基本类型,分别为下表所示:
默认取值下 默认取值上
关键字 变量特征描述
限 限
变量取值没有界限要求,使用者可
free(默认) -inf +inf
以改变变量的上限和下限
变量不可以取负值,使用者可以改
positive 0 +inf
变变量的上限
变量不可以取正值,使用者可以改
negative -inf 0
变变量的下限
binary 0 1 只能取 0 和 1 的离散变量
变量取值只能为值域内的整数,使
integer 0 100
用者可以改变变量的上限和下限

在上述 5 种变量中,free 为默认类型,即如果某变量在 GAMS 程序中没有特别


声明,则该变量就是一个没有界限限制的变量,其取值范围为(-∞,+∞)。

2.变量的定义。在 GAMS 程序中,基本的变量语句格式为:


[var_type] variable[s] var_name [text]
Var_type 是变量类型,不一定在每次变量定以前都使用,可以选用。
Variable 是在 GAMS 程序中用来定义或声明变量的内部语句,同 set,table,
scalar 一样。当定义或声明的变量仅有一个时使用单数形式;当定义
或声明多个变量时,使用复数形式,即 Variables。
Var_name 是定义变量的名称,必须以字母开始,紧跟着更多的字母或数字,
但同其他名称一样,最长不超过 63 个字符。附随的解释性文本用
于描述它前面的集合或元素,文本不能超过 254 个字符,并且必须
与它所描述的名称在同一行内。
定义变量类型有两种方式,第一种方式是列出所有变量及其相应的解释文本,
然后再分组说明变量类型。
例如:
Variables k(t) capital stock(million dollars)
c(t) consumption(million dollars per year)
i(t) investment(million dollars per year)
trade(t) net export (million dollars per year)
utility utility measure ;
positive variables k, c, i ;
根据上述程序,变量 k,c,i 为正值变量;trade 和 utility 为自由变量(free),
其取值范围为(-∞,+∞)。值得注意的是,同 set(s),scalar(s),parameter(s),
table(s)一样,每个 variable 语句必须用分号结束。
另一种常用的定义方式为根据类型对变量进行分组定义。上例的具有等价为:

free variables trade(t) net export (million dollars per year)


utility utility measure ;
positive variables k(t) capital stock(million dollars)
c(t) consumption(million dollars per year)
i(t) investment(million dollars per year);

3.变量属性
在 GAMS 程序结束时,往往需要显示变量的大小(Display)。由于在 GAMS 程
序中,参数或系数往往只有一个数值与之对应,而变量(variable)在求解过程
中,可能有多种取值,多种属性。因此,需要利用变量的一个附加设置来说明变
量的各种属性。GAMS 语言中,每个变量可以有 6 种属性。
表3 变量属性
变量属性 变量后缀 属性描述
变量下限,被使用者设定的准确值或
Lower bound .lo
默认值
变量上限,被使用者设定的准确值或
Upper bound .up
默认值
Fixed value .fx 变量的固定值,使上下限同值
变量的活动水平值,又称当前值。模
Activity .l
型求解后赋予的新值
变量的边际值。模型求解后赋予的新
Marginal or dual value .m

Scale value .scale 变量的比例因子,使非线性规划结果
变量分支优先值,仅在混合整数规划
Branching priority value .prior
模型中使用
例如:
x.up(c,i,j)=1000;
inv.lo=-1 ;
p.fx(“agri”,”mining”,”energy”)=200;
c.l(t) = 4*alpha;
第一个语句为变量x中的所有元素设定了一个上限;
第二个语句为变量 inv 设定了一个下限;
第三个语句为变量p中的三个元素设定了固定值;
最后一个语句将将变量c中的所有元素设定为参数 alpha 的4倍。

在赋值语句中,语句的顺序有时很重要。下面两对语句将得到两个不同的结果。
c.fx(“1990”)=1; c.lo(t)=0.01;
c.lo(t)=0.01; c.fx(“1990”)=1;
第一种情况下,变量 c(“1990”)的下限为 0.01;第二种情况下,变量 c("1990”)
的下限为1。
所用程序为:
set t the year /1980*2000/;
Variables c(t) capital stock(million dollars);
c.fx("1990")=1; c.lo(t)=0.01;
* c.lo(t)=0.01; c.fx("1990")=1;
display c.lo;

需要注意的是:

⑴后缀.fx 是后缀.lo 和后缀.up 的简写,因此在赋值时只能用在赋值语句的左侧。

⑵在显示语句和赋值语句中,变量必须使用带后缀名(.lo, .up, .l, .m)。不带后


缀名的变量只能出现在变量定义语句和方程定义语句中。

⑶当显示变量的时候必须说明示显示变量 6 个相应值中的哪一个,可以通过在变
量名称后面附加一个后缀来实现。例如语句 Display k.l, c.m; 分别显示变量k的
当前值和变量c的边际值。后缀不同,显示结果不同。
五. 方程
1.方程的声明
同参数和变量一样,方程在使用前必须声明。
方程的声明与参数和变量的声明类似,其中可以包括值域和解释文本。方程的名
称必须以字母开头,后跟字母或数字(它只能包括文字数字式字符),最长 63
个字符,后附的文本用于描述它前面的集合或元素,文本不能超过 254 个字符,
并且必须与其描述的标识符在同一行。语法格式为:
Equation[s] eqn_name text ,例如
Equations
Cost the residents’ consumption function
Supply(i) the supplement for productions of i
Demand(i) the demand for production of i
Tsums the total of supplyment for production i

注意,第一个方程的声明必须在关键词 Equation(s)之后。

2.方程的定义
方程的定义就是用解释 GAMS 语言中数学方程。GAMS 定义方程的语法格式为:
Eqn_name(domain_list).. expression eqn_type expression

其中,“Eqn_name”是方程名和代数表达式之间必须加入两个圆点“..”。
“eqn_type”是指表达式之间的符号,主要有
=e= 等于,左边的表达式等于右边的表达式
=g= 大于,左边的表达式大于右边的表达式
=l= 小于,左边的表达式小于右边的表达式
=n= 方程的左边与右边不存在强制性关系。这类方程很少用到。
例如:

Equations vari01(i)
Vari01(i).. consup(i)=salary(i) + transfer(i) –tax(i) –saving(i), or
Vari01(i).. consup(i)+–saving(i)=salary(i) + transfer(i) –tax(i) ,

Equations vari01(i);
Vari01(i).. consup(i)=salary(i) + transfer(i) –tax –saving(i);
Equations vari01;
Vari01.. consup(i)=salary(i) + transfer(i) –tax(i) –saving(i);
Equations vari01;
Vari01.. consup=sum(i,salary(i) + transfer(i) –tax(i) –saving(i));

注意:方程与变量必须是同一索引类型。

有时,在方程中可以使用加引号的标签,如:
Equations vari01;
Vari01.. tconsup1=consup(“richest”) + consup(“midrich”)+consup(“rich”);

六. 模型
定义模型就是选择进入模型的方程,并给模型命名,使之能被求解。最简单
的定义模型的形式就是使用关键词 all,表示在定义模型之前所有被定义的方程
都被选进模型。
1.定义模型
定义模型的语法格式为:

Model(s) model_name [text] /all or eqn_name…/


同所有标示符(参数、变量、方程)一样,model_name 必须以字母开始,后面
紧跟字母或数字,长度最多为 10 个字符,解释性文本不能超过 80 个字符,而且
必须与其描述的模型名称在同一行。 例如:
Model transport “a transportation model ” /all/
几个模型可以在一个 model 语句中声明(定义),这在尝试不同的方程解决同一
问题是往往比较方便,例如:
Models nortonl linear version /cb1, rc1, dfl1, bc1, obj1/
nortonn nonlinear version / cb2, rc2, dfl2, bc2, obj2 /;
或者
Model nortonl linear version /cb1, rc1, dfl1, bc1, obj1/;
Model nortonn nonlinear version / cb2, rc2, dfl2, bc2, obj2 /;

2.模型分类
GAMS 可以求解各种类型的问题,但求解之前必须明确模型的类型,若
GAMS 程序中确定的模型类型与模型数据不符,则 GAMS 就会发布解释性错误
信息。比如,若模型中存在二进制或整数型变量,若使用线性(LP)或非线性
(NLP)方法求解,则 GAMS 在运算时就会给出错误提示信息。
表2 模型的类型及其描述
模型类型 解释说明
LP 线性规划。模型中没有非线性项或离散(二进制或整数)变量
QLP 二次约束规划。模型中有线性和二次项,但没有一般的非线性项或者
离散变量
NLP 非线性规划。模型中有一般的非线性项,仅包含光滑函数,不包含离
散变量

MIP 混合整数规划。模型可以包括离散变量,但离散条件是强制的,也即
离散变量在其边界内必须取整数值。
RMIP 松弛混合整数规划。模型可以包括离散变量,但离散条件是松弛的,
也即整数和二进制变量在边界内可取任意值。
RMINLP 松弛混合整数非线性规划。模型可以包含离散变量和一般的非线性
项,离散条件是松弛的。
MINIP 混合整数非线性规划。模型可以包含离散变量和一般的非线性项,离
散条件是强制的。
MPEC 有均衡约束的数学规划
MCP 混合互补问题
CNS 约束性非线性系统

3.模型求解
模型定义后,就可以可用求解语句(solve)进行模型求解。Solve 语法格式为:
Solve model_name using model_type maximizing/minimizing objvar_name;
Solve model_name maximizing/minimizing objvar_name using model_type;
其中,solve 和 using 是保留字;model_name 是定义的模型名称;objvar_name 是
被优化的目标变量的名称,目标变量必须是标量和 free 类型;model_type 是模型
的类型;maximizing/minimizing 是优化的方向。例如:
Solve transport using lp minimizing cost;
需要注意以下几点:
⑴目标变量必须是标量和 free 类型;
⑵所有方程都被定义,并且至少有一个方程含有目标函数;
⑶每个方程都使用于指定的模型类型。(lp 要求方程均为线性方程;nlp 要求每
个方程均连续可导)。

七. 结果输出(display)
GAMS 默认的输出内容比较丰富,包括程序清单、错误信息、运行参考图、
模型统计、状态报告和结果报告。程序清单将列出带语句序号的所有源程序代
码,编译过程中出现的问题会在这里说明;运行参考图和模型统计会列出模型中
所有变量和参数属性、独立方程与变量的个数。以及它们之间的关系等模型信
息;状态报告会显示计算所用的算法和迭代次数、模型求解结果类型(是否是可
行解或是最优解)。
当结果出现“feasible solution”和“optimal solution”,或者“EXIT-Optimal
Solution found”和“***State: Normal completion”,则表示程序运算成功,得到了
最优解。否则,程序出现语法错误提示、或者算法和逻辑错误。
一般情况下,Display 语法格式为:
Display “text” parameter_name /variable_name.l or .m or .up or .lo 例如:

Set s / s1*s4 /
t / t1*t7 / ;
parameter p(s) /s1 0.33, s3 0.67/;
parameter q(t) /t5 0.33 , t7 0.67/;
variable v(s,t);
v.l(s,t)=p(s)*q(t);
display "the first set",s ,"the second set",t, "then a parameter",p,
"the activity level of a variable",v.l;

通常在 display 语句前,可以加上 optimal 语句以控制输出数值的小数点后显示的


位数,其格式为:
option decimals=“value”;
其中,value 的值为 0~8 之间的整数。如果等于零,则表示不显示小数点后面的
数。默认 value=3。
Set s / s1*s4 /
t / t1*t7 / ;
parameter p(s) /s1 0.33, s3 0.67/;
parameter q(t) /t5 0.33 , t7 0.67/;
variable v(s,t);
v.l(s,t)=p(s)*q(t);
option decimals=4;
display "the first set",s ,"the second set",t, "then a parameter",p,
"the activity level of a variable",v.l;

八. GAMS 模型库
希望每一代经济学家都能够站在前人的肩膀上,在已有的成果基础上前进。
——保罗.赛谬尔教授
GAMS 模型库为新人提供了丰富而翔实的模型案例,这些模型案例几乎包括所
有行业、所有类型的 GAMS 建模问题。比如,农业经济模型、水资源开发和利
用模型、收入分配模型、信贷风险模型、宏观经济模型、税收政策一般均衡模型、
地区经济增长模型、二氧化碳排放税模型、投资组合最优化模型、化学平衡模型、
非线性回归模型、储蓄模型、石油贸易模型、最佳定价和开采模型、工艺流程结
构最优化模型、能源模型、石油战略储备模型、电力规划模型、金融风险管理模
型、贸易及资本流动模型、生产调度模型、基本生产和调度模型、随机规划模型
等等大约 340 个模型。

通过这些模型案例的学习,可以使我们快速掌握应用 GAMS 程序的建模技能,


不断提高模型质量,获得成功的捷径。

第三章 GAMS 特殊符号与命令


一、条件$符号
$符号是 GAMS 中比较有用的运算符之一。$与一个逻辑体条件一起应用就构成
了$条件式。“$(条件)”可以被读成“在条件成立的情况下”。$条件式常常被用
于条件赋值语句、条件表达式和条件方程。注意:$运算符后不留空格。

例如,if(b>1.5), then a=2;


在 GAMS 程序中,用$条件可以表示为:
a$(b>1.5)=2;
以上语句可读为“a 在 b 大于 1.5 条件成立的情况下等于 2”。如果条件不满足,则
不赋值。

例如:
u(k)$(s(k)$t(k))=a(k);
上式表明只有在索引 k 中的元素既属于集合 s 也属于集合 t 时,赋值才成立。上
式等价于:
u(k)$(s(k) and $t(k))=a(k);
为增强程序的可读性,建议采用逻辑符号和括号。

例如:
Rho(i)$(sig(i) ne 0)=(1/sig(i))-1
上式表明:当 sig(i)不零时,rho(i)= (1/sig(i))-1;若 sig(i)为零时,rho(i)不赋值。

例如:
x=2 $(y>1.5)
上式表明:如果 y>1.5,那么 x=2;否则 x=0;
$在等式左边和在等式右边的区别:
$在等式左边,若$条件不成立,则不进行赋值;
$在等式右边,若$条件不成立,则赋值为零;

二、options 命令
Option 是 GAMS 程序中一个有用的选择命令,它一般放在求解命令 solve 语句之
前,它可以对输出格式进行控制,并且在求解过程中对运算方式进行选择。

表3 Option 对输出格式的控制功能
标识符 类型 描述
decimals 整数 控制输出参数、变量小数点后个数
Eject 置于下一页的开头
Limcol 整数 方程的列数
Limrow 整数 方程的行数
Solprint On/off 控制模型解的是否输出
Sysout On/off 控制求解结果文件的是否输出

表4 Option 选择结果对求解过程中计算机资源的需求
标识符 类型 描述
Domlim 整数 限制求解过程中发生值域错误的次数
iterlim 整数 限制求解过程的迭代次数
Reslim 实数 限制求解过程的时间
Optca 实数 对 MIP 类型的模型求绝对优化的解
Optcr 实数 对 MIP 类型的模型求相对优化的解

例如:
Option eject, iterlim=100, solprint=off, reslim=60;
Solve mymodel using lp maximizing profit;

注意:多个选项之间用逗号或者行结束字符进行分隔。

三、程序控制命令(loop 语句、if-else 语句)


1.Loop 语句
循环语句 loop 经常用在完成循环或迭代的计算中,去执行一连串的指令对于集
合里的每一个元素;也就是说,在一个迂圈(loop)里,GAMS 系统会先用集合里
的第一个元素去执行迂圈里的指令,当执行完毕后,GAMS 系统会将集合里的
第二个元素重复相同的动作,如此一直重复下去,直到集合里的最后一个元素执
行完毕后,GAMS 系统才会跳出迴圈,继续执行程式里的下一个指令。
Loop 语法的基本格式为:Loop(索引[$条件],语句);
Loop(set_name, statement or statements to excute);
范例:
set t / 1985*1990 /;

parameter pop(t) 1985 年台湾人口(单位:万人) / 1985 3456 /


growth(t) 历年人口增长(单位:万人)
/ 1985 25.3, 1986 27.3, 1987 26.2, 1988 27.1,
1989 26.6, 1990 26.6 /;

loop(t, pop(t+1) = pop(t) + growth(t) );


display pop;

求解结果:
---- 8 PARAMETER pop
1985 3456.000, 1986 3481.300, 1987 3508.600, 1988 3534.800
1989 3561.900, 1990 3588.500

说明:
当 t = 1985 时,pop(1986) = pop(1985 +1)
= pop(1985) + growth(1985)
= 3456 + 25.3
= 3481.3;
当 t = 1986 时,pop(1987) = pop(1986 +1)
= pop(1986) + growth(1986)
= 3481.3 + 27.3
= 3508.6;
…………………………………………………………
当 t = 1989 时,pop(1990) = pop(1989 +1)
= pop(1989) + growth(1989)
= 3561.9 + 26.6
= 3588.5;
当 GAMS 系统执行完毕后,即跳出迴圈,执行程序的下一个指令。

2.if-(elseif)-else 语句
If-else 语句用于程序中的条件转移,在某些情况下,可以用$条件语句替代,但
是相比而言,由于 if-else 语句类似存在于 fortune 语言、visual basic 语言等,因
此 if 语言使得 GAMS 程序具有更好的可读性。if-elseif-else 语句的语法格式为:
If(条件,
语句;
Elseif 条件,
语句;
Else 语句;);
注意:if 语句后的括号不能少;条件与语句之间的逗号不能缺;语句后面的分号
不能缺。
例如:
p(i)$(f <= 0) = -1 ;
p(i)$((f > 0) and (f < 1)) = p(i)**2 ;
p(i)$(f > 1) = p(i)**3 ;
q(j)$(f <= 0) = -1 ;
q(j)$((f > 0) and (f < 5)) = q(j)**2.5 ;
q(j)$(f > 5) = q(j)**4 ;
set i /i1*i10/
j /j1*j10/;
parameter p(i) /i1 1.3,i2 2.5,i3 8.9,i4 4.2,i5 3.5,i6 6.8,i7 0.2
i8 5.7,i9 9.2 ,i10 1.3/
q(j) /j1 4.2, j2 5.6, j3 4.5, j4 6.9, j5 7.9, j6 4.5, j7 7.2,
j8 1.7, j9 1.2, j10 4.7 /
f /7/;
p(i)$(f <= 0) = -1 ;
p(i)$((f > 0) and (f < 1)) = p(i)**2 ;
p(i)$(f > 1) = p(i)**3 ;
q(j)$(f <= 0) = -1 ;
q(j)$((f > 0) and (f < 5)) = q(j)**2.5 ;
q(j)$(f > 5) = q(j)**4 ;
display p,q,f;

或者,
set i /i1*i10/
j /j1*j10/;
parameter p(i) /i1 1.3,i2 2.5,i3 8.9,i4 4.2,i5 3.5,i6 6.8,i7 0.2
i8 5.7,i9 9.2 ,i10 1.3/
q(j) /j1 4.2, j2 5.6, j3 4.5, j4 6.9, j5 7.9, j6 4.5, j7 7.2,
j8 1.7, j9 1.2, j10 4.7 /
f /7/;
if (f <= 0,
p(i) = -1 ;
q(j) = -1 ;
elseif ((f > 0) and (f < 1)),
p(i) = p(i)**2 ;
q(j) = q(j)**2.5 ;
else
p(i) = p(i)**3 ;
q(j) = q(j)**4 ;
);
display p,q,f;
例如:
p(i)$(f <= 0) = -1 ;
p(i)$((f > 0) and (f < 1)) = p(i)**2 ;
p(i)$((f > 1)and (f<10)) = p(i)**3 ;
p(i)$(f>10) =p(i)**5 ;
q(j)$(f <= 0) = -1 ;
q(j)$((f > 0) and (f < 1)) = q(j)**2.5 ;
q(j)$(f > 1) = q(j)**4 ;

set i /i1*i10/
j /j1*j10/;
parameter p(i) /i1 1.3,i2 2.5,i3 8.9,i4 4.2,i5 3.5,i6 6.8,i7 0.2
i8 5.7,i9 9.2 ,i10 1.3/
q(j) /j1 4.2, j2 5.6, j3 4.5, j4 6.9, j5 7.9, j6 4.5, j7 7.2,
j8 1.7, j9 1.2, j10 4.7 /
f /7/;
if (f <= 0,
p(i) = -1 ;
elseif ((f > 0) and (f < 1)),
p(i) = p(i)**2 ;
elseif((f > 1)and (f<10)),
p(i) = p(i)**3 ;
else
p(i)=p(i)**5;
);

if (f <= 0,
q(j) = -1 ;
elseif ((f > 0) and (f < 1)),
q(j) = q(j)**2 ;
else
q(j) = q(j)**3 ;
);
If 语句内不能进行参数或变量声明或者定义方程。
例如:
If(s>0, eq..sum(i,x(i))=g=2);
例如:
If(s>0, Scalar y; y=5;);

四. GAMS的其它语法及注意事项:
当GAMS程式(即输入档,也就是filename.gms)被执行完成后,会自动产生一
個属出档,也就是filename.lst。
 $Title title-name:定义lst档的标题,通常写于输入档中的第一列。
 $Stitle subtitle-name:定义lst档的子标题。

 蓝色粗体字通常代表程式指令(GAMS reversed words),例如:set、


parameter、variable、equation、model、solve等,亦可在GAMS介面中
点选File→Options→Color自行设定指令的颜色。

 Semicolon (;):
通常置于每句statement的句尾,表示中止这句statement command,但要注
意中文和英文状态下的不同。

 Single line comments(有两种程序语法):


1.在GAMS程式中可插入a single line comment,但必須在每一句句首置入 *
符号,输輸出档中会会显示此comments及其行数。

2.The third style of comment allows embedding a comment within a line. It


must be enabled with the compiler option $inlinecom or $eolcom as in the following
example1:
$eolcom #
$inlinecom {}
x = 1 ; # this is a comment
y = 2 ; { this is also a comment } z = 3 ;

example2:
$eolcom //
variables x1, x2, obj;
x1.l = 10; x2.l = -10; // initial value
x1.lo =-100; x2.lo =-100; // lower bounds
x1.up = 100; x2.up = 100; // upper bounds

 Multiple line comments:


在GAMS程式中亦可插入multiple line comments,通常用于说明明此模型
的目的或摘要。程式的语法如下:
$ontext
Write your comment here
Write your comment here
Write your comment here
$offtext

 Ord运算语法:
 Ord(GAMS的语法),英文全名为order,表示次序的意思。在GAMS用法
中,則表示集合中每个元素的位置,并依序给予其一个编号。
 例如:
假设1995年台湾人口有23,000,000人且每年的人口成长率为1.5%,若以
1995年为基准年,求1995年至2005年之人口各是多少?
GAMS求解:
set t time periods / 1995*2005 /;

parameter pop(t);

pop(t) = 23000000*(1.015**(ord(t) - 1));

display pop;

求解结果:
---- 7 PARAMETER pop
1995 2.300000E+7, 1996 2.334500E+7, 1997 2.369518E+7,
1998 2.405060E+7, 1999 2.441136E+7, 2000 2.477753E+7,
2001 2.514920E+7, 2002 2.552643E+7, 2003 2.590933E+7,
2004 2.629797E+7, 2005 2.669244E+7

说明:
(1) 1995*2005表示从1995年至2005年,*在这里不是乘法之运算符号。
(2) 2005 2.669244E+7表示2005年台湾人口约有26,692,440人,
2.669244E+7 为科学记述法 2.669244 × 107。
(3) ord(1995) = 1、ord(1996) = 2、ord(1997) = 3,…,依此类推。

 Card运算语法:
 Card(GAMS的语法),英文全名为cardinal,表示基数的意思。在GAMS
用法中,则表示集合中元素的zon总个数。
 范例:承上一个范例,求集合t共有几个元素?
GAMS求解:
set t time periods / 1995*2005 /;
parameter s;
s = card(t);
display s;

求解结果:
s = 11,因为1995至2005共有11个数,表示此集合总共11元素。

五. GAMS 软件与 EXCEL 软件的联合应用

1.如何将数据从 GAMS 汇出至 Excel:

 将数据汇出至 Excel 的 GAMS 程式语法如下:

Execute_Unload 'filename.gdx', data_name;

Execute 'Gdxxrw.exe filename.gdx O = filename.xls data_type = data_name

Rng = Excel spreadsheet!';

其中第一行的程式语法是表示创造一个新的档案,副档名为gdx,后面紧

接着所要汇出数据的名称。第二行的程式语法则表示将gdx档转换成Excel

档,副档名为xls,此Excel档储存的路径会紧跟着输出档(副档名为lst)储
存的路径,其路径可在输出档结构中最后的部份---File Summary里找到。

 第二行程式语法中的O是表示output file,即一个输出的Excel档。

 要将一个或多个数据汇出至Excel spreadsheet,首先数据类型(data types)

必須很明确的告知GAMS系統,数据类型通常包括set、par、var、及equ。

 Rng表示要输入汇出数据至Excel的格式范围,注意若沒有输入此范围则以

Excel第一页表格的A1开始读写数据。

 范例:The transportation problem of linear programming

$Title The Transportation Problem of Linear Programming


Sets
i canning plants / Seattle, San-Diego /
j markets / New-York, Chicago, Detroit /;
Parameters
a(i) capacity of plant i in cases
/ Seattle 350
San-Diego 600 /
b(j) demand at market j in cases
/ New-York 325
Chicago 300
Detroit 275 /;
Table d(i,j) distance in thousands of miles
New-York Chicago Detroit
Seattle 2.5 1.7 1.8
San-Diego 2.5 1.8 1.4;

Scalar f freight in dollars per case per thousand miles /90/;

Parameter c(i,j) transport cost in 1000s of dollars per case;


c(i,j) = f*d(i,j)/1000;

Variables
x(i,j) shipment quantities in cases
z total transportation costs in 1000s of dollars;

Positive variable x;
Equations
cost define objective function
supply(i) observe supply limit at plant i
demand(j) satisfy demand at market j;
cost.. z =e= sum((i,j), c(i,j)*x(i,j));
supply(i) .. sum(j, x(i,j)) =l= a(i);
demand(j) .. sum(i, x(i,j)) =g= b(j);

Model transport /all/;

Solve transport using lp minimizing z;


Display x.l, x.m ;

Execute_Unload 'transport.gdx', c, x, z;

Execute 'Gdxxrw transport.gdx O = transport.xls par = c Rng =


Sheet1!a1:d3';

Execute 'Gdxxrw transport.gdx O = transport.xls var = x Rng =


Sheet1!a5:d7';

Execute 'Gdxxrw transport.gdx O = transport.xls var = z Rng =


Sheet1!e8';

其中c, x, z表示所汇出数据的名称,transport表示档案名称,Sheet1!a1:d3表示参

数c的数据会被GAMS系统读写至Excel第一页表格中的a1到d3,Sheet1!a5:d7'表示

变量x的数据会被GAMS系统读写至Excel第一页表格中的a5到d7,Sheet1!e8'表示

变量z的数据会被GAMS系统读写至Excel第一页表格中的e8。

2.如何将数据从 EXCEL 汇出至 GAMS 系统:

第四章 案例分析

案例一:简单的种植水平模型

农场可种植的农作物有 7 种:小麦(wheat)、苜蓿(clover)、豆类(beans)、
洋葱(onions)、棉花(cotton)、玉米(maize)、西红柿(tomato);

种植时期为:一月(Jan)、二月(Feb)、三月(Mar)、四月(Apr)、五月(May)、
六月(Jun)、七月(JUL)、八月(Aug)、九月(Sep)、十月(Oct)、十一
月(Nov)、十二月(Dec);

单位农作物产量(yield)(单位:吨/公顷):小麦 1.5;苜蓿 6.5;豆类 1;洋葱


3;棉花 1.5;玉米 2;西红柿 3;

单位农作物价格(price)(单位:美元/吨):小麦 100;苜蓿 50;豆类 200;洋


葱 125;棉花 350;玉米 70;西红柿 120;

单位农作物杂项费用(miscost)(单位:美元/公顷):小麦 10;苜蓿 35;豆类


5;洋葱 50;棉花 80;玉米 5;西红柿 50;

农场土地总规模(land)=4 公顷;可用的家庭劳动(famlab)=25 天/月;受雇工


资(owage)=3 美元/天;暂时雇佣劳动工资(twage)=4 美元;
表1 单位农作物种植的月份土地需求量(公顷)
小麦 苜蓿 豆类 洋葱 棉花 玉米 西红柿
一月 1.0 1.0 1.0 1.0 0.0 0.0 0.0
二月 1.0 1.0 1.0 1.0 0.0 0.0 0.0
三月 1.0 0.5 1.0 1.0 0.5 0.0 0.0
四月 1.0 0.0 1.0 1.0 1.0 0.0 0.0
五月 1.0 0.0 0.0 0.25 1.0 0.25 0.0
六月 0.0 0.0 0.0 0.0 1.0 1.0 0.0
七月 0.0 0.0 0.0 0.0 1.0 1.0 0.75
八月 0.0 0.0 0.0 0.0 1.0 1.0 1.0
九月 0.0 0.0 0.0 0.0 1.0 1.0 1.0
十月 0.0 0.0 0.0 0.0 1.0 0.5 1.0
十一月 0.5 0.25 0.25 0.5 0.75 0.0 0.75
十二月 1.0 1.0 1.0 1.0 0.0 0.0 0.0

表2 单位农作物种植劳动力需求量(人天/公顷)
小麦 苜蓿 豆类 洋葱 棉花 玉米 西红柿
一月 1.72 4.5 0.75 5.16 0.0 0.0 0.0
二月 0.5 1.0 0.75 5.0 0.0 0.0 0.0
三月 1.0 8.0 0.75 5.0 5.0 0.0 0.0
四月 1.0 0.0 16.0 19.58 5.0 0.0 0.0
五月 17.16 0.0 0.0 2.42 9.0 4.3 0.0
六月 2.34 0.0 0.0 0.0 2.0 5.04 0.0
七月 0.0 0.0 0.0 0.0 1.5 7.16 17.0
八月 0.0 0.0 0.0 0.0 2.0 7.97 15.0
九月 0.0 0.0 0.0 0.0 1.0 4.41 12.0
十月 0.0 0.0 0.0 0.0 26.0 1.12 7.0
十一月 2.43 2.5 7.5 11.16 12.0 0.0 6.0
十二月 1.35 7.5 0.75 4.68 0.0 0.0 0.0

问应该如何种植农作物,才能使得收益最大化?

方程:  xcropc  * landreqt , c   land


c

 xcropc  * laborreqt , c   xflabt   xtlabt 


c

famlab  xflabt   xfoutt 


xrevenue   xcropc  * yield c  * pricec 
c

xm cos t   xcropc  * mis cos t c 


c

xlab cos t   xtlabt  * twage


t

xlabearn   xfout t  * owage


t

yfarm  xrevenue  xlabearn  xlab cos t  xm cos t


xcrop ——农作物种植面积(公顷); yfarm ——农场收入(美元);
xrevenue——农作物产出价值(美元); xm cos t ——农作物杂项总费用(美元);
xlabcos t ——暂时雇佣劳动总费用(美元); xlabearn ——受雇劳动总收入(美
元);
xflabt  ——t 期家庭劳动量(天); xfoutt  ——t 期受雇劳动量(天);
xtlabt  ——t 期暂时劳动量(天)

$Title Simple Farm Level Model (DEMO1,SEQ=91)


$Stitle Crop Data

$Ontext

This is the first in a series of single farm models. This simplest


version has only 7 principal crops and 2 basic inputs, land and labor,
which are specified on a monthly basis.

Kutcher, G P, Meeraus, A, and O'Mara, G T, Agriculture Sector and Policy


Models. The World Bank, 1988.

$Offtext
Sets c crops / wheat, clover, beans, onions,
cotton, maize, tomato /
t period / jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec /

Table landreq(t,c) months of land occupation by crop (hectares)

wheat clover beans onions cotton maize tomato


jan 1. 1. 1. 1.
feb 1. 1. 1. 1.
mar 1. .5 1. 1. .5
apr 1. 1. 1. 1.
may 1. .25 1. .25
jun 1. 1.
jul 1. 1. .75
aug 1. 1. 1.
sep 1. 1. 1.
oct 1. .5 1.
nov .5 .25 .25 .5 .75 .75
dec 1. 1. 1. 1.

Table laborreq(t,c) crop labor requirements (man-days per hectare)

wheat clover beans onions cotton maize tomato


jan 1.72 4.5 .75 5.16
feb .5 1. .75 5.
mar 1. 8. .75 5. 5.
apr 1. 16. 19.58 5.
may 17.16 2.42 9. 4.3
jun 2.34 2. 5.04
jul 1.5 7.16 17.
aug 2. 7.97 15.
sep 1. 4.41 12.
oct 26. 1.12 7.
nov 2.43 2.5 7.5 11.16 12. 6.
dec 1.35 7.5 .75 4.68

$Eject
Parameters yield(c) crop yield (tons per hectare) /
wheat = 1.5, clover = 6.5, beans = 1, onions = 3
cotton = 1.5, maize = 2 , tomato = 3 /

price(c) crop prices (dollars per ton) /


wheat = 100, clover = 50, beans = 200, onions = 125
cotton = 350, maize = 70, tomato = 120 /

miscost(c) misc cash costs (dollars per hectare) /


wheat = 10, clover = 35, beans = 5, onions = 50
cotton = 80, maize = 5, tomato = 50 /;
* farm data, size labor availability etc.

Scalars land farm size (hectares) / 4. /


famlab family labor available (days per month) / 25 /
owage hire-out wage rate (dollars per day) / 3. /
twage temporary labor wage (dollars per day) / 4 /
dpm number of working days per month / 25 /

$Stitle endogenous variables and equations

Variables xcrop(c) cropping activity (hectares)


yfarm farm income (dollars)
revenue value of production (dollars)
mcost misc cash cost (dollars)
labcost labor cost (dollars)
labearn labor income (dollars)
flab(t) family labor use (days)
fout(t) hiring out (days)
tlab(t) temporary labor (days)

Positive Variable xcrop, flab ,fout, tlab

Equations landbal(t) land balance (hectares)


laborbal(t) labor balance (days)
flabor(t) family labor balance (days)
arev revenue accounting (dollars)
acost cash cost accounting (dollars)
alab labor cost accounting (dollars)
aout labor income accounting (dollars)
income income definition (dollars);

landbal(t).. sum(c, xcrop(c)*landreq(t,c)) =l= land ;

laborbal(t).. sum(c, xcrop(c)*laborreq(t,c)) =l= flab(t) + tlab(t);

flabor(t).. famlab =e= flab(t) + fout(t) ;

arev.. revenue =e= sum(c, xcrop(c)*yield(c)*price(c)) ;

acost.. mcost =e= sum(c, xcrop(c)*miscost(c)) ;

alab.. labcost =e= sum(t, tlab(t)*twage) ;

aout.. labearn =e= sum(t, fout(t)*owage) ;

income.. yfarm =e= revenue + labearn - labcost - mcost ;

Model demo1 farm labor model / all /

Solve demo1 using lp maximizing yfarm;

*********************************************************************
*********************************************************************
案例二:家庭效用最大化
商品:X1——面包(bread),价格 px1=1 美元/单位;
X2——牛奶(milk),价格 px2=2 美元/单位;
生产要素(家庭提供):z1——资本(capital),要素回报率 pz1=2 美元;
z2——劳动(labor),要素汇报率为 pz2=1 美元;
要素禀赋:资本 z1=10;劳动 z2=20
1 2
家庭效用函数: U  X 1  X 2 ( 1  0.2 ,  2  0.8 )
s.t. px1  X 1  px2  X 2  pz1  z1  pz 2  z 2
求 X 1 、 X 2 各为多少时,家庭效用最大?

$ Title A Household's Utility Max. Model in Ch. 3 (HHMAX,SEQ=274)

* Definition of the Index Sets ---------------------------------------


Set i goods /BRD bread,
MLK milk/
h factors /CAP capital,
LAB labor/;

* Definition of Parameters -------------------------------------------


Parameter alpha(i) share parameter in utility function
/BRD 0.2
MLK 0.8/;

Parameter px(i) price of the i-th good


/BRD 1
MLK 2/;

Parameter pf(h) price of the h-th factor


/CAP 2
LAB 1/;

Parameter FF(h) factor endowment


/CAP 10
LAB 20/;

* Definition of Primal/Dual Variables --------------------------------


Positive Variable X(i) consumption of the i-th good
;
Variable UU utility
;
Equation eqX(i) household demand function
obj utility function
;
* Specification of Equations ------------------------------------------

eqX(i).. X(i) =e= alpha(i)*sum(h, pf(h)*FF(h))/px(i);


obj.. UU =e= prod(i, X(i)**alpha(i));

* Defining the Model --------------------------------------------------


Model HHmax /all/;

* Solving the Model ---------------------------------------------------


Solve HHmax maximizing UU using NLP;
* ---------------------------------------------------------------------
* end of model --------------------------------------------------------
* ---------------------------------------------------------------------
*********************************************************************
*********************************************************************

案例三:非线性回归问题
已知有关变量 x 与 y 的 6 个样本观察点:
y x
1 127 -5
2 151 -3
3 379 -1
4 421 5
5 460 3
6 426 1
假设这六个样本点的曲线方程为:
Y=b1+b2*exp(b3*x)
求应用最小二乘法估计参数 b1、b2 和 b3 的值,使得曲线拟合误差最小。

$title Nonlinear Regression Problem (LEAST,SEQ=24)


$Ontext

Nonlinear least squares estimation problem of Mitcherlisch's law.

Bracken, J, and McCormick, G P, Chapter 8.4. In Selected Applications of


Nonlinear Programming. John Wiley and Sons, New York, 1968, pp. 89-90.

$Offtext

set i observation number / 1*6 /

table dat(i,*) basic data

y x
1 127 -5
2 151 -3
3 379 -1
4 421 5
5 460 3
6 426 1

variables ols ordinary least squares


dev(i) deviation
b1, b2, b3

equations dols definition of ols


ddev(i) definition of deviations
sequ single equation definition ;

dols.. ols =e= sum(i, sqr(dev(i)));

ddev(i).. dat(i,"y") =e= b1 + b2*exp(b3*dat(i,"x")) + dev(i);

sequ.. ols =e= sum(i, sqr(dat(i,"y")-b1-b2*exp(b3*dat(i,"x"))));

model least ordinary least squares / dols, ddev /


single single equ definition / sequ / ;

b1.l = 500; b2.l = -150; b3.lo = -5.0;


b3.l = - .2;
b3.up = 5.0;

solve single minimizing ols using nlp;

solve least minimizing ols using nlp;

*********************************************************************
*********************************************************************

案例四:经济最优增长 Ramsey 模型
时间期间:1990~2000;
基年(1990)年基本经济数据:基年资本存量 K0=3,基年投资 I0=0.05,基年消
费 C0=0.95,基年人口 L0=1,人口年增长率 g=0.03,资本份额 b=0.25,消费年折
扣因子 bet=0.95;投资年最高增长率 ac=0.15;K(t)>K0,C(t)>C0,I(t)>I0;
经济增长满足以下方程:
At  * K t  * *b  C t   I t  (1)
K t 1  K t   I t  K(t+1)=K(t)+I(t) (2)
g * K 2000  I 2000 (3)
2000
U  betat  * logC t 
1990
(4)

求 K t  、 I t  和 C t  为何值时,效用函数 U 取得最大值?

$Title Ramsey Model of Optimal Economic Growth (RAMSEY,SEQ=63)


$Ontext

This formulation is described in 'GAMS/MINOS: Three examples'


by Alan S. Manne, Department of Operations Research, Stanford
University, May 1986.

Ramsey, F P, A Mathematical Theory of Saving. Economics Journal (1928).

Murtagh, B, and Saunders, M A, A Projected Lagrangian Algorithm and


its Implementation for Sparse Nonlinear Constraints. Mathematical
Programming Study 16 (1982), 84-117.

The optimal objective value is 2.4875

$Offtext

*---------------------------------------------------------------------

Sets t time periods /1990*2000/


tfirst(t) first period
tlast(t) last period

*---------------------------------------------------------------------
* Data may also be entered in the form of SCALAR(S), as illustrated
* below.
*---------------------------------------------------------------------

Scalars bet discount factor /.95 /


b capital's value share /.25 /
g labor growth rate /.03 /
ac absorptive capacity rate /.15/
k0 initial capital /3.00 /
i0 initial investment /.05 /
c0 initial consumption /.95 /
a output scaling factor

Parameters beta(t) discount factor


al(t) output-labor scaling vector;

*-----------------------------------------------------------------------
tfirst(t) = yes$(ord(t) eq 1);
tlast(t) = yes$(ord(t) eq card(t));
Display tfirst, tlast;

beta(t) = bet**ord(t);
beta(tlast) = beta(tlast)/(1-bet);

*-----------------------------------------------------------------------
a = (c0+i0)/k0**b;
al(t) = a*(1+g)**((1-b)*(ord(t)-1));

Display beta, al;

Variables k(t) capital stock (trillion rupees)


c(t) consumption (trillion rupees per year)
i(t) investment (trillion rupees per year)
utility

*---------------------------------------------------------------------*
Equations cc(t) capacity constraint (trillion rupees per year)
kk(t) capital balance (trillion rupees)
tc(t) terminal condition (provides for post-terminal growth)
util discounted log of consumption: objective function ;

*---------------------------------------------------------------------*

cc(t).. al(t)*k(t)**b =e= c(t) + i(t);

kk(t+1).. k(t+1) =e= k(t) + i(t);

tc(tlast).. g*k(tlast) =l= i(tlast);


util.. utility =e= sum(t, beta(t)*log(c(t)));

*-----------------------------------------------------------------------

Model ramsey /cc, kk, tc, util/;

k.lo(t) = k0; c.lo(t) = c0; i.lo(t) = i0;

k.fx(tfirst) = k.lo(tfirst);

i.up(t) = i0*((1+ac)**(ord(t)-1));

*-----------------------------------------------------------------------

Solve ramsey maximizing utility using nlp;

*********************************************************************
*********************************************************************
案例五:OPEC 最佳定价和开采量模型
时间期间:1974~1990,以 1974 年为基年;
世界石油基本需求量: q t  1.0  2.3  1.015 t 1 ,(1974 年 t=1,1975 年 t=2,1976
年 t=3,1977 年 t=4…,)
OPEC 最佳定价和开采量模型由以下方程构成:
TDt  0.87  TDt 1  0.13  Pt  qt (1)
 CS t 7 
S t  0.75  S t 1  1.1  0.1Pt   1.02 (2)
CS t  CS t 1  S t (3)
Dt  TDt  S t ,( t  1 ) (4)
Rt  Rt 1  Dt (5)
 250 
REVt  Dt   Pt   ,( t  1 ) (6)
 Rt 
16
PROFIT   REVt  1.05 1t  ,( t  1 ) (7)
2

其中, TDt ——第 t 年的石油总需求量(开采量), TD1974  18 ;


S t ——第 t 年非 OPEC 国家的石油供给量, S1974  6.5 ;
CS t ——第 t 年非 OPEC 国家的石油累计供给量,其中 CS1974  0 ;
Dt ——第 t 年 OPEC 国家石油需求量(开采量);
Rt ——第 t 年 OPEC 石油储备量, R1974  500 ;
REVt ——第 t 年 OPEC 国家利润收入;
PROFIT ——1975~1990 年期间的总利润现值。
求各年石油价格 Pt 和开采量 Dt 各为多少时,在 1975~1990 年期间的总利润现值
profit 最大?

$Title Optimal Pricing and Extraction for OPEC (PINDYCK,SEQ=28)


$Ontext

This model finds the optimal pricing and extraction of oil for
the OPEC cartel.

Pindyck, R S, Gains to Producers from the Cartelization of


Exhaustible Resources. Review of Economics and Statistics 60
(1978), 238-251.

$Offtext

Sets t overall time horizon / 1974*1990 /


to(t) optimization period / 1975*1990 /

Parameter demand(t) equilibrium world demand for fixed prices;


demand(to) = 1. + 2.3*1.015**(ord(to)-1);

Variables p(t) world price of oil


td(t) total demand for oil
s(t) supply of oil by non-opec countries
cs(t) cumulative supply by non-opec countries
d(t) demand for opec-oil
r(t) opec reserves
rev(t) revenues in each period
profit

Positive Variables p,td,s,cs,d,r

Equations tdeq(t) total demand equation


seq(t) supply equation for non-opec countries
cseq(t) accounting equation for cumulative supply
deq(t) demand equation for opec
req(t) accounting equation for opec reserves
drev(t) yearly objective function value
tprofit total objective function;
$Double

tdeq(t-1).. td(t) =e= 0.87*td(t-1) - 0.13*p(t) + demand(t);


seq(t-1).. s(t) =e= 0.75*s(t-1) + (1.1+0.1*p(t))*1.02**(-cs(t)/7);
cseq(t-1).. cs(t) =e= cs(t-1) + s(t);
deq(to).. d(to) =e= td(to) - s(to);
req(t-1).. r(t) =e= r(t-1) - d(t);
drev(to).. rev(to) =e= d(to)*(p(to)-250/r(to));
tprofit.. profit =e= sum(to,rev(to)*1.05**(1-ord(to)));

$Single

*
* fixed initial conditions
*
td.fx("1974") = 18; s.fx ("1974") = 6.5;
r.fx ("1974") = 500; cs.fx("1974") = 0.0;

td.l(to) = 18; s.l(to)= 7; cs.l(to) = 7*ord(to);


d.l (to) = td.l(to)-s.l(to); p.l(to) = 14;

Loop(t$to(t), r.l(t) = r.l(t-1)-d.l(t) );

Display td.l, s.l, cs.l, d.l, r.l;

Model robert / all /; Solve robert maximizing profit using nlp;


*********************************************************************
*********************************************************************
案例六:工业污染控制问题
有三种工业:化学工业、钢铁工业、电子行业。
每种工业生产均排放四种污染物:COD、SO2、NOx、fwater;
表1 单位产值污染物排放量
COD SO2 NOx fwater
chemicals 0.07689 0.05767 0.05370 0.0968
Steel 0.00633 0.02361 0.089 0.0778
Elec-mach 0.00123 0.00369 0.0295 0.023

表2 其它数据
A beta K0 L0
chemicals 7.794 0.146 80134 36526
Steel 7.928 0.116 102399 31127
Elec-mach 11.146 0.151 29360 29839
A——C-D 生产函数中的全要素生产率;beta——劳动力份额参数;
K0——资本存量;L0——劳动力
各种污染排放总量最高限额:COD=0.153e6;SO2=0.12e6;NOx=fwater=0.25e6;
要求:①工业污染排放总量小于最高限额;
② 0.9 Li   K i  1.4 Li
问:当 K i 、 Li 各取何值时,使得总产值最大?

$Title Industrial Pollution Control (POLLUT,SEQ=96)

$Ontext

This is an example of planning production within certain pollution


standards.

Mangasarian, O L, Nonlinear Programming. McGraw Hill, New York, 1973.

$Offtext

Sets j sectors / food, textile, apparel, lumber, furniture, pulp+paper


printing, chemicals, coal+petro, rubber, leather
clay+stone, steel, nf-metals, metals-pr, machinery
elec-mach, transport, prec-mach, misc /
i pollutant / cod, so2, land, water /

Table w(j,i) unit load

cod so2 land water


food .08488 .00909 .02990 .07195
textile .03353 .02470 .08980 .17032
apparel .03353 .02470 .02780 .01345
lumber .00135 .00084 .06890 .01606
furniture .00153 .00084 .03500 .01429
pulp+paper .23368 .07461 .04690 .15532
printing .07609 .05767 .01290 .01850
chemicals .07689 .05767 .05370 .09680
coal+petro .03736 .01663 .27080 .02900
rubber .02794 .00456 .06040 .09200
leather .02794 .00456 .04980 .07320
clay+stone .00213 .08800 .11510 .09520
steel .00633 .02361 .08900 .07780
nf-metals .00091 .03376 .02670 .03720
metals-pr .00125 .00860 .06790 .04930
machinery .00089 .00376 .06210 .02480
elec-mach .00123 .00369 .02950 .02300
transport .00079 .00127 .07870 .04300
prec-mach .00396 .00252 .03830 .03010
misc .00931 .00252 .04240 .03500

Table z(j,*) other data

a b k k0 l0
food 9.600 .121 .1064 29406 24709
textile 6.353 .194 .1611 21375 18918
apparel 9.818 .204 .0848 8423 20636
lumber 7.371 .181 .1428 13873 10457
furniture 10.220 .171 .0955 8470 9739
pulp+paper 6.255 .145 .1759 36375 18880
printing 8.149 .304 .2190 66016 44480
chemicals 7.794 .146 .1439 80134 36526
coal+petro 8.400 .173 .1314 1327 758
rubber 9.933 .174 .0987 4414 4921
leather 11.069 .167 .0817 3709 6766
clay+stone 6.528 .192 .1665 14496 9368
steel 7.928 .116 .1448 102399 31127
nf-metals 10.559 .091 .1026 28008 1166
metals-pr 6.606 .227 .1567 69314 59525
machinery 7.153 .208 .1506 90014 63048
elec-mach 11.146 .151 .0895 29360 29839
transport 6.884 .199 .1602 27687 16945
prec-mach 6.660 .253 .1446 4009 4828
misc 7.929 .182 .1256 24323 24569

Scalars alpha / .6 /

beta / 1.4 /
gamma1 / 1.4 /, gamma2 / .9 /
Parameter tau(i) / cod .153e6, so2 .12e6, (land, water) .25e6 /;

Variables k(j) capital


l(j) labor
tk
tl
output;

Equations obj
eq4(i)
eq5a
eq5b
kdef
ldef ;

obj.. output =e= sum(j, z(j,"a")*k(j)**(1-z(j,"b"))*l(j)**z(j,"b"));

eq4(i).. sum(j, w(j,i)/z(j,"k")*k(j)) =l= tau(i);

eq5a.. tk =g= gamma2*tl;

eq5b.. tk =l= gamma1*tl;

kdef.. tk =e= sum(j, k(j));

ldef.. tl =e= sum(j, l(j));

k.lo(j) = alpha*z(j,"k0"); k.up(j) = beta*z(j,"k0"); k.l(j) = z(j,"k0");


l.lo(j) = alpha*z(j,"l0"); l.up(j) = beta*z(j,"l0"); l.l(j) = z(j,"l0");

Model one /all/;

Solve one maximizing output using nlp;


*********************************************************************
*********************************************************************

案例七:简单投资组合模型
有五种债券:市政债券 a(municip-a),市政债券 b(municip-b),公司债券
(corporate),美国 ser-e 公司债券(us-ser-e),美国 ser-f 公司债券(us-ser-f);
这些债券的相关信息如下表:
到期时间 债券收益税收
等级(rating) 收益率(yield)
(maturity) 率(tax-rate)
Municip-a 2 9 4.3%
Municip-b 5 2 4.5%
Corporate 2 15 5.4% 0.5
Us-ser-e 1 4 5.0% 0.5
Us-ser-f 1 3 4.4% 0.5

债券投资需要满足以下条件:
债券总投资额不超过 10;
corporate,us-ser-e,us-ser-f 这三种债券的投资总额大于 4;
债券投资的平均等级小于 1.4;
债券投资的平均到期时间小于 5;
在以上信息及约束条件下,求各类型的债券投资额分别为多少时,使得债券投资
收益最大?

$Title Simple Portfolio Model (PORT,SEQ=50)

$Ontext

This simple portfolio selection model examines


investment alternatives in the bond market. The selection
is constrained by rating and maturity considerations.

CDC, IFPS/OPTIMIM - Users Manual, Control Data Corporation, Minneapolis, 1984.

$Offtext

Sets b bonds / municip-a, municip-b, corporate, us-ser-e, us-ser-f /


g(b) grouping / corporate, us-ser-e, us-ser-f /

Table ydat(b,*) yield data

rating maturity yield tax-rate


municip-a 2 9 4.3
municip-b 5 2 4.5
corporate 2 15 5.4 .5
us-ser-e 1 4 5.0 .5
us-ser-f 1 3 4.4 .5

Variables investment(b)
tinvest total investment
return

Positive Variable investment

Equations groupmin minimum investment in group g


rdef rating definition
mdef maturity definition
idef total return definition
tdef total investment definition ;
$Double

tinvest.up = 10;
groupmin.. sum(g, investment(g)) =g= 4;
rdef.. sum(b, ydat(b,"rating ")*investment(b)) =l= 1.4*tinvest;
mdef.. sum(b, ydat(b,"maturity")*investment(b)) =l= 5.0*tinvest;
tdef.. tinvest =e= sum(b, investment(b));
idef.. return =e= sum(b,
ydat(b,"yield")/100*(1-ydat(b,"tax-rate"))*investment(b));

Model port / all / ;


Solve port maximizing return using lp;
*********************************************************************
案例八:贷款偿还因素问题
起初贷款 1000 元;
有三种换款期限选择:12 年期,15 年期,30 年期;
年贷款利息为 8%;
问:在这三种期限选择下,每月应各换款多少?

$Title Repayment factors for loans (REPAY,SEQ=72)

$Ontext

This sample problem computes the monthly payments for a 1000 dollar
loan to be repaid in equal installments. The monthly payment is derived
as follows.

GAMS Development Corporation, Formulation and Language Example.

p(0) = 1000
p(1) = p(0)*(1+rate)/periods - pay

p(t) = p(t-1)*(1+rate)/periods - pay = 0

where "p" is the principal outstanding at the beginning of a period and


"rate" is the annual interest rate. "periods" are the payment periods
per year. "pay" is the payment per period. The loan has to be repaid
completely after "t" payments within "years" years. The number of
payments "t" is "periods"*"years".

with sum(n, q**(ord(n)-1)) = (1-q**card(n))/(1-q) find

pay = 1000*rate/periods/(1-(1+rates/periods)**(-periods*years)).

$Offtext

set m list of maturities / 12-years, 15-years, 30-years /

Parameters rates annual rates


years(m) maturities / 12-years 12, 15-years 15, 30-years 30 /
periods payments per year
pay monthly payments for 1000 dollar loan ;
rates = .08 ;
periods = 12;
pay(m) = 1000*rates/periods
/(1-power(1+rates/periods,-periods*years(m)));
Display rates,pay;

或者
$Title Repayment factors for loans (REPAY,SEQ=72)

$Ontext

This sample problem computes the monthly payments for a 1000 dollar
loan to be repaid in equal installments. The monthly payment is derived
as follows.

GAMS Development Corporation, Formulation and Language Example.

p(0) = 1000
p(1) = p(0)*(1+rate)/periods - pay

p(t) = p(t-1)*(1+rate)/periods - pay = 0

where "p" is the principal outstanding at the beginning of a period and


"rate" is the annual interest rate. "periods" are the payment periods
per year. "pay" is the payment per period. The loan has to be repaid
completely after "t" payments within "years" years. The number of
payments "t" is "periods"*"years".

with sum(n, q**(ord(n)-1)) = (1-q**card(n))/(1-q) find

pay = 1000*rate/periods/(1-(1+rates/periods)**(-periods*years)).

$Offtext

Sets r list of rates / 1*41 /


m list of maturities / 12-years, 15-years, 30-years /

Parameters rates(r) annual rates


years(m) maturities / 12-years 12, 15-years 15, 30-years 30 /
periods payments per year
pay monthly payments for 1000 dollar loan ;

rates(r) = .08 + .00125*(ord(r)-1); periods = 12;

pay(r,"rate") = 100*rates(r);
pay(r,m) = 1000*rates(r)/periods
/(1-power(1+rates(r)/periods,-periods*years(m)));

Display pay;
*********************************************************************
********
*********************************************************************
*********************************************************************
案例九:最优增长模型
时间期间:0~20;
 ——资本存量折旧系数,   0.05 ;
r ——劳动力年增长率, r  0.025 ;
eta ——弹性系数, eta  0.9 ;
 ——CD 生产函数中的资本份额系数,   0.75 ;
z ——技术进步率, z  0.01 ;
 ——福利折旧系数,   0.03 ;
Y0 ——基年收入, Y0  4.725 ;
K 0 ——基年资本存量, K 0  15 ;
1
dist  ——折扣因子, dis t   t

1     1  eta 
At  ——全要素生产率, At   A0 1  r  1     z 
t

模型方程为:
K t  1  Y t   C t   1     K t  1

Y t   At   K t 
20 1 eta

J   dis t  1  C t  1
1

Y20  Y0  1.06 20
问,当 K t  、 C t  为何值时,福利 J 达到最大?

$Title Optimal Growth Model (CHAKRA,SEQ=43)

$Ontext

Simple one sector nonlinear optimal growth model

Kendrick, D, and Taylor, L, Numerical methods and Nonlinear Optimizing


models for Economic Planning. In Chenery, H B, Ed, Studies of
Development Planning. Harvard University Press, 1971.

Chakravarty, S, Optimum Savings with a Finite Planning Horizon.


International Economic Review 3 (1962), 338-355.

$Offtext

Sets t extended horizon / 1980*2000 /


tb(t) base period
tt(t) terminal period ;

tb(t) = yes$(ord(t)eq 1); tt(t) = yes$(ord(t) eq card(t));


Display tb,tt;

Scalars delt rate of depreciation / .05 /


beta exponent on capital / .75 /
a efficiency parameter
r labor force growth rate / .025 /
eta elasticity / .9 /
z technical progress / .01 /
rho welfare discount / .03 /
y0 initial income / 4.275 /
k0 initial capital / 15.0 /

Parameters dis(t) discount factor


alpha(t) production function parameter ;

a = y0/k0**beta;
dis(t) = (1+rho)**(1-ord(t))/(1-eta);
alpha(t) = a*(1+r*(1-beta)+z)**(ord(t)-1);
Display a, dis, alpha ;

Variables c(t) consumption


y(t) income
k(t) capital stock
j performance index

Equations kb(t) capital stock balance


yd(t) income definition
jd performance index definition ;

jd.. j =e= sum(t, dis(t-1)*c(t-1)**(1-eta));

yd(t).. y(t) =e= alpha(t)*k(t)**beta;

kb(t+1).. k(t+1) =e= y(t) - c(t) + (1-delt)*k(t);

y.l(t) = y0*(1.06)**(ord(t)-1); k.l(t) = (y.l(t)/alpha(t))**(1/beta);


c.l(t) = y.l(t) + (1-delt)*k.l(t) - k.l(t+1); display c.l, k.l, y.l;
k.lo(t) = 1; y.lo(t) = 1; c.lo(t) =1; y.fx(tb) = y.l(tb); y.fx(tt) = y.l(tt);

Model growth / all /;


Solve growth maximizing j using nlp;

Parameter report solution summary ;


report(t,"k") = k.l(t); report(t,"y") = y.l(t); report(t,"c") = c.l(t);
report(t,"s-rate") = (y.l(t)-c.l(t))/y.l(t);
Display report;
*********************************************************************
*********************************************************************
案例十:Ajax 纸业公司生产计划
Ajax 纸业公司现有三种机器可以生产出四种类型纸张,生产效率分别为:
表1 机器的生产效率(吨/小时)
Machine-1 Machine-2 Machine-3
20-bond-wt 53 52 49
25-bond-wt 51 49 44
c-bond-ext 52 45 47
tissue-wrp 42 44 40
表2 机器的生产成本(美元/吨)
Machine-1 Machine-2 Machine-3
20-bond-wt 76 75 73
25-bond-wt 82 80 78
c-bond-ext 96 95 92
tissue-wrp 72 71 70
表3 每月不同纸张的需求与价格
Demand(吨) Price(美元/吨)
20-bond-wt 30000 77
25-bond-wt 20000 81
c-bond-ext 12000 99
tissue-wrp 8000 105
这三种机器每月的可用时间分别为:
machine-1:672 小时;
machine-2:600 小时;
machine-3:480 小时。
问,如何安排生产计划,使得公司月利润达到最大化?

$Title Ajax Paper Company Production Schedule (AJAX,SEQ=60)


$Ontext

This sample model is taken from the cybernet pds/apex sample


library of models. A paper manufacturer can produce four different
types of paper on three different machines. Given a fixed demand
schedule the objective is to find a production plan that
maximizes monthly profits.

CDC, PDS/APEX Sample Model Library, 1977. Control Data Corporation

$Offtext

Sets m machines at mills / machine-1, machine-2, machine-3 /


g paper grades / 20-bond-wt, 25-bond-wt, c-bond-ext, tissue-wrp /

Table prate(g,m) production rate (tons per hour)

machine-1 machine-2 machine-3


20-bond-wt 53 52 49
25-bond-wt 51 49 44
c-bond-ext 52 45 47
tissue-wrp 42 44 40

Table pcost(g,m) production cost ($ per ton)

machine-1 machine-2 machine-3


20-bond-wt 76 75 73
25-bond-wt 82 80 78
c-bond-ext 96 95 92
tissue-wrp 72 71 70

Table dempr(g,*) demand and prices

demand price
20-bond-wt 30000 77
25-bond-wt 20000 81
c-bond-ext 12000 99
tissue-wrp 8000 105
Parameter avail(m) available machine time (hours per month) /
machine-1 672, machine-2 600, machine-3 480 /

Variables outp(g,m) production (tons per month)


profit profit ($ per month)

Positive Variable outp

Equations cap(m) machine capacity (hours per month)


dem(g) demand (tons per month)
pdef profit definition ($ per month) ;

cap(m).. sum(g, outp(g,m)/prate(g,m)) =l= avail(m);

dem(g).. sum(m, outp(g,m)) =e= dempr(g,"demand");

pdef.. profit =e= sum(g, dempr(g,"demand")*dempr(g,"price"))


- sum((g,m), pcost(g,m)*outp(g,m));

Model ajax /all/;


Solve ajax using lp maximizing profit;

$Stitle report definitions

Parameter mtr(m,*) machine time report


par(g,*) production allocation report ;

mtr(m,"avail-h") = avail(m); mtr(m,"used-h") = cap.l(m);


mtr(m,"unused-h") = avail(m) - cap.l(m);
mtr(m,"marginal") = - cap.m(m);

par(g,"demand") = dempr(g,"demand"); par(g,"sold") = dem.l(g);


par(g,"unsold") = dempr(g,"demand") - dem.l(g);
par(g,"marginal") = dem.m(g);

Display mtr, par , outp.l, outp.m ;


*********************************************************************
*********************************************************************
案例十一:基本生产和库存模型
已知某厂家用两种原料(raw1 和 raw2)生产三种产品(product1、product2 和
product3)
时间期间:1~3。
表1 每个产品的生产投入系数
Product1 Product2 Product3
Raw1(unit) 5 3 1
Raw2(unit) 1 2 3
表2 不同时期每个产品的生产利润($)
T=1 T=2 T=3
Product1 25 20 10
Product2 50 50 50
Product3 75 80 100
表3 其它相关数据
Raw1(unit) Raw2(unit)
最大库存量(Max-stock) 400 275
储藏成本(storage-c)$ 0.5 2
剩余价值(res-value)$ 15 25
另外满足:每期产品总个数最大值为 40;库存量始终大于零;
问:如何安排生产计划,使得生产总利润和剩余原料价值之和最大化?

$Title Elementary Production and Inventory Model (ROBERT,SEQ=37)

$Ontext

A manufacturer can produce three different products requiring the


storage of two raw materials. Expected profits change over time and
remaining raw materials are valued.

Fourer, R, Modeling Languages versus Matrix Generators For Linear


Programming. ACM Transaction of Mathematical Software 9, 2 (1983),
143-183.

$Offtext

Sets p products / low, medium, high /


r raw materials / scrap, new /
tt long horizon / 1*4 /
t(tt) short horizon / 1*3 /
Table a(r,p) input coefficients

low medium high


scrap 5 3 1
new 1 2 3

Table c(p,t) expected profits

1 2 3
low 25 20 10
medium 50 50 50
high 75 80 100

Table misc(*,r) other data

scrap new
max-stock 400 275
storage-c .5 2
res-value 15 25

Scalar m maximum production / 40 /;

Variables x(p,tt) production and sales


s(r,tt) opening stocks
profit

Positive variables x, s;

Equations cc(t) capacity constraint


sb(r,tt) stock balance
pd profit definition ;

cc(t).. sum(p, x(p,t)) =l= m;

sb(r,tt+1).. s(r,tt+1) =e= s(r,tt) - sum(p, a(r,p)*x(p,tt));

pd.. profit =e= sum(t, sum(p, c(p,t)*x(p,t))-sum(r, misc("storage-c",r)*s(r,t)))


+ sum(r, misc("res-value",r)*s(r,"4"));
s.up(r,"1") = misc("max-stock",r);

Model robert / all /

Solve robert maximizing profit using lp;


*********************************************************************
*********************************************************************
案例十二:Robust 最优化问题

$title Robust Optimization (ROTDK,SEQ=185)


$Ontext

Robust Optimization

Laguna, M, Applying Robust Optimization to Capacity Expansion of


One Location in Telecommunications with Demand Uncertainty.
Management Science 44, 11 (1998), 101-110.

$Offtext

SETS s scenarios / 1*1000/


t time periods / t1*t12 /
j components / C001*C010 /

alias(t,tt);

PARAMETERS
di(s,t) increment
D(t,s) demand
c(j) capacity size
p(j) capacity cost
mu mean capacity parameter
sigma std capacity parameter;

mu = 100; sigma = 10;

c(j) = round(uniform(1,mu));
p(j) = round(mu + c(j) + uniform(-sigma,sigma));
di(s,t)$(ord(s) <= 0.25*card(s)) = round(normal( 50,10));
di(s,t)$(ord(s) > 0.25*card(s) and ord(s) <= 0.75*card(s))
= round(normal(100,20));
di(s,t)$(ord(s) > 0.75*card(s)) = round(normal(150,40));

d(t,s) = sum(tt$(ord(tt) <= ord(t)), di(s,tt));


*display c,p,di,d;

parameters dis(t) discount factor


w shortage penalty;

dis(t) = power(.86,ord(t)-1);
w = 5;

variables x(j,t) expansion


z(s) max capacity shortage
cap(t) installed capacity
obj;

integer variable x; positive variable z;

equations capbal(t) capacity balance


dembal(t,s) demand balance
objdef;

objdef.. obj =e= sum((j,t), dis(t)*p(j)*x(j,t))


+ w/card(s)*sum(s, z(s));

capbal(t).. cap(t) =e= cap(t-1) + sum(j, c(j)*x(j,t));

dembal(t,s).. cap(t) + z(s) =g= d(t,s);

model rotdk / all /;

option optcr=0.05,limcol=0,limrow=0;

solve rotdk min obj us mip;


*********************************************************************
*********************************************************************
案例十三、$title MathOptimizer Example 1 (MATHOPT1,SEQ=255)
* A simple example model that illustrates the formulation structure for
* using LGO in the Mathematica environment.
*
* More information at
* http://www.wolfram.com/products/applications/mathoptimizer/
*
* Mathematica, MathOptimizer - An Advanced Modeling and Optimization System
* for Mathematica Users,
* http://www.wolfram.com/products/applications/mathoptimizer/
* Janos D Pinter, Global Optimization in Action, Kluwer Academic Publishers,
* Dordrecht/Boston/London, 1996.
*
* Janos D Pinter, Computational Global Optimization in Nonlinear Systems,
* Lionheart Publishing, Inc., Atlanta, GA, 2001
*
$eolcom //

variables x1, x2, obj;

x1.lo = -10; x2.lo = -15; // lower bounds


x1.l = 8; x2.l = -14; // initial value
x1.up = 20; x2.up = 20; // upper bounds

equations objdef, eqs, ineqs;

objdef.. obj =e= 10*sqr(sqr(x1) - x2) + sqr(x1 - 1);

eqs .. x1 =e= x1*x2;

ineqs.. 3*x1 + 4*x2 =l= 25;

models m / all /;

* x1.l = 1; x2.l = 1; // optimal values

solve m minimizing obj using nlp;

parameter report solution summary report;


report('x1','global') = 1;
report('x2','global') = 1;
report('x1','solver') = x1.l;
report('x2','solver') = x2.l;
report('x1','diff') = report('x1','global') - report('x1','solver');
report('x2','diff') = report('x2','global') - report('x2','solver');

display report;
*********************************************************************
*********************************************************************
案例十四、$title MathOptimizer Example 2 (MATHOPT2,SEQ=256)
* The following is still a fairly simple constrained model which has
* two variables, two equality and two inequality constraints.
* The optimum value is zero at the vector x = 0.
*
* More information at
*http://www.wolfram.com/products/applications/mathoptimizer/
*
*
* Mathematica, MathOptimizer - An Advanced Modeling and Optimization System
* for Mathematica Users,
*http://www.wolfram.com/products/applications/mathoptimizer/
*
* Janos D Pinter, Global Optimization in Action, Kluwer Academic Publishers,
* Dordrecht/Boston/London, 1996.
*
* Janos D Pinter, Computational Global Optimization in Nonlinear Systems,
* Lionheart Publishing, Inc., Atlanta, GA, 2001

$eolcom //

variables x1, x2, obj;

x1.l = 10; x2.l = -10; // initial value


*x1.lo =-100; x2.lo =-100; // lower bounds
*x1.up = 100; x2.up = 100; // upper bounds

equations objdef, eq1, eq2, ineq1, ineq2;

objdef.. obj =e= sqr(2*sqr(x1) - x2) + sqr(x2 - 6*sqr(x1));


eq1.. x1 =e= 10*x2 + x1*x2 ;
eq2.. x1 =e= 3*x2 ;

ineq1.. x2 + x1 =l= 1;
ineq2.. x2 - x1 =l= 2;

models m / all /;

solve m minimizing obj using nlp;

parameter report diff from global solution;

report('x1') = round(0 - x1.l,6);


report('x2') = round(0 - x2.l,6);

Display report;
*********************************************************************
*********************************************************************
案例十五、 $title MathOptimizer Example 3 (MATHOPT3,SEQ=257)
* A larger example with several constraints.
*
* More information at
*http://www.wolfram.com/products/applications/mathoptimizer/
*
*
* Mathematica, MathOptimizer - An Advanced Modeling and Optimization System
* for Mathematica Users,
*http://www.wolfram.com/products/applications/mathoptimizer/
*
* Janos D Pinter, Global Optimization in Action, Kluwer Academic Publishers,
* Dordrecht/Boston/London, 1996.
*
* Janos D Pinter, Computational Global Optimization in Nonlinear Systems,
* Lionheart Publishing, Inc., Atlanta, GA, 2001
*
variables x1, x2, x3, x4, x5, x6, obj;
equations defobj,eq1,eq2,eq3,eq4,ineq1,ineq2,ineq3;

defobj.. obj =e= sqr(x1 + x2) + sqr(x3 - x5) + sqr(x6 - x4)


+ 2*sqr(x1 + x3 - x4) + sqr(x2 - x1 + x3 - x4)
+ 10*sqr(Sin[x5 - x6 + x1]);
eq1.. sqr(x1) - Sin[x2] - x4 + x5 + x6 =e= 0;
eq2.. x1*x3 - x2*x4*x1 - x5 - Sin[x6 - x1 - x3] =e= 0;
eq3.. x2*x6*Cos[x5] - Sin[x3*x4] + x2 - x5 =e= 0;
eq4.. x1*x2 -sqr(x3) - x4*x5 - sqr(x6) =e= 0;

ineq1.. 2*x1 + 5*x2 + x3 + x4 -1 =l= 0;


ineq2.. 3*x1 - 2*x2 + x3 - 4*x4 =l= 0;
ineq3.. x1 + x2 + x3 + x4 + x5 + x6 - 2 =l= 0;

model m / all /;

* most local solvers will find the global solution from this starting point
* x1.l= 1; x2.l= -2; x3.l= 1; x4.l= 2; x5.l= 1; x6.l= -1;
* solve m us nlp min obj;

x1.l=10; x2.l=-10; x3.l=10; x4.l=10; x5.l=10; x6.l=-10;

solve m us nlp min obj;

parameter report diff from global solution;

report('x1') = round(0 - x1.l,6);


report('x2') = round(0 - x2.l,6);
report('x3') = round(0 - x3.l,6);
report('x4') = round(0 - x4.l,6);
report('x5') = round(0 - x5.l,6);
report('x6') = round(0 - x6.l,6);

Display report;
*********************************************************************
*********************************************************************

案例十六、$title Stochastic Programming Example (PRODSP,SEQ=186)


$ontext
The problem consists of determining the product mix for a furniture shop with two
workstations: carpentry and finishing. The availability of labor in man-hours at
the two stations is limited. There are four product classes, each consuming a
certain number of man-hours at the two stations. Each product earns a certain
profit and the shop has the option to purchase labor from outside. The objective
is to maximize the profit.
King, A J, Stochastic Programming Problems: Examples from the
Literature. In Ermoliev, Y, and Wets, R J, Eds, Numerical
Techniques for Stochastic Optimization Problems. Springer Verlag,
1988, pp. 543-567.

$offtext

Sets i product class / class-1*class-4 /


j workstation / work-1 *work-2 /
s Nodes / s1*s300 /

Parameters c(i) profit / class-1 12,class-2 20, class-3 18, class-4 40 /


q(j) cost / work-1 5, work-2 10 /
h(j,s) available labor
t(j,i,s) labor required

table trand(j,*,i) min and max values


class-1 class-2 class-3 class-4
work-1.min 3.5 8 6 9
work-1.max 4.5 10 8 11
work-2.min .8 .8 2.5 36
work-2.max 1.2 1.2 3.5 44 ;

t(j,i,s) = uniform(trand(j,'min',i),trand(j,'max',i));

h('work-1',s) = normal(6000,100);
h('work-2',s) = normal(4000, 50);

Variables EProfit expected profit


x(i) products sold
v(j,s) labor purchased
positive variable x,v

Equations obj expected cost definition


lbal(j,s) labor balance;

obj.. EProfit =e= sum(i, c(i)*x(i)) - 1/card(s)*sum((j,s), q(j)*v(j,s));


Equation foo(i) dummy stage 0 constraint for OSLSE;
foo(i).. x(i) =g= 0;

lbal(j,s).. sum(i, t(j,i,s)*x(i)) =l= h(j,s) + v(j,s);

model mix / all /;

mix.solprint$(card(s) > 10) = 2;

solve mix using lp maximizing eprofit;

display eprofit.l,x.l;
*********************************************************************
*********************************************************************

案例十七、$Title Social Accounting Matrix Balancing Problem (SAMBAL,SEQ=77)

$Ontext

A Social Accounting Matrix captures all the circular flows in an


economy and is called balanced if the row total equal the column
totals. A sample problem illustrates the use of Nonlinear Programming
to balance such matrices.

Zenios, S A, Drud, A S, and Mulvey, J, Balancing some large Social


Accounting Matrices with Nonlinear Programming. Tech. rep.,
Department of Civil Engineering, Princeton University, 1986.

$Offtext

Set i accounts / lab, h1, h2, p1, p2 / ; alias (i,j);

Table xb(i,j) original estimate

lab h1 h2 p1 p2
lab 15 3 130 80
h1 na
h2 na
p1 15 130 20
p2 25 40 55

Parameter tb(i) original totals / lab 220, (h1,h2) na, p1 190, p2 105 /
tw(i) wights for totals
xw(i,j) weights for cells;

tw(i) = 1; tw(i)$(mapval(tb(i)) eq mapval(na)) = 0;


xw(i,j) = 1$xb(i,j); xw(i,j)$(mapval(xb(i,j)) eq mapval(na)) = 0;

Display tw, xw;


Variables x(i,j) estimated cells
t(i) estimated totals
dev deviations;

Equations rbal(i) row balance


cbal(j) column balance
devsqr definition of square deviations;

rbal(i).. t(i) =e= sum(j$xb(i,j), x(i,j));

cbal(j).. t(j) =e= sum(i$xb(i,j), x(i,j));

devsqr.. dev =e= sum((i,j)$xw(i,j), xw(i,j)*sqr(xb(i,j) - x(i,j))/xb(i,j))


+ sum(i$tw(i), tw(i)*sqr(tb(i) - t(i))/tb(i));

Model bal / all /;

x.l(i,j) = xb(i,j)$xw(i,j); t.l(i) = tb(i)$tw(i);

Solve bal using nlp minimizing dev;


*********************************************************************
*********************************************************************
案例十八、简单 CGE 模型

$ Title A Simple CGE Model in Ch. 5 (SPLCGE,SEQ=275)

* Definition of sets for suffix ---------------------------------------


Set u SAM entry /BRD, MLK, CAP, LAB, HOH/
i(u) goods /BRD, MLK/
h(u) factor /CAP, LAB/;
Alias (u,v), (i,j), (h,k);
* ---------------------------------------------------------------------

* Loading data --------------------------------------------------------


Table SAM(u,v) social accounting matrix
BRD MLK CAP LAB HOH
BRD 15
MLK 35
CAP 5 20
LAB 10 15
HOH 25 25
;
* ---------------------------------------------------------------------

* Loading the initial values ------------------------------------------


Parameter X0(i) household consumption of the i-th good
F0(h,j) the h-th factor input by the j-th firm
Z0(j) output of the j-th good
FF(h) factor endowment of the h-th factor
;

X0(i) =SAM(i,"HOH");
F0(h,j) =SAM(h,j);
Z0(j) =sum(h, F0(h,j));
FF(h) =SAM("HOH",h);
Display X0, F0, Z0, FF;
* Calibration ---------------------------------------------------------

Parameters alpha(i) share parameter in utility function


beta(h,j) share parameter in production function
b(j) scale parameter in production function
;
alpha(i)=X0(i)/sum(j, X0(j));
beta(h,j)=F0(h,j)/sum(k, F0(k,j));
b(j) =Z0(j)/prod(h, F0(h,j)**beta(h,j));
Display alpha, beta, b;
* ---------------------------------------------------------------------

* Defining model system -----------------------------------------------


Variable X(i) household consumption of the i-th good
F(h,j) the h-th factor input by the j-th firm
Z(j) output of the j-th good
px(i) demand price of the i-th good
pz(j) supply price of the i-th good
pf(h) the h-th factor price

UU utility [fictitious]
;

Equation eqX(i) household demand function


eqpz(i) production function
eqF(h,j) factor demand function
eqpx(i) good market clearing condition
eqpf(h) factor market clearing condition
eqZ(i) price equation

obj utility function [fictitious]


;

eqX(i).. X(i) =e= alpha(i)*sum(h, pf(h)*FF(h))/px(i);


eqpz(j).. Z(j) =e= b(j)*prod(h, F(h,j)**beta(h,j));
eqF(h,j).. F(h,j) =e= beta(h,j)*pz(j)*Z(j)/pf(h);
eqpx(i).. X(i) =e= Z(i);
eqpf(h).. sum(j, F(h,j)) =e= FF(h);
eqZ(i).. px(i) =e= pz(i);

obj.. UU =e= prod(i, X(i)**alpha(i));


* ---------------------------------------------------------------------

* Initializing variables ----------------------------------------------


X.l(i) =X0(i);
F.l(h,j)=F0(h,j);
Z.l(j) =Z0(j);
px.l(i) =1;
pz.l(j) =1;
pf.l(h) =1;
* ---------------------------------------------------------------------

* Setting lower bounds to avoid division by zero ----------------------


X.lo(i) =0.001;
F.lo(h,j)=0.001;
Z.lo(j) =0.001;
px.lo(i)=0.001;
pz.lo(j)=0.001;
pf.lo(h)=0.001;
* ---------------------------------------------------------------------
pf.fx("LAB")=1;

* Defining and solving the model --------------------------------------


Model splcge /all/;
Solve splcge maximizing UU using nlp;
* ---------------------------------------------------------------------
The Fifth Chapter The Simple CGE Model
In this chapter, we develop the simplest possible CGE Model, which
includes one household, two firms, two goods (breast and milk) and two
factors (capital and labor). As all the CGE models used for empirical
policy analysis are extensions of this simple CGE model, it is vitally
important to understand how the model is build and what implications
can be derived from the equilibrium of the model.
5.1 Household behavior
The household activity aims to choose the consumption of bread and milk,
in order to maximize its utility, based on sell all of its endowed factors to
the firm to earn income. To simplify the notation, capital and labor are
abbreviated as CAP and LAB. The household expands its factor income
on the consumption of bread and milk, which are also abbreviated as
BRD and MLK. It is assumed that the utility function is the
Cobb-Douglas type. At this stage, prices of goods and factors are
assumed to be given in the household utility maximization problem.
The household maximizes its subject to its budge consumption in the
following manner:
max imize UU   X i i
i
x
Subject to p i  X i   phf  FF f
i h

Where : i :Goods (BRD, MLK),


h : Factors (CAP, LAB),
UU : Utility,
X i : Consumption of the i-th goods ( X i  0 )
FFh : Endowments of the h-th factor for the household,
pix : Demand price of the i-th good ( pix  0 ),
p hf : Price of the h-th factor ( p hf  0 ),
 i : share parameter in the utility function ( 0   i  1 ,   i  1 ),
i

To solve this problem analytically, les us employ the Lagrange multiplier


method. With a Lagrange multiplier  , the Lagrangian is defined as
follows:
 
L X i ,     X i i     p hf  FFh   p ix  X i 
i  h i 
As this problem with a Cobb-Douglas specification usually has an interior
solution, the first-order optimality conditions are:
L
X i
i

 i i    pix  0 2.c
X i Xi
L
  p hf  FFh   p ix  X i  0 2.d
 h i

Eliminating the Lagrange multiplier  by solving the system (2.c)-(2.d)


for the demand X i , we obtain the demand function for the i-th goods:
i f
Xi 
pix
p
h
h  FFh 2.1

The derived demand function 2.1 implies that the demand for the i-th
goods X i increases with a declined of its price pix ,or with an increase
of income  p hf  FFh .
h

**********derivation of household demand functions**************


The first-order condition (2.c) derived from the “household utility
maximization model” in section 2.2 can be rewritten as follows:
L
X i
i

UU
 i i
   p ix   i    p ix  0
X i Xi Xi
Let us consider a two-goods case. Eliminating the Lagrange multiplier
 ,we can merge the above equations for the two goods BRD and MLK
to obtain:
 BRD UU  UU
x
  MLK
x

p BRD X BRD p MLK X MLK
Eliminating UU and rearrange the above equation, we get:
x  x
p BRD  X BRD  BRD p MLK  X MLK
 MLK
Recall the first-order condition(2.d):
L
  p hf  FFh   pix  X i  0
 h i

x  BRD x
Replacing p BRD  X BRD with p MLK  X MLK ,we can transfer (2.d) for
 MLK
f    x
i  MLK as follows: p h  FFh  1  BRD  p MLK  X MLK
h   MLK 
Because  i  1 ,we get (2.1) for MLK; similarly, we get (2.1) for
i

BRD.
***********************************************************

5.2 Firm behavior


This economy has two representative firms; one produces bread and the
other milk. each firm uses only capital and labor to produce bread or milk,
and id supposed to maximize its profits subject to the given production
technology.
Let us formulate the j-th firm’s behavior. It is assumed to maximize its
profits subject to its production technology constraint under given output
and input prices as follows:
max imize  j  p Zj  Z j   p hf  Fh , j
h
Z j , Fh , j

Subject to Z j  b j  Fh , hj , j (2.2)
h

Where: j : firm (BRD,MLK),


h : Factor (CAP, LAB),
 j : Profit of the j-th firm,
Z j : Output of j-th firm,
Fh , j : The h-th factor used by the j-th firm,
p Zj : Supply price of the j-th good,
p hf : Price of the h-th factor,
 h, j : Share coefficient in the production function ( 0   h , j  1 ,   h, j  1 ),
h

b j : scaling coefficient in the production function.


To solve this optimization problem for the j-th firm, we again employ the
Lagrange multiplier method with the Lagrange multiplier  j as follows:
   
L j Z j , Fh , j ;  j    p Zj  Z j   p hf  Fh, j    j  b j  Fh , hj , j  Z j 

 h   h 
Usually, this problem with a Cobb-Douglas specification has an interior
solution. The first-order conditions for j-th firm optimization problem are:
L j
 p Zj   j  0
Z j

b j  Fh , hj , j
L j
  p hf   j  h, j h
0
Fh , j Fh, j
L j 
 b j  Fh , hj , j  Z j  0
 j h

Eliminating the Lagrange multiplier  j by solving this system for the


demand for the h-th factor by the j-th firm Fh , j ,we obtain the following
demand function:
 h, j
Fh, j  p Zj  Z j (2.3)
p hf
The interpretation of this factor demand function is similar to that of the
household demand function for goods in (2.1).demand for the h-th factor
input by the j-th firm increases when either the h-th factor price p hf falls,
the supply price of the j-th goods price, or the production of the j-th
goods Z j increases. The share parameter  h, j plays an important role in
determining demand for the h-th factor input for production of the j-th
good; in other words, the larger the parameter  h, j is, the more sensitive
demand is to change in the other variable.

5.3 Market-clearing conditions


To ensure the market equilibrium of each good and factor in terms of
quantity and price, we need to impose the following market-clearing
conditions:
X i  Zi 2.4
 Fh,i  FFh 2.5
i

p iz  p ix 2.6
Equation (2.4) is the market-clearing condition for the i-th goods,which
ensures equality of its demand and supply quantities.
Equation (2.5) is the market-clearing condition for factors indicating that
the total demand for each factor must be equal to its given endowments.
The last equation (2.6) is the market-clearing condition that equates the
firm’s supply price to the corresponding demand price for the household.
Since no indirect tax, there should be no gap between the supply and
demand prices.
The simultaneous equations (2.1)-(2.6) consist a system of a general
equilibrium. This system includes 6 sets/14 equations (generally speaking
4i+h×j+h equations) and the same number of endogenous variables.
i f
Xi 
p x p h
h  FFh (2.1)
i

Z j  b j  Fh , hj , j (2.2)
h

 h, j
Fh, j  f
p Zj  Z j (2.3)
p h

X i  Zi (2.4)
F h ,i  FFh (2.5)
i

p iz  p ix (2.6)
In concluding our discussion of the simple CGE model, we confirm
the zero-profit condition for competitive firms.
So max imize  j  p Zj  Z j   p hf  Fh , j  0 ,
h

f
We get p h  Fh ,i  p iZ  Z i (2.7)
h

5.4 The Social Accounting Matrix


As discussed above, CGE model are used to analyze economic activities,
which including production behavior (productor), consumption behavior
(household/resident), government behavior (tax and transfer payment),
international trade(import and export). These complex society economic
activities are simplified into SAM.
The SAM is written in a matrix-form table. The agents specified above
are used as both row labels and column labels. (Thus, the matrix is
square).the entries in a SAM indicate flows of goods and service from the
agents listed in the rows to the counterpart agents listed in the columns.
The corresponding payment (or the flows of funds) is made in the
opposite direction. (Resembling I-O).

Table 1 SAM for the simple CEG Model


Final
Activity Factor Total
demand
BRD MLK CAP LAB HOH
BRD 15 15
Activity
MLK 35 35
CAP 5 20 25
Factor
LAB 10 15 25
Final
HOH 25 25 50
demand
Total 15 35 25 25 50
Unit: Yuan

Table 2 SAM for the standard CGE Model


Indirect
Activity Factor Final Demand External Total
Tax
BRD MLK CAP LAB IDT TRF HOH GOV INV EXE
BRD 21 8 20 19 16 8 92
Activity
MLK 17 9 30 14 15 4 89
Factor CAP 20 30 50
LAB 15 25 40
Indirect IDT 5 4 9
Tax TRF 1 2 3
HOH 50 40 90
Final
GOV 9 3 23 35
Demand
INV 17 2 12 31
External EXT 13 11 24
Total 92 89 50 40 9 3 90 35 31 24

5.5 Value, price and quantity


As data in the SAM are expressed only in terms of value, we have to
separate the value data of the SAM into quantity data and price data for
purpose of calibration. Consider the following self-evident equation:
Value=Price × Quantity
If price data are available, quantity data can be extracted immediately.
However, we cannot collect price data for all sectors that the SAM
covers.
Consider this issue from another viewpoint. Price is the unit value of
goods, while conventional units are defined in various ways, such as
Yuan per 100g, US dollar per car, and so on. in place of these
conventional unit of measurement ,we defined a new physical unit that is
worth one Yuan or dollar. So, redefining the physical unit of goods in this
way, all the prices become unity. By setting all the prices at unity, the
following holds:
Value = 1 × Quantity
Given the value data of the SAM, we can immediately obtain quantity
data. In other words, values in the SAM can be now considered as
quantity figures.
A little attention is needed when indirect taxes are incorporated in the
model. We have to modify the above-mentioned process slightly. Having
computed the indirect tax rates beforehand, the equation becomes:
Tax_inclusive Value
=(1+Indirect Tax Rate)×Tax_exclusive Price ×Quantity
When the tax exclusive price is set at unity using the same logic, we can
compute the quantity.
5.6 The basic concept of Calibration
Just according to the SAM, we cannot apply standard econometric
methods, because we usually have a limited number of observations but a
large number of coefficients and exogenous variables to estimate in CGE
model. This leads to insufficient degrees of freedom if econometrics
methods are applied. To overcome this problem, we employ a unique
estimation method called “calibration”.
Calibration is a method to “solve” unknown parameters by pinning down
the endogenous variables at the values in some known equilibrium
observed in the SAM. (Let us call the equilibrium depicted by the SAM
the initial equilibrium).
For example: TARIFFi  rmi  M i
TARIFFi 0
rmi 
M i0
(the TARIFFi 0 and M i0 is the initial equilibrium value in the SAM )
5.7 Calibration procedure –the case without indirect taxes
To demonstrate the calibration process, we use the simple CGE model
consisting of (2.1)-(2.6) shown above. There are three coefficients and an
exogenous variable to be estimated: the expenditure share coefficient in
the utility function  i ,the input share coefficient in the production
function  h, j ,the scaling coefficient in the production function b j ,and the
factor endowments FFh .
Just discussed above, these coefficients and exogenous variables must be
estimated by exploiting data in the SAM in table 1.
Table 1 SAM for the simple CEG Model
Final
Activity Factor Total
demand
BRD MLK CAP LAB HOH
BRD 15 15
Activity
MLK 35 35
Factor CAP 5 20 25
LAB 10 15 25
Final
HOH 25 25 50
demand
Total 15 35 25 25 50

i, j h, k p hf 0  Fh0, j p hfo  FFh p ix 0  X i0


(1) Estimating expenditure share coefficients in the utility function
Recall the utility maximization problem consisting of (2.a) and (2.b), its
first-order condition lead to the demand function:
i f
Xi 
pix
p
h
h  FFh (2.1)

As this equation is also supposed to hold in the initial equilibrium, we


also have:
i
X i0  x0 p h
f0
 FFh
p i h

Rearranging it for  i , we get:


pix 0  X i0
i  f0
p
h
h  FFh

Replacing the denominator on the right-hand side with total expenditure


using the household budget constraint (2.b) evaluated at the initial
equilibrium as follows:
x0
p i  X i0   p hf 0  FFh
i h

p ix 0  X i0
We get:  i  5.1
 pix 0  X i0
i

As the initial equilibrium values of all the endogenous variables on the


right-hand side in (5.1) can be retrieved from the “Activity-HOH” cell in
the SAM (table 1).we can calibrate the expenditure coefficient  i .
1  15 15
 BRD    0.300
1  15  1  35 50
1  35 35
 MLK    0.700
1  15  1  35 50
(2) Estimating input share and scaling coefficients in the production
function
Recall the production function (2.2) and the factor demand function (2.3):

Z j  b j  Fh , j h, j
(2.2)
h

 h, j
Fh, j  p Zj  Z j (2.3)
p hf
As these equations are also supposed to hold in the initial equilibrium, we
also have:
0
Z 0j  b j  Fh , j h , j
h

 h, j
Fh0, j  p Zj 0  Z 0j
p hf 0
Rearranging the factor demand function with the initial equilibrium, we
p hf 0  Fh0, j
get:  h, j 
p Zj 0  Z 0j
The value of p Zj 0  Z 0j is not explicitly shown in the SAM. However,
considering the zero-profit condition(2.7) also evaluated at the initial
equilibrium:
p Zj 0  Z 0j   p hf 0  Fh0, j
h
f0
We can replace the denominator of that equation with p h  Fh0, j to
h
f0 0
p h F h, j
obtain:  h , j  f0
p h  Fh0, j
h

After estimating the input share coefficient  h, j ,we can estimate the
scaling coefficient b j from the production function(2.2),we immediately
Z 0j
obtain: b j  h , j 0
F
h
h, j

According to the SAM (table 1), we can get:


1 5 1 1  10 2
 CAP , BRD    0.333 ;  LAB , BRD    0.667
1  5  1  10 3 1  5  1  10 3
1  20 4 1  15 3
 CAP ,MLK    0.571 ;  LAB , MLK    0.429
1  20  1  15 7 1  20  1  15 7
15 35
bBRD  1 3 23
 1.890 ; bMLK  4 7  1.980
5  10 20  15 3 7
(3) Estimating factor endowments
The factor endowments are exogenous variable, which can be retrieved
directly from the SAM in table 1.
With the market-clearing condition for factors (2.5) evaluated at the
initial equilibrium as follows: FFh   Fh0, j , As the uses of factors by
j
0
sectors F h, j are in the “factor’-“Activity” cells of the SAM, the
endowments of capital and labor are:
FF CAP  5  20  25
FF LAB  10  15  25

5.8 GAMS programming


Explain/interpret the gams programming Splcge.gms
Pay attention to:
(1) uses of lower bounds
If the price becomes zero in the equilibrium or during the numerical
computation process, a computational error may occur because of
division by zero. To avoid such an error, we set artificial lower bounds on
the endogenous variables at an arbitrary level for computational
convenience.
(2) choice of numeraire
According to the Walras’s law, one of the equations in system is
redundant, thus, we must choose one good or one factor as a numeraire
and fix its price. Then, all other prices are expressed as relatively price in
terms of the numeraire.therefore, it should be noted that we cannot solve
absolute prices but only relative prices with CGE model.
In this model, the price of labor is chosen as the numeraire price and is
fixed at unity by using the suffix “.fx” in line 93.
Regarding the GAMS syntax, we should note when we use the suffix“.fx”
to fix endogenous variables, this statement must be placed after the
statement regarding their lower or upper bounds. this is because the
suffixes of “.fx”, “.lo” and “.up” override others places in the previous
lines.

The sixth Chapter The Standard CGE Model


The “simple CEG model” is equipped with only the essential features of a
very basic macroeconomic model, and thus it cannot be used fro
empirical analysis. Here, we extend the model by incorporating the
following four features.
First, we introduce intermediate inputs into the production process.
Second, we introduce a government into the model, where its
consumption, direct taxes, indirect taxes and import tariffs, are
considered.
Third, we also introduce investment and savings.
Finally, we extend the model to an open economy model, where
international trade is considered.
We call this model the “standard CGE Model”, whose social accounting
matrix(SAM) is previously shown in table 2
Table 2 SAM for the standard CGE Model
Indirect
Activity Factor Final Demand External Total
Tax
BRD MLK CAP LAB IDT TRF HOH GOV INV EXE
BRD 21 8 20 19 16 8 92
Activity
MLK 17 9 30 14 15 4 89
Factor CAP 20 30 50
LAB 15 25 40
Indirect IDT 5 4 9
Tax TRF 1 2 3
HOH 50 40 90
Final
GOV 9 3 23 35
Demand
INV 17 2 12 31
External EXT 13 11 24
Total 92 89 50 40 9 3 90 35 31 24
Overview of the standard CEG model
Utility
UU
6. Utility
(Cobb-Douglas Household
)
X pMLK X pBRD X gBRD X vBRD ∑jXBRD,j

Government Investme Intermediat


Consumption e
5. Composite good Uses
Market equilibrium QBRD
Composite
4. Composite
good
production MBRD DBRD EBRD
function Imports Domestic good Exports

3. ZBRD
Transformati Gross domestic
on
2. Cross domestic
Output production Composite
function (Leontief) Factor YBRD XMLK, XBRD,BR
Intermediate
1. Composite
factor production FCAP, FLAB,
function
(Cobb-Douglas) Factor

Figure 1 overview of the standard CGE model


6.1 Firm behavior (including Intermediate inputs)
In the simple CGE model, only capital and labor are assumed to be used
for the production of goods. Here, in contrast, we make the model more
realistic by assuming that firms use intermediate inputs in their
production process. Following this extension, the behavior of firms
become more complicated; we divide the production process into two
stages.
In the first stage, capital and labor are used for the production of a
composite factor (or value added). We assume a Cobb-Douglas-type
production function.
max imize  jy  p jy  Y j   p hf  Fh , j
Y j , Fh , j
h
h, j
Subject to Y j  b j  Fh , j
h

For the second stage, we assume a Leontief-type production function:


 
max imize  Zj  p Zj  Z j   p yj  Y j   piq  X i , j 
Z j ,Y j , X i , j
 i 
 X BRD , j X MLK , j Y j 
Subject to Z j  min  , , 
 ax ax ay 
 BRD , j MLK , j j 
p jy : Price of the j-th composite factor,
p hf : Price of the h-th factor,
p Zj : Price of the j-th gross domestic output,
piq : Price of the i-th composite good.
By solving these two problems, we obtain:

Y j  b j  Fh , hj , j (6.1)
h

 h, j p yj
Fh , j  Yj (6.2)
p hf
X i , j  ax i , j  Z j (6.3)
Y j  ay j  Z j (6.4)
 X BRD , j X MLK , j Y j 
Z j  min  , ,  (6.5’)
 ax ax ay 
 BRD , j MLK , j j 

The production function (6.5’) generates rectangular isoquants


which often cause difficulty in numerical computations. To work around
such a computational problem, we replace (6.5’) with a zero-profit
condition for competitive firms.
 
 Zj  p Zj  Z j   p yj  Y j   piq  X i , j   0
 i 
 
 p Zj  Z j   p yj  Y j   piq  X i , j 
 i 
 
 p Zj  Z j   p yj  ay j  Z j   p iq  axi , j  Z j 
 i 
Z y q
 p j  ay j  p j   axi , j  pi (6.5)
i

Replacing (6.5’) with (6.5), we can describe the firm’s behavior with
(6.1)-(6.5).
Government behavior
CGE models are often used for policy analysis. The main concern is the
consequences of changes in government policy devices, typically taxrate.
Thus, any realistic CGE model must including a government.
However, there is no single perfect way of modeling these government
activities from the viewpoint of micro-foundations, while we have
modeled the behavior of the household and the firms firmly based on
their micro-foundations. Therefore, we must develop our CGE models
with a government, depending on the purpose of our analysis, the
availability of data or sometimes the preference of the modeler.
Here, we assume that the government levies a direct tax on household
income at the tax rate  d , an production tax(indirect tax) on gross
domestic output at the rate  Zj , and import tariff on imports at the rate  mj .
At the same time, we assure that (1) the government save some spends all
tax revenues on their consumption, and that (2) the government
consumption each good in fixed proportions in total government
expenditure.
The above assumptions can be written as follows:
T d   d  p hf  FF f (6.6)
h

T jZ   Zj  p Zj  Z j (6.7)
Ti m   im  pim  M i (6.8)
i  
X ig  q
 T d   T jZ   T jm 
  (6.9’)
p 
i j j 
 i : Share of the i-th good in government expenditure ( 0   i  1,   i  1 )
i

6.2 Investment and savings


Introduction of investment and savings
The investment agent collects funds from the household, the government
and the external sector and spends on them on purchases of investment
goods. We assume investment agent spends all saving on the purchases of
investment goods proportionately with a constant share i , this is similar
to the assumption about the government demand function for goods.
X iv 
i
piq
S p
 S g  Er  S
f
 (6.10)

X iv :demand for the i-th investment goods,


Er :foreign exchange rate(domestic currency/foreign currency),
i :expenditure share of the i-th good in total investment
 
 0  i  1,  i  1 .
 i 
Then , let us assume that household and government savings are
determined by constant average propensities for savings as follow:
S p  ss p   p hf  FFh (6.11)
h

 
S g  ss g   T d   T jZ   T jm  (6.12)
 j j 
6.3 Modification of household and government behavior
The introduction of the government and investment and savings into the
model requires us to modify the original model equations describing the
behavior of the household and the government.
Household:
i
max imize
p
UU   X ip
Xi
i
q
Subject to p i  X i   p  FFh  S p  T d
p
h
f

i h

UU : Utility,
X ip :household consumption of the i-th good,
FF h :endowments of the h-th factor for the household,
S p :household savings,
T d :direct tax,
piq :price of the i-th composite goods,
p hf :price of the h-th factor,
 
 i :share parameter in the utility function  0   i  1 ,   i  1 .
 i 
Solving this modified household problem, we obtain the household
demand function for i-th good:
i  
X ip  q
  p hf  FF h  S p  T d  (6.13)
p  h
i 
The government demand function for the i-th good is modified
analogously by incorporation of government savings in a similar manner:
i  
X ig   T d
  T Z
  T m
 S g
 (6.9)
piq  
j j
j j 
International trade
Small-country assumption and balance of payments
In standard CGE model, we assume that this economy is so small that it
does not have a significant impact on the rest of the world. The essence of
the small-country assumption is that the export and import prices quoted
in foreign currency terms are exogenously given for this economy.
Regarding international trade, we must distinguish between two types of
price variables. One is prices in terms of the domestic currency pie and
pim ; the other is prices in terms of the foreign currency piWe and
p iWm ;they are linked with each other as follows:
pie  Er  piWe (6.14)
m Wm
p i  Er  pi (6.15)
Furthermore, it is assumed that the economy faces balance of payments
constrains, which can be described with export and import prices in
foreign currency terms:
 piWe  Ei  S f   piWm  M i
i i
(6.16)

6.4 Armington’s assumption


When we extend the model to an open economy model, we have to
consider differences (or similarities) between goods and domestically
produced/consumed and those imported/exported. In this section, we find
that it is necessary to assume that they are imperfectly substitutable with
each other. That is, domestic-made bread is supposed to be similar to but
is slightly different from imported bread.
Suppose that all the exported goods are perfectly substitutable with the
corresponding imported goods, such that there cannot be both exports and
imports for the same goods simultaneously. It is nonsense to import 100
units of bread while exporting 20 units.
6.5 Substitution between imports and domestic goods
Armington’s assumption implies that households and firms do not
directly consume or use imported goods but instead a so-called
“Armington composite good”, which comprises imports and the
corresponding domestic goods.
The optimization for the i-th Armington-composite-good-producing firm
can be written as follows:

max imize  iq  piq  Qi  1   im p im  M i  pid  Di
Qi , M i , Di
 
1
Subject to Qi   i mi  M i  d i  Di  i
(6.17) i
i

Notations are :
piq :price of i-th Armington composite good,
Qi :the i-th Armington composite good,
 i :scaling coefficient in the Armington composite good production
function,
mi , d i :input share coefficients in the Armington composite good
production function( 0  mi  1, 0  d i  1, mi  d i  1 )
 i :parameter defined by the elasticity of substitution,
( i   i  1  i , i  1 ) ,
 i :elasticity of substitution in the Armington composite good production

function,(  i  
d M i Di  
d p im pid
)

M i Di pim p id
The first-order conditions for the optimality of the above problem imply
the following demand functions for imports and the domestic good:
1
  ii  mi  piq  1i
Mi   m 
Qi (6.18)
 m
 1   i  pi  
1
  i  d i  piq  1i
Di   i  Qi (6.19)
 p id 
************************the derivation***********************
Les us defined a Lagrange function with Lagrange multiplier  i for the
above profit maximization problem for the i-th firm as follows:
 
L Qi , M i , Di ; i   piq  Qi  1   im pim  M i  p id  Di 
1
 
   m  M
i i i
i
i  d i  Dii 
i
  Qi
 
The first-order conditions are:
Li
 piq   i  0 (6.a)
Qi
1
Li 1
M i
  
  1   im pim   i  i mi  M ii  d i  Dii
i
 i
1
 i  mi  M ii 1  0 (6.b)
1
Li 1
Di i

  pid   i  i mi  M ii  d i  Dii 
i
1
 i  d i  Dii 1  0 (6.c)
1
Li
 i

  i mi  M ii  d i  Dii i  Qi  0  (6.d)

As the transformation of (6.d) implies mi  M i  d i  Di  Qi  i  ,we i i i

can eliminate the terms mi  M i  d i  Di  in (6.b) and (6.c) using this
i i

expression and  i using (6.a) to obtain:


1 i
i
Q  i
 
 1   im p im  piq   i  i   mi  M ii 1  0 (6.b’)
 i 
1 i
i
Q  i
 pid  piq  i  i   d i  Dii 1  0 (6.c’)
 i 
Rearranging (6.b’) and (6.c’) for M i and Di , we can get the expressions
for the demand functions(6.18) and (6.19).
*********************************************************
6.6 Transformation between exports and domestic goods
Let us consider the supply side; we assume that the firms transform the
gross domestic output into goods sold in international market and in
domestic markets. In this transformation process, we also assume
imperfect substitution (strictly speaking, it should be called imperfect
transformation) between exports and the domestic good supply.
The optimization for the i-th firm transformation the gross domestic
output can be written as follows:

max imize  i  pie  Ei  pid  Di  1   iZ  p iZ  Z i
Z i , Ei , Di
  
1
Subject to Z i   i ei  Ei  d i  Di  (6.20)
i i
i

Notations are :
 iZ :production tax on the i-th gross domestic output,
 i :scaling coefficient of i-th tranformation,
ei , d i :share coefficients for the i-th good transformation,
( 0  ei  1, 0  d i  1, ei  d i  1 )
i :parameter defined by the elasticity of transformation,
( i   i  1  i , i  1 ) ,
 i :elasticity of transformation for the i-th good transformation ,

( i  
d Ei Di  
d p ie pid
)

Ei Di pie pid
By solving this maximization problem, we get the following supply
functions for exports and for domestic goods:
1

 i  ei  1   iZ p iZ  1i
Ei   i
 (6.21)
e  Zi
 p i 
1

 i  d i  1   iZ piZ  1i
Di   i
 (6.22)
d  Zi
 p i 

6.7 Market-clearing conditions


The final step of this modeling process is imposing the market-clearing
conditions so that demand meets supply in all market as follows:
Qi  X ip  X ig  X iv   X i , j (6.23)
j

F
j
h, j  FF h (6.24)

(6.23) is the armington composite goods market-clearing condition;


(6.24) is the factor market-clearing condition.
6.8 Model system
As we discuss above, we have developed a system of simultaneous
equations for the standard CGE model consisting of (6.1)-(6.24).
-Domestic production:

Y j  b j  Fh , j h, j
(6.1)
h

 h, j p yj
Fh , j  Yj (6.2)
p hf
X i , j  ax i , j  Z j (6.3)
Y j  ay j  Z j (6.4)
p Zj  ay j  p yj   axi , j  piq (6.5)
i

-Government:
T d   d  p hf  FF f (6.6)
h

T jZ   Zj  p Zj  Z j (6.7)
Ti m   im  pim  M i (6.8)
i  
X ig   T d   T jZ   T jm  S g 
 q  (6.9)
p  i j j 
-Investment and savings:
X iv 
i
piq
S p
 S g  Er  S
f
 (6.10)

S p  ss p   p hf  FFh (6.11)
h

 
S g  ss g   T d   T jZ   T jm  (6.12)
 j j 
-Household
i  
X ip    p hf  FF h  S p  T d 
q
(6.13)
p  h
i 
-Export and Import prices and the balance of payments constraint:
pie  Er  piWe (6.14)
p im  Er  piWm (6.15)
We f
p i  Ei  S   piWm  M i (6.16)
i i

-substitution between imports and domestic goods (armington


composite):
1

Qi   i mi  M ii  d i  Dii i (6.17)
1
  i  mi  piq  1 i
Mi   i m 
Qi (6.18)
m
 1   i  pi  
1
  ii  d i  piq  1i
Di    Qi (6.19)
 p id 
-Transformation between exports and domestic goods:
1

Z i   i ei  Eii  d i  Dii i (6.20)
1

Ei  

 ii  ei  1   iZ p iZ   1i
Zi (6.21)

 pie 
1

 i  d i  1   iZ piZ  1i
Di   i
 (6.22)
 Zi
 pid 
-Market-clearing conditions:
Qi  X ip  X ig  X iv   X i , j (6.23)
j

F
j
h, j  FF h (6.24)

The above system of simultaneous equations consist of 24 sets of


equations/48 single equations and the same number of endogenous
variables.(more precisely, the number of single equations and endogenous
variables is (h+i+17)*j+h+4). The endogenous variables in the model are:
Y j , Fh, j , X i , j , Z j , X ip , X ig , X iv , Ei , M i , Qi , Di , p hf
p yj , p Zj , piq , pie , pim , pid , Er , S p , S g , T d , T jZ , Ti m
The exogenous variables are:
FF h , Sf, piWe , p iWm ,  d ,  Zj ,  im
Before concluding our modeling of the standart CGE model, we have
to reconsider Walras’s law. According to Walras’s law, we do not have to
impose the market-clearing conditions on all the n market because the
general equilibrium of this model economy holds with only the n-1
market clearing conditions. One of the equations of the model is
redundant; therefore, all the prices cannot be solved, we have to choose a
numeraire and fix its price.
6.9 Calibration
Calibration of the coefficients of tax
From function (6.6) T d   d  p hf  FF f ,we get:
h

T d0
d 
 p hf 0  FF f
h

From function (6.7) T    p Zj  Z j , we get:


j
Z Z
j

Z
T jZ 0
 
j
p Zj 0  Z 0j
From function (6.8) Ti m   im  pim  M i , we get:
Ti m 0
 im 
p im 0  M i 0
Calibration of the Leontief-type function
Recall that these formaulae are derived from the demand function for
the intermediate inputs and the composite factor:
X i , j  ax i , j  Z j (6.3)
Y j  ay j  Z j (6.4)
As the initial equilibrium value X i0, j , Y j0 and Z 0j have been already
determined, so The coefficients in the Leontief-type production function
ax i , j and ay i , j as follows:
X i0, j
axi , j 
Z 0j
Y j0
ay i , j 
Z 0j
6.10 Calibration of the CES function
First, we suppose the elasticity of substitution  i is exogenous, once
the elasticity of substitution  i is decided, we can obtain the elasticity
parameter  i in the CES function as  i   i  1  i .
1
i q
   mi  p  1 i
From function (6.18) Mi   i 
i
Qi and (6.19)
m

 1 i  p   m
i
1
  i  d i  piq  1i
Di   i  Qi ,we divide both sides of the import demand
 p id 
function(6.18) by the domestic good demand function(6.19) as follow:
1
d
M i  mi p  i
1 i
 m 
Di  d i 1    pi   i
m

As mi  d i  1
M i Di 1 1   im  pim pid i

 mi 
1  M i Di  1   im  pim pid
1 i

M i 0 Di 0 1 1   im  pim0 pid 0 i

So, mi 
1  M i 0 Di 0  1   im  pim 0 pid 0
1 i

And d i  1  mi
1
From function (6.17) 
Qi   i mi  M ii  d i  Dii 
i ,
0
Q
We get:  i  i
1
m  Mi
i
i0  d i  Di0i  i

6.11 Calibration of the CET function


The calibration procedures for the CET functions are almost the same as
those for CES functions discussed above. First, we assume the elasticity
of transformation  i is exogenously set. Then the elasticity parameter
i is determined as i   i  1  i .
1
 ii  ei  1   iZ piZ  1i
From function (6.21) Ei  
  and (6.22)
 Zi
 pie 
1

Di   i
i
  d i  1    i
Z
p i
Z
 1i
Z i , we divide both sides of the import demand

 pid 
function(6.21) by the domestic good demand function(6.22) as follow:
1
Ei  ei pid  1i
 
Di  d i pim 
As ei  d i  1
pie  Ei1i 
 ei  e 1 
pi  Ei  pid  Di1i 
So, d i  1  ei
1
From function (6.20) 
Z i   i ei  Eii  d i  Dii 
i ,
Z i0
We get:  i  1
e  E
i
i
i0  d i  Di0i i

6.12 Estimation of savings rates


From savings functions (6.11) S p  ss p   p hf  FFh and (6.12)
h

 
S g  ss g   T d   T jZ   T jm  , we can get:
 j j 
p0
S
ss p 
 p hf 0  FF h
h

S g0
ss g 
T d0   T jZ 0   T jm 0
j j
Just discussed above, these coefficients and exogenous variables must
be estimated by exploiting data in the SAM in table 2.

Table 2 SAM for the standard CGE Model


Indirect
Activity Factor Final Demand External Total
Tax
BRD MLK CAP LAB IDT TRF HOH GOV INV EXE
Activity BRD 21 8 20 19 16 8 92
MLK 17 9 30 14 15 4 89
Factor CAP 20 30 50
LAB 15 25 40
Indirect IDT 5 4 9
Tax TRF 1 2 3
HOH 50 40 90
Final
GOV 9 3 23 35
Demand
INV 17 2 12 31
External EXT 13 11 24
Total 92 89 50 40 9 3 90 35 31 24
Z0 m0
Piq0Xi,j0 Phf0F0h,j Pjm0M0j Phf0FFh ∑Tj ∑Tj
Td0 Sp0 Sg0 Er0Sf

TjZ0 Tjm0 Piq0Xip0 Piq0Xig0 Piq0Xiv0 Pie0Ei0


6.13 GAMS programming
Explain/interpret the gams programming Stdcge.gms

A.5 Communicating with spreadsheet software


In dealing with a large-scale model, we face difficulty in communicating
the large number of solved or calibrated values of variables, constants and
other information in an output file. Similarly, it is cumbersome to transfer
data in other files into an input file manually. To mitigate these problems,
GAMS has been equipped with the GAMS Data Exchange (GDX)
facilities and utilities, which help the GAMS system to communicate with
spreadsheet software such as Excel and other database systems.
By using GDX facilities and utilities, we can transfer data in an input file
or computed by GAMS system into a separate file in the GDX format,
and then we can unload these data from the GDX file into a spreadsheet
file.
We can also read data from spreadsheet file through a GDX file and
transfer these data from the GDX file for GAMS computation (figure
A.1).
Input File Output File
GAMS System
(gms) (lst)

GDX Facility

GDX File
(gdx)

GDX Utility: GDXXRW

Spreadsheet
File
Figure A.1 Data exchange between files

A.5.1 Transfer of data in an input file into a spreadsheet


(1) To store all the symbols and values used in an input file in a GDX file
named, say , output.gdx, attach the following code to the end of
stdcge.gms :
Execute_unload “output.gdx”;
In the above code, output.gdx indicates the name of the target GDX
file, where data are stored. Instead of output.gdx, we can name the GDX
file whatever we like. By omitting symbol names (i.e., endogenous
variable and constant names ,etc) , all symbols will be written to the GDX
file. We can freely browse the data in this GDX file using GAMS IDE.
Using standard Windows operations, we can also copy the data from the
GAMS IDE window and paste them into any other files such as
spreadsheet.
While the code above inserts all the symbols and their values in an
input file into the GDX file, the following code inserts only the values of
SAM(u,v).
Execute_unload “output.gdx”, SAM;
The last part of the above statement (i.e. SAM) indicates the names of
sets, constants, variables, etc. to be inserted into the GDX file.

(2) The social accounting matrix (SAM), generated by the above


statement, is not easy to read; we can rearrange the placement of the
columns and rows of the SAM with our using mouse operation by
dragging the column and row labels. The GAMS IDE documentation
provides more details for changing the layout in the GDX viewer.
(3) Finally, using the GDXXRW utility, we can create a spreadsheet file
that stores data kept in the GDX file. Supposed we want to put the value
of SAM(u,v) kept in the GDX file into a spreadsheet file, say, sam.xls.
after the code above, namely:
Execute_unload “output.gdx”, SAM;
Insert the following line:
Execute “gdxxrw output.gdx output=sam.xls par=sam”;
Then, a spreadsheet file containing the SAM, sam.xls, is generated.
In the above code,’ execute’ is the GAMS command to run the
subsequent program enclosed by the double quotation marks. In other
words, the GDXXRW utility is launched to open putput.gdx, read the
parameter value of SAM(u,v) and generate a spreadsheet file sam.xls.
The values of variables and others generated by GAMS computation can
be transferred into a spreadsheet in a similar manner to that stated above.
A.5.2 Transfer of data from a spreadsheet into a GDX file
Now we explain how to transfer data from s spreadsheet file into a GDX
file then read this file for GAMS computation. The process explained
below is convenient, particularly when the SAM is large and/or when a
dataset is shared by several modelers and users:
(1) Given the SAM in sam.xls, we convert in into a GDX file, say,
sam.gdx, using the following code in a new input file. Note that we
should name the new file other than stgcge.gms, so as not to destroy the
original input file.
Execute “gdxxrw sam.xls output=sam.gdx par=sam
rng=a1:k11 cdim=1 rdim=1”
(note!!)
(2) Now that the SAM data are stored in a GDX file(sam.gdx), we can
replace lines 12-36 in the stgceg code with the following:
Parameter SAM(u,v) social accounting matrix;
$gdxin sam.gdx
$loaddc sam
$gdxin
In the code above, “$gdxin sam.gdx” initiates the retrieval of the SAM
data from the GDX file sam.gdx. This is followed by “$loaddc sam”,
which specifies the name of the parameters to be loaded from the GDX
file; in this case, it is “sam” . Finally, “$gdxin” appearing in the last file is
not followed by any filename.
第七章 实用的 CGE 模型构建及应用(静态)
1.部门划分
根据国家统计局部门(行业)划分标准,国民经济共划分成第一产业、第二产业和第三产业,
其中第一产业是农业;第二产业分为:煤炭采选业、石油开采业及加工业、天然气开采业及
加工业、金属矿采选业、非金属矿采选业、食品制造与烟草加工业、纺织业、木材加工及家
具制造业、造纸印刷机文教用品制造业、化学医药业、非金属矿物制品业、金属冶炼制品业、
机械设备制造业、电子通信仪器办公品制造业、其他制造业、火电、水电、核电及风电、水
的生产和供应业、建筑业;第三产业划分为交通运输仓储和邮政业、批发零售住宿餐饮业、
金融及房地产业、科教文卫社会服务业;共 25 个行业。
2.生产要素
生产要素包括劳动力和资本。
生产函数用道格拉斯 CD 生产函数,也可以进一步修改为 CES 生产函数;
3. 经济行为主体
经济行为主体包括:企业、居民、政府、国外。
4. 社会核算矩阵概述
4.1.1 社会核算矩阵的概念和基本特点
社会核算矩阵(以下简称 SAM 表)的出现和发展源于人们对国民核算账户
局限性的认识。通常国民核算账户偏重于经济总量及增长的核算,但经济增长并
不能保证所有人群的生活水平都能有所改善,因此需要了解有关收入分配方面的
信息。而 SAM 表恰好是一套连接所有经济交易(包括生产、收入分配、流通、
消费、储蓄和投资等内容),对生产活动、生产要素和社会经济主体进行分解和
分类的完整数据体系,它能定量描述一个经济体内部有关生产、要素收入分配、
经济主体收入分配和支出的循环关系。通过 SAM 表,可以很清楚地看到:增加
值是如何分配到各生产要素,进而分配到各机构主体(居民、企业、政府),机
构主体的收入通过转移支付等手段进行调整后又用于消费支出。用于消费的各种
商品又来自于各部门的生产活动,并在此过程中创造增加值。消费以外的其他收
入则转化为储蓄,并进一步转化为投资。简言之, SAM 表可以看作是以数字方
式再现经济循环,并着重于反映分配层面。
由于 SAM 表能准确刻画模型中包含的各种收支均衡关系,因此被用作 CGE
模型的基础数据集,并被当作 CGE 模型的基准均衡解。
4.1.2 SAM 表的基本结构

SAM 表的结构是一个方阵,它根据复式记账的原则将各账户的收支情况进行记录,其中行方向记录账户的收入,列方向记录账户支出,
同一账户行和列的合计金额是相等的。通常开放经济体的 SAM 表账户包括以下几类:生产活动账户、商品账户、生产要素账户、机构账户、
资本积累(投资储蓄)账户和国外账户。 SAM 表的基本结构见表

表:开放经济体的宏观 SAM 表结构


支出

部门\部门 生产活动 要素 机构 资本 世界其它地


合计
活动 商品 劳动 资本 居民 企业 政府 资本 存货 区

国内生产国内供
活动 出口 总产出
生产活 给

动 中间投 固定资本形成 存货增 国内总需


商品 居民消费 政府消费
入 额 加 求

劳动 劳动报
要素收入
收 力 酬

入 固定资
要素
产折旧+
资本 要素收入
企业盈

劳动报 企业转移支 政府转移支


机构 居民 资本收入 国外收益 居民收入
酬 付 付

114
固定资产折旧+ 政府转移支
企业 企业收入
企业盈余 付

个人所得
政府 间接税 进口关税 企业直接税 国外收入 政府收入

资本 居民储蓄 企业储蓄 政府储蓄 国外净储蓄 储蓄总额


资本
存货 存货投资 存货变动

国外资投资收 对国外的支
世界其它地区 进口 国外收入
益 付

要素支 存货变
合计 总投入 国内总供给 要素支出 居民支出 企业支出 政府支出 总投资 国外支出
出 动
SAM 表各账户的主要核算内容是:
“生产活动”账户核算生产者的生产活动。与“生产活动”对应的是投入产出核算中的生产部门,反映中间投入的生产关系。账户的行方
向表示生产活动的收入来自于各种不同商品的供应,行的总和构成生产活动的总产出;账户的列方向表示生产活动的投入,即向“要素”和“商
品”账户支出以获得中间投入和要素投入,并且还需向“机构”(政府)支付生产税,列的总和构成生产活动的总成本。
“商品”账户核算各种商品的供应来源和使用。账户的行方向反映国内各机构和世界其他地区购买或使用各种商品的情况,核算的是对
“生产活动”的中间投入、各经济主体的最终使用以及出口,行的总和构成对各种商品的总需求;账户的列方向表示本国或国外各种商品的来
源,把国内生产活动的供给和进口加上进口环节税收就构成了国内市场的总供给。
“生产要素”账户核算各种要素的收入和要素收入在要素提供者之间的分配。账户的行方向反映各要素从生产活动中获得的要素报酬,反
映初次分配;账户的列方向则描述的是要素收入在生产要素提供者即机构间的分配。
“机构”账户核算各机构的收入来源和各项支出。账户的行方向反映机构的收入来源与要素收入和机构间的转移,行的总和是各机构的总

115
收入;账户的列方向反映机构的收入使用情况,除了部分转移支出外,其余收入都在储蓄和消费之间分配,列的总和反映机构总支出。
“资本”账户核算社会的总资本来源和使用。账户的行方向反映各机构的资本来源于储蓄和机构间的资本转移,行的总和表示总储蓄;列
的总和反映社会的总投资。
“国外”账户核算与国外有关的交易。账户的行方向反映国外各种商品的进口和支付给国外要素的报酬;账户的列方向则反映商品的出口
和从国外得到的各项净收入。

4.2 SAM 构建

4.2.1 宏观 SAM 构建

要素 资本
项目 1.活动 2.商品 5.居民 6.企业 7.政府 10.国外 收入合计
3.劳动力 4.资本 8.固定资产投资 9.存货变动

1.活动 723317.96 95540.99 818858.96


2.商品 552815.15 96552.62 35190.92 105435.87 7343.97 797338.53
3.劳动力 110047.30 110047.30
要素
4.资本 117477.79 117477.79
5.居民 110047.30 8979.60 27695.71 7276.13 2952.86 156951.60
6.企业 110121.49 110121.49
7.政府 38518.72 7585.98 3185.58 8779.25 -12.62 58056.91

8.固定资产投资 57213.40 73646.53 15466.04 -33546.13 112779.84


投资储蓄
9.存货变动 7343.97 7343.97

116
10.国外 66434.58 -1623.30 123.82 64935.10
支出合计 818858.96 797338.53 110047.30 117477.79 156951.60 110121.49 58056.91 112779.84 7343.97 64935.10

表 :宏观社会核算矩阵数据来源说明
行 列 数据来源及出处 帐户 原始数据

1.活动 1.商品 07 年投入产出表 总产出-出口 723317.97


2.国外 07 年投入产出表 出口合计 95540.99
2.商品 1.活动 07 年投入产出表 中间投入合计 552815.15
5.居民 07 年投入产出表 居民消费支出合计 96552.62
7.政府 07 年投入产出表 政府消费支出 35190.92
8.投资 07 年投入产出表 固定资本形成总额 105435.87
9.存货 07 年投入产出表 存货增加+其它 7343.97
3.劳动力 1.活动 07 年投入产出表 劳动者报酬 110047.3
4.资本 1.活动 07 年投入产出表 固定资产折旧+营业盈余 117477.79
5.居民 3.劳动力 07 年投入产出表 劳动者报酬 110047.3
4.资本 《中国统计年鉴 2008》 资金流量表“住户部门”财产收入来源 8979.6
6.企业 列余量

包括价格补贴、社会保障和就业支付、政府对居民的利息支付其中社会保障和就业支付为 5447.16
7.政府 《中国财政年鉴 2008》 7276.13
亿元,政府对居民的利息支付为 1040.62 亿元,价格补贴根据 1994—2006 年数据推算,为 788.35

117
亿元。合计为 7276.13 亿元。

国际收支平衡表中,“其它部门”差额,为 388.33 美元,依据汇率 1 美元=7.604 元(人民币),合计


10.国外 《中国统计年鉴 2008》 2952.86
为 2952.86 亿元。

6.企业 4.资本 列余量

7.政府 1.活动 07 年投入产出表 生产税净额 38518.72


2.商品 《中国财政年鉴 2008》 进口货物的关税及消费税、增值税 7585.98
5.居民 《中国财政年 2008》 个人所得税 3185.58
6.企业 《中国财政年鉴 2008》 决算中“企业所得税“ 8779.25
10.国外 《中国统计年鉴 2008》 国际收支平衡表中,“经常转移”中“各级政府差额,-16596 万美元,折合人民币为-12.62 亿元。 -12.62
8.固定资产投资 5.居民 资金流量表(2007) 居民储蓄 57213.4
6.企业 列余量

7.政府 列余量

10.国外 列余量

9.存货变动 8.固定资产投资 07 年投入产出表 存货增加+其它 7343.97

10.国外 2.商品 07 年投入产出表 投入产出表中的货物进口 74020.56 万元,减去关税及进口产品消费税、增值税。 66434.58

4.资本 《中国统计年鉴 2008》 国际收支平衡表中经常项目“投资收益差额”,为-213.48 美元,折算人民币为-1623.30 亿元。 -1623.30


7.政府 《中国统计年鉴 2008》 政府对国外的“对外援助”与支付给国外的借款利息支出之和. 123.82

118
本章实用 CGE 模型的宏观 SAM 表:
生产活动 商品 劳动力 资本 居民 企业 政府 投资储蓄 国外
国内生产国内
出口
生产活动 供给
一般商品的中
居民消费 政府消费 固定资本投资
商品 间投入
劳动力 劳动收入
资本 总资本收入
居民 劳动收入 居民资本收入
企业 企业资本收入
政府 生产税 进口关税 居民所得税 企业所得税
投资储蓄 资本折旧 居民储蓄 企业储蓄 政府储蓄 国外储蓄
国外 进口

119
7.1 社会核算矩阵:
宏观社会核算矩阵(单位:亿元)
生产活动 商品 劳动力 资本 居民 企业 政府 投资储蓄 国外 合计
生产活动 707474.38 113114.17 820588.55
商品 551901.51 96552.62 35190.92 105435.87 789080.91
劳动力 110047.30 110047.30
资本 117477.79 117477.79
居民 110047.30 20053.08 130100.38
企业 60169.18 60169.18
政府 41161.96 7585.98 3126.52 8514.39 60388.85
投资储蓄 37255.53 30421.24 51654.79 25197.93 -39093.62 105435.87
国外 74020.55 74020.55
合计 820588.55 789080.91 110047.30 117477.79 130100.38 60169.18 60388.85 105435.87 74020.55

120
7.2 模型方程:
(1)生产行为方程:

Yj  bj  Lj j  K j
1  j
(7.1)
 i  PYi
Li  Yi (7.2)
PLi
1   i   PYi
Ki  Yi (7.3)
PK i
X i , j  ax i , j  Z j (7.4)
Y j  ay j  Z j (7.5)
PZ j  ay j  PY j   axi , j  PQi (7.6)
i

YK i  PK i  K i (7.7)
YLi  PLi  Li ( 7 . 8)
YHK  rykhe  TYK (7.9)
YEK  1  rykhe  TYK ( 7 .1 0 )
DEPR  rdepr  YEK (7.11)
TYL   YLi (7.12)
i

TYK   YK i (7.13)
i

(2)政府行为方程:
TAX dh   dh  TYL  YHK  (7.14)
TAX de   de  YEK  DEPR  (7.15)
TAX zj   zj  PZ j  Z j (7.16)
TAX im   im  PM i  M i (7.17)
 
 
XGi   i   TAX dh  TAX de   TAX zj  TAX mj  SG  / PQi (7.18)
 j 
(3)投资储蓄行为方程:
SP  rsp  TYL  YHK  (7.19)
 
SG  rsg   TAX dh  TAX de   TAX jz  TAX mj  (7.20)
 j 
SE  1   de   YEK  DEPR  (7.21)
(4)居民家庭消费行为函数:
XPi   i  TYL  YHK  SP  TAX dh  / PQi (7.22)
(5)国际贸易行为函数:
PEi  EXR  pwei (7.23)
PM i  EXR  pwmi (7.24)
1

Qi   i mi  M ii  d i  Dii 
i (7.25)

121
1
  i  mi  piq  1i
Mi   i m 
Qi (7.26)
 1  
 i
m
 p i  
1
  ii  d i  piq  1i
Di    Qi (7.27)
 p id 
1

Z i   i ei  Eii  d i  Dii 
i ( 7.28)
1

Ei   i

 i  ei  1   iZ p iZ   1i
Zi (7.29)

 pie 
1

 ii  d i  1   iZ piZ  1i
Di  
 (7.30)
 Zi
 pid 
(6)市场出清条件:
 pwe i  Ei  SF   pwmi  M i (7.31)
i i

Qi  XPi  XGi  XVi   X ij (7.32)


j

 L   lo
i i (7.33)
i i

 K   ko
i i (7.34)
i i

TSAV  SP  SG  SE  EXR  SF  DEPR (7.35)


TINV   XVi (7.36)
i

TSAV  TINV (7.37)


(7)居民效用函数:
UU   XP  i ( 7 .3 8 )
i

7.3 The program:

第八章 实用的 CGE 模型构建及应用(动态)

8.1 The SAM Table:


8.2 The model:
8.3 The program:

122
参考文献:
1.Richard E. Rosenthal,“GAMS——A User's Guide Tutorial”,2008, GAMS
Development Corporation, Washington, DC, USA

2.魏传江等译,“GAMS 用户指南”,中国水利水电出版社,2009

3.李洪心,“可计算的一般均衡模型——建模与仿真”,机械工业出版社,2008
4.黄宗煌,“GAMS 基础篇——中文操作手册及程序式语法”,2009
5.Hosoe, N, Gasawa, K, and Hashimoto, H, Handbook of Computible General Equilibrium
Modeling. University of Tokyo Press, Tokyo, Japan, 2004.

123

You might also like