%* gmpl.tex *% %*********************************************************************** % This code is part of GLPK (GNU Linear Programming Kit). % % Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, % 2009, 2010, 2011, 2013, 2014, 2015 Andrew Makhorin, Department for % Applied Informatics, Moscow Aviation Institute, Moscow, Russia. All % rights reserved. E-mail: . % % GLPK is free software: you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % GLPK is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY % or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public % License for more details. % % You should have received a copy of the GNU General Public License % along with GLPK. If not, see . %*********************************************************************** \documentclass[11pt, brazil]{report} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{amssymb} \usepackage[dvipdfm,linktocpage,colorlinks,linkcolor=blue, urlcolor=blue]{hyperref} \usepackage{indentfirst} \setlength{\textwidth}{6.5in} \setlength{\textheight}{8.5in} \setlength{\oddsidemargin}{0in} \setlength{\topmargin}{0in} \setlength{\headheight}{0in} \setlength{\headsep}{0in} \setlength{\footskip}{0.5in} \setlength{\parindent}{16pt} \setlength{\parskip}{5pt} \setlength{\topsep}{0pt} \setlength{\partopsep}{0pt} \setlength{\itemsep}{\parskip} \setlength{\parsep}{0pt} \setlength{\leftmargini}{\parindent} \renewcommand{\labelitemi}{---} \def\para#1{\noindent{\bf#1}} \renewcommand\contentsname{\sf\bfseries Conteúdo} \renewcommand\chaptername{\sf\bfseries Capítulo} \renewcommand\appendixname{\sf\bfseries Apêndice} % \renewcommand\contentsname{\sf\bfseries Contents} % \renewcommand\chaptername{\sf\bfseries Chapter} % \renewcommand\appendixname{\sf\bfseries Appendix} \begin{document} \thispagestyle{empty} \begin{center} \vspace*{1.5in} \begin{huge} \sf\bfseries Linguagem de Modelagem GNU MathProg \end{huge} \vspace{0.5in} \begin{LARGE} \sf Linguagem de Referência % Language Reference \end{LARGE} \vspace{0.5in} \begin{LARGE} \sf para o GLPK Versão 4.57 \end{LARGE} \vspace{0.5in} \begin{Large} \sf (RASCUNHO, Fevereiro 2016) \end{Large} \end{center} \newpage \vspace*{1in} \vfill \noindent % The GLPK package is part of the GNU Project released under the aegis of GNU. O pacote GLPK é parte do Projeto GNU distribuído sob a égide do GNU. \noindent Copyright \copyright{} 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2015, 2016 Andrew Makhorin, Department for Applied Informatics, Moscow Aviation Institute, Moscow, Russia. % All rights reserved. Todos os direitos reservados. \noindent Título original: Modeling Language GNU MathProg - Language Reference for GLPK Version 4.57 \noindent Tradução: João Flávio de Freitas Almeida, Departamento de Engenharia de Produção, Universidade Federal de Minas Gerais, Minas Gerais, Brasil. \noindent Copyright \copyright{} 2015 João Flávio de Freitas Almeida, para esta tradução. Todos os direitos reservados. \noindent Free Software Foundation, Inc., Rua Franklin, 51, 5$^{o}$ andar, Boston, MA 02110-1301, USA. \noindent É permitido realizar e distribuir cópias textuais deste manual mantendo o aviso de copyright e preservando este aviso de permissão em todas as cópias. % Permission is granted to make and distribute verbatim copies of this % manual provided the copyright notice and this permission notice are % preserved on all copies. \noindent É concedida a permissão para copiar e distribuir versões modificadas deste manual sob as condições de cópias textuais, desde que o resultado completo derivado do trabalho resultante seja distribuído sob os termos de uma notificação de permissão idêntica a esta. % Permission is granted to copy and distribute modified versions of this % manual under the conditions for verbatim copying, provided also that % the entire resulting derived work is distributed under the terms of % a permission notice identical to this one. \noindent É concedida a permissão para copiar e distribuir traduções deste manual em outra linguagem, sob as condições acima para as versões modificadas. % Permission is granted to copy and distribute translations of this % manual into another language, under the above conditions for modified % versions. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newpage {\setlength{\parskip}{0pt} \tableofcontents } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Introdução} {\it GNU MathProg} é uma linguagem de modelagem projetada para descrever modelos lineares de programação matemática. \footnote{A linguagem GNU MathProg é um subconjunto da linguagem AMPL. A implementação do GLPK é \linebreak principalmente baseada no artigo: {\it Robert Fourer}, {\it David M. Gay}, and {\it Brian W. Kernighan}, ``A Modeling Language for Mathematical Programming.'' {\it Management Science} 36 (1990), pp.~519-54.} % {\it GNU MathProg} is a modeling language intended for describing % linear mathematical programming models.\footnote{The GNU MathProg % language is a subset of the AMPL language. Its GLPK implementation is % mainly based on the paper: {\it Robert Fourer}, {\it David M. Gay}, and % {\it Brian W. Kernighan}, ``A Modeling Language for Mathematical % Programming.'' {\it Management Science} 36 (1990), pp.~519-54.} A descrição de um modelo escrito na linguagem GNU MathProg consiste em um conjunto de sentenças e blocos de dados construído pelo usuário a partir dos elementos de linguagem descritos neste documento. % Model descriptions written in the GNU MathProg language consist of % a set of statements and data blocks constructed by the user from the % language elements described in this document. Em um processo denominado {\it tradução}, um programa denominado {\it tradutor do modelo} analisa a descrição do modelo e o traduz para uma estrutura de dados interna, que pode ser usado tanto para gerar instância de um problema de programação matemática ou obter diretamente a solução numérica do problema por meio de um programa chamado {\it solver}. % In a process called {\it translation}, a program called the {\it model % translator} analyzes the model description and translates it into % internal data structures, which may be then used either for generating % mathematical programming problem instance or directly by a program % called the {\it solver} to obtain numeric solution of the problem. \section{Problema de programação linear} \label{problem} Em MathProg o problema de programação linear (PL) é expresso da seguinte forma: % In MathProg the linear programming (LP) problem is stated as follows: \medskip \noindent\hspace{1in}minimizar (ou maximizar) $$z=c_1x_1+c_2x_2+\dots+c_nx_n+c_0\eqno(1.1)$$ \noindent\hspace{1in}subjeito às restrições lineares $$ \begin{array}{l@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }l} L_1&\leq&a_{11}x_1&+&a_{12}x_2&+\dots+&a_{1n}x_n&\leq&U_1\\ L_2&\leq&a_{21}x_1&+&a_{22}x_2&+\dots+&a_{2n}x_n&\leq&U_2\\ \multicolumn{9}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\ L_m&\leq&a_{m1}x_1&+&a_{m2}x_2&+\dots+&a_{mn}x_n&\leq&U_m\\ \end{array}\eqno(1.2) $$ \noindent\hspace{1in}e os limites das variáveis $$ \begin{array}{l@{\ }c@{\ }c@{\ }c@{\ }l} l_1&\leq&x_1&\leq&u_1\\ l_2&\leq&x_2&\leq&u_2\\ \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .}\\ l_n&\leq&x_n&\leq&u_n\\ \end{array}\eqno(1.3) $$ % \newpage \noindent onde $x_1$, $x_2$, \dots, $x_n$ são variáveis; $z$ é a função objetivo ; $c_1$, $c_2$, \dots, $c_n$ são coeficientes da função objetivo; $c_0$ é o termo constante da função objetivo; $a_{11}$, $a_{12}$, \dots, $a_{mn}$ são coeficientes das restrições; $L_1$, $L_2$, \dots, $L_m$ são limites inferiores das restrições; $U_1$, $U_2$, \dots, $U_m$ são limites superiores das restrições; $l_1$, $l_2$, \dots, $l_n$ são limites inferiores das variáveis; $u_1$, $u_2$, \dots, $u_n$ são limites superiores das variáveis. Os limites das variáveis e das restrições podem ser tanto finitos quanto infinitos. Além disso, os limites inferiores podem ser igual aos limites superiores correspondentes. Logo, os seguintes tipos de variáveis e restrições são permitidos: % where $x_1$, $x_2$, \dots, $x_n$ are variables; $z$ is the objective % function; $c_1$, $c_2$, \dots, $c_n$ are objective coefficients; $c_0$ % is the constant term (``shift'') of the objective function; $a_{11}$, % $a_{12}$, \dots, $a_{mn}$ are constraint coefficients; $L_1$, $L_2$, % \dots, $L_m$ are lower constraint bounds; $U_1$, $U_2$, \dots, $U_m$ % are upper constraint bounds; $l_1$, $l_2$, \dots, $l_n$ are lower % bounds of variables; $u_1$, $u_2$, \dots, $u_n$ are upper bounds of % variables. % % Bounds of variables and constraint bounds can be finite as well as % infinite. Besides, lower bounds can be equal to corresponding upper % bounds. Thus, the following types of variables and constraints are % allowed: \medskip {\def\arraystretch{1.4} \noindent\hspace{54pt} \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }l@{\hspace*{39.5pt}}l} $-\infty$&$<$&$x$&$<$&$+\infty$&Variável livre (ilimitada)\\ $l$&$\leq$&$x$&$<$&$+\infty$&Variável com limite inferior\\ $-\infty$&$<$&$x$&$\leq$&$u$&Variável com limite superior\\ $l$&$\leq$&$x$&$\leq$&$u$&Variável duplamente limitada\\ $l$&$=$&$x$&=&$u$&Variável fixa\\ \end{tabular} % \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }l@{\hspace*{39.5pt}}l} % $-\infty$&$<$&$x$&$<$&$+\infty$&Free (unbounded) variable\\ % $l$&$\leq$&$x$&$<$&$+\infty$&Variable with lower bound\\ % $-\infty$&$<$&$x$&$\leq$&$u$&Variable with upper bound\\ % $l$&$\leq$&$x$&$\leq$&$u$&Double-bounded variable\\ % $l$&$=$&$x$&=&$u$&Fixed variable\\ % \end{tabular} \noindent\hfil \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }ll} $-\infty$&$<$&$\sum a_jx_j$&$<$&$+\infty$&Forma linear livre (ilimitada)\\ $L$&$\leq$&$\sum a_jx_j$&$<$&$+\infty$&Restrição de desigualdade ``maior ou igual a''\\ $-\infty$&$<$&$\sum a_jx_j$&$\leq$&$U$&Restrição de desigualdade ``menor ou igual a''\\ $L$&$\leq$&$\sum a_jx_j$&$\leq$&$U$&Restrição de desigualdade duplamente limitada\\ $L$&$=$&$\sum a_jx_j$&=&$U$&Restrição de igualdade\\ \end{tabular} % \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }ll} % $-\infty$&$<$&$\sum a_jx_j$&$<$&$+\infty$&Free (unbounded) linear % form\\ % $L$&$\leq$&$\sum a_jx_j$&$<$&$+\infty$&Inequality constraint ``greater % than or equal to''\\ % $-\infty$&$<$&$\sum a_jx_j$&$\leq$&$U$&Inequality constraint ``less % than or equal to''\\ % $L$&$\leq$&$\sum a_jx_j$&$\leq$&$U$&Double-bounded inequality % constraint\\ % $L$&$=$&$\sum a_jx_j$&=&$U$&Equality constraint\\ % \end{tabular} } \medskip Além de problemas puramente PL, MathProg também permite problemas de programação inteira mista (PIM), onde algumas ou todas as variáveis são restritas a serem inteiras ou binárias. % In addition to pure LP problems MathProg also allows mixed integer % linear programming (MIP) problems, where some or all variables are % restricted to be integer or binary. \section{Objetos do modelo} Em MathProg o modelo é descrito em termos de conjuntos, parâmetros, variáveis, restrições e objetivos, que se denominam {\it objetos do modelo}. O usuário introduz objetos particulares do modelo usando as sentenças da linguagem. Cada objeto do modelo possui um nome simbólico que o identifica de maneira única sendo projetado para propósitos de referenciação. % In MathProg the model is described in terms of sets, parameters, % variables, constraints, and objectives, which are called {\it model % objects}. % % The user introduces particular model objects using the language % statements. Each model object is provided with a symbolic name which % uniquely identifies the object and is intended for referencing % purposes. Objetos do modelo, incluindo conjuntos, podem ser matrizes multidimensionais construídos sobre conjuntos indexantes. Formalmente, uma matriz $n$-dimensional $A$ é o mapeamento: % Model objects, including sets, can be multidimensional arrays built % over indexing sets. Formally, $n$-dimensional array $A$ is the mapping: $$A:\Delta\rightarrow\Xi,\eqno(1.4)$$ onde $\Delta\subseteq S_1\times\dots\times S_n$ é um subconjunto do produto Cartesiano de conjuntos indexantes, $\Xi$ é um conjunto dos membros da matriz. Em MathProg o conjunto $\Delta$ é chamado o {\it domínio do subíndice}. % REVISAR Seus membros são $n$-tuplas $(i_1,\dots,i_n)$, onde $i_1\in S_1$, \dots, $i_n\in S_n$. % where $\Delta\subseteq S_1\times\dots\times S_n$ is a subset of the % Cartesian product of indexing sets, $\Xi$ is a set of array members. % In MathProg the set $\Delta$ is called the {\it subscript domain}. Its % members are $n$-tuples $(i_1,\dots,i_n)$, where $i_1\in S_1$, \dots, % $i_n\in S_n$. Se $n=0$, o produto Cartesiano acima possui exatamente um membro (denominado 0-tupla), portanto, é conveniente pensar nos objetos escalares como sendo matrizes 0-dimensionais que \linebreak possuem apenas um membro. % If $n=0$, the Cartesian product above has exactly one member (namely, % 0-tuple), so it is convenient to think scalar objects as 0-dimensional % arrays having one member. % \newpage O tipo dos membros da matriz é determinado pelo tipo de objeto do modelo correspondente, como segue: % The type of array members is determined by the type of corresponding % model object as follows: \medskip \noindent\hfil \begin{tabular}{@{}ll@{}} Objeto do modelo&Membro da matriz\\ \hline Conjunto&Conjunto plano elementar\\ Parâmetro&Número ou símbolo\\ Variável&Variável elementar\\ Restrição&Restrição elementar\\ Objetivo&Objetivo elementar\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % Model object&Array member\\ % \hline % Set&Elemental plain set\\ % Parameter&Number or symbol\\ % Variable&Elemental variable\\ % Constraint&Elemental constraint\\ % Objective&Elemental objective\\ % \end{tabular} \medskip Para referir a um membro particular de um objeto, este deve possuir {\it subíndices}. Por exemplo, se $a$ é um parâmetro 2-dimensional definido sobre $I\times J$, uma referência a seus membros particulares pode ser escrito como $a[i,j]$, onde $i\in I$ e $j\in J$. Entende-se que objetos escalares não necessitam de subíndices por serem 0-dimensionais. % In order to refer to a particular object member the object should be % provided with {\it subscripts}. For example, if $a$ is a 2-dimensional % parameter defined over $I\times J$, a reference to its particular % member can be written as $a[i,j]$, where $i\in I$ and $j\in J$. It is % understood that scalar objects being 0-dimensional need no subscripts. \section{Estrutura da descrição do modelo} Às vezes é desejável escrever um modelo que, por diferentes motivos, tenha que requerer diferentes dados para resolver cada instância do problema usando o mesmo modelo. Por esta razão, em MathProg a descrição do modelo consiste em duas partes: a {\it seção de modelo} e a {\it seção de dados}. % It is sometimes desirable to write a model which, at various points, % may require different data for each problem instance to be solved using % that model. For this reason in MathProg the model description consists % of two parts: the {\it model section} and the {\it data section}. A seção de modelo é a principal parte da descrição do modelo, pois ela contém as declarações dos objetos do modelo. Ela também é comum a todos os problemas baseados no modelo correspondente. % The model section is a main part of the model description that contains % declarations of model objects and is common for all problems based on % the corresponding model. A seção de dados é uma parte opcional da descrição do modelo que contém dados específicos para uma instância particular do problema. % The data section is an optional part of the model description that % contains data specific for a particular problem instance. Dependendo do que seja mais conveniente, as seções de modelo e de dados podem ser dispostas em um arquivo único ou em dois arquivos separados. Esta última funcionalidade permite que se tenha um quantidade arbitrária de seções de dados diferentes a serem usadas com a mesma seção de modelo. % Depending on what is more convenient the model and data sections can be % placed either in one file or in two separate files. The latter feature % allows having arbitrary number of different data sections to be used % with the same model section. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Codificação da descrição do modelo} \label{coding} A descrição do modelo é codificada em um formato de arquivo plano de texto usando o conjunto de caracteres ASCII. Os caracteres válidos na descrição do modelo são os seguintes: % The model description is coded in a plain text format using ASCII % character set. Characters valid in the model description are the % following: \begin{itemize} \item Caracteres alfabéticos:\\ \verb|A B C D E F G H I J K L M N O P Q R S T U V W X Y Z|\\ \verb|a b c d e f g h i j k l m n o p q r s t u v w x y z _| \item caracteres numéricos:\\ \verb|0 1 2 3 4 5 6 7 8 9| \item caracteres especiais:\\ \verb?! " # & ' ( ) * + , - . / : ; < = > [ ] ^ { | } ~? \item caracteres de espaço em branco:\\ \verb|SP HT CR NL VT FF| \end{itemize} Dentro de literais de cadeia e comentários quaisquer caracteres ASCII (exceto caracteres de controle) são válidos. % Within string literals and comments any ASCII characters (except % control characters) are valid. Caracteres de espaço-em-branco não são significativos. Eles podem ser usados livremente entre unidades léxicas para melhorar a legibilidade da descrição do modelo. Eles também são usados para separar unidades léxicas entre si, no caso de não existir outra forma de fazê-lo. % White-space characters are non-significant. They can be used freely % between lexical units to improve readability of the model description. % They are also used to separate lexical units from each other if there % is no other way to do that. Sintaticamente a descrição do modelo é uma sequência de unidades léxicas nas seguintes \linebreak categorias: % Syntactically model description is a sequence of lexical units in the % following categories: \begin{itemize} \item nomes simbólicos; \item literais numéricos; \item literais de cadeia; \item palavras-chave; \item delimitadores; \item comentários. \end{itemize} % \begin{itemize} % \item symbolic names; % \item numeric literals; % \item string literals; % \item keywords; % \item delimiters; % \item comments. % \end{itemize} As unidades léxicas da linguagem são discutidas abaixo. % \newpage \section{Nomes simbólicos} Um {\it nome simbólico} consiste de caracteres alfabéticos e numéricos, em que o primeiro deste deve ser alfabético. Todos os nomes simbólicos devem ser distintos (sensibilidade às maiúsculas: case-sensitive). % A {\it symbolic name} consists of alphabetic and numeric characters, % the first of which should be alphabetic. All symbolic names are % distinct (case sensitive). \para{Exemplos} \begin{verbatim} alfa123 Este_eh_um_nome _P123_abc_321 \end{verbatim} Nomes simbólicos são usados para identificar objetos do modelo (conjuntos, parâmetros, \linebreak variáveis, restrições, objetivos) e os índices. % Symbolic names are used to identify model objects (sets, parameters, % variables, constraints, objectives) and dummy indices. Todos os nomes simbólicos (exceto os nomes dos índices) devem ser únicos, i.e., a descrição do modelo não pode ter objetos com nomes idênticos. Nomes simbólicos de índices devem ser únicos dentro do escopo em que são válidos. % All symbolic names (except names of dummy indices) should be unique, % i.e. the model description should have no objects with identical names. % Symbolic names of dummy indices should be unique within the scope, % where they are valid. \section{Literais numéricos} Um {\it literal numérico} possui a forma {\it xx}{\tt E}{\it syy}, onde {\it xx} é um número com ponto decimal opcional, {\it s} é o sinal {\tt+} ou {\tt-}, {\it yy} é um expoente decimal. A letra {\tt E} é insensível à maiúsculas (case-insensitive) e pode ser codificada como {\tt e}. % A {\it numeric literal} has the form {\it xx}{\tt E}{\it syy}, where % {\it xx} is a number with optional decimal point, {\it s} is the sign % {\tt+} or {\tt-}, {\it yy} is a decimal exponent. The letter {\tt E} is % case insensitive and can be coded as {\tt e}. \para{Exemplos} \begin{verbatim} 123 3.14159 56.E+5 .78 123.456e-7 \end{verbatim} Literais numéricos são usados para representar quantidades numéricas. Eles possuem significado fixo óbvio. % Numeric literals are used to represent numeric quantities. They have % obvious fixed meaning. \section{Literais de cadeia} Uma {\it literal de cadeia} é uma sequência arbitrária de caracteres cercada por aspas tanto simples como duplas. Ambas formas são equivalentes. % A {\it string literal} is a sequence of arbitrary characters enclosed % either in single quotes or in double quotes. Both these forms are % equivalent. Se uma aspa simples é parte de uma literal de cadeia cercada por aspas simples, ela deve ser codificada duas vezes. De forma análoga, se uma aspa dupla é parte de um literal de cadeia cercada por aspas duplas, ela deve ser codificada duas vezes. % If a single quote is part of a string literal enclosed in single % quotes, it should be coded twice. Analogously, if a double quote is % part of a string literal enclosed in double quotes, it should be coded % twice. \para{Exemplos} \begin{verbatim} 'Esta eh uma string' "Esta eh outra string" 'Copo d''agua' """Beleza"" disse o capitao." \end{verbatim} Literais de cadeia são usadas para representar quantidades simbólicas. % String literals are used to represent symbolic quantities. \section{Palavras-chave} Uma {\it palavra-chave} é uma sequência de caracteres alfabéticos e possivelmente alguns caracteres especiais. % A {\it keyword} is a sequence of alphabetic characters and possibly % some special characters. Todas as palavras-chave caem em algumas das duas categorias: {\it palavras-chave reservadas}, que não podem ser usadas como nomes simbólicos, e {\it palavras-chave não-reservadas}, que são reconhecidas pelo contexto, portanto, podem ser usadas como nomes simbólicos. As palavras-chave reservadas são as seguintes: % All keywords fall into two categories: {\it reserved keywords}, which % cannot be used as symbolic names, and {\it non-reserved keywords}, % which are recognized by context and therefore can be used as symbolic % names. % % The reserved keywords are the following: \noindent\hfil \begin{tabular}{@{}p{.7in}p{.7in}p{.7in}p{.7in}@{}} {\tt and}&{\tt else}&{\tt mod}&{\tt union}\\ {\tt by}&{\tt if}&{\tt not}&{\tt within}\\ {\tt cross}&{\tt in}&{\tt or}\\ {\tt diff}&{\tt inter}&{\tt symdiff}\\ {\tt div}&{\tt less}&{\tt then}\\ \end{tabular} Palavras-chave não-reservadas são descritas nas seções posteriores. Todas as palavras-chave possuem um significado fixo, a ser explicado nas discussões das \linebreak construções sintáticas correspondentes, onde as palavras-chave são usadas. % Non-reserved keywords are described in following sections. % % All the keywords have fixed meaning, which will be explained on % discussion of corresponding syntactic constructions, where the keywords % are used. \section{Delimitadores} Um {\it delimitador} é tanto um caractere especial único quanto uma sequência de dois caracteres especiais, como segue: % A {\it delimiter} is either a single special character or a sequence of % two special characters as follows: \noindent\hfil \begin{tabular}{@{}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in} p{.3in}p{.3in}@{}} {\tt+}&{\tt**}&{\tt<=}&{\tt>}&{\tt\&\&}&{\tt:}&{\tt|}&{\tt[}& {\tt>>}\\ {\tt-}&{\tt\textasciicircum}&{\tt=}&{\tt<>}&{\tt||}&{\tt;}& {\tt\char126}&{\tt]}&{\tt<-}\\ {\tt*}&{\tt\&}&{\tt==}&{\tt!=}&{\tt.}&{\tt:=}&{\tt(}&{\tt\{}\\ {\tt/}&{\tt<}&{\tt>=}&{\tt!}&{\tt,}&{\tt..}&{\tt)}&{\tt\}}\\ \end{tabular} Se um delimitador consiste de dois caracteres, não deve haver espaços entre os eles. Todos os delimitadores possuem um significado fixo, a ser explicado nas discussões das \linebreak construções sintáticas correspondentes, onde os delimitadores são usados. % If the delimiter consists of two characters, there should be no spaces % between the characters. % % All the delimiters have fixed meaning, which will be explained on % discussion corresponding syntactic constructions, where the delimiters % are used. \section{Comentários} Com propósitos de documentação, a descrição do modelo pode conter {\it comentários}, que podem ter duas formas diferentes. A primeira forma é um {\it comentário de linha-única}, que começa com o caractere {\tt\#} e se estende até o final da linha. A segunda forma é uma {\it sequência de comentários}, que é uma sequência de quaisquer caracteres cercados por {\tt/*} e {\tt*/}. % For documenting purposes the model description can be provided with % {\it comments}, which may have two different forms. The first form is % a {\it single-line comment}, which begins with the character {\tt\#} % and extends until end of line. The second form is a {\it comment % sequence}, which is a sequence of any characters enclosed within % {\tt/*} and {\tt*/}. \para{Exemplos} \begin{verbatim} param n := 10; # Este é um comentario /* Este é outro comentário */ \end{verbatim} Comentários e caracteres de espaço-em-branco são ignorados pelo tradutor do modelo e podem aparecer em qualquer local da descrição do modelo. % Comments are ignored by the model translator and can appear anywhere in % the model description, where white-space characters are allowed. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newpage \chapter{Expressões} Uma {\it expressão} é uma regra para calcular um valor. Na descrição de um modelo, expressões são usadas como constituintes de certas sentenças. No geral, expressões são constituídas de operandos e operadores. Dependendo do tipo de valor resultante, todas expressões se enquadram nas seguintes categorias: % An {\it expression} is a rule for computing a value. In model % description expressions are used as constituents of certain statements. % % In general case expressions consist of operands and operators. % % Depending on the type of the resultant value all expressions fall into % the following categories: \vspace*{-8pt} \begin{itemize} \item expressões numéricas; \item expressões simbólicas; \item expressões indexantes; \item expressões de conjuntos; \item expressões lógicas; \item expressões lineares. \end{itemize} % \begin{itemize} % \item numeric expressions; % \item symbolic expressions; % \item indexing expressions; % \item set expressions; % \item logical expressions; % \item linear expressions. % \end{itemize} \vspace*{-8pt} \section{Expressões numéricas} Uma {\it expressão numérica} é uma regra para calcular um valor numérico individual representado como um número de ponto-flutuante. A expressão numérica primária pode ser um literal numérico, um índice, um parâmetro não-indexado, um parâmetro indexado, uma função interna de referência, uma expressão numérica iterada, uma expressão numérica condicional ou outra expressão cercada por parênteses. % A {\it numeric expression} is a rule for computing a single numeric % value represented as a floating-point number. % % The primary numeric expression may be a numeric literal, dummy index, % unsubscripted parameter, subscripted parameter, built-in function % reference, iterated numeric expression, conditional numeric expression, % or another numeric expression enclosed in parentheses. \para{Exemplos} \noindent \begin{tabular}{@{}ll@{}} \verb|1.23 |&(literal numérico)\\ \verb|j|&(índice)\\ \verb|time|&(parâmetro não-indexado)\\ \verb|a['May 2003',j+1]|&(parâmetro indexado)\\ \verb|abs(b[i,j])|&(função de referência)\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % \verb|1.23 |&(numeric literal)\\ % \verb|j|&(dummy index)\\ % \verb|time|&(unsubscripted parameter)\\ % \verb|a['May 2003',j+1]|&(subscripted parameter)\\ % \verb|abs(b[i,j])|&(function reference)\\ % \end{tabular} \newpage \noindent \begin{tabular}{@{}ll@{}} \verb|sum{i in S diff T} alpha[i] * b[i,j]|&(expressão iterada)\\ \verb|if i in I then 2 * p else q[i+1]|&(expressão condicional)\\ \verb|(b[i,j] + .5 * c)|&(expressão entre parênteses)\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % \verb|sum{i in S diff T} alpha[i] * b[i,j]|&(iterated expression)\\ % \verb|if i in I then 2 * p else q[i+1]|&(conditional expression)\\ % \verb|(b[i,j] + .5 * c)|&(parenthesized expression)\\ % \end{tabular} Expressões numéricas mais genéricas, contendo duas ou mais expressões numéricas primárias, podem ser construídas usando determinados operadores aritméticos. % More general numeric expressions containing two or more primary numeric % expressions may be constructed by using certain arithmetic operators. \para{Exemplos} \begin{verbatim} j+1 2 * a[i-1,j+1] - b[i,j] sum{j in J} a[i,j] * x[j] + sum{k in K} b[i,k] * x[k] (if i in I and p >= 1 then 2 * p else q[i+1]) / (a[i,j] + 1.5) \end{verbatim} \subsection{Literais numéricos} Se a expressão numérica primária é um literal numérico, o valor resultante é óbvio. % If the primary numeric expression is a numeric literal, the resultant % value is obvious. \subsection{Índices} Se a expressão numérica primária é um índice, o valor resultante é o valor corrente atribuído àquele índice. % If the primary numeric expression is a dummy index, the resultant value % is current value assigned to that dummy index. \subsection{Parâmetros não-indexados} Se a expressão numérica primária é um parâmetro não-indexado (que deve ser 0-dimensional), o valor resultante é o valor do parâmetro. % If the primary numeric expression is an unsubscripted parameter (which % should be 0-dimen\-sional), the resultant value is the value of that % parameter. \subsection{Parâmetros indexados} A expressão numérica primária, que se refere ao parâmetro indexado, possui a seguinte forma sintática: % The primary numeric expression, which refers to a subscripted % parameter, has the following syntactic form: $$ \mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} $i_n${\tt]}} $$ onde {\it nome} é o nome simbólico do parâmetro e $i_1$, $i_2$, \dots, $i_n$ são subíndices. Cada subíndice deve ser uma expressão numérica ou simbólica. O número de subíndices na lista de subíndices deve ser o mesmo da dimensão do parâmetro com o qual a lista de subíndices está associada. Os valores reais das expressões de subíndice são usadas para identificar um membro particular do parâmetro que determina o valor resultante da expressão primária. % where {\it name} is the symbolic name of the parameter, $i_1$, $i_2$, % \dots, $i_n$ are subscripts. % % Each subscript should be a numeric or symbolic expression. The number % of subscripts in the subscript list should be the same as the dimension % of the parameter with which the subscript list is associated. % % Actual values of subscript expressions are used to identify % a particular member of the parameter that determines the resultant % value of the primary expression. \newpage \subsection{Funções de referência} Em MathProg existem as seguintes funções internas, que podem ser usadas como expressões numéricas: % In MathProg there exist the following built-in functions which may be % used in numeric expressions: \begin{tabular}{@{}p{112pt}p{328pt}@{}} {\tt abs(}$x${\tt)}&$|x|$, valor absoluto de $x$\\ {\tt atan(}$x${\tt)}&$\arctan x$, valor principal do arco tangente de $x$ (em radianos)\\ {\tt atan(}$y${\tt,} $x${\tt)}&$\arctan y/x$, valor principal do arco tangente de $y/x$ (em radianos). Neste caso, os sinais de ambos argumentos $y$ e $x$ são usados para determinar o quadrante do valor resultante\\ {\tt card(}$X${\tt)}&$|X|$, cardinalidade (o número de elementos) do conjunto $X$\\ {\tt ceil(}$x${\tt)}&$\lceil x\rceil$, menor inteiro não menor que $x$ (``teto de $x$'')\\ {\tt cos(}$x${\tt)}&$\cos x$, cosseno de $x$ (em radianos)\\ {\tt exp(}$x${\tt)}&$e^x$, exponencial de $x$ na base-$e$\\ {\tt floor(}$x${\tt)}&$\lfloor x\rfloor$, maior inteiro não maior que $x$ (``piso de $x$'')\\ {\tt gmtime()}&o número de segundos decorridos deste 00:00:00 de~01~de~Jan de 1970, Tempo Universal Coordenado (detalhes na Seção \ref{gmtime}, página \pageref{gmtime})\\ {\tt length(}$s${\tt)}&$|s|$, comprimento da cadeia de caracteres $s$\\ {\tt log(}$x${\tt)}&$\log x$, logaritmo natural de $x$\\ {\tt log10(}$x${\tt)}&$\log_{10}x$, logaritmo comum (decimal) de $x$\\ {\tt max(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&o maior dos valores $x_1$, $x_2$, \dots, $x_n$\\ {\tt min(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&o menor dos valores $x_1$, $x_2$, \dots, $x_n$\\ {\tt round(}$x${\tt)}&arrendondamento de $x$ ao inteiro mais próximo\\ {\tt round(}$x${\tt,} $n${\tt)}&arrendondamento de $x$ a $n$ dígitos decimais\\ {\tt sin(}$x${\tt)}&$\sin x$, seno de $x$ (em radianos)\\ {\tt sqrt(}$x${\tt)}&$\sqrt{x}$, raiz quadrada não-negativa de $x$\\ {\tt str2time(}$s${\tt,} $f${\tt)}&conversão de uma cadeia de caracteres $s$ ao tempo calendário (detalhes na Seção \ref{str2time}, página \pageref{str2time})\\ {\tt trunc(}$x${\tt)}&truncado de $x$ ao inteiro mais próximo\\ {\tt trunc(}$x${\tt,} $n${\tt)}&truncado de $x$ a $n$ dígitos decimais\\ {\tt Irand224()}&gera inteiro pseudo-aleatório uniformemente distribuído em $[0,2^{24})$\\ {\tt Uniform01()}&gera número pseudo-aleatório uniformemente distribuído em $[0,1)$\\ {\tt Uniform(}$a${\tt,} $b${\tt)}&gera número pseudo-aleatório uniformemente distribuído em $[a,b)$\\ {\tt Normal01()}&gera variável Gaussiana pseudo-aleatória com $\mu=0$ e $\sigma=1$\\ {\tt Normal(}$\mu${\tt,} $\sigma${\tt)}&gera variável Gaussiana pseudo-aleatória com $\mu$ e $\sigma$ dados\\ \end{tabular} % \begin{tabular}{@{}p{112pt}p{328pt}@{}} % {\tt abs(}$x${\tt)}&$|x|$, absolute value of $x$\\ % {\tt atan(}$x${\tt)}&$\arctan x$, principal value of the arc tangent of % $x$ (in radians)\\ % {\tt atan(}$y${\tt,} $x${\tt)}&$\arctan y/x$, principal value of the % arc tangent of $y/x$ (in radians). In this case the signs of both % arguments $y$ and $x$ are used to determine the quadrant of the % resultant value\\ % {\tt card(}$X${\tt)}&$|X|$, cardinality (the number of elements) of % set $X$\\ % {\tt ceil(}$x${\tt)}&$\lceil x\rceil$, smallest integer not less than % $x$ (``ceiling of $x$'')\\ % {\tt cos(}$x${\tt)}&$\cos x$, cosine of $x$ (in radians)\\ % {\tt exp(}$x${\tt)}&$e^x$, base-$e$ exponential of $x$\\ % {\tt floor(}$x${\tt)}&$\lfloor x\rfloor$, largest integer not greater % than $x$ (``floor of $x$'')\\ % {\tt gmtime()}&the number of seconds elapsed since 00:00:00~Jan~1, 1970, % Coordinated Universal Time (for details see Section \ref{gmtime}, % page \pageref{gmtime})\\ % {\tt length(}$s${\tt)}&$|s|$, length of character string $s$\\ % {\tt log(}$x${\tt)}&$\log x$, natural logarithm of $x$\\ % {\tt log10(}$x${\tt)}&$\log_{10}x$, common (decimal) logarithm of $x$\\ % {\tt max(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&the largest % of values $x_1$, $x_2$, \dots, $x_n$\\ % {\tt min(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&the smallest % of values $x_1$, $x_2$, \dots, $x_n$\\ % {\tt round(}$x${\tt)}&rounding $x$ to nearest integer\\ % {\tt round(}$x${\tt,} $n${\tt)}&rounding $x$ to $n$ fractional decimal % digits\\ % {\tt sin(}$x${\tt)}&$\sin x$, sine of $x$ (in radians)\\ % {\tt sqrt(}$x${\tt)}&$\sqrt{x}$, non-negative square root of $x$\\ % {\tt str2time(}$s${\tt,} $f${\tt)}&converting character string $s$ to % calendar time (for details see Section \ref{str2time}, page % \pageref{str2time})\\ % {\tt trunc(}$x${\tt)}&truncating $x$ to nearest integer\\ % {\tt trunc(}$x${\tt,} $n${\tt)}&truncating $x$ to $n$ fractional % decimal digits\\ % {\tt Irand224()}&generating pseudo-random integer uniformly distributed % in $[0,2^{24})$\\ % {\tt Uniform01()}&generating pseudo-random number uniformly distributed % in $[0,1)$\\ % {\tt Uniform(}$a${\tt,} $b${\tt)}&generating pseudo-random number % uniformly distributed in $[a,b)$\\ % {\tt Normal01()}&generating Gaussian pseudo-random variate with % $\mu=0$ and $\sigma=1$\\ % {\tt Normal(}$\mu${\tt,} $\sigma${\tt)}&generating Gaussian % pseudo-random variate with given $\mu$ and $\sigma$\\ % \end{tabular} Os argumentos de todas as funções internas, exceto {\tt card}, {\tt length}, e {\tt str2time}, devem ser \linebreak expressões numéricas. O argumento de {\tt card} deve ser uma expressão de conjunto. O argumento de {\tt length} e ambos argumentos de {\tt str2time} devem ser expressões simbólicas. O valor resultante da expressão numérica, que é uma função de referência, é o resultado da aplicação da função ao(s) seu(s) argumento(s). Note que cada função geradora de números pseudo-aleatórios possui um argumento latente (i.e., algum estado interno), que é alterado sempre que função é aplicada. Assim, se a função é aplicada repetidamente mesmos aos argumentos idênticos, devido ao efeito secundário, sempre se produzirão valores resultantes diferentes. % Arguments of all built-in functions, except {\tt card}, {\tt length}, % and {\tt str2time}, should be numeric expressions. The argument of % {\tt card} should be a set expression. The argument of {\tt length} and % both arguments of {\tt str2time} should be symbolic expressions. % % The resultant value of the numeric expression, which is a function % reference, is the result of applying the function to its argument(s). % % Note that each pseudo-random generator function has a latent argument % (i.e. some internal state), which is changed whenever the function has % been applied. Thus, if the function is applied repeatedly even to % identical arguments, due to the side effect different resultant values % are always produced. \newpage \subsection{Expressões iteradas} \label{itexpr} Uma {\it expressão numérica iterada} é uma expressão numérica primária, que possui a seguinte forma sintática: $$\mbox{\it operador-iterado expressão-indexada integrando}$$ onde o {\it operador-iterado} é o nome simbólico do operador de iteração a ser executado (veja abaixo), {\it expressão-indexada} é uma expressão indexada que introduz índices e controla a iteração e {\it integrando} é uma expressão numérica que participa da operação. \noindent Em MathProg existem quatro operadores iterados, que podem ser usados em expressões numéricas: % An {\it iterated numeric expression} is a primary numeric expression, % which has the following syntactic form: % $$\mbox{\it iterated-operator indexing-expression integrand}$$ % where {\it iterated-operator} is the symbolic name of the iterated % operator to be performed (see below), {\it indexing-expression} is an % indexing expression which introduces dummy indices and controls % iterating, {\it integrand} is a numeric expression that participates in % the operation. % % In MathProg there exist four iterated operators, which may be used in % numeric expressions: {\def\arraystretch{2} \noindent\hfil \begin{tabular}{@{}lll@{}} {\tt sum}&somatório&$\displaystyle\sum_{(i_1,\dots,i_n)\in\Delta} f(i_1,\dots,i_n)$\\ {\tt prod}&produtório&$\displaystyle\prod_{(i_1,\dots,i_n)\in\Delta} f(i_1,\dots,i_n)$\\ {\tt min}&mínimo&$\displaystyle\min_{(i_1,\dots,i_n)\in\Delta} f(i_1,\dots,i_n)$\\ {\tt max}&máximo&$\displaystyle\max_{(i_1,\dots,i_n)\in\Delta} f(i_1,\dots,i_n)$\\ \end{tabular} } % {\def\arraystretch{2} % \noindent\hfil % \begin{tabular}{@{}lll@{}} % {\tt sum}&summation&$\displaystyle\sum_{(i_1,\dots,i_n)\in\Delta} % f(i_1,\dots,i_n)$\\ % {\tt prod}&production&$\displaystyle\prod_{(i_1,\dots,i_n)\in\Delta} % f(i_1,\dots,i_n)$\\ % {\tt min}&minimum&$\displaystyle\min_{(i_1,\dots,i_n)\in\Delta} % f(i_1,\dots,i_n)$\\ % {\tt max}&maximum&$\displaystyle\max_{(i_1,\dots,i_n)\in\Delta} % f(i_1,\dots,i_n)$\\ % \end{tabular} % } \noindent onde $i_1$, \dots, $i_n$ são índices introduzidos nas expressões indexadas, $\Delta$ é o domínio, um conjunto de $n$-tuplas especificado pela expressão indexada que define valores particulares atribuído aos índices ao executar a operação iterada e $f(i_1,\dots,i_n)$ é o integrando, uma expressão numérica cujo valor resultante depende dos índices. O valor resultante de uma expressão numérica iterada é o resultado da aplicação do operador iterado ao seu integrando por todas as $n$-tuplas contidas no domínio. % \noindent where $i_1$, \dots, $i_n$ are dummy indices introduced in % the indexing expression, $\Delta$ is the domain, a set of $n$-tuples % specified by the indexing expression which defines particular values % assigned to the dummy indices on performing the iterated operation, % $f(i_1,\dots,i_n)$ is the integrand, a numeric expression whose % resultant value depends on the dummy indices. % % The resultant value of an iterated numeric expression is the result of % applying of the iterated operator to its integrand over all $n$-tuples % contained in the domain. \subsection{Expressões condicionais} \label{ifthen} Uma {\it expressão numérica condicional} é uma expressão numérica primária que possui uma das seguintes formas sintáticas: % A {\it conditional numeric expression} is a primary numeric expression, % which has one of the following two syntactic forms: $$ {\def\arraystretch{1.4} \begin{array}{l} \mbox{{\tt if} $b$ {\tt then} $x$ {\tt else} $y$}\\ \mbox{{\tt if} $b$ {\tt then} $x$}\\ \end{array} } $$ onde $b$ é uma expressão lógica, enquanto que $x$ e $y$ são expressões numéricas. % where $b$ is an logical expression, $x$ and $y$ are numeric % expressions. O valor resultante da expressão condicional depende do valor da expressão lógica que segue a palavra-chave {\tt if}. Se ela recebe o valor {\it verdadeiro}, o valor da expressão condicional é o valor da expressão que segue a palavra-chave {\tt then}. Caso contrário, se a expressão lógica recebe o valor {\it falso}, o valor da expressão condicional é o valor da expressão que segue a palavra-chave {\it else}. Se ocorre a segunda forma sintática da expressão condicional, a reduzida, e a expressão lógica recebe o valor {\it falso}, então o valor resultante da expressão condicional é zero. % The resultant value of the conditional expression depends on the value % of the logical expression that follows the keyword {\tt if}. If it % takes on the value {\it true}, the value of the conditional expression % is the value of the expression that follows the keyword {\tt then}. % Otherwise, if the logical expression takes on the value {\it false}, % the value of the conditional expression is the value of the expression % that follows the keyword {\it else}. If the second, reduced form of the % conditional expression is used and the logical expression takes on the % value {\it false}, the resultant value of the conditional expression is % zero. \newpage \subsection{Expressões parentizadas} Qualquer expressão numérica pode ser cercada por parênteses, o que as torna sintaticamente uma expressão numérica primária. Parênteses podem ser usados em expressões numéricas, como em álgebra, para especificar a ordem desejada na qual as operações devem ser realizadas. Quando se usam parênteses, a expressão entre parênteses é avaliada antes e seu o valor resultante é usado. O valor resultante de uma expressão parentizada é o mesmo valor de uma expressão cercada entre parênteses. % Any numeric expression may be enclosed in parentheses that % syntactically makes it a primary numeric expression. % % Parentheses may be used in numeric expressions, as in algebra, to % specify the desired order in which operations are to be performed. % Where parentheses are used, the expression within the parentheses is % evaluated before the resultant value is used. % % The resultant value of the parenthesized expression is the same as the % value of the expression enclosed within parentheses. \subsection{Operadores aritméticos} Em MathProg exitem os seguintes operadores aritméticos, que podem ser usados em expressões numéricas: % In MathProg there exist the following arithmetic operators, which may % be used in numeric expressions: \begin{tabular}{@{}ll@{}} {\tt +} $x$&mais unário\\ {\tt -} $x$&menos unário\\ $x$ {\tt +} $y$&adição\\ $x$ {\tt -} $y$&subtração\\ $x$ {\tt less} $y$&diferença positiva (se $x1$, a segunda forma deve ser usada. % The number of indices in the indexing entry should be the same as the % dimension of the basic set $S$, i.e. if $S$ consists of 1-tuples, the % first form should be used, and if $S$ consists of $n$-tuples, where % $n>1$, the second form should be used. Se a primeira forma da entrada indexante é usada, o índice $i$ pode ser apenas um índice (veja mais adiante). Se a segunda forma é utilizada, os índices $i_1$, $i_2$, \dots, $i_n$ podem ser tanto índices como alguma expressão numérica ou simbólica, em que pelo menos um dos índices deve ser um índice. Na terceira, a forma reduzida da entrada indexante possui o mesmo efeito se houver $i$ (se $S$ é 1-dimensional) ou $i_1$, $i_2$, \dots, $i_n$ (se $S$ é $n$-dimensional) onde todos são especificados como índices. % If the first form of the indexing entry is used, the index $i$ can be % a dummy index only (see below). If the second form is used, the indices % $i_1$, $i_2$, \dots, $i_n$ can be either dummy indices or some numeric % or symbolic expressions, where at least one index should be a dummy % index. The third, reduced form of the indexing entry has the same % effect as if there were $i$ (if $S$ is 1-dimensional) or % $i_1$, $i_2$, \dots, $i_n$ (if $S$ is $n$-dimensional) all specified as % dummy indices. Um {\it índice} é um objeto auxiliar do modelo, que atua como uma variável individual. Os valores atribuídos aos índices são componentes das $n$-tuplas dos conjuntos básicos, i.e., algumas quantidades numéricas e simbólicas. % A {\it dummy index} is an auxiliary model object, which acts like an % individual variable. Values assigned to dummy indices are components of % $n$-tuples from basic sets, i.e. some numeric and symbolic quantities. Com propósitos de referência, índices podem ter nomes simbólicos. No entanto, diferentemente de outros objetos de modelo (conjuntos, parâmetros, etc.) índices não precisam ser \linebreak explicitamente declarados. Cada nome simbólico {\it não-declarado} usado na posição indexante de uma entrada indexante é reconhecida como o nome simbólico do índice correspondente. % For referencing purposes dummy indices can be provided with symbolic % names. However, unlike other model objects (sets, parameters, etc.) % dummy indices need not be explicitly declared. Each {\it undeclared} % symbolic name being used in the indexing position of an indexing entry % is recognized as the symbolic name of corresponding dummy index. Os nomes simbólicos dos índices são válidos somente dentro do escopo da expressão indexante, onde o índice foi inserido. Além do escopo, os índices são completamente inacessíveis, de modo que os mesmos nomes simbólicos podem ser usados para outros propósitos, em particular, para representar índices em outras expressões indexantes. % Symbolic names of dummy indices are valid only within the scope of the % indexing expression, where the dummy indices were introduced. Beyond % the scope the dummy indices are completely inaccessible, so the same % symbolic names may be used for other purposes, in particular, to % represent dummy indices in other indexing expressions. O escopo da expressão indexante, em que declarações implícitas de índices são válidas, depende do contexto em que a expressão indexante é usada: % The scope of indexing expression, where implicit declarations of dummy % indices are valid, depends on the context, in which the indexing % expression is used: \vspace*{-8pt} \begin{itemize} \item Se a expressão indexante é usada em um operador-iterado, seu escopo se estende até o final do integrando. \item Se a expressão indexante é usada como uma expressão de conjunto primária, seu escopo de estende até o final desta expressão indexante. \item Se a expressão indexante é usada para definir o domínio do subíndice na declaração de alguns objetos de modelo, seu escopo se estende até o final da declaração correspondente. \end{itemize} % \begin{itemize} % \item If the indexing expression is used in iterated operator, its % scope extends until the end of the integrand. % \item If the indexing expression is used as a primary set expression, % its scope extends until the end of that indexing expression. % \item If the indexing expression is used to define the subscript domain % in declarations of some model objects, its scope extends until the end % of the corresponding statement. % \end{itemize} \vspace*{-8pt} O mecanismo de indexação implementado para indexar expressões é melhor explicado por alguns exemplos discutidos abaixo. Sejam três conjuntos: % The indexing mechanism implemented by means of indexing expressions is % best explained by some examples discussed below. % % Let there be given three sets: $$ {\def\arraystretch{1.4} \begin{array}{l} A=\{4,7,9\},\\ B=\{(1,Jan),(1,Fev),(2,Mar),(2,Abr),(3,Mai),(3,Jun)\},\\ C=\{a,b,c\},\\ \end{array} } $$ % $$ % {\def\arraystretch{1.4} % \begin{array}{l} % A=\{4,7,9\},\\ % B=\{(1,Jan),(1,Feb),(2,Mar),(2,Apr),(3,May),(3,Jun)\},\\ % C=\{a,b,c\},\\ % \end{array} % } % $$ onde $A$ e $C$ consistem de 1-tuplas (singletos), $B$ consiste de 2-tuplas (dobletes). Considere a seguinte expressão indexante: $$\mbox{{\tt\{i in A, (j,k) in B, l in C\}}}$$ onde {\tt i}, {\tt j}, {\tt k}, e {\tt l} são índices. % where $A$ and $C$ consist of 1-tuples (singlets), $B$ consists of % 2-tuples (doublets). Consider the following indexing expression: % $$\mbox{{\tt\{i in A, (j,k) in B, l in C\}}}$$ % where {\tt i}, {\tt j}, {\tt k}, and {\tt l} are dummy indices. \newpage Embora MathProg não seja uma linguagem procedural, para qualquer expressão indexante uma descrição algorítmica equivalente pode ser dada. Em particular, a descrição algorítmica da expressão indexante acima poderia ser vista como segue: % Although MathProg is not a procedural language, for any indexing % expression an equivalent algorithmic description can be given. In % particular, the algorithmic description of the indexing expression % above could look like follows: \noindent\hfil \begin{tabular}{@{}l@{}} {\bf para todo} $i\in A$ {\bf faça}\\ \hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf faça}\\ \hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\ \hspace{48pt}{\it ação};\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}l@{}} % {\bf for all} $i\in A$ {\bf do}\\ % \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf do}\\ % \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\ % \hspace{48pt}{\it action};\\ % \end{tabular} \noindent onde os índices $i$, $j$, $k$, $l$ são consecutivamente atribuídos aos componentes correspondentes das $n$-tuplas dos conjuntos básicos $A$, $B$, $C$, e {\it ação} é alguma ação que dependa do contexto no qual a expressão indexante é usada. Por exemplo, se a ação fosse imprimir os valores atuais dos índices, a impressão seria vista como segue: % \noindent where the dummy indices $i$, $j$, $k$, $l$ are consecutively % assigned corresponding components of $n$-tuples from the basic sets $A$, % $B$, $C$, and {\it action} is some action that depends on the context, % where the indexing expression is used. For example, if the action were % printing current values of dummy indices, the printout would look like % follows: \noindent\hfil \begin{tabular}{@{}llll@{}} $i=4$&$j=1$&$k=Jan$&$l=a$\\ $i=4$&$j=1$&$k=Jan$&$l=b$\\ $i=4$&$j=1$&$k=Jan$&$l=c$\\ $i=4$&$j=1$&$k=Fev$&$l=a$\\ $i=4$&$j=1$&$k=Fev$&$l=b$\\ \multicolumn{4}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\ $i=9$&$j=3$&$k=Jun$&$l=b$\\ $i=9$&$j=3$&$k=Jun$&$l=c$\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}llll@{}} % $i=4$&$j=1$&$k=Jan$&$l=a$\\ % $i=4$&$j=1$&$k=Jan$&$l=b$\\ % $i=4$&$j=1$&$k=Jan$&$l=c$\\ % $i=4$&$j=1$&$k=Feb$&$l=a$\\ % $i=4$&$j=1$&$k=Feb$&$l=b$\\ % \multicolumn{4}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\ % $i=9$&$j=3$&$k=Jun$&$l=b$\\ % $i=9$&$j=3$&$k=Jun$&$l=c$\\ % \end{tabular} Seja o exemplo da expressão indexante usado na seguinte operação iterada: $$\mbox{{\tt sum\{i in A, (j,k) in B, l in C\} p[i,j,k,l]}}$$ onde {\tt p} é uma parâmetro numérico 4-dimensional ou alguma expressão numérica cujo valor resultante dependa de {\tt i}, {\tt j}, {\tt k} e {\tt l}. Neste caso, a ação é o somatório, de forma que o valor resultante da expressão numérica primária é: $$\sum_{i\in A,(j,k)\in B,l\in C}(p_{ijkl}).$$ % Let the example indexing expression be used in the following iterated % operation: % $$\mbox{{\tt sum\{i in A, (j,k) in B, l in C\} p[i,j,k,l]}}$$ % where {\tt p} is a 4-dimensional numeric parameter or some numeric % expression whose resultant value depends on {\tt i}, {\tt j}, {\tt k}, % and {\tt l}. In this case the action is summation, so the resultant % value of the primary numeric expression is: % $$\sum_{i\in A,(j,k)\in B,l\in C}(p_{ijkl}).$$ Agora seja a expressão indexante do exemplo usada como uma expressão de conjunto primária. Neste caso, a ação é reunir todas as 4-tuplas (quádruplas) da forma $(i,j,k,l)$ em um conjunto, de forma que o valor resultante de tal operação é simplesmente o produto Cartesiano dos conjuntos básicos: $$A\times B\times C=\{(i,j,k,l):i\in A,(j,k)\in B,l\in C\}.$$ Note que neste caso, a mesma expressão indexante pode ser escrita na forma reduzida: $$\mbox{{\tt\{A, B, C\}}}$$ pois os índices $i$, $j$, $k$ e $l$ não são referenciados, portanto, seus nomes simbólicos não precisam ser especificados. % Now let the example indexing expression be used as a primary set % expression. In this case the action is gathering all 4-tuples % (quadruplets) of the form $(i,j,k,l)$ in one set, so the resultant % value of such operation is simply the Cartesian product of the basic % sets: % $$A\times B\times C=\{(i,j,k,l):i\in A,(j,k)\in B,l\in C\}.$$ % Note that in this case the same indexing expression might be written in % the reduced form: % $$\mbox{{\tt\{A, B, C\}}}$$ % because the dummy indices $i$, $j$, $k$, and $l$ are not referenced and % therefore their symbolic names need not be specified. \newpage Finalmente, seja a expressão indexante do exemplo usada como o domínio do subíndice na declaração de um objeto de modelo 4-dimensional, por exemplo, um parâmetro numérico: % Finally, let the example indexing expression be used as the subscript % domain in the declaration of a 4-dimensional model object, say, % a numeric parameter: $$\mbox{{\tt param p\{i in A, (j,k) in B, l in C\}} \dots {\tt;}}$$ \noindent Neste caso, a ação é gerar os membros do parâmetro, onde cada membro possui a forma $p[i,j,k,l]$. % \noindent In this case the action is generating the parameter members, % where each member has the form $p[i,j,k,l]$. Como mencionado anteriormente, alguns índices da segunda forma das entradas indexantes podem ser expressões numéricas ou simbólicas, não apenas índices. Neste caso, os valores resultantes destas expressões desempenham o papel de algumas condições lógicas para selecionar apenas aquelas $n$-tuplas do produto Cartesiano dos conjuntos básicos que satisfaçam estas condições. % As was said above, some indices in the second form of indexing entries % may be numeric or symbolic expressions, not only dummy indices. In this % case resultant values of such expressions play role of some logical % conditions to select only that $n$-tuples from the Cartesian product of % basic sets that satisfy these conditions. Considere, por exemplo, a seguinte expressão indexante: $$\mbox{{\tt\{i in A, (i-1,k) in B, l in C\}}}$$ onde {\tt i}, {\tt k} e {\tt l} são índices, e {\tt i-1} é uma expressão numérica. A descrição algorítmica desta expressão indexante é a seguinte: % Consider, for example, the following indexing expression: % $$\mbox{{\tt\{i in A, (i-1,k) in B, l in C\}}}$$ % where {\tt i}, {\tt k}, {\tt l} are dummy indices, and {\tt i-1} is % a numeric expression. The algorithmic decsription of this indexing % expression is the following: \noindent\hfil \begin{tabular}{@{}l@{}} {\bf para todo} $i\in A$ {\bf faça}\\ \hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf e} $j=i-1$ {\bf faça}\\ \hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\ \hspace{48pt}{\it ação};\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}l@{}} % {\bf for all} $i\in A$ {\bf do}\\ % \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf and} $j=i-1$ {\bf do}\\ % \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\ % \hspace{48pt}{\it action};\\ % \end{tabular} \noindent Assim, se esta expressão indexante fosse usada como uma expressão de conjunto primária, o conjunto resultante seira o seguinte: $$\{(4,Mai,a),(4,Mai,b),(4,Mai,c),(4,Jun,a),(4,Jun,b),(4,Jun,c)\}.$$ Deve-se notar que neste caso o conjunto resultante consiste em 3-tuplas, e não de 4-tuplas, porque na expressão indexante não há índice que corresponda ao primeiro componente das 2-tuplas do conjunto $B$. % \noindent Thus, if this indexing expression were used as a primary set % expression, the resultant set would be the following: % $$\{(4,May,a),(4,May,b),(4,May,c),(4,Jun,a),(4,Jun,b),(4,Jun,c)\}.$$ % Should note that in this case the resultant set consists of 3-tuples, % not of 4-tuples, because in the indexing expression there is no dummy % index that corresponds to the first component of 2-tuples from the set % $B$. A regra geral é: o número de componentes de $n$-tuplas definido por uma expressão indexante é o mesmo do número de índices naquela expressão, onde a correspondência entre índices e componentes nas $n$-tuplas no conjunto resultante é posicional, i.e., o primeiro índice corresponde ao primeiro componente, o segundo índice corresponde ao segundo componente, etc. % The general rule is: the number of components of $n$-tuples defined by % an indexing expression is the same as the number of dummy indices in % that expression, where the correspondence between dummy indices and % components on $n$-tuples in the resultant set is positional, i.e. the % first dummy index corresponds to the first component, the second dummy % index corresponds to the second component, etc. Em alguns casos é necessário selecionar um subconjunto do produto Cartesiano de alguns \linebreak conjuntos. Isto pode ser alcançado mediante o emprego de um predicado lógico opcional, que é especificado na expressão indexante. % In some cases it is needed to select a subset from the Cartesian % product of some sets. This may be attained by using an optional logical % predicate, which is specified in the indexing expression. Considere, por exemplo, a seguinte expressão indexante: $$\mbox{{\tt\{i in A, (j,k) in B, l in C: i <= 5 and k <> 'Mar'\}}}$$ onde a expressão lógica após os dois pontos é um predicado. A descrição algorítmica desta expressão indexante é a seguinte: % Consider, for example, the following indexing expression: % $$\mbox{{\tt\{i in A, (j,k) in B, l in C: i <= 5 and k <> 'Mar'\}}}$$ % where the logical expression following the colon is a predicate. The % algorithmic description of this indexing expression is the following: \noindent\hfil \begin{tabular}{@{}l@{}} {\bf para todo} $i\in A$ {\bf faça}\\ \hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf faça}\\ \hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\ \hspace{48pt}{\bf se} $i\leq 5$ {\bf e} $k\neq`Mar'$ {\bf então}\\ \hspace{64pt}{\it ação};\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}l@{}} % {\bf for all} $i\in A$ {\bf do}\\ % \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf do}\\ % \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\ % \hspace{48pt}{\bf if} $i\leq 5$ {\bf and} $k\neq`Mar'$ {\bf then}\\ % \hspace{64pt}{\it action};\\ % \end{tabular} \noindent Assim, se a expressão indexante fosse usada como uma expressão de conjunto primária, o conjunto resultante seria o seguinte: $$\{(4,1,Jan,a),(4,1,Fev,a),(4,2,Abr,a),\dots,(4,3,Jun,c)\}.$$ Se o predicado não é especificado na expressão indexante assume-se um, que recebe o valor {\it verdadeiro}. % \noindent Thus, if this indexing expression were used as a primary set % expression, the resultant set would be the following: % $$\{(4,1,Jan,a),(4,1,Feb,a),(4,2,Apr,a),\dots,(4,3,Jun,c)\}.$$ % % If no predicate is specified in the indexing expression, one, which % takes on the value {\it true}, is assumed. \section{Expressões de conjunto} Uma {\it expressão de conjunto} é uma regra para calcular um conjunto elementar, i.e., uma coleção de $n$-tuplas, onde os componentes das $n$-tuplas são quantidades numéricas e simbólicas. % A {\it set expression} is a rule for computing an elemental set, i.e. % a collection of $n$-tuples, where components of $n$-tuples are numeric % and symbolic quantities. A expressão de conjunto primária pode ser um conjunto de literais, um conjunto não-indexado, um conjunto indexado, um conjunto ``aritmético'', uma expressão indexante, uma expressão de \linebreak conjunto iterada, uma expressão de conjunto condicional ou outra expressão cercada por \linebreak parênteses. \para{Exemplos} % The primary set expression may be a literal set, unsubscripted set, % subscripted set, ``arithmetic'' set, indexing expression, iterated set % expression, conditional set expression, or another set expression % enclosed in parentheses. % % \para{Examples} \noindent \begin{tabular}{@{}ll@{}} \verb|{(123,'aaa'), (i+1,'bbb'), (j-1,'ccc')}| &(conjunto de literais)\\ \verb|I| &(conjunto não-indexado)\\ \verb|S[i-1,j+1]| &(conjunto indexado)\\ \verb|1..t-1 by 2| &(conjunto ``aritmético'')\\ \verb|{t in 1..T, (t+1,j) in S: (t,j) in F}| &(expressão indexante)\\ \verb|setof{i in I, j in J}(i+1,j-1)| &(expressão de conjunto iterado)\\ \verb|if i < j then S[i,j] else F diff S[i,j]| &(expressão de conjunto condicional)\\ \verb|(1..10 union 21..30)| &(expressão de conjunto parentizado)\\ \end{tabular} % \noindent % \begin{tabular}{@{}ll@{}} % \verb|{(123,'aaa'), (i+1,'bbb'), (j-1,'ccc')}| &(literal set)\\ % \verb|I| &(unsubscripted set)\\ % \verb|S[i-1,j+1]| &(subscripted set)\\ % \verb|1..t-1 by 2| &(``arithmetic'' set)\\ % \verb|{t in 1..T, (t+1,j) in S: (t,j) in F}| &(indexing expression)\\ % \verb|setof{i in I, j in J}(i+1,j-1)| &(iterated set expression)\\ % \verb|if i < j then S[i,j] else F diff S[i,j]| &(conditional set % expression)\\ % \verb|(1..10 union 21..30)| &(parenthesized set expression)\\ % \end{tabular} Expressões de conjuntos mais genéricas contendo duas ou mais expressões de conjunto primárias podem ser construídas usando operadores específicos de conjunto . \para{Exemplos} % More general set expressions containing two or more primary set % expressions may be constructed by using certain set operators. % % \para{Examples} \begin{verbatim} (A union B) inter (I cross J) 1..10 cross (if i < j then {'a', 'b', 'c'} else {'d', 'e', 'f'}) \end{verbatim} \subsection{Conjuntos de literais} Um {\it conjunto de literais} é uma expressão de conjunto primária que possui as duas formas \linebreak sintáticas seguintes: % A {\it literal set} is a primary set expression, which has the % following two syntactic forms: $$ {\def\arraystretch{1.4} \begin{array}{l} \mbox{{\tt\{}$e_1${\tt,} $e_2${\tt,} \dots{\tt,} $e_m${\tt\}}}\\ \mbox{{\tt\{(}$e_{11}${\tt,} \dots{\tt,} $e_{1n}${\tt),} {\tt(}$e_{21}${\tt,} \dots{\tt,} $e_{2n}${\tt),} \dots{\tt,} {\tt(}$e_{m1}${\tt,} \dots{\tt,} $e_{mn}${\tt)\}}}\\ \end{array} } $$ % $$ % {\def\arraystretch{1.4} % \begin{array}{l} % \mbox{{\tt\{}$e_1${\tt,} $e_2${\tt,} \dots{\tt,} $e_m${\tt\}}}\\ % \mbox{{\tt\{(}$e_{11}${\tt,} \dots{\tt,} $e_{1n}${\tt),} % {\tt(}$e_{21}${\tt,} \dots{\tt,} $e_{2n}${\tt),} \dots{\tt,} % {\tt(}$e_{m1}${\tt,} \dots{\tt,} $e_{mn}${\tt)\}}}\\ % \end{array} % } % $$ onde $e_1$, \dots, $e_m$, $e_{11}$, \dots, $e_{mn}$ são expressões numéricas ou simbólicas. Se a primeira forma é adotada, o conjunto resultante consiste de 1-tuplas (singletos) enumerados entre as chaves. É permitido especificar um conjunto vazio como {\tt\{\ \}}, que não possui 1-tuplas. Se a segunda forma é adotada, o conjunto resultante consiste de $n$-tuplas enumeradas entre as chaves, onde uma $n$-tupla particular consiste nos componentes correspondentes enumerados entre parênteses. Todas as $n$-tuplas devem ter o mesmo número de componentes. % where $e_1$, \dots, $e_m$, $e_{11}$, \dots, $e_{mn}$ are numeric or % symbolic expressions. % % If the first form is used, the resultant set consists of 1-tuples % (singlets) enumerated within the curly braces. It is allowed to specify % an empty set as {\tt\{\ \}}, which has no 1-tuples. If the second form % is used, the resultant set consists of $n$-tuples enumerated within the % curly braces, where a particular $n$-tuple consists of corresponding % components enumerated within the parentheses. All $n$-tuples should % have the same number of components. \subsection{Conjuntos não-indexados} Se a expressão de conjunto primária é um conjunto não-indexado (que deve ser 0-dimensional), o conjunto resultante é um conjunto elementar associado com o objeto conjunto correspondente. % If the primary set expression is an unsubscripted set (which should be % 0-dimen\-sional), the resultant set is an elemental set associated with % the corresponding set object. \subsection{Conjuntos indexados} A expressão de conjunto primária, que se refere a um conjunto indexado, tem a seguinte forma sintática: $$\mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} $i_n${\tt]}}$$ onde {\it nome} é o nome simbólico do objeto conjunto e $i_1$, $i_2$, \dots, $i_n$ são subíndices. % The primary set expression, which refers to a subscripted set, has the % following syntactic form: % $$\mbox{{\it name}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} % $i_n${\tt]}}$$ % where {\it name} is the symbolic name of the set object, $i_1$, $i_2$, % \dots, $i_n$ are subscripts. Cada subíndice deve ser uma expressão numérica ou simbólica. O número de subíndices nas lista de subíndices deve ser o mesmo da dimensão do objeto conjunto com o qual as lista de subíndice está associada. Os valores correntes das expressões de subíndices são usados para identificar um membro \linebreak particular do objeto conjunto que determina o conjunto resultante. % Each subscript should be a numeric or symbolic expression. The number % of subscripts in the subscript list should be the same as the dimension % of the set object with which the subscript list is associated. % % Actual values of subscript expressions are used to identify a % particular member of the set object that determines the resultant set. \subsection{Conjuntos ``aritméticos''} A expressão de conjunto primária que constitui um conjunto ``aritmético'', possui as duas formas sintáticas seguintes: % The primary set expression, which is an ``arithmetic'' set, has the % following two syntactic forms: $$ {\def\arraystretch{1.4} \begin{array}{l} \mbox{$t_0$ {\tt..} $t_1$ {\tt by} $\delta t$}\\ \mbox{$t_0$ {\tt..} $t_1$}\\ \end{array} } $$ onde $t_0$, $t_1$, e $\delta t$ são expressões numéricas (o valor de $\delta t$ não deve ser zero). A segunda forma é equivalente a primeira forma, onde $\delta t=1$. Se $\delta t>0$, o conjunto resultante é determinado como segue: $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_0\leq t\leq t_1)\}.$$ Caso contrário, se $\delta t<0$, o conjunto resultante é determinado como segue: $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_1\leq t\leq t_0)\}.$$ % $$ % {\def\arraystretch{1.4} % \begin{array}{l} % \mbox{$t_0$ {\tt..} $t_1$ {\tt by} $\delta t$}\\ % \mbox{$t_0$ {\tt..} $t_1$}\\ % \end{array} % } % $$ % where $t_0$, $t_1$, and $\delta t$ are numeric expressions (the value % of $\delta t$ should not be zero). The second form is equivalent to the % first form, where $\delta t=1$. % % If $\delta t>0$, the resultant set is determined as follows: % $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_0\leq t\leq t_1)\}.$$ % Otherwise, if $\delta t<0$, the resultant set is determined as follows: % $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_1\leq t\leq t_0)\}.$$ \subsection{Expressões indexantes} Se a expressão primária é uma expressão indexante, o conjunto resultante é determinado como descrito anteriormente, na Seção \ref{indexing}, página \pageref{indexing}. % If the primary set expression is an indexing expression, the resultant % set is determined as described above in Section \ref{indexing}, page % \pageref{indexing}. \newpage \subsection{Expressões iteradas} Uma {\it expressão de conjunto iterada} é uma expressão de conjunto primária, que possui a seguinte forma sintática: $$\mbox{{\tt setof} {\it expressão-indexante} {\it integrando}}$$ onde {\it expressão-indexante} é uma expressão indexante, que introduz índices e controla a iteração, {\it integrando} é tanto uma expressão numérica ou simbólica individual, como uma lista de expressões numéricas ou simbólicas separadas por vírgula e cercadas entre parênteses. % An {\it iterated set expression} is a primary set expression, which has % the following syntactic form: % $$\mbox{{\tt setof} {\it indexing-expression} {\it integrand}}$$ % where {\it indexing-expression} is an indexing expression, which % introduces dummy indices and controls iterating, {\it integrand} is % either a single numeric or symbolic expression or a list of numeric and % symbolic expressions separated by commae and enclosed in parentheses. Se o integrando é uma expressão numérica ou simbólica individual, o conjunto resultante consiste de 1-tuplas, sendo determinado como segue: $$\{x:(i_1,\dots,i_n)\in\Delta\},$$ \noindent onde $x$ é um valor do integrando, $i_1$, \dots, $i_n$ são índices introduzidos na expressão indexante, $\Delta$ é o domínio, um conjunto de $n$-tuplas especificado pela expressão indexante que define valores particulares atribuídos aos índices ao realizar a operação de iteração. % If the integrand is a single numeric or symbolic expression, the % resultant set consists of 1-tuples and is determined as follows: % $$\{x:(i_1,\dots,i_n)\in\Delta\},$$ % \noindent where $x$ is a value of the integrand, $i_1$, \dots, $i_n$ % are dummy indices introduced in the indexing expression, $\Delta$ is % the domain, a set of $n$-tuples specified by the indexing expression, % which defines particular values assigned to the dummy indices on % performing the iterated operation. Se o integrando é uma lista contendo $m$ expressões numéricas e simbólicas, o conjunto resultante consiste de $m$-tuplas, sendo determinado como segue: $$\{(x_1,\dots,x_m):(i_1,\dots,i_n)\in\Delta\},$$ onde $x_1$, \dots, $x_m$ são valores das expressões na lista de integrandos, $i_1$, \dots, $i_n$ e $\Delta$ possuem o mesmo significado anterior. % If the integrand is a list containing $m$ numeric and symbolic % expressions, the resultant set consists of $m$-tuples and is determined % as follows: % $$\{(x_1,\dots,x_m):(i_1,\dots,i_n)\in\Delta\},$$ % where $x_1$, \dots, $x_m$ are values of the expressions in the % integrand list, $i_1$, \dots, $i_n$ and $\Delta$ have the same meaning % as above. \subsection{Expressões condicionais} Uma {\it expressão de conjunto condicional} é uma expressão de conjunto primária que possui a seguinte forma sintática: $$\mbox{{\tt if} $b$ {\tt then} $X$ {\tt else} $Y$}$$ onde $b$ é uma expressão lógica, $X$ e $Y$ são expressões de conjunto, que devem definir conjuntos da mesma dimensão. % A {\it conditional set expression} is a primary set expression that has % the following syntactic form: % $$\mbox{{\tt if} $b$ {\tt then} $X$ {\tt else} $Y$}$$ % where $b$ is an logical expression, $X$ and $Y$ are set expressions, % which should define sets of the same dimension. O valor resultante da expressão condicional depende do valor da expressão lógica que segue a palavra-chave {\tt if}. Se ela recebe o valor {\it verdadeiro}, o conjunto resultante é o valor da expressão que segue a palavra-chave {\tt then}. Caso contrário, se a expressão lógica recebe o valor {\it falso}, o conjunto resultante é o valor da expressão que segue a palavra-chave {\tt else}. % The resultant value of the conditional expression depends on the value % of the logical expression that follows the keyword {\tt if}. If it % takes on the value {\it true}, the resultant set is the value of the % expression that follows the keyword {\tt then}. Otherwise, if the % logical expression takes on the value {\it false}, the resultant set is % the value of the expression that follows the keyword {\tt else}. \subsection{Expressões parentizadas} Qualquer expressão de conjunto pode ser cercada entre parênteses, o que as tornam \linebreak sintaticamente uma expressão de conjunto primária. Parênteses podem ser usados em expressões de conjunto, como em álgebra, para especificar a ordem desejada nas quais as operações devem ser executadas. Quando se usam parênteses, a expressão entre parênteses é avaliada antes que o valor resultante seja usado. O valor resultante de uma expressão parentizada é idêntico ao valor da expressão cercada entre parênteses. % Any set expression may be enclosed in parentheses that syntactically % makes it a primary set expression. % % Parentheses may be used in set expressions, as in algebra, to specify % the desired order in which operations are to be performed. Where % parentheses are used, the expression within the parentheses is % evaluated before the resultant value is used. % % The resultant value of the parenthesized expression is the same as the % value of the expression enclosed within parentheses. \newpage \subsection{Operadores de conjunto} Em MathProg existem os seguintes operadores de conjunto, que podem ser usados em expressões de conjunto: % In MathProg there exist the following set operators, which may be used % in set expressions: \begin{tabular}{@{}ll@{}} $X$ {\tt union} $Y$&união $X\cup Y$\\ $X$ {\tt diff} $Y$&diferença $X\backslash Y$\\ $X$ {\tt symdiff} $Y$&diferença simétrica $X\oplus Y=(X\backslash Y)\cup(Y\backslash X)$\\ $X$ {\tt inter} $Y$&interseção $X\cap Y$\\ $X$ {\tt cross} $Y$&produto Cartesiano (cruzado) $X\times Y$\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % $X$ {\tt union} $Y$&union $X\cup Y$\\ % $X$ {\tt diff} $Y$&difference $X\backslash Y$\\ % $X$ {\tt symdiff} $Y$&symmetric difference % $X\oplus Y=(X\backslash Y)\cup(Y\backslash X)$\\ % $X$ {\tt inter} $Y$&intersection $X\cap Y$\\ % $X$ {\tt cross} $Y$&cross (Cartesian) product $X\times Y$\\ % \end{tabular} \noindent onde $X$ e Y são expressões de conjunto, que devem definir conjuntos de dimensões idênticas (exceto o produto Cartesiano). Se a expressão inclui mais de um operador de conjunto, todos operadores são executados da esquerda para a direita de acordo com a hierarquia das operações (veja adiante). O valor resultante da expressão, que contém operadores de conjunto, é o resultado da aplicação dos operadores aos seus operandos. A dimensão do conjunto resultante, i.e., a dimensão das $n$-tuplas, dos quais consistem o conjunto resultante, é a mesma da dimensão dos operandos, exceto o produto Cartesiano, onde a dimensão do conjunto resultante é a soma das dimensões dos seus operandos. % \noindent where $X$ and Y are set expressions, which should define sets % of identical dimension (except the Cartesian product). % % If the expression includes more than one set operator, all operators % are performed from left to right according to the hierarchy of % operations (see below). % % The resultant value of the expression, which contains set operators, is % the result of applying the operators to their operands. % % The dimension of the resultant set, i.e. the dimension of $n$-tuples, % of which the resultant set consists of, is the same as the dimension of % the operands, except the Cartesian product, where the dimension of the % resultant set is the sum of the dimensions of its operands. \subsection{Hierarquia das operações} A lista seguinte mostra a hierarquia das operações em expressões de conjunto: % The following list shows the hierarchy of operations in set % expressions: \noindent\hfil \begin{tabular}{@{}ll@{}} Operação&Hierarquia\\ \hline Avaliação de operações numéricas& 1{\textsuperscript{\b{a}}}-7{\textsuperscript{\b{a}}}\\ Avaliação de operações simbólicas& 8{\textsuperscript{\b{a}}}-9{\textsuperscript{\b{a}}}\\ Avaliação de conjuntos iterados ou ``aritméticos'' ({\tt setof}, {\tt..})& 10{\textsuperscript{\b{a}}}\\ Produto Cartesiano ({\tt cross})& 11{\textsuperscript{\b{a}}}\\ Interseção ({\tt inter})& 12{\textsuperscript{\b{a}}}\\ União e diferença ({\tt union}, {\tt diff}, {\tt symdiff})& 13{\textsuperscript{\b{a}}}\\ Avaliação condicional ({\tt if} \dots {\tt then} \dots {\tt else})& 14{\textsuperscript{\b{a}}}\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}ll@{}} % Operation&Hierarchy\\ % \hline % Evaluation of numeric operations&1st-7th\\ % Evaluation of symbolic operations&8th-9th\\ % Evaluation of iterated or ``arithmetic'' set ({\tt setof}, {\tt..})& % 10th\\ % Cartesian product ({\tt cross})&11th\\ % Intersection ({\tt inter})&12th\\ % Union and difference ({\tt union}, {\tt diff}, {\tt symdiff})&13th\\ % Conditional evaluation ({\tt if} \dots {\tt then} \dots {\tt else})& % 14th\\ % \end{tabular} Esta hierarquia possui o mesmo significado como explicado anteriormente para expressões \linebreak numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}). % This hierarchy has the same meaning as was explained above for numeric % expressions (see Subsection \ref{hierarchy}, page \pageref{hierarchy}). \newpage \section{Expressões lógicas} Uma {\it expressão lógica} é uma regra para calcular um valor lógico individual, que pode ser {\it verdadeiro} ou {\it falso}. A expressão lógica primária pode ser uma expressão numérica, uma expressão relacional, uma expressão lógica iterada ou outra expressão lógica cercada entre parênteses. \para{Exemplos} % A {\it logical expression} is a rule for computing a single logical % value, which can be either {\it true} or {\it false}. % % The primary logical expression may be a numeric expression, relational % expression, iterated logical expression, or another logical expression % enclosed in parentheses. % % \para{Examples} \noindent \begin{tabular}{@{}ll@{}} \verb|i+1| &(expressão numérica)\\ \verb|a[i,j] < 1.5| &(expressão relacional)\\ \verb|s[i+1,j-1] <> 'Mar' & year | &(expressão relacional)\\ \verb|(i+1,'Jan') not in I cross J| &(expressão relacional)\\ \verb|S union T within A[i] inter B[j]| &(expressão relacional)\\ \verb|forall{i in I, j in J} a[i,j] < .5 * b[i]| &(expressão lógica iterada)\\ \verb|(a[i,j] < 1.5 or b[i] >= a[i,j])| &(expressão lógica parentizada)\\ \end{tabular} % \noindent % \begin{tabular}{@{}ll@{}} % \verb|i+1| &(numeric expression)\\ % \verb|a[i,j] < 1.5| &(relational expression)\\ % \verb|s[i+1,j-1] <> 'Mar' & year | &(relational expression)\\ % \verb|(i+1,'Jan') not in I cross J| &(relational expression)\\ % \verb|S union T within A[i] inter B[j]| &(relational expression)\\ % \verb|forall{i in I, j in J} a[i,j] < .5 * b[i]| &(iterated logical % expression)\\ % \verb|(a[i,j] < 1.5 or b[i] >= a[i,j])| &(parenthesized logical % expression)\\ % \end{tabular} Expressões lógicas mais genéricas, contendo duas ou mais expressões lógicas primárias, podem ser construídas usando determinados operadores lógicos. \para{Exemplos} \begin{verbatim} not (a[i,j] < 1.5 or b[i] >= a[i,j]) and (i,j) in S (i,j) in S or (i,j) not in T diff U \end{verbatim} % More general logical expressions containing two or more primary logical % expressions may be constructed by using certain logical operators. % % \para{Examples} % % \begin{verbatim} % not (a[i,j] < 1.5 or b[i] >= a[i,j]) and (i,j) in S % (i,j) in S or (i,j) not in T diff U % \end{verbatim} \vspace*{-8pt} \subsection{Expressões numéricas} O valor resultante da expressão lógica primária, que é uma expressão numérica, é {\it verdadeiro}, se o valor resultante da expressão numérica é diferente de zero. Caso contrário o valor resultante da expressão lógica é {\it falso}. % The resultant value of the primary logical expression, which is a % numeric expression, is {\it true}, if the resultant value of the % numeric expression is non-zero. Otherwise the resultant value of the % logical expression is {\it false}. \vspace*{-8pt} \subsection{Operadores relacionais} Em MathProg existem os seguintes operadores relacionais, que podem ser usados em expressões lógicas: % In MathProg there exist the following relational operators, which may % be used in logical expressions: \begin{tabular}{@{}ll@{}} $x$ {\tt<} $y$&verifica se $x=} $y$&verifica se $x\geq y$\\ $x$ {\tt>} $y$&verifica se $x>y$\\ $x$ {\tt<>} $y$, $x$ {\tt!=} $y$&verifica se $x\neq y$\\ $x$ {\tt in} $Y$&verifica se $x\in Y$\\ {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt in} $Y$&verifica se $(x_1,\dots,x_n)\in Y$\\ $x$ {\tt not} {\tt in} $Y$, $x$ {\tt!in} $Y$&verifica se $x\not\in Y$\\ {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt not} {\tt in} $Y$, {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt !in} $Y$&verifica se $(x_1,\dots,x_n)\not\in Y$\\ $X$ {\tt within} $Y$&verifica se $X\subseteq Y$\\ $X$ {\tt not} {\tt within} $Y$, $X$ {\tt !within} $Y$&verifica se $X\not\subseteq Y$\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % $x$ {\tt<} $y$&test on $x=} $y$&test on $x\geq y$\\ % $x$ {\tt>} $y$&test on $x>y$\\ % $x$ {\tt<>} $y$, $x$ {\tt!=} $y$&test on $x\neq y$\\ % $x$ {\tt in} $Y$&test on $x\in Y$\\ % {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt in} $Y$&test on % $(x_1,\dots,x_n)\in Y$\\ % $x$ {\tt not} {\tt in} $Y$, $x$ {\tt!in} $Y$&test on $x\not\in Y$\\ % {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt not} {\tt in} $Y$, % {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt !in} $Y$&test on % $(x_1,\dots,x_n)\not\in Y$\\ % $X$ {\tt within} $Y$&test on $X\subseteq Y$\\ % $X$ {\tt not} {\tt within} $Y$, $X$ {\tt !within} $Y$&test on % $X\not\subseteq Y$\\ % \end{tabular} \noindent onde $x$, $x_1$, \dots, $x_n$, $y$ são expressões numéricas ou simbólicas, $X$ e $Y$ são expressões de conjunto. % \noindent where $x$, $x_1$, \dots, $x_n$, $y$ are numeric or symbolic % expressions, $X$ and $Y$ are set expression. \newpage 1. Nas operações {\tt in}, {\tt not in} e {\tt !in} o número de componentes nos primeiros operandos deve ser igual a dimensão do segundo operando. 2. Nas operações {\tt within}, {\tt not within} e {\tt !within} ambos operandos devem ter a mesma dimensão. Todos operadores relacionais listados acima têm seus significados matemáticos convencionais. O valor resultante é {\it verdadeiro}, se a relação correspondente é satisfeita para seus operandos, caso contrário é {\it falso}. (Note que valores simbólicos são ordenados de forma lexicográfica e qualquer valor numérico precede qualquer valor simbólico.) % 1. In the operations {\tt in}, {\tt not in}, and {\tt !in} the % number of components in the first operands should be the same as the % dimension of the second operand. % % 2. In the operations {\tt within}, {\tt not within}, and {\tt !within} % both operands should have identical dimension. % % All the relational operators listed above have their conventional % mathematical meaning. The resultant value is {\it true}, if % corresponding relation is satisfied for its operands, otherwise % {\it false}. (Note that symbolic values are ordered lexicographically, % and any numeric value precedes any symbolic value.) \subsection{Expressões iteradas} Uma {\it expressão lógica iterada} é uma expressão lógica primária com a seguinte forma sintática: $$\mbox{{\it operador-iterado} {\it expressão-indexante} {\it integrando}}$$ onde {\it operador-iterado} é o nome simbólico do operador iterado a ser executado (veja adiante), {\it expressão-indexante} é uma expressão indexante que introduz índices e controla a iteração, \linebreak {\it integrando} é uma expressão numérica que participa da operação. Em MathProg existem dois operadores iterados que podem ser usados em expressões lógicas: % An {\it iterated logical expression} is a primary logical expression, % which has the following syntactic form: % $$\mbox{{\it iterated-operator} {\it indexing-expression} % {\it integrand}}$$ % where {\it iterated-operator} is the symbolic name of the iterated % operator to be performed (see below), {\it indexing-expression} is an % indexing expression which introduces dummy indices and controls % iterating, {\it integrand} is a numeric expression that participates in % the operation. % % In MathProg there exist two iterated operators, which may be used in % logical expressions: {\def\arraystretch{1.4} \noindent\hfil \begin{tabular}{@{}lll@{}} {\tt forall}&quantificador-$\forall$&$\displaystyle \forall(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\ {\tt exists}&quantificador-$\exists$&$\displaystyle \exists(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\ \end{tabular} } % {\def\arraystretch{1.4} % \noindent\hfil % \begin{tabular}{@{}lll@{}} % {\tt forall}&$\forall$-quantification&$\displaystyle % \forall(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\ % {\tt exists}&$\exists$-quantification&$\displaystyle % \exists(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\ % \end{tabular} % } \noindent onde $i_1$, \dots, $i_n$ são índices introduzidos na expressão indexante, $\Delta$ é o domínio, um conjunto de $n$-tuplas especificado pela expressão indexante que define valores específicos atribuídos aos índices ao executar a operação iterada, e $f(i_1,\dots,i_n)$ é o integrando, uma expressão lógica cujo valor resultante depende dos índices. Para o quantificador $\forall$, o valor resultante da expressão lógica iterada é {\it verdadeiro}, se o valor do integrando é {\it verdadeiro} para todas as $n$-tuplas contidas no domínio, caso contrário, é {\it falso}. Para o quantificador $\exists$ o valor resultante da expressão lógica iterada é {\it falso}, se o valor do integrando é {\it falso} para todas as $n$-tuplas contidas no domínio, caso contrário, é {\it verdadeiro}. % \noindent where $i_1$, \dots, $i_n$ are dummy indices introduced in % the indexing expression, $\Delta$ is the domain, a set of $n$-tuples % specified by the indexing expression which defines particular values % assigned to the dummy indices on performing the iterated operation, % $f(i_1,\dots,i_n)$ is the integrand, a logical expression whose % resultant value depends on the dummy indices. % % For $\forall$-quantification the resultant value of the iterated % logical expression is {\it true}, if the value of the integrand is % {\it true} for all $n$-tuples contained in the domain, otherwise % {\it false}. % % For $\exists$-quantification the resultant value of the iterated % logical expression is {\it false}, if the value of the integrand is % {\it false} for all $n$-tuples contained in the domain, otherwise % {\it true}. \subsection{Expressões parentizadas} Qualquer expressão lógica pode ser cercada entre parênteses, o que a converte sintaticamente em uma expressão lógica primária. Parênteses podem ser usados em expressões lógicas, como em álgebra, para especificar a ordem desejada na qual as operações devem ser executadas. Quando se usam parênteses, a expressão entre parênteses é avaliada antes que o valor resultante seja usado. O valor resultante da expressão parentizada é idêntico ao valor da expressão cercada entre parênteses. % Any logical expression may be enclosed in parentheses that % syntactically makes it a primary logical expression. % % Parentheses may be used in logical expressions, as in algebra, to % specify the desired order in which operations are to be performed. % Where parentheses are used, the expression within the parentheses is % evaluated before the resultant value is used. % % The resultant value of the parenthesized expression is the same as the % value of the expression enclosed within parentheses. \newpage \subsection{Operadores lógicos} Em MathProg existem os seguintes operadores lógicos, que podem ser usados em expressões lógicas: % In MathProg there exist the following logical operators, which may be % used in logical expressions: \begin{tabular}{@{}ll@{}} {\tt not} $x$, {\tt!}$x$&negação $\neg\ x$\\ $x$ {\tt and} $y$, $x$ {\tt\&\&} $y$&conjunção (``e'' lógico) $x\;\&\;y$\\ $x$ {\tt or} $y$, $x$ {\tt||} $y$&disjunção (``ou'' lógico) $x\vee y$\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % {\tt not} $x$, {\tt!}$x$&negation $\neg\ x$\\ % $x$ {\tt and} $y$, $x$ {\tt\&\&} $y$&conjunction (logical ``and'') % $x\;\&\;y$\\ % $x$ {\tt or} $y$, $x$ {\tt||} $y$&disjunction (logical ``or'') % $x\vee y$\\ % \end{tabular} \noindent onde $x$ e $y$ são expressões lógicas. Se a expressão inclui mais de um operador lógico, todos operadores são executados da esquerda para a direita de acordo com a hierarquia das operações (veja adiante). O valor resultante da \linebreak expressão que contém operadores lógicos é o resultado da aplicação dos operadores aos seus \linebreak operandos. % \noindent where $x$ and $y$ are logical expressions. % % If the expression includes more than one logical operator, all % operators are performed from left to right according to the hierarchy % of the operations (see below). The resultant value of the expression, % which contains logical operators, is the result of applying the % operators to their operands. \subsection{Hierarquia das operações} A lista seguinte mostra a hierarquia das operações em expressões lógicas: % The following list shows the hierarchy of operations in logical % expressions: \noindent\hfil \begin{tabular}{@{}ll@{}} Operation&Hierarchy\\ \hline Avaliação de operações numéricas& 1{\textsuperscript{\b{a}}}-7{\textsuperscript{\b{a}}}\\ Avaliação de operações simbólicas& 8{\textsuperscript{\b{a}}}-9{\textsuperscript{\b{a}}}\\ Avaliação de operações de conjunto& 10{\textsuperscript{\b{a}}}-14{\textsuperscript{\b{a}}}\\ Operações relacionais ({\tt<}, {\tt<=}, etc.)& 15{\textsuperscript{\b{a}}}\\ negação ({\tt not}, {\tt!})& 16{\textsuperscript{\b{a}}}\\ Conjunção({\tt and}, {\tt\&\&})& 17{\textsuperscript{\b{a}}}\\ Quantificação-$\forall$ e -$\exists$ ({\tt forall}, {\tt exists})& 18{\textsuperscript{\b{a}}}\\ Disjunção ({\tt or}, {\tt||})& 19{\textsuperscript{\b{a}}}\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}ll@{}} % Operation&Hierarchy\\ % \hline % Evaluation of numeric operations&1st-7th\\ % Evaluation of symbolic operations&8th-9th\\ % Evaluation of set operations&10th-14th\\ % Relational operations ({\tt<}, {\tt<=}, etc.)&15th\\ % Negation ({\tt not}, {\tt!})&16th\\ % Conjunction ({\tt and}, {\tt\&\&})&17th\\ % $\forall$- and $\exists$-quantification ({\tt forall}, {\tt exists})& % 18th\\ % Disjunction ({\tt or}, {\tt||})&19th\\ % \end{tabular} Esta hierarquia possui o mesmo significado como explicado anteriormente para expressões \linebreak numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}). % This hierarchy has the same meaning as was explained above for numeric % expressions (see Subsection \ref{hierarchy}, page \pageref{hierarchy}). \newpage \section{Expressões lineares} Uma {\it expressão linear} é uma regra para calcular a chamada {\it forma linear} ou simplesmente {\it fórmula}, que é uma função linear (ou afim) de variáveis elementares. A expressão linear primária pode ser uma variável não-indexada, uma variável indexada, uma expressão linear iterada, uma expressão linear condicional ou outra expressão linear cercada entre parênteses. Também e permitido usar uma expressão numérica como a expressão linear primária, neste caso, o valor resultante da expressão numérica é automaticamente convertido para uma fórmula que inclui o termo constante apenas. \para{Exemplos} % A {\it linear expression} is a rule for computing so called % a {\it linear form} or simply a {\it formula}, which is a linear (or % affine) function of elemental variables. % % The primary linear expression may be an unsubscripted variable, % subscripted variable, iterated linear expression, conditional linear % expression, or another linear expression enclosed in parentheses. % % It is also allowed to use a numeric expression as the primary linear % expression, in which case the resultant value of the numeric expression % is automatically converted to a formula that includes the constant term % only. % % \para{Examples} \noindent \begin{tabular}{@{}ll@{}} \verb|z| &(variável não-indexada)\\ \verb|x[i,j]| &(variável indexada)\\ \verb|sum{j in J} (a[i,j] * x[i,j] + 3 * y[i-1])| & (expressão linear iterada)\\ \verb|if i in I then x[i,j] else 1.5 * z + 3.25| & (expressão linear condicional)\\ \verb|(a[i,j] * x[i,j] + y[i-1] + .1)| & (expressão linear parentizada)\\ \end{tabular} % \noindent % \begin{tabular}{@{}ll@{}} % \verb|z| &(unsubscripted variable)\\ % \verb|x[i,j]| &(subscripted variable)\\ % \verb|sum{j in J} (a[i,j] * x[i,j] + 3 * y[i-1])| & % (iterated linear expression)\\ % \verb|if i in I then x[i,j] else 1.5 * z + 3.25| & % (conditional linear expression)\\ % \verb|(a[i,j] * x[i,j] + y[i-1] + .1)| & % (parenthesized linear expression)\\ % \end{tabular} Expressões lineares mais genéricas, contendo duas ou mais expressões lineares primárias, podem ser construídas usando determinados operadores aritméticos. \para{Exemplos} % More general linear expressions containing two or more primary linear % expressions may be constructed by using certain arithmetic operators. % % \para{Examples} \begin{verbatim} 2 * x[i-1,j+1] + 3.5 * y[k] + .5 * z (- x[i,j] + 3.5 * y[k]) / sum{t in T} abs(d[i,j,t]) \end{verbatim} \vspace*{-5pt} \subsection{Variáveis não-indexadas} Se a expressão linear primária é uma variável não-indexada (que deve se 0-dimensional), a fórmula resultante formula é aquela variável não-indexada. % If the primary linear expression is an unsubscripted variable (which % should be 0-dimensional), the resultant formula is that unsubscripted % variable. \vspace*{-5pt} \subsection{Variáveis indexadas} A expressão linear primária que se refere a uma variável indexada possui a seguinte forma sintática: $$\mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} $i_n${\tt]}}$$ onde {\it nome} é o nome simbólico da variável do modelo, $i_1$, $i_2$, \dots, $i_n$ são subíndices. Cada subíndice deve ser uma expressão numérica ou simbólica. O número de subíndices na lista de subíndices deve ser igual ao da dimensão da variável do modelo com a qual está associada a lista de subíndices. Os valores correntes das expressões dos subíndices são usados para identificar um membro \linebreak particular da variável do modelo que determina a fórmula resultante, que é uma variável elementar associada com o membro correspondente. % The primary linear expression, which refers to a subscripted variable, % has the following syntactic form: % $$\mbox{{\it name}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} % $i_n${\tt]}}$$ % where {\it name} is the symbolic name of the model variable, $i_1$, % $i_2$, \dots, $i_n$ are subscripts. % % Each subscript should be a numeric or symbolic expression. The number % of subscripts in the subscript list should be the same as the dimension % of the model variable with which the subscript list is associated. % % Actual values of the subscript expressions are used to identify a % particular member of the model variable that determines the resultant % formula, which is an elemental variable associated with corresponding % member. \vspace*{-5pt} \subsection{Expressões iteradas} Uma {\it expressão linear iterada} é uma expressão linear primária, que tem a seguinte forma sintática: $$\mbox{{\tt sum} {\it expressão-indexante} {\it integrando}}$$ onde {\it expressão-indexante} é uma expressão indexante, que introduz índices e controla iterações, {\it integrando} é uma expressão linear que participa da operação. A expressão linear iterada é avaliada exatamente da mesma forma que a expressão numérica iterada (ver Subseção \ref{itexpr}, página \pageref{itexpr}), exceto que o integrando participante do somatório é uma fórmula e não um valor numérico. % An {\it iterated linear expression} is a primary linear expression, % which has the following syntactic form: % $$\mbox{{\tt sum} {\it indexing-expression} {\it integrand}}$$ % where {\it indexing-expression} is an indexing expression, which % introduces dummy indices and controls iterating, {\it integrand} is % a linear expression that participates in the operation. % % The iterated linear expression is evaluated exactly in the same way as % the iterated numeric expression (see Subection \ref{itexpr}, page % \pageref{itexpr}) with exception that the integrand participated in the % summation is a formula, not a numeric value. \vspace*{-5pt} \subsection{Expressões condicionais} Uma {\it expressão linear condicional} é uma expressão linear primária, que possui uma das duas formas sintáticas seguintes: $$ {\def\arraystretch{1.4} \begin{array}{l} \mbox{{\tt if} $b$ {\tt then} $f$ {\tt else} $g$}\\ \mbox{{\tt if} $b$ {\tt then} $f$}\\ \end{array} } $$ onde $b$ é uma expressão lógica, $f$ e $g$ são expressões lineares. % A {\it conditional linear expression} is a primary linear expression, % which has one of the following two syntactic forms: % $$ % {\def\arraystretch{1.4} % \begin{array}{l} % \mbox{{\tt if} $b$ {\tt then} $f$ {\tt else} $g$}\\ % \mbox{{\tt if} $b$ {\tt then} $f$}\\ % \end{array} % } % $$ % where $b$ is an logical expression, $f$ and $g$ are linear expressions. % \newpage A expressão linear condicional é avaliada exatamente da mesma forma que a expressão \linebreak condicional numérica (ver Subseção \ref{ifthen}, página \pageref{ifthen}), exceto que os operandos que participam da operação são fórmulas e não valores numéricos. % The conditional linear expression is evaluated exactly in the same way % as the conditional numeric expression (see Subsection \ref{ifthen}, % page \pageref{ifthen}) with exception that operands participated in the % operation are formulae, not numeric values. \subsection{Expressões parentizadas} Qualquer expressão linear pode ser cercada entre parênteses, o que a converte sintaticamente em uma expressão linear primária. Parênteses podem ser usados em expressões lineares, como em álgebra, para especificar a ordem desejada na qual as operações devem ser executadas. Quando se usam parênteses, a expressão entre parênteses é avaliada antes que a fórmula resultante seja usada. O valor resultante da expressão parentizada é idêntico ao valor da expressão cercada entre parênteses. % Any linear expression may be enclosed in parentheses that syntactically % makes it a primary linear expression. % % Parentheses may be used in linear expressions, as in algebra, to % specify the desired order in which operations are to be performed. % Where parentheses are used, the expression within the parentheses is % evaluated before the resultant formula is used. % % The resultant value of the parenthesized expression is the same as the % value of the expression enclosed within parentheses. \subsection{Operadores aritméticos} Em MathProg existem os seguintes operadores aritméticos, que podem ser usados em expressões lineares: % In MathProg there exists the following arithmetic operators, which may % be used in linear expressions: \begin{tabular}{@{}ll@{}} {\tt+} $f$&mais unário\\ {\tt-} $f$&menos unário\\ $f$ {\tt+} $g$&adição\\ $f$ {\tt-} $g$&subtração\\ $x$ {\tt*} $f$, $f$ {\tt*} $x$&multiplicação\\ $f$ {\tt/} $x$&divisão \end{tabular} % \begin{tabular}{@{}ll@{}} % {\tt+} $f$&unary plus\\ % {\tt-} $f$&unary minus\\ % $f$ {\tt+} $g$&addition\\ % $f$ {\tt-} $g$&subtraction\\ % $x$ {\tt*} $f$, $f$ {\tt*} $x$&multiplication\\ % $f$ {\tt/} $x$&division % \end{tabular} \noindent onde $f$ e $g$ são expressões lineares, $x$ é uma expressão numérica (mais precisamente, uma expressão linear contendo apenas o termo constante). Se a expressão inclui mais de um operador aritmético, todos operadores são executados da esquerda para a direita de acordo com a hierarquia das operações (veja adiante). O valor resultante da expressão, que contém operadores aritméticos, é o resultado de aplicar os operadores aos seus operandos. % \noindent where $f$ and $g$ are linear expressions, $x$ is a numeric % expression (more precisely, a linear expression containing only the % constant term). % % If the expression includes more than one arithmetic operator, all % operators are performed from left to right according to the hierarchy % of operations (see below). The resultant value of the expression, which % contains arithmetic operators, is the result of applying the operators % to their operands. \subsection{Hierarquia das operações} A hierarquia de operações aritméticas usada em expressões lineares é a mesma para expressões numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}). % The hierarchy of arithmetic operations used in linear expressions is % the same as for numeric expressions (see Subsection \ref{hierarchy}, % page \pageref{hierarchy}). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Sentenças} {\it Sentenças} são unidades básicas da descrição do modelo. Em MathProg todas as sentenças são divididas em duas categorias: sentenças de declaração e sentenças funcionais. {\it Sentenças de declaração} (sentença {\it set}, sentença {\it parameter}, sentença {\it variable}, sentença \linebreak {\it constraint}, sentença {\it objective}) são usados para declarar objetos de certo tipo do modelo e definir certas propriedades de tais objetos. {\it Sentenças funcionais} (sentença {\it solve}, sentença {\it check}, sentença {\it display}, sentença {\it printf}, sentença {\it loop}, sentença {\it table}) são projetadas para executar ações específicas. Note que sentenças de declaração podem seguir em qualquer ordem arbitrária, o que não afeta o resultado da tradução. Entretanto, qualquer objeto de modelo deve ser declarado antes de ser referenciado por outras sentenças. % {\it Statements} are basic units of the model description. In MathProg % all statements are divided into two categories: declaration statements % and functional statements. % % {\it Declaration statements} (set statement, parameter statement, % variable statement, constraint statement, objective statement) are used % to declare model objects of certain kinds and define certain properties % of such objects. % % {\it Functional statements} (solve statement, check statement, display % statement, printf statement, loop statement, table statement) are % intended for performing some specific actions. % % Note that declaration statements may follow in arbitrary order, which % does not affect the result of translation. However, any model object % should be declared before it is referenced in other statements. \section{Sentença set} \noindent \framebox[468pt][l]{ \parbox[c][24pt]{468pt}{ \hspace{6pt} {\tt set} {\it nome} {\it alias} {\it domínio} {\tt,} {\it atributo} {\tt,} \dots {\tt,} {\it atributo} {\tt;} }} % \noindent % \framebox[468pt][l]{ % \parbox[c][24pt]{468pt}{ % \hspace{6pt} {\tt set} {\it name} {\it alias} {\it domain} {\tt,} % {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;} % }} \medskip \noindent {\it nome} é um nome simbólico do conjunto; \noindent {\it alias} é um literal de cadeia opcional que especifica um pseudônimo para o conjunto; \noindent {\it domínio} é uma expressão indexante opcional que especifica o domínio do subíndice do conjunto; \noindent {\it atributo}, \dots, {\it atributo} são atributos opcionais do conjunto (as vírgulas que precedem os atributos podem ser omitidas.) \para{Atributos opcionais} % \noindent % {\it name} is a symbolic name of the set; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the set; % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the set; % % \noindent % {\it attrib}, \dots, {\it attrib} are optional attributes of the set. % (Commae preceding attributes may be omitted.) % % \para{Optional attributes} \vspace*{-8pt} \begin{description} \item[{\tt dimen} $n$]\hspace*{0pt}\\ especifica a dimensão de $n$-tuplas das quais o conjunto é consistido; \item[{\tt within} {\it expressão}]\hspace*{0pt}\\ especifica um superconjunto que restringe ao conjunto ou a todos seus membros (conjuntos elementares) a estarem incluídos naquele superconjunto; \item[{\tt:=} {\it expressão}]\hspace*{0pt}\\ especifica um conjunto elementar atribuído ao conjunto ou aos seus membros; \item[{\tt default} {\it expressão}]\hspace*{0pt}\\ especifica um conjunto elementar atribuído ao conjunto ou aos seus membros sempre que não há dados apropriados disponíveis na seção de dados. \end{description} % \begin{description} % \item[{\tt dimen} $n$]\hspace*{0pt}\\ % specifies the dimension of $n$-tuples which the set consists of; % \item[{\tt within} {\it expression}]\hspace*{0pt}\\ % specifies a superset which restricts the set or all its members % (elemental sets) to be within that superset; % \item[{\tt:=} {\it expression}]\hspace*{0pt}\\ % specifies an elemental set assigned to the set or its members; % \item[{\tt default} {\it expression}]\hspace*{0pt}\\ % specifies an elemental set assigned to the set or its members whenever % no appropriate data are available in the data section. % \end{description} \vspace*{-8pt} \para{Exemplos} % \para{Examples} \begin{verbatim} set nos; set arcos within nos cross nos; set passo{s in 1..maxiter} dimen 2 := if s = 1 then arcos else passo[s-1] union setof{k in nos, (i,k) in passo[s-1], (k,j) in passo[s-1]}(i,j); set A{i in I, j in J}, within B[i+1] cross C[j-1], within D diff E, default {('abc',123), (321,'cba')}; \end{verbatim} % \begin{verbatim} % set nodes; % set arcs within nodes cross nodes; % set step{s in 1..maxiter} dimen 2 := if s = 1 then arcs else step[s-1] % union setof{k in nodes, (i,k) in step[s-1], (k,j) in step[s-1]}(i,j); % set A{i in I, j in J}, within B[i+1] cross C[j-1], within D diff E, % default {('abc',123), (321,'cba')}; % \end{verbatim} A sentença set declara um conjunto. Se o domínio do subíndice não é especificado, o conjunto é um conjunto simples, caso contrário será uma matriz de conjuntos elementares. O atributo {\tt dimen} especifica a dimensão de $n$-tuplas da qual é consistida o conjunto (se o conjunto é simples) ou seus membros (se o conjunto é uma matriz de conjuntos elementares), em que $n$ deve ser um inteiro de 1 a 20. Pode-se especificar no máximo um atributo {\tt dimen}. Se o atributo {\tt dimen} não é especificado, a dimensão das $n$-tuplas é implicitamente determinada por outros atributos (por exemplo, se há uma expressão que segue {\tt:=} ou a palavra-chave {\tt default}, usa-se a dimensão das $n$-tuplas do conjunto elementar correspondente). Se nenhuma informação de dimensão é fornecida, assume-se {\tt dimen 1}. O atributo {\tt within} especifica uma expressão de conjunto cujo valor resultante é um superconjunto usado para restringir o conjunto (se o conjunto é simples) ou seus membros (se o conjunto é uma matriz de conjuntos elementares) a estar incluído naquele superconjunto. Um número arbitrário de atributos {\tt within} podem ser especificados na mesma sentença set. O atributo de atribuição ({\tt:=}) especifica uma expressão de conjunto usada para avaliar conjunto(s) \linebreak elementar(es) atribuído(s) ao conjunto (se o conjunto é simples) ou seus membros (se o conjunto é uma matriz de conjuntos elementares). Se o atributo de atribuição é especificado, o conjunto é {\it calculável}, portanto, não há a necessidade de fornecer dados na seção de dados. Se o atributo de atribuição não é especificado, deve-se fornecer os dados na seção de dados. Pode-se especificar no máximo um atributo de atribuição ou {\tt default} para o mesmo conjunto. O atributo {\tt default} especifica uma expressão de conjunto usado para avaliar conjunto(s) \linebreak elementar(es) atribuído(s) ao conjunto (se o conjunto é simples) ou seus membros (se o conjunto é uma matriz de conjuntos elementares) sempre que não houver dados apropriados disponíveis na seção de dados. Se não se especifica nem o atributo de atribuição nem o atributo {\tt default}, a falta de dados causará um erro. % The set statement declares a set. If the subscript domain is not % specified, the set is a simple set, otherwise it is an array of % elemental sets. % % The {\tt dimen} attribute specifies the dimension of $n$-tuples, which % the set (if it is a simple set) or its members (if the set is an array % of elemental sets) consist of, where $n$ should be an unsigned integer % from 1 to 20. At most one {\tt dimen} attribute can be specified. If % the {\tt dimen} attribute is not specified, the dimension of $n$-tuples % is implicitly determined by other attributes (for example, if there is % a set expression that follows {\tt:=} or the keyword {\tt default}, the % dimension of $n$-tuples of corresponding elemental set is used). % If no dimension information is available, {\tt dimen 1} is assumed. % % The {\tt within} attribute specifies a set expression whose resultant % value is a superset used to restrict the set (if it is a simple set) or % its members (if the set is an array of elemental sets) to be within % that superset. Arbitrary number of {\tt within} attributes may be % specified in the same set statement. % % The assign ({\tt:=}) attribute specifies a set expression used to % evaluate elemental set(s) assigned to the set (if it is a simple set) % or its members (if the set is an array of elemental sets). If the % assign attribute is specified, the set is {\it computable} and % therefore needs no data to be provided in the data section. If the % assign attribute is not specified, the set should be provided with data % in the data section. At most one assign or default attribute can be % specified for the same set. % % The {\tt default} attribute specifies a set expression used to evaluate % elemental set(s) assigned to the set (if it is a simple set) or its % members (if the set is an array of elemental sets) whenever % no appropriate data are available in the data section. If neither % assign nor default attribute is specified, missing data will cause an % error. \newpage \section{Sentença parameter} \noindent \framebox[468pt][l]{ \parbox[c][24pt]{468pt}{ \hspace{6pt} {\tt param} {\it nome} {\it alias} {\it domínio} {\tt,} {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;} }} % \noindent % \framebox[468pt][l]{ % \parbox[c][24pt]{468pt}{ % \hspace{6pt} {\tt param} {\it name} {\it alias} {\it domain} {\tt,} % {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;} % }} \medskip \noindent {\it nome} é um nome simbólico do parâmetro; \noindent {\it alias} é um literal de cadeia opcional que especifica um pseudônimo para o parâmetro; \noindent {\it domínio} é uma expressão indexante opcional que especifica o domínio do subíndice do parâmetro; \noindent {\it atributo}, \dots, {\it atributo} são atributos opcionais do parâmetro (as vírgulas que precedem os atributos podem ser omitidas.) \para{Atributos opcionais} % \noindent % {\it name} is a symbolic name of the parameter; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the parameter; % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the parameter; % % \noindent % {\it attrib}, \dots, {\it attrib} are optional attributes of the % parameter. (Commae preceding attributes may be omitted.) % % \para{Optional attributes} \vspace*{-8pt} \begin{description} \item[{\tt integer}]\hspace*{0pt}\\ especifica que o parâmetro é inteiro; \item[{\tt binary}]\hspace*{0pt}\\ especifica que o parâmetro é binário; \item[{\tt symbolic}]\hspace*{0pt}\\ especifica que o parâmetro é simbólico; \item[{\it expressão de relação}]\hspace*{0pt}\\ (onde {\it relação} é algum de: {\tt<}, {\tt<=}, {\tt=}, {\tt==}, {\tt>=}, {\tt>}, {\tt<>}, {\tt!=})\\ especifica uma condição que restringe o parâmetro ou seus membros a satisfazer aquela condição; \item[{\tt in} {\it expressão}]\hspace*{0pt}\\ especifica um superconjunto que restringe o parâmetro ou seus membros a estarem inseridos naquele superconjunto; \item[{\tt:=} {\it expressão}]\hspace*{0pt}\\ especifica um valor atribuído ao parâmetro ou a seus membros; \item[{\tt default} {\it expressão}]\hspace*{0pt}\\ especifica um valor atribuído ao parâmetro ou aos seus membros sempre que não houverem dados disponíveis na seção de dados. \end{description} % \begin{description} % \item[{\tt integer}]\hspace*{0pt}\\ % specifies that the parameter is integer; % \item[{\tt binary}]\hspace*{0pt}\\ % specifies that the parameter is binary; % \item[{\tt symbolic}]\hspace*{0pt}\\ % specifies that the parameter is symbolic; % \item[{\it relation expression}]\hspace*{0pt}\\ % (where {\it relation} is one of: {\tt<}, {\tt<=}, {\tt=}, {\tt==}, % {\tt>=}, {\tt>}, {\tt<>}, {\tt!=})\\ % specifies a condition that restricts the parameter or its members to % satisfy that condition; % \item[{\tt in} {\it expression}]\hspace*{0pt}\\ % specifies a superset that restricts the parameter or its members to be % in that superset; % \item[{\tt:=} {\it expression}]\hspace*{0pt}\\ % specifies a value assigned to the parameter or its members; % \item[{\tt default} {\it expression}]\hspace*{0pt}\\ % specifies a value assigned to the parameter or its members whenever % no appropriate data are available in the data section. % \end{description} \vspace*{-8pt} \para{Exemplos} % \para{Examples} \begin{verbatim} param unidades{insumo, produto} >= 0; param lucro{produto, 1..T+1}; param N := 20 integer >= 0 <= 100; param combinacao 'n escolhe k' {n in 0..N, k in 0..n} := if k = 0 or k = n then 1 else combinacao[n-1,k-1] + combinacao[n-1,k]; param p{i in I, j in J}, integer, >= 0, <= i+j, in A[i] symdiff B[j], in C[i,j], default 0.5 * (i + j); param mes symbolic default 'Mai' in {'Mar', 'Abr', 'Mai'}; \end{verbatim} % \begin{verbatim} % param units{raw, prd} >= 0; % param profit{prd, 1..T+1}; % param N := 20 integer >= 0 <= 100; % param comb 'n choose k' {n in 0..N, k in 0..n} := % if k = 0 or k = n then 1 else comb[n-1,k-1] + comb[n-1,k]; % param p{i in I, j in J}, integer, >= 0, <= i+j, in A[i] symdiff B[j], % in C[i,j], default 0.5 * (i + j); % param month symbolic default 'May' in {'Mar', 'Apr', 'May'}; % \end{verbatim} A sentença parameter declara um parâmetro. Se o domínio de subíndice não é especificado, o parâmetro é simples (escalar), caso contrário, é uma matriz $n$-dimensional. Os atributos de tipo {\tt integer}, {\tt binary} e {\tt symbolic} qualificam os tipos de valores que podem ser atribuídos ao parâmetro, conforme demonstrado: % The parameter statement declares a parameter. If a subscript domain is % not specified, the parameter is a simple (scalar) parameter, otherwise % it is a $n$-dimensional array. % % The type attributes {\tt integer}, {\tt binary}, and {\tt symbolic} % qualify the type of values that can be assigned to the parameter as % shown below: \noindent\hfil \begin{tabular}{@{}ll@{}} Tipo de atributo&Valores atribuídos\\ \hline (não especificado)&Qualquer valor numérico\\ {\tt integer}&Apenas valores numéricos inteiros\\ {\tt binary}&Tanto 0 quanto 1\\ {\tt symbolic}&Qualquer valor numérico e simbólico\\ \end{tabular} % \noindent\hfil % \begin{tabular}{@{}ll@{}} % Type attribute&Assigned values\\ % \hline % (not specified)&Any numeric values\\ % {\tt integer}&Only integer numeric values\\ % {\tt binary}&Either 0 or 1\\ % {\tt symbolic}&Any numeric and symbolic values\\ % \end{tabular} O atributo {\tt symbolic} não pode ser especificado juntamente com outros tipos de atributos. Uma vez especificado, ele deve preceder todos os outros atributos. O atributo de condição especifica uma condição opcional que restringe os valores atribuídos ao parâmetro para satisfazer aquela condição. Este atributo tem as seguintes formas sintáticas: % The {\tt symbolic} attribute cannot be specified along with other type % attributes. Being specified it should precede all other attributes. % % The condition attribute specifies an optional condition that restricts % values assigned to the parameter to satisfy that condition. This % attribute has the following syntactic forms: \begin{tabular}{@{}ll@{}} {\tt<} $v$&verifica se $x=} $v$&verifica se $x\geq v$\\ {\tt>} $v$&verifica se $x\geq v$\\ {\tt<>} $v$, {\tt!=} $v$&verifica se $x\neq v$\\ \end{tabular} % \begin{tabular}{@{}ll@{}} % {\tt<} $v$&check for $x=} $v$&check for $x\geq v$\\ % {\tt>} $v$&check for $x\geq v$\\ % {\tt<>} $v$, {\tt!=} $v$&check for $x\neq v$\\ % \end{tabular} \noindent onde $x$ é um valor atribuído ao parâmetro, $v$ é o valor resultante de uma expressão numérica ou simbólica especificado no atributo de condição. Um número arbitrário de atributos de condição pode ser especificado para o mesmo parâmetro. Se, durante a avaliação do modelo, um valor atribuído ao parâmetro viola pelo menos uma das condições especificadas, ocorrerá um erro. (Note que valores simbólicos são ordenados de forma lexicográfica e qualquer valor numérico precede qualquer valor simbólico.) O atributo {\tt in} é similar ao atributo de condição e especifica uma expressão de conjunto cujo valor resultante é um superconjunto usado para restringir valores numéricos ou simbólicos atribuídos ao parâmetro a estarem incluídos naquele superconjunto. Pode-se especificar um número arbitrário de atributos {\tt in} para o mesmo parâmetro. Se, durante a avaliação do modelo, o valor atribuído ao parâmetro não pertence a pelo menos um dos superconjuntos especificados, ocorrerá um erro. O atributo de atribuição ({\tt:=}) especifica uma expressão numérica ou simbólica usada para \linebreak computar um valor atribuído ao parâmetro (se é um parâmetro simples) ou seus membros (se o parâmetro é uma matriz). Se o atributo de atribuição é especificado, o parâmetro é {\it calculável}, \linebreak portanto, não há a necessidade de fornecer dados na seção de dados. Se o atributo de atribuição não é especificado, deve-se fornecer os dados para o parâmetro na seção de dados. Pode-se especificar no máximo um atributo de atribuição ou {\tt default} para o mesmo parâmetro. O atributo {\tt default} especifica uma expressão numérica ou simbólica usada para computar um valor atribuído ao parâmetro ou seus membros sempre que não houver dados apropriados disponíveis na seção de dados. Se não se especifica nem o atributo de atribuição nem o atributo {\tt default}, a falta de dados causará um erro. % \noindent where $x$ is a value assigned to the parameter, $v$ is the % resultant value of a numeric or symbolic expression specified in the % condition attribute. Arbitrary number of condition attributes can be % specified for the same parameter. If a value being assigned to the % parameter during model evaluation violates at least one of specified % conditions, an error is raised. (Note that symbolic values are ordered % lexicographically, and any numeric value precedes any symbolic value.) % % The {\tt in} attribute is similar to the condition attribute and % specifies a set expression whose resultant value is a superset used to % restrict numeric or symbolic values assigned to the parameter to be in % that superset. Arbitrary number of the {\tt in} attributes can be % specified for the same parameter. If a value being assigned to the % parameter during model evaluation is not in at least one of specified % supersets, an error is raised. % % The assign ({\tt:=}) attribute specifies a numeric or symbolic % expression used to compute a value assigned to the parameter (if it is % a simple parameter) or its member (if the parameter is an array). If % the assign attribute is specified, the parameter is {\it computable} % and therefore needs no data to be provided in the data section. If the % assign attribute is not specified, the parameter should be provided % with data in the data section. At most one assign or {\tt default} % attribute can be specified for the same parameter. % % The {\tt default} attribute specifies a numeric or symbolic expression % used to compute a value assigned to the parameter or its member % whenever no appropriate data are available in the data section. If % neither assign nor {\tt default} attribute is specified, missing data % will cause an error. \newpage \section{Sentença variable} \noindent \framebox[468pt][l]{ \parbox[c][24pt]{468pt}{ \hspace{6pt} {\tt var} {\it nome} {\it alias} {\it domínio} {\tt,} {\it atrib} {\tt,} \dots {\tt,} {\it atrib} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico da variável; \noindent {\it alias} é um literal de cadeia opcional que especifica um pseudônimo para a variável; \noindent {\it domínio} é uma expressão indexante opcional que especifica o domínio do subíndice da variável; \noindent {\it atrib}, \dots, {\it atrib} são atributos opcionais da variável (as vírgulas que precedem os atributos podem ser omitidas.) \para{Atributos opcionais} \vspace*{-8pt} \begin{description} \item[{\tt integer}]\hspace*{0pt}\\ restringe a variável a ser inteira; \item[{\tt binary}]\hspace*{0pt}\\ restringe a variável a ser binária; \item[{\tt>=} {\it expressão}]\hspace*{0pt}\\ especifica um limite inferior para a variável; \item[{\tt<=} {\it expressão}]\hspace*{0pt}\\ especifica um limite superior para a variável; \item[{\tt=} {\it expressão}]\hspace*{0pt}\\ especifica um valor fixo para a variável; \end{description} % \noindent % \framebox[468pt][l]{ % \parbox[c][24pt]{468pt}{ % \hspace{6pt} {\tt var} {\it name} {\it alias} {\it domain} {\tt,} % {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the variable; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the variable; % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the variable; % % \noindent % {\it attrib}, \dots, {\it attrib} are optional attributes of the % variable. (Commae preceding attributes may be omitted.) % % \para{Optional attributes} % % \vspace*{-8pt} % % \begin{description} % \item[{\tt integer}]\hspace*{0pt}\\ % restricts the variable to be integer; % \item[{\tt binary}]\hspace*{0pt}\\ % restricts the variable to be binary; % \item[{\tt>=} {\it expression}]\hspace*{0pt}\\ % specifies an lower bound of the variable; % \item[{\tt<=} {\it expression}]\hspace*{0pt}\\ % specifies an upper bound of the variable; % \item[{\tt=} {\it expression}]\hspace*{0pt}\\ % specifies a fixed value of the variable; % \end{description} \vspace*{-8pt} \para{Exemplos} % \para{Examples} \begin{verbatim} var x >= 0; var y{I,J}; var produzir{p in prod}, integer, >= comprometido[p], <= mercado[p]; var armazenar{insumo, 1..T+1} >= 0; var z{i in I, j in J} >= i+j; \end{verbatim} % \begin{verbatim} % var x >= 0; % var y{I,J}; % var make{p in prd}, integer, >= commit[p], <= market[p]; % var store{raw, 1..T+1} >= 0; % var z{i in I, j in J} >= i+j; % \end{verbatim} A sentença variable declara uma variável. Se não se especifica o domínio do subíndice, a variável e uma variável simples (escalar), caso contrário é uma matriz $n$-dimensional de variáveis elementares. As variáveis elementares associadas com a variável do modelo (se é uma variável simples) ou seus membros (se é uma matriz) corresponde às variáveis na formulação do problema PL/PIM (ver Seção \ref{problem}, página \pageref{problem}). Note que somente variáveis elementares realmente referenciadas em algumas restrições e/ou objetivos serão incluídas na instância do problema PL/PIM a ser gerado. Os atributos de tipo {\tt integer} e {\tt binary} restringem a variável a ser inteira ou binária, \linebreak respectivamente. Se nenhum atributo de tipo é especificado, a variável é contínua. Se todas as variáveis no modelo são contínuas, o problema correspondente é da classe PL. Se há pelo menos uma variável inteira ou binária, o problema é da classe PIM. \newpage O atributo de limite inferior ({\tt>=}) especifica uma expressão numérica para calcular um limite inferior da variável. No máximo um limite inferior pode ser especificado. Por padrão, todas as variáveis (exceto as binárias) não tem limite inferior, assim, se há a necessidade de uma variável ser não-negativa, seu limite inferior zero deve ser explicitamente especificado. O atributo de limite superior ({\tt<=}) especifica uma expressão numérica para calcular um limite superior da variável. No máximo um limite superior pode ser especificado. O atributo de valor fixo ({\tt=}) especifica uma expressão numérica para calcular um valor no qual a variável é fixada. Este atributo não pode ser especificado junto com os atributos de limite. % The variable statement declares a variable. If a subscript domain is % not specified, the variable is a simple (scalar) variable, otherwise it % is a $n$-dimensional array of elemental variables. % % Elemental variable(s) associated with the model variable (if it is a % simple variable) or its members (if it is an array) correspond to the % variables in the LP/MIP problem formulation (see Section \ref{problem}, % page \pageref{problem}). Note that only elemental variables actually % referenced in some constraints and/or objectives are included in the % LP/MIP problem instance to be generated. % % The type attributes {\tt integer} and {\tt binary} restrict the % variable to be integer or binary, respectively. If no type attribute is % specified, the variable is continuous. If all variables in the model % are continuous, the corresponding problem is of LP class. If there is % at least one integer or binary variable, the problem is of MIP class. % % The lower bound ({\tt>=}) attribute specifies a numeric expression for % computing an lower bound of the variable. At most one lower bound can % be specified. By default all variables (except binary ones) have no % lower bound, so if a variable is required to be non-negative, its zero % lower bound should be explicitly specified. % % The upper bound ({\tt<=}) attribute specifies a numeric expression for % computing an upper bound of the variable. At most one upper bound % attribute can be specified. % % The fixed value ({\tt=}) attribute specifies a numeric expression for % computing a value, at which the variable is fixed. This attribute % cannot be specified along with the bound attributes. \section{Sentença constraint} \noindent \framebox[468pt][l]{ \parbox[c][106pt]{468pt}{ \hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt,} {\tt=} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt,} {\tt<=} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt,} {\tt>=} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt,} {\tt<=} {\it expressão} {\tt,} {\tt<=} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt,} {\tt>=} {\it expressão} {\tt,} {\tt>=} {\it expressão} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico da restrição; \noindent {\it alias} é um literal de cadeia opcional que especifica um pseudônimo da restrição; \noindent {\it domínio} é uma expressão indexante opcional, que especifica o domínio do subíndice da restrição; \noindent {\it expressão} é uma expressão linear usada para calcular um componente da restrição (as vírgulas que precedem os atributos podem ser omitidas). \noindent (A palavra-chave {\tt s.t.} pode ser escrita como {\tt subject to}, como {\tt subj to} ou pode ser omitido por completo). % \noindent % \framebox[468pt][l]{ % \parbox[c][106pt]{468pt}{ % \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt,} {\tt=} {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt,} {\tt<=} {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt,} {\tt>=} {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt,} {\tt<=} {\it expression} {\tt,} {\tt<=} % {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt,} {\tt>=} {\it expression} {\tt,} {\tt>=} % {\it expression} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the constraint; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the constraint; % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the constraint; % % \noindent % {\it expression} is a linear expression used to compute a component of % the constraint. (Commae following expressions may be omitted.) % % \noindent % (The keyword {\tt s.t.} may be written as {\tt subject to} or as % {\tt subj to}, or may be omitted at all.) \para{Exemplos} % \para{Examples} \begin{verbatim} s.t. r: x + y + z, >= 0, <= 1; limite{t in 1..T}: sum{j in produto} produzir[j,t] <= max_prod; subject to balanco{i in insumo, t in 1..T}: estoque[i,t+1] = estoque[i,t] - sum{j in produto} unidades[i,j] * produzir[j,t]; subject to rlim 'limite tempo-regular' {t in tempo}: sum{p in produto} pt[p] * rprod[p,t] <= 1.3 * dpp[t] * equipes[t]; \end{verbatim} % \begin{verbatim} % s.t. r: x + y + z, >= 0, <= 1; % limit{t in 1..T}: sum{j in prd} make[j,t] <= max_prd; % subject to balance{i in raw, t in 1..T}: % store[i,t+1] = store[i,t] - sum{j in prd} units[i,j] * make[j,t]; % subject to rlim 'regular-time limit' {t in time}: % sum{p in prd} pt[p] * rprd[p,t] <= 1.3 * dpp[t] * crews[t]; % \end{verbatim} A sentença de restrição declara uma restrição. Se o domínio do subíndice não é especificado, a restrição é uma restrição simples (escalar), caso contrário, é uma matriz $n$-dimensional de restrições elementares. Restrições elementares associadas com a restrição do modelo (se é uma restrição simples) ou seus membros (se é uma matriz) correspondem a restrições lineares na formulação do problema de PL/PIM (ver Seção \ref{problem}, página \pageref{problem}). Se a restrição possui a forma de igualdade ou desigualdade simples, i.e., inclui duas expressões, uma segue depois dos dois pontos e a outra segue depois do sinal de relação {\tt=}, {\tt<=} ou {\tt>=}, \linebreak ambas expressões na sentença podem ser expressões lineares. Se a restrição possui a forma de uma \linebreak desigualdade dupla, i.e., inclui três expressões, a expressão do meio pode ser uma expressão linear, enquanto a da esquerda e a da direita podem ser apenas expressões numéricas. Gerar o modelo é, a grosso modo, gerar suas restrições, que são sempre avaliadas para todo domínio do subíndice. Avaliar as restrições, por sua vez, leva a avaliação de outros objetos de modelo tais como conjuntos, parâmetros e variáveis. A construção de uma restrição linear incluída na instância do problema, que corresponde a uma restrição elementar particular, é realizada como segue. % The constraint statement declares a constraint. If a subscript domain % is not specified, the\linebreak constraint is a simple (scalar) % constraint, otherwise it is a $n$-dimensional array of elemental % constraints. % % Elemental constraint(s) associated with the model constraint (if it is % a simple constraint) or its members (if it is an array) correspond to % the linear constraints in the LP/MIP problem formulation (see % Section \ref{problem}, page \pageref{problem}). % % If the constraint has the form of equality or single inequality, i.e. % includes two expressions, one of which follows the colon and other % follows the relation sign {\tt=}, {\tt<=}, or {\tt>=}, both expressions % in the statement can be linear expressions. If the constraint has the % form of double inequality,\linebreak i.e. includes three expressions, % the middle expression can be a linear expression while the leftmost and % rightmost ones can be only numeric expressions. % % Generating the model is, roughly speaking, generating its constraints, % which are always evaluated for the entire subscript domain. Evaluation % of the constraints leads, in turn, to evaluation of other model objects % such as sets, parameters, and variables. % % Constructing an actual linear constraint included in the problem % instance, which (constraint) corresponds to a particular elemental % constraint, is performed as follows. Se a restrição possui a forma de igualdade ou desigualdade simples, a avaliação de ambas \linebreak expressões lineares resultam em duas formas lineares: $$\begin{array}{r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r} f&=&a_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&a_0,\\ g&=&b_1x_1&+&b_2x_2&+\dots+&b_nx_n&+&b_0,\\ \end{array}$$ onde $x_1$, $x_2$, \dots, $x_n$ são variáveis elementares; $a_1$, $a_2$, \dots, $a_n$, $b_1$, $b_2$, \dots, $b_n$ são coeficientes numéricos; $a_0$ e $b_0$ são termos constantes. Em seguida, todos os termos lineares de $f$ e $g$ são levados ao lado esquerdo, enquanto que os termos constantes são levados ao lado direito, resultando na restrição elementar final na forma padrão: $$(a_1-b_1)x_1+(a_2-b_2)x_2+\dots+(a_n-b_n)x_n\left\{ \begin{array}{@{}c@{}}=\\\leq\\\geq\\\end{array}\right\}b_0-a_0.$$ Se a restrição possui a forma de desigualdade dupla, a avaliação da expressão linear do meio resulta na seguinte forma linear: $$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$ e a avaliação das expressões numéricas da esquerda e da direita dão dois valores numéricos $l$ e $u$, respectivamente. Logo, o termo constante da forma linear é levado tanto à esquerda como à direita para gerar a restrição elementar final na forma padrão: $$l-a_0\leq a_1x_1+a_2x_2+\dots+a_nx_n\leq u-a_0.$$ % If the constraint has the form of equality or single inequality, % evaluation of both linear expressions gives two resultant linear forms: % $$\begin{array}{r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r} % f&=&a_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&a_0,\\ % g&=&b_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&b_0,\\ % \end{array}$$ % where $x_1$, $x_2$, \dots, $x_n$ are elemental variables; $a_1$, $a_2$, % \dots, $a_n$, $b_1$, $b_2$, \dots, $b_n$ are numeric coefficients; % $a_0$ and $b_0$ are constant terms. Then all linear terms of $f$ and % $g$ are carried to the left-hand side, and the constant terms are % carried to the right-hand side, that gives the final elemental % constraint in the standard form: % $$(a_1-b_1)x_1+(a_2-b_2)x_2+\dots+(a_n-b_n)x_n\left\{ % \begin{array}{@{}c@{}}=\\\leq\\\geq\\\end{array}\right\}b_0-a_0.$$ % % If the constraint has the form of double inequality, evaluation of the % middle linear expression gives the resultant linear form: % $$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$ % and evaluation of the leftmost and rightmost numeric expressions gives % two numeric values $l$ and $u$, respectively. Then the constant term of % the linear form is carried to both left-hand and right-handsides that % gives the final elemental constraint in the standard form: % $$l-a_0\leq a_1x_1+a_2x_2+\dots+a_nx_n\leq u-a_0.$$ \section{Sentença objective} \noindent \framebox[468pt][l]{ \parbox[c][44pt]{468pt}{ \hspace{6pt} {\tt minimize} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt maximize} {\it nome} {\it alias} {\it domínio} {\tt:} {\it expressão} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico do objetivo; \noindent {\it alias} é uma literal de cadeia opcional que especifica um pseudônimo do objetivo; \noindent {\it domínio} é uma expressão indexante opcional que especifica um domínio do subíndice do objetivo; \noindent {\it expressão} é uma expressão linear usada pra calcular a forma linear do objetivo. % \noindent % \framebox[468pt][l]{ % \parbox[c][44pt]{468pt}{ % \hspace{6pt} {\tt minimize} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt maximize} {\it name} {\it alias} {\it domain} {\tt:} % {\it expression} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the objective; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the objective; % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the objective; % % \noindent % {\it expression} is a linear expression used to compute the linear form % of the objective. \newpage \para{Exemplos} % \para{Examples} \begin{verbatim} minimize obj: x + 1.5 * (y + z); maximize lucro_total: sum{p in produto} lucro[p] * produzir[p]; \end{verbatim} % \begin{verbatim} % minimize obj: x + 1.5 * (y + z); % maximize total_profit: sum{p in prd} profit[p] * make[p]; % \end{verbatim} A sentença objective declara um objetivo. Se o domínio do subíndice não é especificado, o objetivo é um objetivo simples (escalar). Caso contrário, é uma matriz $n$-dimensional de objetivos elementares. Objetivos elementares associados com o objetivo do modelo (se é um objetivo simples) ou seus membros (se é uma matriz) correspondem a restrições lineares genéricas na formulação do problema PL/PIM (ver Seção \ref{problem}, página \pageref{problem}). No entanto, diferentemente das restrições, estas formas lineares são livres (ilimitadas). A construção de uma forma linear incluída na instância do problema, a qual corresponde a uma restrição elementar particular, é realizada como segue. A expressão linear especificada da na sentença objective é avaliada para resultar na seguinte forma linear: $$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$ onde $x_1$, $x_2$, \dots, $x_n$ são variáveis elementares; $a_1$, $a_2$, \dots, $a_n$ são coeficientes numéricos; $a_0$ é o termo constante. Logo, a forma linear é usada para construir a restrição final elementar na forma padrão: $$-\infty= 0 and y >= 0; check sum{i in ORIG} suprimento[i] = sum{j in DEST} demanda[j]; check{i in I, j in 1..10}: S[i,j] in U[i] union V[j]; \end{verbatim} A sentença check permite a verificação do valor resultante de uma expressão lógica especificada na sentença. Se o valor é {\it falso}, um erro é reportado. Se o domínio do subíndice não é especificado, a verificação é realizada apenas uma vez. \linebreak Especificar o domínio do subíndice permite a execução de verificações múltiplas para cada $n$-tupla no conjunto domínio. Neste último caso, a expressão lógica pode incluir índices introduzidos na expressão indexante correspondente. % \noindent % \framebox[468pt][l]{ % \parbox[c][24pt]{468pt}{ % \hspace{6pt} {\tt check} {\it domain} {\tt:} {\it expression} {\tt;} % }} % % \medskip % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the check statement; % % \noindent % {\it expression} is an logical expression which specifies the logical % condition to be checked. (The colon preceding {\it expression} may be % omitted.) % % \para{Examples} % % \begin{verbatim} % check: x + y <= 1 and x >= 0 and y >= 0; % check sum{i in ORIG} supply[i] = sum{j in DEST} demand[j]; % check{i in I, j in 1..10}: S[i,j] in U[i] union V[j]; % \end{verbatim} % % The check statement allows checking the resultant value of an logical % expression specified in the statement. If the value is {\it false}, an % error is reported. % % If the subscript domain is not specified, the check is performed only % once. Specifying the subscript domain allows performing multiple check % for every $n$-tuple in the domain set. In the latter case the logical % expression may include dummy indices introduced in corresponding % indexing expression. \section{Sentença display} \noindent \framebox[468pt][l]{ \parbox[c][24pt]{468pt}{ \hspace{6pt} {\tt display} {\it domínio} {\tt:} {\it item} {\tt,} \dots {\tt,} {\it item} {\tt;} }} \medskip \noindent {\it domínio} é uma expressão indexante opcional que especifica um domínio do subíndice da sentença display; \noindent {\it item}, \dots, {\it item} são itens a serem mostrados (os dois pontos que precedem o primeiro item podem ser omitidos). \para{Exemplos} \begin{verbatim} display: 'x =', x, 'y =', y, 'z =', z; display sqrt(x ** 2 + y ** 2 + z ** 2); display{i in I, j in J}: i, j, a[i,j], b[i,j]; \end{verbatim} A sentença display avalia todos itens especificados na sentença e escreve seus valores em saída padrão (terminal) em formato de texto plano. Se um domínio de subíndice não é especificado, os itens são avaliados e mostrados apenas uma vez. Ao especificar o domínio do subíndice, itens são avaliados e mostrados para cada $n$-tupla no conjunto do domínio. No último caso, os itens podem incluir índices introduzidos na expressão indexante correspondente. Um item a ser mostrado pode ser um objeto de modelo (conjunto, parâmetro, variável, restrição, objetivo) ou uma expressão. Se um item é um objeto calculável (i.e., um conjunto ou parâmetro com o atributo de atribuição), o objeto é avaliado por todo domínio e em seguida, seu conteúdo (i.e., o conteúdo da matriz de objetos) é mostrado. Caso contrário, se o item não é um objeto calculável, somente seu seu conteúdo corrente (i.e., os membros realmente gerados durante a avaliação do modelo) é mostrado. Se o item é uma expressão, a expressão é avaliada e seu valor resultante é mostrado. % \noindent % \framebox[468pt][l]{ % \parbox[c][24pt]{468pt}{ % \hspace{6pt} {\tt display} {\it domain} {\tt:} {\it item} {\tt,} % \dots {\tt,} {\it item} {\tt;} % }} % % \medskip % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the display statement; % % \noindent % {\it item}, \dots, {\it item} are items to be displayed. (The colon % preceding the first item may be omitted.) % % \para{Examples} % % \begin{verbatim} % display: 'x =', x, 'y =', y, 'z =', z; % display sqrt(x ** 2 + y ** 2 + z ** 2); % display{i in I, j in J}: i, j, a[i,j], b[i,j]; % \end{verbatim} % % The display statement evaluates all items specified in the statement % and writes their values on the standard output (terminal) in plain text % format. % % If a subscript domain is not specified, items are evaluated and then % displayed only once. Specifying the subscript domain causes items to be % evaluated and displayed for every $n$-tuple in the domain set. In the % latter case items may include dummy indices introduced in corresponding % indexing expression. % % An item to be displayed can be a model object (set, parameter, % variable, constraint, objective) or an expression. % % If the item is a computable object (i.e. a set or parameter provided % with the assign attribute), the object is evaluated over the entire % domain and then its content (i.e. the content of the object array) is % displayed. Otherwise, if the item is not a computable object, only its % current content (i.e. members actually generated during the model % evaluation) is displayed. % % If the item is an expression, the expression is evaluated and its % resultant value is displayed. \section{Sentença printf} \noindent \framebox[468pt][l]{ \parbox[c][64pt]{468pt}{ \hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,} {\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt;} \medskip \hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,} {\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt>} {\it nome-do-arquivo} {\tt;} \medskip \hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,} {\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt>>} {\it nome-do-arquivo} {\tt;} }} \medskip \noindent {\it domínio} é uma expressão indexante opcional que especifica o domínio do subíndice da sentença printf; \noindent {\it formato} é uma expressão simbólica cujo valor especifica uma cadeia de controle de formato (os dois pontos que precedem a expressão de formato podem ser omitidos). \noindent {\it expressão}, \dots, {\it expressão} são zero ou mais expressões cujos valores devem ser formatados e impressos. Cada expressão deve ser de tipo numérico, simbólico ou lógico. \noindent {\it nome-do-arquivo} é uma expressão simbólica cujo valor especifica um nome de um arquivo de texto para onde a saída é redirecionada. O sinal {\tt>} significa criar um novo aquivo vazio, enquanto o sinal {\tt>>} significa acrescentar a saída a um arquivo existente. Se o nome do arquivo não é especificado, a saída é escrita na saída padrão (terminal). \para{Exemplos} \begin{verbatim} printf 'Ola, mundo!\n'; printf: "x = %.3f; y = %.3f; z = %.3f\n", x, y, z > "resultado.txt"; printf{i in I, j in J}: "fluxo de %s para %s eh %d\n", i, j, x[i,j] >> arquivo_resultado & ".txt"; printf{i in I} 'fluxo total de %s eh %g\n', i, sum{j in J} x[i,j]; printf{k in K} "x[%s] = " & (if x[k] < 0 then "?" else "%g"), k, x[k]; \end{verbatim} A sentença printf é similar a sentença display, no entanto, ela permite formatar os dados a serem escritos. Se um domínio do subíndice não é especificado, a sentença printf é executada apenas uma vez. Especificar um domínio do subíndice gera a execução da sentença printf para cada $n$-tupla no conjunto do domínio. No último caso, o formato e a expressão podem incluir índices introduzidos nas expressões indexantes correspondentes. A cadeia de controle de formato é valor da expressão simbólica {\it formato} especificada na sentença printf. Ela é composta de zero ou mais diretivas, como segue: tanto caracteres ordinários (exceto {\tt\%}), que são copiados sem modificação ao fluxo de saída, quanto especificações de conversão, provocam a avaliação da expressão correspondente especificada na sentença printf, do seu formato e da escrita do valor resultante no fluxo de saída. As especificações de conversão que podem ser usadas na cadeia de controle de formato são as seguintes: {\tt d}, {\tt i}, {\tt f}, {\tt F}, {\tt e}, {\tt E}, {\tt g}, {\tt G} e {\tt s}. Estas especificações possuem a mesma sintaxe e semântica que na linguagem de programação C. % \noindent % \framebox[468pt][l]{ % \parbox[c][64pt]{468pt}{ % \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,} % {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt;} % % \medskip % % \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,} % {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt>} % {\it filename} {\tt;} % % \medskip % % \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,} % {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt>>} % {\it filename} {\tt;} % }} % % \medskip % % \noindent % {\it domain} is an optional indexing expression, which specifies % a subscript domain of the printf statement; % % \noindent % {\it format} is a symbolic expression whose value specifies a format % control string. (The colon preceding the format expression may be % omitted.) % % \noindent % {\it expression}, \dots, {\it expression} are zero or more expressions % whose values have to be formatted and printed. Each expression should % be of numeric, symbolic, or logical type. % % \noindent % {\it filename} is a symbolic expression whose value specifies a name % of a text file, to which the output is redirected. The flag {\tt>} % means creating a new empty file while the flag {\tt>>} means appending % the output to an existing file. If no file name is specified, the % output is written on the standard output (terminal). % % \para{Examples} % % \begin{verbatim} % printf 'Hello, world!\n'; % printf: "x = %.3f; y = %.3f; z = %.3f\n", x, y, z > "result.txt"; % printf{i in I, j in J}: "flow from %s to %s is %d\n", i, j, x[i,j] % >> result_file & ".txt"; % printf{i in I} 'total flow from %s is %g\n', i, sum{j in J} x[i,j]; % printf{k in K} "x[%s] = " & (if x[k] < 0 then "?" else "%g"), % k, x[k]; % \end{verbatim} % % The printf statement is similar to the display statement, however, it % allows formatting data to be written. % % If a subscript domain is not specified, the printf statement is % executed only once. Specifying a subscript domain causes executing the % printf statement for every $n$-tuple in the domain set. In the latter % case the format and expression may include dummy indices introduced in % corresponding indexing expression. % % The format control string is a value of the symbolic expression % {\it format} specified in the printf statement. It is composed of zero % or more directives as follows: ordinary characters (not {\tt\%}), which % are copied unchanged to the output stream, and conversion % specifications, each of which causes evaluating corresponding % expression specified in the printf statement, formatting it, and % writing its resultant value to the output stream. % % Conversion specifications that may be used in the format control string % are the following:\linebreak {\tt d}, {\tt i}, {\tt f}, {\tt F}, % {\tt e}, {\tt E}, {\tt g}, {\tt G}, and {\tt s}. These specifications % have the same syntax and semantics as in the C programming language. \section{Sentença for} \noindent \framebox[468pt][l]{ \parbox[c][44pt]{468pt}{ \hspace{6pt} {\tt for} {\it domínio} {\tt:} {\it sentença} {\tt;} \medskip \hspace{6pt} {\tt for} {\it domínio} {\tt:} {\tt\{} {\it sentença} \dots {\it sentença} {\tt\}} {\tt;} }} \medskip \noindent {\it domínio} é uma expressão indexante que especifica um domínio do subíndice da sentença for. (Os dois pontos que seguem a expressão indexante podem ser omitidos). \noindent {\it sentença} é uma sentença que deve ser executada sob o controle da sentença for; \noindent {\it sentença}, \dots, {\it sentença} é uma sequência de sentenças (cercada entre chaves) que deve ser executada sob o controle da sentença for. Apenas as sentenças seguintes podem ser usadas dentro da sentença for: check, display, printf e outro for. \para{Exemplos} \begin{verbatim} for {(i,j) in E: i != j} { printf "fluxo de %s para %s eh %g\n", i, j, x[i,j]; check x[i,j] >= 0; } for {i in 1..n} { for {j in 1..n} printf " %s", if x[i,j] then "Q" else "."; printf("\n"); } for {1..72} printf("*"); \end{verbatim} A sentença for faz com que a sentença, ou uma sequência de sentenças especificadas como parte da sentença for, seja executada para cada $n$-tupla no conjunto do domínio. Assim, sentenças dentro da sentença for podem incluir índices introduzidos na expressão indexante correspondente. % \noindent % \framebox[468pt][l]{ % \parbox[c][44pt]{468pt}{ % \hspace{6pt} {\tt for} {\it domain} {\tt:} {\it statement} {\tt;} % % \medskip % % \hspace{6pt} {\tt for} {\it domain} {\tt:} {\tt\{} {\it statement} % \dots {\it statement} {\tt\}} {\tt;} % }} % % \medskip % % \noindent % {\it domain} is an indexing expression which specifies a subscript % domain of the for statement. (The colon following the indexing % expression may be omitted.) % % \noindent % {\it statement} is a statement, which should be executed under control % of the for statement; % % \noindent % {\it statement}, \dots, {\it statement} is a sequence of statements % (enclosed in curly braces), which should be executed under control of % the for statement. % % Only the following statements can be used within the for statement: % check, display, printf, and another for. % % \para{Examples} % % \begin{verbatim} % for {(i,j) in E: i != j} % { printf "flow from %s to %s is %g\n", i, j, x[i,j]; % check x[i,j] >= 0; % } % for {i in 1..n} % { for {j in 1..n} printf " %s", if x[i,j] then "Q" else "."; % printf("\n"); % } % for {1..72} printf("*"); % \end{verbatim} % % The for statement causes a statement or a sequence of statements % specified as part of the for statement to be executed for every % $n$-tuple in the domain set. Thus, statements within the for statement % may include dummy indices introduced in corresponding indexing % expression. \newpage \section{Sentença table} \noindent \framebox[468pt][l]{ \parbox[c][80pt]{468pt}{ \hspace{6pt} {\tt table} {\it nome} {\it alias} {\tt IN} {\it controlador} {\it arg} \dots {\it arg} {\tt:} \hspace{6pt} {\tt\ \ \ \ \ } {\it conjunto} {\tt<-} {\tt[} {\it cmp} {\tt,} \dots {\tt,} {\it cmp} {\tt]} {\tt,} {\it par} {\tt\textasciitilde} {\it cmp} {\tt,} \dots {\tt,} {\it par} {\tt\textasciitilde} {\it cmp} {\tt;} \medskip \hspace{6pt} {\tt table} {\it nome} {\it alias} {\it domínio} {\tt OUT} {\it controlador} {\it arg} \dots {\it arg} {\tt:} \hspace{6pt} {\tt\ \ \ \ \ } {\it expr} {\tt\textasciitilde} {\it cmp} {\tt,} \dots {\tt,} {\it expr} {\tt\textasciitilde} {\it cmp} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico da tabela; \noindent {\it alias} é um literal de cadeia opcional que especifica um pseudônimo da tabela; \noindent {\it domínio} é uma expressão indexante que especifica o domínio do subíndice da tabela (de saída); \noindent {\tt IN} significa ler dados de uma tabela de entrada; \noindent {\tt OUT} significa escrever dados em uma tabela de saída; \noindent {\it controlador} é uma expressão simbólica que especifica o controlador usado para acessar a tabela (para mais detalhes, ver Apêndice \ref{drivers}, página \pageref{drivers}); \noindent {\it arg} é uma expressão simbólica opcional, que é um argumento passado ao controlador da tabela. Esta expressão simbólica não deveria incluir índices especificados no domínio; \noindent {\it conjunto} é o nome de um conjunto simples opcional chamado {\it conjunto de controle}. Pode ser omitido junto com o delimitador {\tt<-}; \noindent {\it cmp} é um nome de campo. Entre colchetes, pelo menos um campo deve ser especificado. O nome do campo, que segue o nome do parâmetro ou de uma expressão, é opcional e pode ser omitido juntamente com o delimitador~{\tt\textasciitilde}. Neste caso o nome do objeto de modelo correspondente é usado como nome de campo; \noindent {\it par} é um nome simbólico de um parâmetro do modelo; \noindent {\it expr} é uma expressão numérica ou simbólica. \para{Exemplos} \begin{verbatim} table dados IN "CSV" "dados.csv": S <- [DE,PARA], d~DISTANCIA, c~CUSTO; table resultado{(d,p) in S} OUT "CSV" "resultado.csv": d~DE, p~PARA, x[d,p]~FLUXO; \end{verbatim} A sentença table permite a leitura de dados de uma tabela para objetos de modelo como conjuntos e parâmetros (não-escalares) assim como escrever dados do modelo para uma tabela. % \noindent % \framebox[468pt][l]{ % \parbox[c][80pt]{468pt}{ % \hspace{6pt} {\tt table} {\it name} {\it alias} {\tt IN} {\it driver} % {\it arg} \dots {\it arg} {\tt:} % % \hspace{6pt} {\tt\ \ \ \ \ } {\it set} {\tt<-} {\tt[} {\it fld} {\tt,} % \dots {\tt,} {\it fld} {\tt]} {\tt,} {\it par} {\tt\textasciitilde} % {\it fld} {\tt,} \dots {\tt,} {\it par} {\tt\textasciitilde} {\it fld} % {\tt;} % % \medskip % % \hspace{6pt} {\tt table} {\it name} {\it alias} {\it domain} {\tt OUT} % {\it driver} {\it arg} \dots {\it arg} {\tt:} % % \hspace{6pt} {\tt\ \ \ \ \ } {\it expr} {\tt\textasciitilde} {\it fld} % {\tt,} \dots {\tt,} {\it expr} {\tt\textasciitilde} {\it fld} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the table; % % \noindent % {\it alias} is an optional string literal, which specifies an alias of % the table; % % \noindent % {\it domain} is an indexing expression, which specifies a subscript % domain of the (output) table; % % \noindent % {\tt IN} means reading data from the input table; % % \noindent % {\tt OUT} means writing data to the output table; % % \noindent % {\it driver} is a symbolic expression, which specifies the driver used % to access the table (for details see Appendix \ref{drivers}, page % \pageref{drivers}); % % \noindent % {\it arg} is an optional symbolic expression, which is an argument % pass\-ed to the table driver. This symbolic expression should not % include dummy indices specified in the domain; % % \noindent % {\it set} is the name of an optional simple set called {\it control % set}. It can be omitted along with the delimiter {\tt<-}; % % \noindent % {\it fld} is a field name. Within square brackets at least one field % should be specified. The field name following a parameter name or % expression is optional and can be omitted along with the % delimiter~{\tt\textasciitilde}, in which case the name of corresponding % model object is used as the field name; % % \noindent % {\it par} is a symbolic name of a model parameter; % % \noindent % {\it expr} is a numeric or symbolic expression. % % \para{Examples} % % \begin{verbatim} % table data IN "CSV" "data.csv": S <- [FROM,TO], d~DISTANCE, % c~COST; % table result{(f,t) in S} OUT "CSV" "result.csv": f~FROM, t~TO, % x[f,t]~FLOW; % \end{verbatim} % % The table statement allows reading data from a table into model % objects such as sets and (non-scalar) parameters as well as writing % data from the model to a table. \newpage \subsection{Estrutura de tabelas} Uma {\it tabela de dados} é um conjunto (desordenado) de {\it registros}, onde cada registro consiste do mesmo número de {\it campos} e cada campo possui um único nome simbólico denominado o {\it nome do campo}. Por exemplo: \bigskip \begin{tabular}{@{\hspace*{42mm}}c@{\hspace*{11mm}}c@{\hspace*{10mm}}c @{\hspace*{9mm}}c} Primeiro&Segundo&&Último\\ campo&campo&.\ \ .\ \ .&campo\\ $\downarrow$&$\downarrow$&&$\downarrow$\\ \end{tabular} \begin{tabular}{ll@{}} Cabeçalho da tabela&$\rightarrow$\\ Primeiro registro&$\rightarrow$\\ Segundo registro&$\rightarrow$\\ \\ \hfil .\ \ .\ \ .\\ \\ Último registro&$\rightarrow$\\ \end{tabular} \begin{tabular}{|l|l|c|c|} \hline {\tt DE}&{\tt PARA}&{\tt DISTANCIA}&{\tt CUSTO}\\ \hline {\tt Seattle} &{\tt New-York}&{\tt 2.5}&{\tt 0.12}\\ {\tt Seattle} &{\tt Chicago} &{\tt 1.7}&{\tt 0.08}\\ {\tt Seattle} &{\tt Topeka} &{\tt 1.8}&{\tt 0.09}\\ {\tt San-Diego}&{\tt New-York}&{\tt 2.5}&{\tt 0.15}\\ {\tt San-Diego}&{\tt Chicago} &{\tt 1.8}&{\tt 0.10}\\ {\tt San-Diego}&{\tt Topeka} &{\tt 1.4}&{\tt 0.07}\\ \hline \end{tabular} % A {\it data table} is an (unordered) set of {\it records}, where each % record consists of the same number of {\it fields}, and each field is % provided with a unique symbolic name called the {\it field name}. For % example: % % \bigskip % % \begin{tabular}{@{\hspace*{42mm}}c@{\hspace*{11mm}}c@{\hspace*{10mm}}c % @{\hspace*{9mm}}c} % First&Second&&Last\\ % field&field&.\ \ .\ \ .&field\\ % $\downarrow$&$\downarrow$&&$\downarrow$\\ % \end{tabular} % % \begin{tabular}{ll@{}} % Table header&$\rightarrow$\\ % First record&$\rightarrow$\\ % Second record&$\rightarrow$\\ % \\ % \hfil .\ \ .\ \ .\\ % \\ % Last record&$\rightarrow$\\ % \end{tabular} % \begin{tabular}{|l|l|c|c|} % \hline % {\tt FROM}&{\tt TO}&{\tt DISTANCE}&{\tt COST}\\ % \hline % {\tt Seattle} &{\tt New-York}&{\tt 2.5}&{\tt 0.12}\\ % {\tt Seattle} &{\tt Chicago} &{\tt 1.7}&{\tt 0.08}\\ % {\tt Seattle} &{\tt Topeka} &{\tt 1.8}&{\tt 0.09}\\ % {\tt San-Diego}&{\tt New-York}&{\tt 2.5}&{\tt 0.15}\\ % {\tt San-Diego}&{\tt Chicago} &{\tt 1.8}&{\tt 0.10}\\ % {\tt San-Diego}&{\tt Topeka} &{\tt 1.4}&{\tt 0.07}\\ % \hline % \end{tabular} \subsection{Lendo dados de uma tabela de entrada} A sentença tabela de entrada faz a leitura de dados da tabela especificada, registro por registro. Uma vez que o registro subsequente foi lido, valores numéricos ou simbólicos dos campos, cujos nomes são cercados entre colchetes na sentença table, são reunidos em um $n$-tuplo. Se o conjunto de controle é especificado na sentença table, este $n$-tuplo é adicionado a ele. Além disso, um valor numérico ou simbólico de cada campo associado com um parâmetro do modelo é atribuído ao membro do parâmetro identificado por subíndices, que são componentes da $n$-tupla que acabou de ser lida. Por exemplo, a seguinte sentença de tabela de entrada: \noindent\hfil \verb|table dados IN "...": S <- [DE,PARA], d~DISTANCIA, c~CUSTO;| \noindent faz a leitura de valores de quatro campos chamados {\tt DE}, {\tt PARA}, {\tt DISTANCIA} e {\tt CUSTO} de cada registro da tabela especificada. Os valores dos campos {\tt DE} e {\tt PARA} dão um par $(f,t)$, que é adicionado ao conjunto de controle {\tt S}. O valor do campo {\tt DISTANCIA} é atribuído ao membro do parâmetro ${\tt d}[f,t]$ enquanto que o valor do campo {\tt CUSTO} é atribuído ao membro do parâmetro ${\tt c}[f,t]$. Note que a tabela de entrada pode conter campos adicionais cujos nomes não sejam especificados na sentença tabela, neste caso, os valores destes campos serão ignorados na leitura da tabela. % The input table statement causes reading data from the specified table % record by record. % % Once a next record has been read, numeric or symbolic values of fields, % whose names are enclosed in square brackets in the table statement, are % gathered into $n$-tuple, and if the control set is specified in the % table statement, this $n$-tuple is added to it. Besides, a numeric or % symbolic value of each field associated with a model parameter is % assigned to the parameter member identified by subscripts, which are % components of the $n$-tuple just read. % % For example, the following input table statement: % % \noindent\hfil % \verb|table data IN "...": S <- [FROM,TO], d~DISTANCE, c~COST;| % % \noindent % causes reading values of four fields named {\tt FROM}, {\tt TO}, % {\tt DISTANCE}, and {\tt COST} from each record of the specified table. % Values of fields {\tt FROM} and {\tt TO} give a pair $(f,t)$, which is % added to the control set {\tt S}. The value of field {\tt DISTANCE} is % assigned to parameter member ${\tt d}[f,t]$, and the value of field % {\tt COST} is assigned to parameter member ${\tt c}[f,t]$. % % Note that the input table may contain extra fields whose names are not % specified in the table statement, in which case values of these fields % on reading the table are ignored. \subsection{Escrevendo dados em uma tabela de saída} A sentença tabela de saída gera a escrita de dados na tabela especificada. Note que alguns controladores (chamados CSV e xBASE) destroem a tabela de saída antes de escrever os dados, i.e., deletam todos os registros existentes. Cada $n$-tupla no domínio do conjunto especificado gera um registro escrito na tabela de saída. Os valores dos campos são valores numéricos ou simbólicos das expressões correspondentes especificadas na sentença table. Estas expressões são avaliadas para cada $n$-tupla no conjunto do domínio, portanto, podem incluir índices introduzidos na expressão indexante correspondente. Por exemplo, a seguinte sentença da tabela de saída: \noindent\hfil \verb|table resultado{(f,t) in S} OUT "...": f~DE, t~PARA, x[f,t]~FLUXO;| \noindent gera a escrita de registros; um registro para cada par $(f,t)$ no conjunto {\tt S} para a tabela de saída, onde cada registro consiste de três campos chamados {\tt DE}, {\tt PARA} e {\tt FLUXO}. Os valores escritos nos campos {\tt DE} e {\tt PARA} são os valores correntes dos índices {\tt f} e {\tt t}. O valor escrito no campo {\tt FLUXO} é um valor do membro ${\tt x}[f,t]$ do correspondente parâmetro ou variável indexada. % The output table statement causes writing data to the specified table. % Note that some drivers (namely, CSV and xBASE) destroy the output table % before writing data, i.e. delete all its existing records. % % Each $n$-tuple in the specified domain set generates one record written % to the output table. Values of fields are numeric or symbolic values of % corresponding expressions specified in the table statement. These % expressions are evaluated for each $n$-tuple in the domain set and, % thus, may include dummy indices introduced in the corresponding indexing % expression. % % For example, the following output table statement: % % \noindent\hfil % \verb|table result{(f,t) in S} OUT "...": f~FROM, t~TO, x[f,t]~FLOW;| % % \noindent % causes writing records, by one record for each pair $(f,t)$ in set % {\tt S}, to the output table, where each record consists of three % fields named {\tt FROM}, {\tt TO}, and {\tt FLOW}. The values written % to fields {\tt FROM} and {\tt TO} are current values of dummy indices % {\tt f} and {\tt t}, and the value written to field {\tt FLOW} is % a value of member ${\tt x}[f,t]$ of corresponding subscripted parameter % or variable. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Dados do modelo} Os {\it dados do modelo} includem conjuntos elementares, que são ``valores'' dos conjuntos do modelo, e valores numéricos e simbólicos dos parâmetros do modelo. Em MathProg existem duas formas diferentes de fornecer valores aos conjuntos e parâmetros do modelo. Uma forma é simplesmente prover os dados necessários usando o atributo de atribuição. No entanto, em muitos casos é mais prático separar o modelo próprio dos dados particulares necessários para o modelo. Para o último caso, em MathProg há uma outra forma, em que a descrição do modelo é dividida em duas partes: a seção de modelo e a seção de dados. A {\it seção de modelo} é a principal parte da descrição do modelo. Ela contém todas as declarações de todos objetos do modelo, sendo comum a todos problemas baseados naquele modelo. A {\it seção de dados} é uma parte opcional da descrição do modelo que contém dados específicos para um problema particular. Em MathProg seções de modelo e de dados podem ser localizadas tanto em um arquivo de texto ou em dois arquivos de texto separados. 1. Se ambas seções de modelo e de dados estão localizados em um arquivo, o arquivo é composto como segue: \bigskip \noindent\hfil \framebox{\begin{tabular}{l} {\it sentença}{\tt;}\\ {\it sentença}{\tt;}\\ \hfil.\ \ .\ \ .\\ {\it sentença}{\tt;}\\ {\tt data;}\\ {\it bloco de dados}{\tt;}\\ {\it bloco de dados}{\tt;}\\ \hfil.\ \ .\ \ .\\ {\it bloco de dados}{\tt;}\\ {\tt end;} \end{tabular}} % {\it Model data} include elemental sets, which are ``values'' of model % sets, and numeric and symbolic values of model parameters. % % In MathProg there are two different ways to saturate model sets and % parameters with data. One way is simply providing necessary data using % the assign attribute. However, in many cases it is more practical to % separate the model itself and particular data needed for the model. For % the latter reason in MathProg there is another way, when the model % description is divided into two parts: model section and data section. % % A {\it model section} is a main part of the model description that % contains declarations of all model objects and is common for all % problems based on that model. % % A {\it data section} is an optional part of the model description that % contains model data specific for a particular problem. % % In MathProg model and data sections can be placed either in one text % file or in two separate text files. % % 1. If both model and data sections are placed in one file, the file is % composed as follows: % % \bigskip % % \noindent\hfil % \framebox{\begin{tabular}{l} % {\it statement}{\tt;}\\ % {\it statement}{\tt;}\\ % \hfil.\ \ .\ \ .\\ % {\it statement}{\tt;}\\ % {\tt data;}\\ % {\it data block}{\tt;}\\ % {\it data block}{\tt;}\\ % \hfil.\ \ .\ \ .\\ % {\it data block}{\tt;}\\ % {\tt end;} % \end{tabular}} % 2. Se a seção de modelo e dados são posicionados em dois arquivos separados, os % arquivos são compostos como segue: \newpage 2. Se a seção de modelo e dados são posicionados em dois arquivos separados, os arquivos são compostos como segue: \bigskip \noindent\hfil \begin{tabular}{@{}c@{}} \framebox{\begin{tabular}{l} {\it sentença}{\tt;}\\ {\it sentença}{\tt;}\\ \hfil.\ \ .\ \ .\\ {\it sentença}{\tt;}\\ {\tt end;}\\ \end{tabular}}\\ \\\\Arquivo de modelo\\ \end{tabular} \hspace{32pt} \begin{tabular}{@{}c@{}} \framebox{\begin{tabular}{l} {\tt data;}\\ {\it bloco de dados}{\tt;}\\ {\it bloco de dados}{\tt;}\\ \hfil.\ \ .\ \ .\\ {\it bloco de dados}{\tt;}\\ {\tt end;}\\ \end{tabular}}\\ \\Arquivo de dados\\ \end{tabular} \bigskip Nota: Se a seção de dados é posicionada em um arquivo separado, a palavra-chave {\tt data} é opcional e pode ser omitida juntamente como o ponto e vírgula que a segue. % \bigskip % % \noindent\hfil % \begin{tabular}{@{}c@{}} % \framebox{\begin{tabular}{l} % {\it statement}{\tt;}\\ % {\it statement}{\tt;}\\ % \hfil.\ \ .\ \ .\\ % {\it statement}{\tt;}\\ % {\tt end;}\\ % \end{tabular}}\\ % \\\\Model file\\ % \end{tabular} % \hspace{32pt} % \begin{tabular}{@{}c@{}} % \framebox{\begin{tabular}{l} % {\tt data;}\\ % {\it data block}{\tt;}\\ % {\it data block}{\tt;}\\ % \hfil.\ \ .\ \ .\\ % {\it data block}{\tt;}\\ % {\tt end;}\\ % \end{tabular}}\\ % \\Data file\\ % \end{tabular} % % \bigskip % % Note: If the data section is placed in a separate file, the keyword % {\tt data} is optional and may be omitted along with the semicolon that % follows it. \section{Programando a seção de dados} A {\it seção de dados} é uma sequência de blocos de dados em vários formatos e são discutidos nas seções seguintes. A ordem na qual os blocos de dados seguem na seção de dados pode ser arbitrária, portanto, não precisa ser necessariamente a mesma ordem que seguem os elementos correspondentes da seção de modelo. As regras para programar a seção de dados são comumente as mesmas que as regras de \linebreak programar a descrição do modelo (ver Seção \ref{coding}, página \pageref{coding}), i.e., blocos de dados são compostos com unidades léxicas básicas, como nomes simbólicos, literais numéricos e de cadeia, palavras-chave, \linebreak delimitadores e comentários. No entanto, por conveniência e para melhorar legibilidade, há um desvio da regra comum: se um literal de cadeia consiste unicamente de caracteres alfanuméricos (incluindo o caractere sublinhado), os sinais {\tt+} e {\tt-} e/ou o ponto decimal, ele pode ser programado sem aspas limitadoras (simples ou duplas). Todo material numérico e simbólico provido na seção de dados é programado na forma de números e símbolos, i.e., diferentemente da seção de modelo, não são permitidas expressões na seção de dados. Apesar disso, os sinais {\tt+} e {\tt-} podem preceder literais numéricos para permitir a programação de quantidades numéricas com sinais. Neste caso não deve haver caractere de espaço em branco entre o sinal e o literal numérico seguinte (se houver pelo menos uma espaço em branco, o sinal e o literal numérico seguinte são reconhecidos como duas unidades léxicas diferentes). % The {\it data section} is a sequence of data blocks in various formats, % which are discussed in following sections. The order, in which data % blocks follow in the data section, may be arbitrary, not necessarily % the same, in which corresponding model objects follow in the model % section. % % The rules of coding the data section are commonly the same as the rules % of coding the model description (see Section \ref{coding}, page % \pageref{coding}), i.e. data blocks are composed from basic lexical % units such as symbolic names, numeric and string literals, keywords, % delimiters, and comments. However, for the sake of convenience and for % improving readability there is one deviation from the common rule: if % a string literal consists of only alphanumeric characters (including % the underscore character), the signs {\tt+} and {\tt-}, and/or the % decimal point, it may be coded without bordering by (single or double) % quotes. % % All numeric and symbolic material provided in the data section is coded % in the form of numbers and symbols, i.e. unlike the model section % no expressions are allowed in the data section. Nevertheless, the signs % {\tt+} and {\tt-} can precede numeric literals to allow coding signed % numeric quantities, in which case there should be no white-space % characters between the sign and following numeric literal (if there is % at least one white-space, the sign and following numeric literal are % recognized as two different lexical units). \newpage \section{Bloco de dados set} \noindent \framebox[468pt][l]{ \parbox[c][44pt]{468pt}{ \hspace{6pt} {\tt set} {\it nome} {\tt,} {\it registro} {\tt,} \dots {\tt,} {\it registro} {\tt;} \medskip \hspace{6pt} {\tt set} {\it nome} {\tt[} {\it símbolo} {\tt,} \dots {\tt,} {\it símbolo} {\tt]} {\tt,} {\it registro} {\tt,} \dots {\tt,} {\it registro} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico do conjunto; \noindent {\it símbolo}, \dots, {\it símbolo} são subíndices que especificam um membro particular do conjunto \linebreak(se o conjunto é uma matriz, i.e., um conjunto de conjuntos); \noindent {\it registro}, \dots, {\it registro} são registros. \noindent As vírgulas que precedem os registros podem ser omitidas. \para{Registros} \vspace*{-8pt} \begin{description} \item[{\tt :=}]\hspace*{0pt}\\ é um elemento de atribuição de registro não-significativo que pode ser usado livremente para melhorar a legibilidade; \item[{\tt(} {\it fatia} {\tt)}]\hspace*{0pt}\\ especifica uma fatia; \item[{\it dados-simples}]\hspace*{0pt}\\ especifica os dados do conjunto em formato simples; \item[{\tt:} {\it dados matriciais}]\hspace*{0pt}\\ especifica os dados do conjunto em formato de matriz; \item[{\tt(tr)} {\tt:} {\it dados matriciais}]\hspace*{0pt}\\ especifica os dados do conjunto em formato de matriz transposta. (Neste caso, os dois pontos que seguem a palavra-chave {\tt(tr)} podem ser omitidos). \end{description} \vspace*{-8pt} \para{Exemplos} \begin{verbatim} set mes := Jan Fev Mar Abr Mai Jun; set mes "Jan", "Fev", "Mar", "Abr", "Mai", "Jun"; set A[3,Mar] := (1,2) (2,3) (4,2) (3,1) (2,2) (4,4) (3,4); set A[3,'Mar'] := 1 2 2 3 4 2 3 1 2 2 4 4 3 4; set A[3,'Mar'] : 1 2 3 4 := 1 - + - - 2 - + + - 3 + - - + 4 - + - + ; set B := (1,2,3) (1,3,2) (2,3,1) (2,1,3) (1,2,2) (1,1,1) (2,1,1); set B := (*,*,*) 1 2 3, 1 3 2, 2 3 1, 2 1 3, 1 2 2, 1 1 1, 2 1 1; set B := (1,*,2) 3 2 (2,*,1) 3 1 (1,2,3) (2,1,3) (1,1,1); set B := (1,*,*) : 1 2 3 := 1 + - - 2 - + + 3 - + - (2,*,*) : 1 2 3 := 1 + - + 2 - - - 3 + - - ; \end{verbatim} \noindent(Nestes exemplos {\tt mes} é um conjunto simples de singletos, {\tt A} é uma matriz 2-dimensional de duplas e {\tt B} é um conjunto simples de triplas. Os blocos de dados para o mesmo conjunto são equivalentes no sentido que especificam os mesmos dados em formatos distintos.) O {\it bloco de dados do conjunto} é usado para especificar um conjunto elementar completo que é atribuído a um conjunto (se é um conjunto simples) ou a um de seus membros (se o conjunto é uma matriz de conjuntos).\footnote{Há uma outra forma de especificar dados para um conjunto simples com dados para os parâmetros. Esta questão é discutida na próxima seção.} Blocos de dados podem ser especificados somente para conjuntos não-calculáveis, i.e., para \linebreak conjuntos que possuem o atributo de atribuição ({\tt:=}) na sentença set correspondente. Se o conjunto é um conjunto simples, somente seus nomes simbólicos devem ser especificados no cabeçalho do bloco de dados. Caso contrário, se o conjunto é uma matriz $n$-dimensional, seus nomes simbólicos devem ser fornecidos com uma lista completa de subíndices separados por vírgulas e cercados em colchetes para especificar um membro particular da matriz de conjuntos. O número de subíndices deve ser igual ao da dimensão da matriz de conjuntos, onde cada subíndice deve ser um número ou um símbolo. Um conjunto elementar definido no bloco de dados é programado como uma sequência de \linebreak registros descritos abaixo.\footnote{{\it Registro} é simplesmente um termo técnico. Não significa que os mesmos possuem qualquer formato especial.} % \noindent % \framebox[468pt][l]{ % \parbox[c][44pt]{468pt}{ % \hspace{6pt} {\tt set} {\it name} {\tt,} {\it record} {\tt,} \dots % {\tt,} {\it record} {\tt;} % % \medskip % % \hspace{6pt} {\tt set} {\it name} {\tt[} {\it symbol} {\tt,} \dots % {\tt,} {\it symbol} {\tt]} {\tt,} {\it record} {\tt,} \dots {\tt,} % {\it record} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the set; % % \noindent % {\it symbol}, \dots, {\it symbol} are subscripts, which specify % a particular member of the set (if the set is an array, i.e. a set of % sets); % % \noindent % {\it record}, \dots, {\it record} are data records. % % \noindent % Commae preceding data records may be omitted. % % \para{Data records} % % \vspace*{-8pt} % % \begin{description} % \item[{\tt :=}]\hspace*{0pt}\\ % is a non-significant data record, which may be used freely to improve % readability; % \item[{\tt(} {\it slice} {\tt)}]\hspace*{0pt}\\ % specifies a slice; % \item[{\it simple-data}]\hspace*{0pt}\\ % specifies set data in the simple format; % \item[{\tt:} {\it matrix-data}]\hspace*{0pt}\\ % specifies set data in the matrix format; % \item[{\tt(tr)} {\tt:} {\it matrix-data}]\hspace*{0pt}\\ % specifies set data in the transposed matrix format. (In this case the % colon following the keyword {\tt(tr)} may be omitted.) % \end{description} % % \vspace*{-8pt} % % \para{Examples} % % \begin{verbatim} % set month := Jan Feb Mar Apr May Jun; % set month "Jan", "Feb", "Mar", "Apr", "May", "Jun"; % set A[3,Mar] := (1,2) (2,3) (4,2) (3,1) (2,2) (4,4) (3,4); % set A[3,'Mar'] := 1 2 2 3 4 2 3 1 2 2 4 4 3 4; % set A[3,'Mar'] : 1 2 3 4 := % 1 - + - - % 2 - + + - % 3 + - - + % 4 - + - + ; % set B := (1,2,3) (1,3,2) (2,3,1) (2,1,3) (1,2,2) (1,1,1) (2,1,1); % set B := (*,*,*) 1 2 3, 1 3 2, 2 3 1, 2 1 3, 1 2 2, 1 1 1, 2 1 1; % set B := (1,*,2) 3 2 (2,*,1) 3 1 (1,2,3) (2,1,3) (1,1,1); % set B := (1,*,*) : 1 2 3 := % 1 + - - % 2 - + + % 3 - + - % (2,*,*) : 1 2 3 := % 1 + - + % 2 - - - % 3 + - - ; % \end{verbatim} % % \noindent(In these examples {\tt month} is a simple set of singlets, % {\tt A} is a 2-dimensional array of doublets, and {\tt B} is a simple % set of triplets. Data blocks for the same set are equivalent in the % sense that they specify the same data in different formats.) % % The {\it set data block} is used to specify a complete elemental set, % which is assigned to a set (if it is a simple set) or one of its % members (if the set is an array of sets).\footnote{There is another way % to specify data for a simple set along with data for parameters. This % feature is discussed in the next section.} % % Data blocks can be specified only for non-computable sets, i.e. for % sets, which have no assign attribute ({\tt:=}) in the corresponding set % statements. % % If the set is a simple set, only its symbolic name should be specified % in the header of the data block. Otherwise, if the set is a % $n$-dimensional array, its symbolic name should be provided with a % complete list of subscripts separated by commae and enclosed in square % brackets to specify a particular member of the set array. The number of % subscripts should be the same as the dimension of the set array, where % each subscript should be a number or symbol. % % An elemental set defined in the set data block is coded as a sequence % of data records described below.\footnote{{\it Data record} is simply a % technical term. It does not mean that data records have any special % formatting.} \subsection{Registro de atribuição de dados} O {\it registro de atribuição de dados} ({\tt:=}) é um elemento não-significante. Ele pode ser usado para melhorar a legibilidade de blocos de dados. % The {\it assign data record} ({\tt:=}) is a non-signficant element. % It may be used for improving readability of data blocks. \subsection{Registro em fatia de dados} O {\it registro em fatia de dados} é um registro de controle que especifica uma {\it fatia} do conjunto elementar definido no bloco de dados. Ele possui a seguinte forma sintática: $$\mbox{{\tt(} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt)}}$$ onde $s_1$, $s_2$, \dots, $s_n$ são componentes da fatia. Cada componente da fatia pode ser um número, símbolo ou asterisco ({\tt*}). O número de \linebreak componentes na fatia deve ser o mesmo da dimensão $n$-tuplas do conjunto elementar a ser definido. Por exemplo, se o conjunto elementar contém 4-tuplas (quádruplas), a fatia deve ter quatro \linebreak componentes. O número de asteriscos na fatia denomina a {\it dimensão da fatia}. O efeito de usar fatias é o seguinte: se uma fatia $m$-dimensional (i.e., uma fatia contendo $m$ asteriscos) é especificada no bloco de dados, todos registros subsequentes devem especificar tuplas de dimensão~$m$. Sempre que uma $m$-tupla é encontrada, cada asterisco da fatia é substituído pelos componentes correspondentes da $m$-tupla, o que resulta na $n$-tupla, que é incluída no conjunto \linebreak elementar a ser definido. Por exemplo, se a fatia $(a,*,1,2,*)$ está vigente e a dupla $(3,b)$ é encontrada no registro subsequente, a 5-tupla resultante a ser incluída no conjunto elementar é $(a,3,1,2,b)$. Se a fatia não possui asteriscos, ela própria define uma $n$-tupla completa que é incluída no conjunto elementar. Uma vez especificada uma fatia, a mesma está vigente até que apareça uma nova fatia ou até que se encontre o fim do bloco de dados. Note que se uma fatia não é especificada no bloco de dados, assume-se uma cujos componentes são asteriscos em todas as posições. % The {\it slice data record} is a control record, which specifies a % {\it slice} of the elemental set defined in the data block. It has the % following syntactic form: % $$\mbox{{\tt(} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt)}}$$ % where $s_1$, $s_2$, \dots, $s_n$ are components of the slice. % % Each component of the slice can be a number or symbol or the asterisk % ({\tt*}). The number of components in the slice should be the same as % the dimension of $n$-tuples in the elemental set to be defined. For % instance, if the elemental set contains 4-tuples (quadruplets), the % slice should have four components. The number of asterisks in the slice % is called the {\it slice dimension}. % % The effect of using slices is the following. If a $m$-dimensional slice % (i.e. a slice having $m$ asterisks) is specified in the data block, all % subsequent data records should specify tuples of the dimension~$m$. % Whenever a $m$-tuple is encountered, each asterisk in the slice is % replaced by corresponding components of the $m$-tuple that gives the % resultant $n$-tuple, which is included in the elemental set to be % defined. For example, if the slice $(a,*,1,2,*)$ is in effect, and % 2-tuple $(3,b)$ is encountered in a subsequent data record, the % resultant 5-tuple included in the elemental set is $(a,3,1,2,b)$. % % The slice having no asterisks itself defines a complete $n$-tuple, % which is included in the elemental set. % % Being once specified the slice effects until either a new slice or the % end of data block is encountered. Note that if no slice is specified in % the data block, one, components of which are all asterisks, is assumed. \subsection{Registro simples} O {\it registro simples} define uma $n$-tupla em um formato simples e possui a seguinte forma sintática: $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$}$$ onde $t_1$, $t_2$, \dots, $t_n$ são componentes da $n$-tupla. Cada componente pode ser um número ou um símbolo. As vírgulas entre os componentes são opcionais e podem ser omitidas. % The {\it simple data record} defines one $n$-tuple in a simple format % and has the following syntactic form: % $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$}$$ % where $t_1$, $t_2$, \dots, $t_n$ are components of the $n$-tuple. Each % component can be a number or symbol. Commae between components are % optional and may be omitted. \subsection{Registro de matriz} O {\it registro de matriz} define diversas 2-tuplas (duplas) em um formato matricial e possui a seguinte forma sintática: $$\begin{array}{cccccc} \mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ \end{array}$$ onde $r_1$, $r_2$, \dots, $r_m$ são números e/ou símbolos que correspondem a linhas da matriz; $c_1$, $c_2$, \dots, $c_n$ são números e/ou símbolos que correspondem a colunas da matriz, $a_{11}$, $a_{12}$, \dots, $a_{mn}$ são elementos da matriz, que podem ser tanto {\tt+} como {\tt-}. (Neste registro, o delimitador {\tt:} que precede a lista de colunas e o delimitador {\tt:=} que segue após a lista de colunas, não podem ser omitidos.) Cada elemento $a_{ij}$ do bloco de dados matricial (onde $1\leq i\leq m$, $1\leq j\leq n$) correspondem a 2-tuplas $(r_i,c_j)$. Se $a_{ij}$ é o sinal mais ({\tt+}), a 2-tupla correspondente (ou uma $n$-tupla maior, se uma fatia é usada) é incluída no conjunto elementar. Caso contrário, se $a_{ij}$ é o sinal menos ({\tt-}), aquela 2-tupla não é incluída no conjunto elementar. Uma vez que o registro de matriz define 2-tuplas, tanto o conjunto elementar quanto a fatia vigente devem ser 2-dimensional. \newpage \subsection{Registro de matriz transposta} O {\it registro de matriz transposta} possui a seguinte forma sintática: $$\begin{array}{cccccc} \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ \end{array}$$ (Neste caso, o delimitador {\tt:} que segue a palavra-chave {\tt(tr)} é opcional e pode ser omitido.) Este registro é completamente análogo ao registro de matriz (ver anteriormente) com a única exceção de que neste caso, cada elemento $a_{ij}$ da matriz passa a corresponder a 2-tupla $(c_j,r_i)$ ao invés de $(r_i,c_j)$. Uma vez especificado, o indicador {\tt(tr)} tem alcance em todos registros subsequentes até que se encontre outra fatia ou o fim do bloco de dados. % The {\it transposed matrix data record} has the following syntactic % form: % $$\begin{array}{cccccc} % \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ % r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ % r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ % \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ % r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ % \end{array}$$ % (In this case the delimiter {\tt:} following the keyword {\tt(tr)} is % optional and may be omitted.) % % This data record is completely analogous to the matrix data record (see % above) with only exception that in this case each element $a_{ij}$ of % the matrix corresponds to 2-tuple $(c_j,r_i)$ rather than $(r_i,c_j)$. % % Being once specified the {\tt(tr)} indicator affects all subsequent % data records until either a slice or the end of data block is % encountered. \section{Bloco de dados de parâmetro} \noindent \framebox[468pt][l]{ \parbox[c][88pt]{468pt}{ \hspace{6pt} {\tt param} {\it nome} {\tt,} {\it registro} {\tt,} \dots {\tt,} {\it registro} {\tt;} \medskip \hspace{6pt} {\tt param} {\it nome} {\tt default} {\it valor} {\tt,} {\it registro} {\tt,} \dots {\tt,} {\it registro} {\tt;} \medskip \hspace{6pt} {\tt param} {\tt:} {\it dados-tabulação} {\tt;} \medskip \hspace{6pt} {\tt param} {\tt default} {\it valor} {\tt:} {\it dados-tabulação} {\tt;} }} \medskip \noindent {\it nome} é um nome simbólico do parâmetro; \noindent {\it valor} é um valor opcional padrão do parâmetro; \noindent {\it registro}, \dots, {\it registro} são registros; \noindent {\it dados-tabulação} especifica os dados do parâmetro em formato tabulação. \noindent As vírgulas que precedem os registros podem ser omitidas. \para{Registros} \vspace*{-8pt} \begin{description} \item[{\tt :=}]\hspace*{0pt}\\ é um elemento de atribuição de registro não-significativo que pode ser usado livremente para melhorar a legibilidade; \item[{\tt[} {\it fatia} {\tt]}]\hspace*{0pt}\\ especifica uma fatia; \item[{\it dados-planos}]\hspace*{0pt}\\ especifica os dados do parâmetro em formato simples; \item[{\tt:} {\it dados-tabulares}]\hspace*{0pt}\\ especifica dados do parâmetro em formato tabular; \item[{\tt(tr)} {\tt:} {\it dados-tabulares}]\hspace*{0pt}\\ especifica dados do parâmetro no formato tabular transposto. (Neste caso, os dois pontos que seguem a palavra-chave {\tt(tr)} podem ser omitidos). \end{description} \vspace*{-8pt} \para{Exemplos} \begin{verbatim} param T := 4; param mes := 1 Jan 2 Fev 3 Mar 4 Abr 5 Mai; param mes := [1] 'Jan', [2] 'Fev', [3] 'Mar', [4] 'Abr', [5] 'Mai'; param estoque_inicial := ferro 7.32 niquel 35.8; param estoque_inicial [*] ferro 7.32, niquel 35.8; param custo [ferro] .025 [niquel] .03; param valor := ferro -.1, niquel .02; param : estoque_inicial custo valor := ferro 7.32 .025 -.1 niquel 35.8 .03 .02 ; param : insumo : estoque_inicial custo valor := ferro 7.32 .025 -.1 niquel 35.8 .03 .02 ; param demanda default 0 (tr) : FRA DET LAN WIN STL FRE LAF := chapa 300 . 100 75 . 225 250 bobina 500 750 400 250 . 850 500 placa 100 . . 50 200 . 250 ; param custo_transporte := [*,*,chapa]: FRA DET LAN WIN STL FRE LAF := GARY 30 10 8 10 11 71 6 CLEV 22 7 10 7 21 82 13 PITT 19 11 12 10 25 83 15 [*,*,bobina]: FRA DET LAN WIN STL FRE LAF := GARY 39 14 11 14 16 82 8 CLEV 27 9 12 9 26 95 17 PITT 24 14 17 13 28 99 20 [*,*,placa]: FRA DET LAN WIN STL FRE LAF := GARY 41 15 12 16 17 86 8 CLEV 29 9 13 9 28 99 18 PITT 26 14 17 13 31 104 20 ; \end{verbatim} O {\it bloco de dados do parâmetro} é usado para especificar dados completos para um parâmetro (ou parâmetros, se os dados são especificados no formato tabulação). Os blocos de dados podem ser especificados apenas para parâmetros não-calculáveis, i.e., para parâmetros que não possuem o atributo de atribuição ({\tt:=}) nas sentenças parameter correspondentes. Os dados definidos no bloco de dados do parâmetro são programados como uma sequência de registros descritos em seguida. Adicionalmente, o bloco de dados pode vir com o atributo opcional {\tt default}, que especifica um valor numérico ou simbólico padrão do parâmetro (ou parâmetros). Este valor padrão é atribuído ao parâmetro ou a seus membros quando não se definem valores apropriados no bloco de dados do parâmetro. O atributo {\tt default} não pode ser usado se ele já tiver sido especificado na sentença parameter correspondente. % \noindent % \framebox[468pt][l]{ % \parbox[c][88pt]{468pt}{ % \hspace{6pt} {\tt param} {\it name} {\tt,} {\it record} {\tt,} \dots % {\tt,} {\it record} {\tt;} % % \medskip % % \hspace{6pt} {\tt param} {\it name} {\tt default} {\it value} {\tt,} % {\it record} {\tt,} \dots {\tt,} {\it record} {\tt;} % % \medskip % % \hspace{6pt} {\tt param} {\tt:} {\it tabbing-data} {\tt;} % % \medskip % % \hspace{6pt} {\tt param} {\tt default} {\it value} {\tt:} % {\it tabbing-data} {\tt;} % }} % % \medskip % % \noindent % {\it name} is a symbolic name of the parameter; % % \noindent % {\it value} is an optional default value of the parameter; % % \noindent % {\it record}, \dots, {\it record} are data records; % % \noindent % {\it tabbing-data} specifies parameter data in the tabbing format. % % \noindent % Commae preceding data records may be omitted. % % \para{Data records} % % \vspace*{-8pt} % % \begin{description} % \item[{\tt :=}]\hspace*{0pt}\\ % is a non-significant data record, which may be used freely to improve % readability; % \item[{\tt[} {\it slice} {\tt]}]\hspace*{0pt}\\ % specifies a slice; % \item[{\it plain-data}]\hspace*{0pt}\\ % specifies parameter data in the plain format; % \item[{\tt:} {\it tabular-data}]\hspace*{0pt}\\ % specifies parameter data in the tabular format; % \item[{\tt(tr)} {\tt:} {\it tabular-data}]\hspace*{0pt}\\ % specifies set data in the transposed tabular format. (In this case the % colon following the keyword {\tt(tr)} may be omitted.) % \end{description} % % \vspace*{-8pt} % % \para{Examples} % % \begin{verbatim} % param T := 4; % param month := 1 Jan 2 Feb 3 Mar 4 Apr 5 May; % param month := [1] 'Jan', [2] 'Feb', [3] 'Mar', [4] 'Apr', [5] 'May'; % param init_stock := iron 7.32 nickel 35.8; % param init_stock [*] iron 7.32, nickel 35.8; % param cost [iron] .025 [nickel] .03; % param value := iron -.1, nickel .02; % param : init_stock cost value := % iron 7.32 .025 -.1 % nickel 35.8 .03 .02 ; % param : raw : init stock cost value := % iron 7.32 .025 -.1 % nickel 35.8 .03 .02 ; % param demand default 0 (tr) % : FRA DET LAN WIN STL FRE LAF := % bands 300 . 100 75 . 225 250 % coils 500 750 400 250 . 850 500 % plate 100 . . 50 200 . 250 ; % param trans_cost := % [*,*,bands]: FRA DET LAN WIN STL FRE LAF := % GARY 30 10 8 10 11 71 6 % CLEV 22 7 10 7 21 82 13 % PITT 19 11 12 10 25 83 15 % [*,*,coils]: FRA DET LAN WIN STL FRE LAF := % GARY 39 14 11 14 16 82 8 % CLEV 27 9 12 9 26 95 17 % PITT 24 14 17 13 28 99 20 % [*,*,plate]: FRA DET LAN WIN STL FRE LAF := % GARY 41 15 12 16 17 86 8 % CLEV 29 9 13 9 28 99 18 % PITT 26 14 17 13 31 104 20 ; % \end{verbatim} % % The {\it parameter data block} is used to specify complete data for a % parameter (or parameters, if data are specified in the tabbing format). % % Data blocks can be specified only for non-computable parameters, i.e. % for parameters, which have no assign attribute ({\tt:=}) in the % corresponding parameter statements. % % Data defined in the parameter data block are coded as a sequence of % data records described below. Additionally the data block can be % provided with the optional {\tt default} attribute, which specifies a % default numeric or symbolic value of the parameter (parameters). This % default value is assigned to the parameter or its members when % no appropriate value is defined in the parameter data block. The % {\tt default} attribute cannot be used, if it is already specified in % the corresponding parameter statement. \subsection{Registro de atribuição} O {\it registro de atribuição} ({\tt:=}) é um elemento não-significativo. Ele pode ser usado para melhorar a legibilidade dos blocos de dados; % The {\it assign data record} ({\tt:=}) is a non-signficant element. % It may be used for improving readability of data blocks. \subsection{Registro em fatia} O {\it registro em fatia} é um registro de controle que especifica uma {\it fatia} da matriz do parâmetro. Ele tem a seguinte forma sintática: $$\mbox{{\tt[} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt]}}$$ onde $s_1$, $s_2$, \dots, $s_n$ são componentes da fatia. Cada componente da fatia pode ser um número, símbolo ou asterisco ({\tt*}). O número de componentes na fatia deve ser o mesmo da dimensão $n$-tuplas do parâmetro. Por exemplo, se o parâmetro é uma matriz 4-dimensional, a fatia deve ter quatro componentes. O número de \linebreak asteriscos na fatia denomina a {\it dimensão da fatia}. O efeito de usar fatias é o seguinte: se uma fatia $m$-dimensional (i.e., uma fatia contendo $m$ asteriscos) é especificada no bloco de dados, todos registros subsequentes devem especificar os subíndices do membros do parâmetro, como se o parâmetro fosse $m$-dimensional, não $n$-dimensional. Sempre que $m$ subíndices são encontrados, cada asterisco da fatia é substituído pelos \linebreak componentes correspondentes que dão $n$ subíndices, que definem o membro corrente do parâmetro. Por exemplo, se a fatia $(a,*,1,2,*)$ está vigente e os subíndices 3 e $b$ são encontradas no \linebreak registro subsequente, a lista completa de subíndices usada para escolher o membro do parâmetro é $(a,3,1,2,b)$. É permitido especificar uma fatia que não tenha asteriscos. Tal fatia, em si própria, define uma lista completa de subíndice, em cujo caso o próximo registro deve definir apenas um único valor do membro correspondentes do parâmetro. Uma vez especificada uma fatia, a mesma está vigente até que apareça uma nova fatia ou até que se encontre o fim do bloco de dados. Note que se uma fatia não é especificada no bloco de dados, assume-se uma cujos componentes são asteriscos em todas as posições. \subsection{Registro plano} O {\it registro plano} define uma lista de subíndice e um valor individual no formato plano. Este registro possui a seguinte forma sintática: $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$ {\tt,} $v$}$$ onde $t_1$, $t_2$, \dots, $t_n$ são subíndices e $v$ é um valor. Cada subíndice, assim como o valor, pode ser um número ou um símbolo. As vírgulas que seguem os subíndices são opcionais e podem ser omitidas. No caso de um parâmetro ou fatia 0-dimensional, o registro plano não possui subíndice e consiste de um valor individual apenas. % The {\it plain data record} defines a subscript list and a single value % in the plain format. This record has the following syntactic form: % $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$ {\tt,} $v$}$$ % where $t_1$, $t_2$, \dots, $t_n$ are subscripts, and $v$ is a value. % Each subscript as well as the value can be a number or symbol. Commae % following subscripts are optional and may be omitted. % % In case of 0-dimensional parameter or slice the plain data record has % no subscripts and consists of a single value only. \subsection{Registro tabular} O {\it registro tabular} define diversos valores onde cada valor é provido de dois subíndices. Este registro possui a seguinte forma sintática: $$\begin{array}{cccccc} \mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ \end{array}$$ onde $r_1$, $r_2$, \dots, $r_m$ são números e/ou símbolos que correspondem a linhas da tabela; enquanto que $c_1$, $c_2$, \dots, $c_n$ são são números e/ou símbolos que correspondem a colunas da tabela, $a_{11}$, $a_{12}$, \dots, $a_{mn}$ são elementos da tabela. Cada elemento pode ser um número, símbolo ou o ponto decimal ({\tt.}) individual. (neste registro, o delimitador {\tt:} que precede a lista de colunas e o delimitador {\tt:=} que segue após a lista de colunas, não podem ser omitidos). Cada elemento $a_{ij}$ do bloco de dados tabulares ($1\leq i\leq m$, $1\leq j\leq n$) define dois subíndices, onde o primeiro subíndice é $r_i$ e o segundo é $c_j$. Estes subíndices são usados juntamente com a fatia vigente para formar a lista completa de subíndices que identifica um membro particular da matriz de parâmetros. Se $a_{ij}$ é um número ou um símbolo, este valor é atribuído ao membro do parâmetro. No entanto, se $a_{ij}$ é um ponto decimal individual, o membro é atribuído ao valor padrão especificado ou no bloco de dados do parâmetro ou na sentença parameter, ou ainda, se nenhum valor padrão é especificado, o membro permanece indefinido. Uma vez que o registro tabular fornece dois subíndices para cada valor, tanto o parâmetro quanto a fatia vigente em uso devem ser 2-dimensional. % The {\it tabular data record} defines several values, where each value % is provided with two subscripts. This record has the following % syntactic form: % $$\begin{array}{cccccc} % \mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ % r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ % r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ % \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ % r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ % \end{array}$$ % where $r_1$, $r_2$, \dots, $r_m$ are numbers and/or symbols % corresponding to rows of the table; $c_1$, $c_2$, \dots, $c_n$ are % numbers and/or symbols corresponding to columns of the table, $a_{11}$, % $a_{12}$, \dots, $a_{mn}$ are table elements. Each element can be a % number or symbol or the single decimal point ({\tt.}). (In this data % record the delimiter {\tt:} preceding the column list and the delimiter % {\tt:=} following the column list cannot be omitted.) % % Each element $a_{ij}$ of the tabular data block ($1\leq i\leq m$, % $1\leq j\leq n$) defines two subscripts, where the first subscript is % $r_i$, and the second one is $c_j$. These subscripts are used in % conjunction with the current slice to form the complete subscript list % that identifies a particular member of the parameter array. If $a_{ij}$ % is a number or symbol, this value is assigned to the parameter member. % However, if $a_{ij}$ is the single decimal point, the member is % assigned a default value specified either in the parameter data block % or in the parameter statement, or, if no default value is specified, % the member remains undefined. % % Since the tabular data record provides two subscripts for each value, % either the parameter or the slice currently used should be % 2-dimensional. \subsection{Registro tabular transposto} O {\it registro tabular transposto} possui a seguinte forma sintática: $$\begin{array}{cccccc} \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ \end{array}$$ (Neste caso, o delimitador {\tt:} que segue a palavra-chave {\tt(tr)} é opcional e pode ser omitida.) Este registro é completamente análogo ao registro tabular (ver anteriormente) com a única exceção que o primeiro subíndice definido pelo elemento $a_{ij}$ é $c_j$ enquanto que o segundo é $r_i$. Uma vez especificado, o indicador {\tt(tr)} afeta todos registros subsequentes até que se encontre outra fatia ou o fim do bloco de dados. % The {\it transposed tabular data record} has the following syntactic % form: % $$\begin{array}{cccccc} % \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\ % r_1&a_{11}&a_{12}&\dots&a_{1n}&\\ % r_2&a_{21}&a_{22}&\dots&a_{2n}&\\ % \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\ % r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\ % \end{array}$$ % (In this case the delimiter {\tt:} following the keyword {\tt(tr)} is % optional and may be omitted.) % % This data record is completely analogous to the tabular data record % (see above) with only exception that the first subscript defined by % element $a_{ij}$ is $c_j$ while the second one is $r_i$. % % Being once specified the {\tt(tr)} indicator affects all subsequent % data records until either a slice or the end of data block is % encountered. % \newpage \subsection{Formato de dados em tabulação} O bloco de dados do parâmetro no {\it formato tabulação} possui a seguinte forma sintática: $$ \begin{array}{*{8}{l}} \multicolumn{4}{l} {{\tt param}\ {\tt default}\ valor\ {\tt :}\ s\ {\tt :}}& p_1\ \ \verb|,|&p_2\ \ \verb|,|&\dots\ \verb|,|&p_r\ \ \verb|:=|\\ r_{11}\ \verb|,|& r_{12}\ \verb|,|& \dots\ \verb|,|& r_{1n}\ \verb|,|& a_{11}\ \verb|,|& a_{12}\ \verb|,|& \dots\ \verb|,|& a_{1r}\ \verb|,|\\ r_{21}\ \verb|,|& r_{22}\ \verb|,|& \dots\ \verb|,|& r_{2n}\ \verb|,|& a_{21}\ \verb|,|& a_{22}\ \verb|,|& \dots\ \verb|,|& a_{2r}\ \verb|,|\\ \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\ r_{m1}\ \verb|,|& r_{m2}\ \verb|,|& \dots\ \verb|,|& r_{mn}\ \verb|,|& a_{m1}\ \verb|,|& a_{m2}\ \verb|,|& \dots\ \verb|,|& a_{mr}\ \verb|;|\\ \end{array} $$ 1. A palavra-chave {\tt default} pode ser omitida juntamente com o valor que a segue. 2. O nome simbólico $s$ pode ser omitido juntamente com os dois pontos que o segue. 3. Todas as vírgulas são opcionais e podem ser omitidas. O bloco de dados no formato tabulação mostrado acima é exatamente equivalente aos seguintes blocos de dados: \verb|set| $s$\ \verb|:=|\ $ \verb|(|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|) | \verb|(|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|) | \dots \verb| (|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|);|$ \verb|param| $p_1$\ \verb|default|\ $valor$\ \verb|:=| $\verb| | \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{11} \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{21} \verb| |\dots \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m1} \verb|;| $ \verb|param| $p_2$\ \verb|default|\ $valor$\ \verb|:=| $\verb| | \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{12} \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{22} \verb| |\dots \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m2} \verb|;| $ \verb| |.\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ . \verb|param| $p_r$\ \verb|default|\ $valor$\ \verb|:=| $\verb| | \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{1r} \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{2r} \verb| |\dots \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{mr} \verb|;| $ % The parameter data block in the {\it tabbing format} has the following % syntactic form: % $$ % \begin{array}{*{8}{l}} % \multicolumn{4}{l} % {{\tt param}\ {\tt default}\ value\ {\tt :}\ s\ {\tt :}}& % p_1\ \ \verb|,|&p_2\ \ \verb|,|&\dots\ \verb|,|&p_r\ \ \verb|:=|\\ % r_{11}\ \verb|,|& r_{12}\ \verb|,|& \dots\ \verb|,|& r_{1n}\ \verb|,|& % a_{11}\ \verb|,|& a_{12}\ \verb|,|& \dots\ \verb|,|& a_{1r}\ \verb|,|\\ % r_{21}\ \verb|,|& r_{22}\ \verb|,|& \dots\ \verb|,|& r_{2n}\ \verb|,|& % a_{21}\ \verb|,|& a_{22}\ \verb|,|& \dots\ \verb|,|& a_{2r}\ \verb|,|\\ % \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\ % r_{m1}\ \verb|,|& r_{m2}\ \verb|,|& \dots\ \verb|,|& r_{mn}\ \verb|,|& % a_{m1}\ \verb|,|& a_{m2}\ \verb|,|& \dots\ \verb|,|& a_{mr}\ \verb|;|\\ % \end{array} % $$ % % 1. The keyword {\tt default} may be omitted along with a value % following it. % % 2. Symbolic name $s$ may be omitted along with the colon following it. % % 3. All commae are optional and may be omitted. % % The data block in the tabbing format shown above is exactly equivalent % to the following data blocks: % % \verb|set| $s$\ \verb|:=|\ $ % \verb|(|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|) | % \verb|(|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|) | % \dots % \verb| (|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|);|$ % % \verb|param| $p_1$\ \verb|default|\ $value$\ \verb|:=| % % $\verb| | % \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{11} % \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{21} % \verb| |\dots % \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m1} % \verb|;| % $ % % \verb|param| $p_2$\ \verb|default|\ $value$\ \verb|:=| % % $\verb| | % \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{12} % \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{22} % \verb| |\dots % \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m2} % \verb|;| % $ % % \verb| |.\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ . % % \verb|param| $p_r$\ \verb|default|\ $value$\ \verb|:=| % % $\verb| | % \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{1r} % \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{2r} % \verb| |\dots % \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{mr} % \verb|;| % $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \appendix \chapter{Usando sufixos} \vspace*{-12pt} Sufixos podem ser usados para recuperar valores adicionais associados com as variáveis, restrições e objetivos do modelo. Um {\it sufixo} consiste de um ponto ({\tt.}) seguido por uma palavra-chave não-reservada. Por exemplo, se {\tt x} é uma variável bi-dimensional, {\tt x[i,j].lb} é um valor numérico igual ao limite inferior da variável elementar {\tt x[i,j]}, que (cujo valor) pode ser usado em expressões como um parâmetro numérico. Para as variáveis do modelo, os sufixos possuem o seguinte significado: \begin{tabular}{@{}ll@{}} {\tt.lb}&limite inferior (lower bound)\\ {\tt.ub}&limite superior (upper bound)\\ {\tt.status}&status na solução:\\ &0 --- indefinida\\ &1 --- básica\\ &2 --- não-básica no limite inferior\\ &3 --- não-básica no limite superior\\ &4 --- variável não-básica livre (ilimitada)\\ &5 --- variável não-básica fixa\\ {\tt.val}&valor primal na solução\\ {\tt.dual}&valor dual (custo reduzido) na solução\\ \end{tabular} Para as restrições e objetivos do modelo, os sufixos têm os seguintes significados: \begin{tabular}{@{}ll@{}} {\tt.lb}&limite inferior (lower bound) da forma linear\\ {\tt.ub}&limite superior (upper bound) da forma linear\\ {\tt.status}&status na solução:\\ &0 --- indefinida\\ &1 --- não-limitante\\ &2 --- limitante no limite inferior\\ &3 --- limitante no limite superior\\ &4 --- linha limitante livre (ilimitada)\\ &5 --- restrição de igualdade limitante\\ {\tt.val}&valor primal da forma linear na solução\\ {\tt.dual}&valor dual (custo reduzido) da forma linear na solução\\ \end{tabular} Note que os sufixos {\tt.status}, {\tt.val} e {\tt.dual} podem ser usados apenas abaixo da sentença solve. % Suffixes can be used to retrieve additional values associated with % model variables, constraints, and objectives. % % A {\it suffix} consists of a period ({\tt.}) followed by a non-reserved % keyword. For example, if {\tt x} is a two-dimensional variable, % {\tt x[i,j].lb} is a numeric value equal to the lower bound of % elemental variable {\tt x[i,j]}, which (value) can be used everywhere % in expressions like a numeric parameter. % % For model variables suffixes have the following meaning: % % \begin{tabular}{@{}ll@{}} % {\tt.lb}&lower bound\\ % {\tt.ub}&upper bound\\ % {\tt.status}&status in the solution:\\ % &0 --- undefined\\ % &1 --- basic\\ % &2 --- non-basic on lower bound\\ % &3 --- non-basic on upper bound\\ % &4 --- non-basic free (unbounded) variable\\ % &5 --- non-basic fixed variable\\ % {\tt.val}&primal value in the solution\\ % {\tt.dual}&dual value (reduced cost) in the solution\\ % \end{tabular} % % For model constraints and objectives suffixes have the following % meaning: % % \begin{tabular}{@{}ll@{}} % {\tt.lb}&lower bound of the linear form\\ % {\tt.ub}&upper bound of the linear form\\ % {\tt.status}&status in the solution:\\ % &0 --- undefined\\ % &1 --- non-active\\ % &2 --- active on lower bound\\ % &3 --- active on upper bound\\ % &4 --- active free (unbounded) row\\ % &5 --- active equality constraint\\ % {\tt.val}&primal value of the linear form in the solution\\ % {\tt.dual}&dual value (reduced cost) of the linear form in the % solution\\ % \end{tabular} % % Note that suffixes {\tt.status}, {\tt.val}, and {\tt.dual} can be used % only below the solve statement. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Funções de data e hora} \noindent\hfil \begin{tabular}{c} por Andrew Makhorin \verb||\\ e Heinrich Schuchardt \verb||\\ \end{tabular} \section{Obtendo o tempo de calendário corrente} \label{gmtime} Para obter o tempo de calendário corrente em MathProg existe a função {\tt gmtime}. Ela não possui argumentos e retorna o número de segundos transcorridos desde 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 1970, pelo Tempo Universal Coordenado (UTC). Por exemplo: \begin{verbatim} param utc := gmtime(); \end{verbatim} MathProg não possui uma função para converter o tempo UTC retornado pela função {\tt gmtime} para os tempos de calendário {\it local}. Assim, para determinar o tempo de calendário local corrente, é preciso que adicione ao tempo UTC retornado a diferença de horas, com respeito a UTC, expressa em segundos. Por exemplo, a hora em Berlim durante o inverno é uma hora à frente do UTC, que corresponde a uma diferença horária de +1~hora~= +3600~segundos, assim, o tempo de calendário corrente no inverno em Berlim pode ser determinado como segue: \begin{verbatim} param now := gmtime() + 3600; \end{verbatim} \noindent De forma análoga, o horário de verão em Chicago (Zona Horária Central-CDT) é cinco horas atrás da UTC, de modo que o horário corrente do calendário local pode ser determinado como segue: \begin{verbatim} param now := gmtime() - 5 * 3600; \end{verbatim} Note que o valor retornado por {\tt gmtime} é volátil, i.e., ao ser chamada diversas vezes, esta função pode retornar diferentes valores. % \noindent\hfil % \begin{tabular}{c} % by Andrew Makhorin \verb||\\ % and Heinrich Schuchardt \verb||\\ % \end{tabular} % % \section{Obtaining current calendar time} % \label{gmtime} % % To obtain the current calendar time in MathProg there exists the % function {\tt gmtime}. It has no arguments and returns the number of % seconds elapsed since 00:00:00 on January 1, 1970, Coordinated % Universal Time (UTC). For example: % % \begin{verbatim} % param utc := gmtime(); % \end{verbatim} % % MathProg has no function to convert UTC time returned by the function % {\tt gmtime} to {\it local} calendar times. Thus, if you need to % determine the current local calendar time, you have to add to the UTC % time returned the time offset from UTC expressed in seconds. For % example, the time in Berlin during the winter is one hour ahead of UTC % that corresponds to the time offset +1~hour~= +3600~secs, so the % current winter calendar time in Berlin may be determined as follows: % % \begin{verbatim} % param now := gmtime() + 3600; % \end{verbatim} % % \noindent Similarly, the summer time in Chicago (Central Daylight Time) % is five hours behind UTC, so the corresponding current local calendar % time may be determined as follows: % % \begin{verbatim} % param now := gmtime() - 5 * 3600; % \end{verbatim} % % Note that the value returned by {\tt gmtime} is volatile, i.e. being % called several times this function may return different values. \section{Convertendo cadeia de caracteres ao tempo de calendário} \label{str2time} A função {\tt str2time(}{\it s}{\tt,} {\it f}{\tt)} converte uma cadeia de caractere (impressão da data e hora) \linebreak especificada pelo seu primeiro argumento {\it s}, que deve ser uma expressão simbólica, para o tempo de calendário apropriado para cálculos aritméticos. A conversão é controlada pela cadeia de formato especificado {\it f} (o segundo argumento), que também deve ser uma expressão simbólica. % The function {\tt str2time(}{\it s}{\tt,} {\it f}{\tt)} converts a % character string (timestamp) specified by its first argument {\it s}, % which should be a symbolic expression, to the calendar time suitable % for arithmetic calculations. The conversion is controlled by the % specified format string {\it f} (the second argument), which also % should be a symbolic expression. % \newpage A conversão resultante retornada por {\tt str2time} possui o mesmo significado dos valores retornados pela função {\tt gmtime} (ver Subseção \ref{gmtime}, página \pageref{gmtime}). Note que {\tt str2time} {\tt não corrige} o tempo de calendário retornado para zona horária local, i.e., ao se aplicar a 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 1970, ela sempre retorna 0. % The result of conversion returned by {\tt str2time} has the same % meaning as values returned by the function {\tt gmtime} (see Subsection % \ref{gmtime}, page \pageref{gmtime}). Note that {\tt str2time} does % {\tt not} correct the calendar time returned for the local timezone, % i.e. being applied to 00:00:00 on January 1, 1970 it always returns 0. Por exemplo, as sentenças de modelo: \begin{verbatim} param s, symbolic, := "07/14/98 13:47"; param t := str2time(s, "%m/%d/%y %H:%M"); display t; \end{verbatim} \noindent produz a seguinte saída: \begin{verbatim} t = 900424020 \end{verbatim} \noindent onde o tempo de calendário impresso corresponde a 13:47:00 em 14 de Julho de 1998. A cadeia de formato passada à função {\tt str2time} consiste de especificadores de conversão e caracteres ordinários. Cada especificador de conversão inicia com um caractere de porcentagem ({\tt\%}) seguido de uma letra. Os seguintes especificadores de conversão podem ser usados na cadeia de formato: \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%b}&O nome do mês abreviado (insensível a maiúsculas). Pelo menos as três primeiras letras do mês devem aparecer na cadeia de entrada.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%d}&O dia do mês como número decimal (de 1 até 31). Se permite o zero como primeiro dígito, embora não seja necessário.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%h}&O mesmo que {\tt\%b}.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%H}&A hora como um número decimal, usando um relógio de 24-horas (de 0 a 23). Se permite o zero como primeiro dígito, embora não seja necessário.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%m}&O mês como um número decimal (de 1 a 12). Se permite o zero como primeiro dígito, embora não seja necessário.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%M}&O minuto como um número decimal (de 0 a 59). Se permite o zero como primeiro dígito, embora não seja necessário.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%S}&O segundo como um número decimal (de 0 to 60). Se permite o zero como primeiro dígito, embora não seja necessário.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%y}&O ano sem o século, como um número decimal (de 0 to 99). Se permite o zero como primeiro dígito, embora não seja necessário. Valores de entrada de 0 a 68 são considerados dos anos 2000 a 2068 enquanto que os valores 69 até 99 como dos anos 1969 to 1999.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%z}&A diferença horária do GMT no formato ISO 8601.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%\%}&Um caractere {\tt\%} literal.\\ \end{tabular} Todos os outros caracteres (ordinários) na cadeia de formato devem ter um caractere \linebreak correspondente com a cadeia de entrada a ser convertida. Exceções são espaços na cadeia de entrada, a qual pode coincidir com zero ou mais caracteres de espaço na cadeia de formato. % For example, the model statements: % % \begin{verbatim} % param s, symbolic, := "07/14/98 13:47"; % param t := str2time(s, "%m/%d/%y %H:%M"); % display t; % \end{verbatim} % % \noindent produce the following printout: % % \begin{verbatim} % t = 900424020 % \end{verbatim} % % \noindent where the calendar time printed corresponds to 13:47:00 on % July 14, 1998. % % The format string passed to the function {\tt str2time} consists of % conversion specifiers and ordinary characters. Each conversion % specifier begins with a percent ({\tt\%}) character followed by a % letter. % % The following conversion specifiers may be used in the format string: % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%b}&The abbreviated month name (case insensitive). At least three % first letters of the month name should appear in the input string.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%d}&The day of the month as a decimal number (range 1 to 31). % Leading zero is permitted, but not required.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%h}&The same as {\tt\%b}.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%H}&The hour as a decimal number, using a 24-hour clock (range 0 % to 23). Leading zero is permitted, but not required.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%m}&The month as a decimal number (range 1 to 12). Leading zero is % permitted, but not required.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%M}&The minute as a decimal number (range 0 to 59). Leading zero % is permitted, but not required.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%S}&The second as a decimal number (range 0 to 60). Leading zero % is permitted, but not required.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%y}&The year without a century as a decimal number (range 0 to 99). % Leading zero is permitted, but not required. Input values in the range % 0 to 68 are considered as the years 2000 to 2068 while the values 69 to % 99 as the years 1969 to 1999.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%z}&The offset from GMT in ISO 8601 format.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%\%}&A literal {\tt\%} character.\\ % \end{tabular} % % All other (ordinary) characters in the format string should have a % matching character in the input string to be converted. Exceptions are % spaces in the input string which can match zero or more space % characters in the format string. % \newpage Se algum componente de data e/ou hora estão ausentes no formato e, portanto, na cadeia de entrada, a função {\tt str2time} usa seus valores padrão correspondendo a 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 1970, ou seja, o valor padrão para o ano é 1970, o valor padrão para o mês é Janeiro, etc. A função {\tt str2time} é aplicável a todos horários calendário desde 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 0001 até 23:59:59 de 31 de Dezembro de 4000 do calendário Gregoriano. % If some date and/or time component(s) are missing in the format and, % therefore, in the input string, the function {\tt str2time} uses their % default values corresponding to 00:00:00 on January 1, 1970, that is, % the default value of the year is 1970, the default value of the month % is January, etc. % % The function {\tt str2time} is applicable to all calendar times in the % range 00:00:00 on January 1, 0001 to 23:59:59 on December 31, 4000 of % the Gregorian calendar. \section{Convertendo tempo de calendário a uma cadeia de caracteres} \label{time2str} A função {\tt time2str(}{\it t}{\tt,} {\it f}{\tt)} converte o tempo de calendário especificado pelo seu primeiro \linebreak argumento {\it t}, que deve ser uma expressão numérica, para uma cadeia de caracteres (valor \linebreak simbólico). A conversão é controlada pela cadeia de formato {\it f} (o segundo argumento), que deve ser uma expressão numérica. O tempo de calendário passado para {\tt time2str} possui o mesmo significado dos valores retornados pela função {\tt gmtime} (ver Subseção \ref{gmtime}, página \pageref{gmtime}). Note que {\tt time2str} {\it não corrige} o tempo de calendário especificado para zona horária local, i.e., o tempo de calendário 0 sempre corresponde a 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 1970. Por exemplo, as sentenças de modelo: \begin{verbatim} param s, symbolic, := time2str(gmtime(), "%FT%TZ"); display s; \end{verbatim} \noindent pode produzir a seguinte impressão: \begin{verbatim} s = '2008-12-04T00:23:45Z' \end{verbatim} \noindent que é a impressão da data e hora no formato ISO. A cadeia de formato passada para a função {\tt time2str} consiste de especificadores de conversão e caracteres ordinários. Cada especificador de conversão começa com um caractere de porcentagem ({\tt\%}) seguido de uma letra. Os seguintes especificadores de conversão podem ser usados na cadeia de formato: \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%a}&O nome do dia da semana abreviado(2 caracteres).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%A}&O nome do dia da semana completo.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%b}&O nome do dia do mês abreviado (3 caracteres).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%B}&O nome do mês completo.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%C}&O século do ano, ou seja, o maior inteiro não maior que o ano dividido por~100.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%d}&O dia do mês como um número decimal (de 01 até 31).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%D}&A data usando o formato \verb|%m/%d/%y|.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%e}&O dia do mês, como em \verb|%d|, mas preenchido com espaço em branco ao invés de zero.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%F}&A data usando o formato \verb|%Y-%m-%d|.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%g}&O ano correspondente ao número de semana ISO, mas sem o século (de 00 até~99). Este possui o mesmo formato e valor que \verb|%y|, exceto que se o número de semana ISO (ver \verb|%V|) pertence ao ano anterior ou seguinte, se usa aquele ano em seu lugar.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%G}&O ano correspondente ao número de semana ISO. Este possui o mesmo formato e valor que \verb|%Y|, exceto que se o número de semana ISO (ver \verb|%V|) pertence ao ano anterior ou seguinte, se usa aquele ano em seu lugar.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%h}&O mesmo que \verb|%b|.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%H}&A hora como um número decimal usando um relógio 24 horas (de 00 até 23).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%I}&A hora como um número decimal usando um relógio 12 horas (de 01 até 12).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%j}&O dia do ano como um número decimal (de 001 até 366).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%k}&A hora como um número decimal usando um relógio 24 horas, como \verb|%H|, mas preenchido com espaço em branco ao invés de zero.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%l}&A hora como um número decimal usando um relógio 12 horas, como \verb|%I|, mas preenchido com espaço em branco ao invés de zero. \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%m}&O mês como um número decimal (de 01 até 12).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%M}&O minuto como um número decimal (de 00 até 59).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%p}&Tanto {\tt AM} como {\tt PM}, de acordo com o valor da hora fornecido. Meia-noite é tratada como {\tt AM} e meio-dia, como {\tt PM}.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%P}&Tanto {\tt am} como {\tt pm}, de acordo com o valor da hora fornecido. Meia-noite é tratada como {\tt am} e meio-dia, como {\tt pm}.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%R}&A hora e minuto em números decimais usando o formato \verb|%H:%M|.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%S}&O segundo como um número decimal (de 00 até 59).\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%T}&A hora do dia em números decimais usando o formato \verb|%H:%M:%S|.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%u}&O dia da semana como número decimal (de 1 até 7) em que Segunda é 1.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%U}&O número da semana do ano corrente como um número decimal (de 00 até 53) iniciando com o primeiro Domingo como o primeiro dia da primeira semana. Os dias que precedem o primeiro Domingo do ano são considerados parte da semana 00. \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%V}&O número da semana ISO como um número decimal (de 01 até 53). Semanas ISO iniciam com Segunda e finalizam com Domingo. A semana 01 de um ano é a primeira semana que possui a maioria de seus dias naquele ano. Isto é equivalente à semana contendo 4 de Janeiro. A semana 01 de um ano pode conter dias do ano anterior. A semana anterior à semana 01 de um ano é a última semana (52 ou 53) do ano anterior, mesmo se ela contém dias do novo ano. Em outras palavras, se 1{\textsuperscript{\b{o}}} de Janeiro é Segunda, Terça, Quarta ou Quinta, ele está na semana 01; Se 1{\textsuperscript{\b{o}}} de Janeiro é Sexta, Sábado ou Domingo, ele está na semana 52 ou 53 do ano anterior.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%w}&O dia da semana como um número decimal (de 0 até 6) em que Domingo é 0.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%W}&O número da semana do ano corrente como um número decimal (de 00 até 53), iniciando com a primeira Segunda como o primeiro dia da primeira semana. Dias que precedem a primeira Segunda do ano são considerados parte da semana 00.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%y}&O ano sem o século como um número decimal (de 00 até 99), ou seja, o ano \verb|mod|~100.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%Y}&O ano como um número decimal, usando o calendário Gregoriano.\\ \end{tabular} \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} {\tt\%\%}&Um caractere \verb|%| literal.\\ \end{tabular} Todos os outros caracteres (ordinários) na cadeia de formato são simplesmente copiados à cadeia resultante. O primeiro argumento (tempo do calendário) passado para a função {\tt time2str} deve estar entre $-62135596800$ até $+64092211199$, o que corresponde ao período de 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 0001 até 23:59:59 de 31 de Dezembro de 4000 do calendário Gregoriano. % The function {\tt time2str(}{\it t}{\tt,} {\it f}{\tt)} converts the % calendar time specified by its first argument {\it t}, which should be % a numeric expression, to a character string (symbolic value). The % conversion is controlled by the specified format string {\it f} (the % second argument), which should be a symbolic expression. % % The calendar time passed to {\tt time2str} has the same meaning as % values returned by the function {\tt gmtime} (see Subsection % \ref{gmtime}, page \pageref{gmtime}). Note that {\tt time2str} does % {\it not} correct the specified calendar time for the local timezone, % i.e. the calendar time 0 always corresponds to 00:00:00 on January 1, % 1970. % % For example, the model statements: % % \begin{verbatim} % param s, symbolic, := time2str(gmtime(), "%FT%TZ"); % display s; % \end{verbatim} % % \noindent may produce the following printout: % % \begin{verbatim} % s = '2008-12-04T00:23:45Z' % \end{verbatim} % % \noindent which is a timestamp in the ISO format. % % The format string passed to the function {\tt time2str} consists of % conversion specifiers and ordinary characters. Each conversion % specifier begins with a percent ({\tt\%}) character followed by a % letter. % % The following conversion specifiers may be used in the format string: % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%a}&The abbreviated (2-character) weekday name.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%A}&The full weekday name.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%b}&The abbreviated (3-character) month name.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%B}&The full month name.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%C}&The century of the year, that is the greatest integer not % greater than the year divided by~100.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%d}&The day of the month as a decimal number (range 01 to 31).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%D}&The date using the format \verb|%m/%d/%y|.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%e}&The day of the month like with \verb|%d|, but padded with % blank rather than zero.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%F}&The date using the format \verb|%Y-%m-%d|.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%g}&The year corresponding to the ISO week number, but without the % century (range 00 to~99). This has the same format and value as % \verb|%y|, except that if the ISO week number (see \verb|%V|) belongs % to the previous or next year, that year is used instead.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%G}&The year corresponding to the ISO week number. This has the % same format and value as \verb|%Y|, except that if the ISO week number % (see \verb|%V|) belongs to the previous or next year, that year is used % instead. % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%h}&The same as \verb|%b|.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%H}&The hour as a decimal number, using a 24-hour clock (range 00 % to 23).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%I}&The hour as a decimal number, using a 12-hour clock (range 01 % to 12).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%j}&The day of the year as a decimal number (range 001 to 366).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%k}&The hour as a decimal number, using a 24-hour clock like % \verb|%H|, but padded with blank rather than zero.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%l}&The hour as a decimal number, using a 12-hour clock like % \verb|%I|, but padded with blank rather than zero. % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%m}&The month as a decimal number (range 01 to 12).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%M}&The minute as a decimal number (range 00 to 59).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%p}&Either {\tt AM} or {\tt PM}, according to the given time value. % Midnight is treated as {\tt AM} and noon as {\tt PM}.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%P}&Either {\tt am} or {\tt pm}, according to the given time value. % Midnight is treated as {\tt am} and noon as {\tt pm}.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%R}&The hour and minute in decimal numbers using the format % \verb|%H:%M|.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%S}&The second as a decimal number (range 00 to 59).\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%T}&The time of day in decimal numbers using the format % \verb|%H:%M:%S|.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%u}&The day of the week as a decimal number (range 1 to 7), Monday % being 1.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%U}&The week number of the current year as a decimal number (range % 00 to 53), starting with the first Sunday as the first day of the first % week. Days preceding the first Sunday in the year are considered to be % in week 00. % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%V}&The ISO week number as a decimal number (range 01 to 53). ISO % weeks start with Monday and end with Sunday. Week 01 of a year is the % first week which has the majority of its days in that year; this is % equivalent to the week containing January 4. Week 01 of a year can % contain days from the previous year. The week before week 01 of a year % is the last week (52 or 53) of the previous year even if it contains % days from the new year. In other word, if 1 January is Monday, Tuesday, % Wednesday or Thursday, it is in week 01; if 1 January is Friday, % Saturday or Sunday, it is in week 52 or 53 of the previous year.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%w}&The day of the week as a decimal number (range 0 to 6), Sunday % being 0.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%W}&The week number of the current year as a decimal number (range % 00 to 53), starting with the first Monday as the first day of the first % week. Days preceding the first Monday in the year are considered to be % in week 00.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%y}&The year without a century as a decimal number (range 00 to % 99), that is the year modulo~100.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%Y}&The year as a decimal number, using the Gregorian calendar.\\ % \end{tabular} % % \begin{tabular}{@{}p{20pt}p{421.5pt}@{}} % {\tt\%\%}&A literal \verb|%| character.\\ % \end{tabular} % % All other (ordinary) characters in the format string are simply copied % to the resultant string. % % The first argument (calendar time) passed to the function {\tt time2str} % should be in the range from $-62135596800$ to $+64092211199$ that % corresponds to the period from 00:00:00 on January 1, 0001 to 23:59:59 % on December 31, 4000 of the Gregorian calendar. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Controladores de tabelas} \label{drivers} \noindent\hfil \begin{tabular}{c} por Andrew Makhorin \verb||\\ e Heinrich Schuchardt \verb||\\ \end{tabular} \bigskip\bigskip O {\it controlador de tabelas} é um módulo do programa que permite transmitir dados entre objetos de um modelo MathProg e tabela de dados. Atualmente, o pacote GLPK possui quatro controladores de tabelas: \vspace*{-8pt} \begin{itemize} \item controlador interno de tabelas CSV; \item controlador interno de tabelas xBASE; \item controlador de tabelas ODBC; \item controlador de tabelas MySQL. \end{itemize} % The {\it table driver} is a program module which provides transmitting % data between MathProg model objects and data tables. % % Currently the GLPK package has four table drivers: % % \vspace*{-8pt} % % \begin{itemize} % \item built-in CSV table driver; % \item built-in xBASE table driver; % \item ODBC table driver; % \item MySQL table driver. % \end{itemize} \vspace*{-8pt} \section{Controlador de tabelas CSV} O controlador de tabelas CSV assume que a tabela de dados está representada na forma de \linebreak arquivo de texto plano, em formato de arquivo CSV (valores serparados por vígula: \linebreak comma-separated values) como descrito abaixo. Para escolher o controlador de tabelas CSV, seu nome na sentença table deve ser especificado como \verb|"CSV"| e o único argumento deve especificar o nome do arquivo de texto plano contendo a tabela. Por exemplo: \begin{verbatim} table dados IN "CSV" "dados.csv": ... ; \end{verbatim} O sufixo do nome do arquivo pode ser arbitrário, no entanto, é recomendado usar o sufixo `\verb|.csv|'. Ao ler tabelas de entrada o controlador de tabelas CSV fornece um campo implícito chamado \verb|RECNO|, que contém o número do registro corrente. Este campo pode ser especificado na sentença de entrada table, como se realmente houvesse um campo chamado \verb|RECNO| no arquivo CSV. Por exemplo: \begin{verbatim} table lista IN "CSV" "lista.csv": num <- [RECNO], ... ; \end{verbatim} % The CSV table driver assumes that the data table is represented in the % form of a plain text file in the CSV (comma-separated values) file % format as described below. % % To choose the CSV table driver its name in the table statement should % be specified as \verb|"CSV"|, and the only argument should specify the % name of a plain text file containing the table. For example: % % \begin{verbatim} % table data IN "CSV" "data.csv": ... ; % \end{verbatim} % % The filename suffix may be arbitrary, however, it is recommended to use % the suffix `\verb|.csv|'. % % On reading input tables the CSV table driver provides an implicit field % named \verb|RECNO|, which contains the current record number. This % field can be specified in the input table statement as if there were % the actual field named \verb|RECNO| in the CSV file. For example: % % \begin{verbatim} % table list IN "CSV" "list.csv": num <- [RECNO], ... ; % \end{verbatim} \newpage \subsection*{Formato CSV\footnote{Este material é baseado no documento RFC 4180.}} O formato CSV (\textit{comma-separated values}) é um formato de arquivo de texto plano definido como segue. 1. Cada registro é localizado em uma linha separada, delimitada por uma quebra de linha. Por exemplo: \begin{verbatim} aaa,bbb,ccc\n xxx,yyy,zzz\n \end{verbatim} \noindent onde \verb|\n| significa o caractere de controle \verb|LF| ({\tt 0x0A}). 2. O último registro no arquivo pode ou não ter a quebra de linha. Por exemplo: \begin{verbatim} aaa,bbb,ccc\n xxx,yyy,zzz \end{verbatim} 3. Deve haver uma linha de cabeçalho na primeira linha do arquivo no mesmo formato das linhas de registros normais. Este cabeçalho deve conter nomes correspondendo aos campos no arquivo. O número de nomes de campos na linha de cabeçalho deve ser o mesmo do número de campos dos registros do arquivo. Por exemplo: \begin{verbatim} nome1,nome2,nome3\n aaa,bbb,ccc\n xxx,yyy,zzz\n \end{verbatim} 4. Dentro do cabeçalho e de cada registro, podem haver um ou mais campos separados por vírgulas. Cada linha deve conter o mesmo número de campos por todos arquivo. Espaços são considerados parte de um campo, portanto, não são ignorados. O último campo do registro não deve ser seguido de vírgula. Por exemplo: \begin{verbatim} aaa,bbb,ccc\n \end{verbatim} 5. Campos podem ou não estar cercados em aspas duplas. Por exemplo: \begin{verbatim} "aaa","bbb","ccc"\n zzz,yyy,xxx\n \end{verbatim} 6. Se um campo é cercado de aspas duplas, cada aspa dupla que faça parte do campo deve ser codificado duas vezes. Por exemplo: \begin{verbatim} "aaa","b""bb","ccc"\n \end{verbatim} \para{Exemplo} \begin{verbatim} DE,PARA,DISTANCIA,CUSTO Seattle,New-York,2.5,0.12 Seattle,Chicago,1.7,0.08 Seattle,Topeka,1.8,0.09 San-Diego,New-York,2.5,0.15 San-Diego,Chicago,1.8,0.10 San-Diego,Topeka,1.4,0.07 \end{verbatim} % The CSV (comma-separated values) format is a plain text file format % defined as follows. % % 1. Each record is located on a separate line, delimited by a line % break. For example: % % \begin{verbatim} % aaa,bbb,ccc\n % xxx,yyy,zzz\n % \end{verbatim} % % \noindent % where \verb|\n| means the control character \verb|LF| ({\tt 0x0A}). % % 2. The last record in the file may or may not have an ending line % break. For example: % % \begin{verbatim} % aaa,bbb,ccc\n % xxx,yyy,zzz % \end{verbatim} % % 3. There should be a header line appearing as the first line of the % file in the same format as normal record lines. This header should % contain names corresponding to the fields in the file. The number of % field names in the header line should be the same as the number of % fields in the records of the file. For example: % % \begin{verbatim} % name1,name2,name3\n % aaa,bbb,ccc\n % xxx,yyy,zzz\n % \end{verbatim} % % 4. Within the header and each record there may be one or more fields % separated by commas. Each line should contain the same number of fields % throughout the file. Spaces are considered as part of a field and % therefore not ignored. The last field in the record should not be % followed by a comma. For example: % % \begin{verbatim} % aaa,bbb,ccc\n % \end{verbatim} % % 5. Fields may or may not be enclosed in double quotes. For example: % % \begin{verbatim} % "aaa","bbb","ccc"\n % zzz,yyy,xxx\n % \end{verbatim} % % 6. If a field is enclosed in double quotes, each double quote which is % part of the field should be coded twice. For example: % % \begin{verbatim} % "aaa","b""bb","ccc"\n % \end{verbatim} % % \para{Example} % % \begin{verbatim} % FROM,TO,DISTANCE,COST % Seattle,New-York,2.5,0.12 % Seattle,Chicago,1.7,0.08 % Seattle,Topeka,1.8,0.09 % San-Diego,New-York,2.5,0.15 % San-Diego,Chicago,1.8,0.10 % San-Diego,Topeka,1.4,0.07 % \end{verbatim} \newpage \section{Controlador de tabelas xBASE} O controlador de tabelas xBASE assume que a tabela de dados é armazenada no formato de arquivo .dbf. Para escolher o controlador de tabela xBASE, seu nome na sentença table deve ser especificado como \verb|"xBASE"| e o primeiro argumento deve especificar o nome de um arquivo .dbf contendo a tabela. Para a tabela de saída deve haver um segundo argumento definindo o formato da tabela na forma \verb|"FF...F"|, onde \verb|F| é tanto {\tt C({\it n})}, que especifica um campo de caractere de tamanho $n$, ou {\tt N({\it n}{\rm [},{\it p}{\rm ]})}, que especifica um campo numérico de tamanho $n$ e precisão $p$ (por padrão $p$ é 0). Adiante está um simples exemplo que ilustra a criação e leitura de um arquivo .dbf: \begin{verbatim} table tab1{i in 1..10} OUT "xBASE" "foo.dbf" "N(5)N(10,4)C(1)C(10)": 2*i+1 ~ B, Uniform(-20,+20) ~ A, "?" ~ FOO, "[" & i & "]" ~ C; set S, dimen 4; table tab2 IN "xBASE" "foo.dbf": S <- [B, C, RECNO, A]; display S; end; \end{verbatim} % The xBASE table driver assumes that the data table is stored in the % .dbf file format. % % To choose the xBASE table driver its name in the table statement should % be specified as \verb|"xBASE"|, and the first argument should specify % the name of a .dbf file containing the table. For the output table there % should be the second argument defining the table format in the form % \verb|"FF...F"|, where \verb|F| is either {\tt C({\it n})}, % which specifies a character field of length $n$, or % {\tt N({\it n}{\rm [},{\it p}{\rm ]})}, which specifies a numeric field % of length $n$ and precision $p$ (by default $p$ is 0). % % The following is a simple example which illustrates creating and % reading a .dbf file: % % \begin{verbatim} % table tab1{i in 1..10} OUT "xBASE" "foo.dbf" % "N(5)N(10,4)C(1)C(10)": 2*i+1 ~ B, Uniform(-20,+20) ~ A, % "?" ~ FOO, "[" & i & "]" ~ C; % set S, dimen 4; % table tab2 IN "xBASE" "foo.dbf": S <- [B, C, RECNO, A]; % display S; % end; % \end{verbatim} \section{Controlador de tabelas ODBC} O controlador de tabelas ODBC permite conexões com bancos de dados SQL usando uma \linebreak implementação da interface ODBC baseada na Call Level Interface (CLI).\footnote{A norma software correspondente é definida na ISO/IEC 9075-3:2003.} \para{Debian GNU/Linux.} No Debian GNU/Linux o controlador de tabelas ODBC usa o pacote iODBC, \footnote{Ver {\tt}.} que deve ser instalado antes de montar o pacote GLPK. A instalação pode ser efetuada com o seguinte comando: \begin{verbatim} sudo apt-get install libiodbc2-dev \end{verbatim} Note que, ao configurar o pacote GLPK, para habilitar o uso da biblioteca do iODBC a opção `\verb|--enable-odbc|' deve ser passada para o script de configuração. Para seu uso em todo sistema, as bases de dados individuais devem ser inseridas em \verb|/etc/odbc.ini| e \verb|/etc/odbcinst.ini|. As conexões das bases de dados a serem usadas por um único usuário são especificadas por arquivos do diretório home (\verb|.odbc.ini| e \verb|.odbcinst.ini|). \para{Microsoft Windows.} No Microsoft Windows o controlador de tabelas ODBC usa a biblioteca Microsoft ODBC. Para habilitar esta funcionalidade, o símbolo: \begin{verbatim} #define ODBC_DLNAME "odbc32.dll" \end{verbatim} \noindent deve ser definido no arquivo de configuração do GLPK `\verb|config.h|'. Fontes de dados podem ser criados via Ferramentas Administrativas do Painel de Controle. Para escolher do controlador de tabelas ODBC, seu nome na sentença table deve ser especificado como \verb|'ODBC'| ou \verb|'iODBC'|. % \newpage A lista de argumentos é especificada como segue. O primeiro argumento é a cadeia de conexão passada para a biblioteca ODBC, por exemplo: \verb|'DSN=glpk;UID=user;PWD=password'|, ou \verb|'DRIVER=MySQL;DATABASE=glpkdb;UID=user;PWD=password'|. Diferentes partes da cadeia são separadas por ponto e vírgula. Cada parte consiste de um par {\it nome-do-campo} e {\it valor} separados pelo sinar de igualdade. Os nomes de campo permitidos dependem da biblioteca ODBC. Tipicamente os seguintes nomes-de-campo são permitidos: \verb|DATABASE | base de dados; \verb|DRIVER | controlador ODBC; \verb|DSN | nome de uma fonte de dados; \verb|FILEDSN | nome de um arquivo de fonte de dados; \verb|PWD | senha de usuário; \verb|SERVER | base de dados; \verb|UID | nome de usuário. O segundo argumento e todos os seguintes são considerados como sentenças SQL. As sentenças SQL podem ser estendidas sobre múltiplos argumentos. Se o último caractere de um argumento é um ponto e vírgula, este indica o fim de uma sentença SQL. Os argumentos de uma sentença SQL são concatenados separados por espaço. O eventual ponto e vírgula final será removido. Todas as sentenças SQL, exceto a última, serão executadas diretamente. Para tabela-IN, a última sentença SQL pode ser um comando SELECT que se inicia com \verb|'SELECT '| em letras maiúsculas. Se a cadeia não se inicia com \verb|'SELECT '|, se considera que é um nome de uma tabela e uma sentença SELECT é automaticamente gerada. Para tabela-OUT, a última sentença SQL pode conter um ou múltiplos pontos de interrogação. Se contém um ponto de interrogação, é considerado um gabarito para a rotina de escrita. Caso contrário, a cadeia é considerada um nome de tabela e um gabarito INSERT é automaticamente gerado. A rotina de escrita usa um gabarito com o pontos de interrogação e o substitui o primeiro ponto de interrogação pelo primeiro parâmetro de saída, o segundo ponto de interrogação, pelo segundo parâmetro e assim por diante. Em seguida, o comando SQL é emitido. O que segue é um exemplo da sentença table de saída: \begin{verbatim} table ta { l in LOCAIS } OUT 'ODBC' 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' 'DROP TABLE IF EXISTS resultado;' 'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' 'INSERT INTO resultado 'VALUES ( 4, ?, ? )' : l ~ LOC, quantidade[l] ~ QUAN; \end{verbatim} % \newpage \noindent Alternativamente pode se escrever como segue: \begin{verbatim} table ta { l in LOCAIS } OUT 'ODBC' 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' 'DROP TABLE IF EXISTS resultado;' 'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' 'resultado' : l ~ LOC, quantidade[l] ~ QUAN, 4 ~ ID; \end{verbatim} O uso de gabaritos com `\verb|?|' não só permite INSERT, como também o UPDATE, DELETE, etc. Por exemplo: \begin{verbatim} table ta { l in LOCAIS } OUT 'ODBC' 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' 'UPDATE resultado SET DATA = ' & data & ' WHERE ID = 4;' 'UPDATE resultado SET QUAN = ? WHERE LOC = ? AND ID = 4' : quantidade[l], l; \end{verbatim} % The ODBC table driver allows connecting to SQL databases using an % implementation of the ODBC interface based on the Call Level Interface % (CLI).\footnote{The corresponding software standard is defined in % ISO/IEC 9075-3:2003.} % % \para{Debian GNU/Linux.} % Under Debian GNU/Linux the ODBC table driver uses the iODBC % package,\footnote{See {\tt}.} which should be % installed before building the GLPK package. The installation can be % effected with the following command: % % \begin{verbatim} % sudo apt-get install libiodbc2-dev % \end{verbatim} % % Note that on configuring the GLPK package to enable using the iODBC % library the option `\verb|--enable-odbc|' should be passed to the % configure script. % % The individual databases should be entered for systemwide usage in % \verb|/etc/odbc.ini| and\linebreak \verb|/etc/odbcinst.ini|. Database % connections to be used by a single user are specified by files in the % home directory (\verb|.odbc.ini| and \verb|.odbcinst.ini|). % % \para{Microsoft Windows.} % Under Microsoft Windows the ODBC table driver uses the Microsoft ODBC % library. To enable this feature the symbol: % % \begin{verbatim} % #define ODBC_DLNAME "odbc32.dll" % \end{verbatim} % % \noindent % should be defined in the GLPK configuration file `\verb|config.h|'. % % Data sources can be created via the Administrative Tools from the % Control Panel. % % To choose the ODBC table driver its name in the table statement should % be specified as \verb|'ODBC'| or \verb|'iODBC'|. % % \newpage % % The argument list is specified as follows. % % The first argument is the connection string passed to the ODBC library, % for example: % % \verb|'DSN=glpk;UID=user;PWD=password'|, or % % \verb|'DRIVER=MySQL;DATABASE=glpkdb;UID=user;PWD=password'|. % % Different parts of the string are separated by semicolons. Each part % consists of a pair {\it fieldname} and {\it value} separated by the % equal sign. Allowable fieldnames depend on the ODBC library. Typically % the following fieldnames are allowed: % % \verb|DATABASE | database; % % \verb|DRIVER | ODBC driver; % % \verb|DSN | name of a data source; % % \verb|FILEDSN | name of a file data source; % % \verb|PWD | user password; % % \verb|SERVER | database; % % \verb|UID | user name. % % The second argument and all following are considered to be SQL % statements % % SQL statements may be spread over multiple arguments. If the last % character of an argument is a semicolon this indicates the end of % a SQL statement. % % The arguments of a SQL statement are concatenated separated by space. % The eventual trailing semicolon will be removed. % % All but the last SQL statement will be executed directly. % % For IN-table the last SQL statement can be a SELECT command starting % with the capitalized letters \verb|'SELECT '|. If the string does not % start with \verb|'SELECT '| it is considered to be a table name and a % SELECT statement is automatically generated. % % For OUT-table the last SQL statement can contain one or multiple % question marks. If it contains a question mark it is considered a % template for the write routine. Otherwise the string is considered a % table name and an INSERT template is automatically generated. % % The writing routine uses the template with the question marks and % replaces the first question mark by the first output parameter, the % second question mark by the second output parameter and so forth. Then % the SQL command is issued. % % The following is an example of the output table statement: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'ODBC' % 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'DROP TABLE IF EXISTS result;' % 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' % 'INSERT INTO result 'VALUES ( 4, ?, ? )' : % l ~ LOC, quantity[l] ~ QUAN; % \end{verbatim} % % \newpage % % \noindent % Alternatively it could be written as follows: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'ODBC' % 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'DROP TABLE IF EXISTS result;' % 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' % 'result' : % l ~ LOC, quantity[l] ~ QUAN, 4 ~ ID; % \end{verbatim} % % Using templates with `\verb|?|' supports not only INSERT, but also % UPDATE, DELETE, etc. For example: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'ODBC' % 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'UPDATE result SET DATE = ' & date & ' WHERE ID = 4;' % 'UPDATE result SET QUAN = ? WHERE LOC = ? AND ID = 4' : % quantity[l], l; % \end{verbatim} \section{Controlador de tabelas MySQL} O controlador de tabelas MySQL permite a conexão a base de dados MySQL. \para{Debian GNU/Linux.} No Debian GNU/Linux o controlador de tabelas MySQL usa o pacote MySQL, \footnote{Para fazer o download de arquivos de desenvolvimento, ver {\tt}.} que deve ser instalado antes da criação do pacote GLPK. A instalação pode ser efetuada com o seguinte comando: \begin{verbatim} sudo apt-get install libmysqlclient15-dev \end{verbatim} Note que ao configurar o pacote GLPK para habilitar o uso da biblioteca MySQL a opção `\verb|--enable-mysql|' deve ser passada ao script de configuração. \para{Microsoft Windows.} No Microsoft Windows o controlador de tabelas MySQL também usa a biblioteca MySQL. Para habilitar esta funcionalidade o símbolo: \begin{verbatim} #define MYSQL_DLNAME "libmysql.dll" \end{verbatim} \noindent deve ser definido no arquivo de configuração do GLPK `\verb|config.h|'. Para escolher o controlador de tabelas MySQL, seu nome na sentença table deve ser especificada como \verb|'MySQL'|. A lista de argumentos é especificada como segue. O primeiro argumento especifica como conectar a base de dados no estilo DSN, por exemplo: \verb|'Database=glpk;UID=glpk;PWD=gnu'|. Diferentes partes da cadeia são separadas por ponto e vírgula. Cada parte consiste de um par {\it nome-do-campo} e {\it valor} separado pelo sinal de igualdade. Os seguintes nomes de campo são permitidos: % \newpage \verb|Server | servidor rodando a base de dados (localhost por padrão); \verb|Database | nome da base de dados; \verb|UID | nome de usuário; \verb|PWD | senha de usuário; \verb|Port | porta usada pelo servidor (3306 por padrão). O segundo argumento e todos os seguintes são considerados sentenças SQL. Sentenças SQL podem se estender sobre múltiplos argumentos. Se o último caractere de um argumento é um ponto e vírgula, isto indica o fim de uma sentença SQL. Os argumentos de uma sentença SQL são concatenados e separados por espaço. O eventual ponto e vírgula final será removido. Todas sentenças SQL, menos a última, serão executadas diretamente. Para tabela-IN, a última sentença SQL pode ser um comando SELECT iniciado com letras maiúsculas \verb|'SELECT '|. Se a cadeia não inicia com \verb|'SELECT '| é considerado um nome de tabela e a sentença SELECT é automaticamente gerada. Para tabela-OUT, a última sentença SQL pode conter um ou múltiplos pontos de interrogação. Se contém um ponto de interrogação, é considerado um gabarito para a rotina de escrita. Caso contrário, a cadeia é considerada um nome de tabela e um gabarito INSERT é automaticamente gerado. A rotina de escrita usa um gabarito com o pontos de interrogação e o substitui o primeiro ponto de interrogação pelo primeiro parâmetro de saída, o segundo ponto de interrogação, pelo segundo parâmetro e assim por diante. Em seguida, o comando SQL é emitido. O que segue é um exemplo da sentença table de saída: \begin{verbatim} table ta { l in LOCAIS } OUT 'MySQL' 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' 'DROP TABLE IF EXISTS resultado;' 'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' 'INSERT INTO resultado VALUES ( 4, ?, ? )' : l ~ LOC, quantidade[l] ~ QUAN; \end{verbatim} \noindent Alternativamente poderia ser escrito como segue: \begin{verbatim} table ta { l in LOCAIS } OUT 'MySQL' 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' 'DROP TABLE IF EXISTS resultado;' 'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' 'resultado' : l ~ LOC, quantidade[l] ~ QUAN, 4 ~ ID; \end{verbatim} % \newpage O uso de gabaritos com `\verb|?|' não só permite INSERT, como também o UPDATE, DELETE, etc. Por exemplo: \begin{verbatim} table ta { l in LOCAIS } OUT 'MySQL' 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' 'UPDATE resultado SET DATE = ' & date & ' WHERE ID = 4;' 'UPDATE resultado SET QUAN = ? WHERE LOC = ? AND ID = 4' : quantidade[l], l; \end{verbatim} % The MySQL table driver allows connecting to MySQL databases. % % \para{Debian GNU/Linux.} % Under Debian GNU/Linux the MySQL table driver uses the MySQL % package,\footnote{For download development files see % {\tt}.} which should be % installed before building the GLPK package. The installation can be % effected with the following command: % % \begin{verbatim} % sudo apt-get install libmysqlclient15-dev % \end{verbatim} % % Note that on configuring the GLPK package to enable using the MySQL % library the option `\verb|--enable-mysql|' should be passed to the % configure script. % % \para{Microsoft Windows.} % Under Microsoft Windows the MySQL table driver also uses the MySQL % library. To enable this feature the symbol: % % \begin{verbatim} % #define MYSQL_DLNAME "libmysql.dll" % \end{verbatim} % % \noindent % should be defined in the GLPK configuration file `\verb|config.h|'. % % To choose the MySQL table driver its name in the table statement should % be specified as \verb|'MySQL'|. % % The argument list is specified as follows. % % The first argument specifies how to connect the data base in the DSN % style, for example: % % \verb|'Database=glpk;UID=glpk;PWD=gnu'|. % % Different parts of the string are separated by semicolons. Each part % consists of a pair {\it fieldname} and {\it value} separated by the % equal sign. The following fieldnames are allowed: % % \newpage % % \verb|Server | server running the database (defaulting to localhost); % % \verb|Database | name of the database; % % \verb|UID | user name; % % \verb|PWD | user password; % % \verb|Port | port used by the server (defaulting to 3306). % % The second argument and all following are considered to be SQL % statements. % % SQL statements may be spread over multiple arguments. If the last % character of an argument is a semicolon this indicates the end of % a SQL statement. % % The arguments of a SQL statement are concatenated separated by space. % The eventual trailing semicolon will be removed. % % All but the last SQL statement will be executed directly. % % For IN-table the last SQL statement can be a SELECT command starting % with the capitalized letters \verb|'SELECT '|. If the string does not % start with \verb|'SELECT '| it is considered to be a table name and a % SELECT statement is automatically generated. % % For OUT-table the last SQL statement can contain one or multiple % question marks. If it contains a question mark it is considered a % template for the write routine. Otherwise the string is considered a % table name and an INSERT template is automatically generated. % % The writing routine uses the template with the question marks and % replaces the first question mark by the first output parameter, the % second question mark by the second output parameter and so forth. Then % the SQL command is issued. % % The following is an example of the output table statement: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'MySQL' % 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'DROP TABLE IF EXISTS result;' % 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' % 'INSERT INTO result VALUES ( 4, ?, ? )' : % l ~ LOC, quantity[l] ~ QUAN; % \end{verbatim} % % \noindent % Alternatively it could be written as follows: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'MySQL' % 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'DROP TABLE IF EXISTS result;' % 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );' % 'result' : % l ~ LOC, quantity[l] ~ QUAN, 4 ~ ID; % \end{verbatim} % % \newpage % % Using templates with `\verb|?|' supports not only INSERT, but also % UPDATE, DELETE, etc. For example: % % \begin{verbatim} % table ta { l in LOCATIONS } OUT % 'MySQL' % 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword' % 'UPDATE result SET DATE = ' & date & ' WHERE ID = 4;' % 'UPDATE result SET QUAN = ? WHERE LOC = ? AND ID = 4' : % quantity[l], l; % \end{verbatim} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ##################### PAREI AQUI % ##################### \chapter{Resolvendo modelos com glpsol} O pacote GLPK \footnote{{\tt http://www.gnu.org/software/glpk/}} inclui o programa {\tt glpsol}, um solver de PL/PIM autônomo. Este programa pode ser chamado por uma linha de comando ou pelo shell para resolver modelos escritos na \linebreak linguagem de modelagem GNU MathProg. Para comunicar ao solver que o arquivo de entrada contém uma descrição do modelo, é necessário especificar a opção \verb|--model| na linha de comando. Por exemplo: \begin{verbatim} glpsol --model foo.mod \end{verbatim} Às vezes é necessário usar a seção de dados posicionado em um arquivo separado. Neste caso, deve-se usar o seguinte comando: \begin{verbatim} glpsol --model foo.mod --data foo.dat \end{verbatim} \noindent Note que ser o arquivo de modelo também contém a seção de dados, aquela seção é ignorada. Também é permitido especificar mais de um arquivo contendo a seção de dados, por exemplo: \begin{verbatim} glpsol --model foo.mod --data foo1.dat --data foo2.dat \end{verbatim} Se a descrição do modelo contém alguma sentença display e/ou printf, o resultado é enviado para o terminal por padrão. Se há a necessidade de redirecionar a saída para um arquivo, deve-se usar o seguinte comando: \begin{verbatim} glpsol --model foo.mod --display foo.out \end{verbatim} Se há a necessidade de ver o problema que está sendo gerado pelo tradutor de modelo, deve-ser usar a opção \verb|--wlp| como segue: \begin{verbatim} glpsol --model foo.mod --wlp foo.lp \end{verbatim} \noindent Neste caso, os dados do problema são escritos no arquivo \verb|foo.lp| no formato CPLEX LP viável para análise visual. Ás vezes, é necessário checar a descrição do modelo sem ter que resolver a instância do problema gerado. Neste caso, deve-se especificar a opção \verb|--check|, por exemplo: \begin{verbatim} glpsol --check --model foo.mod --wlp foo.lp \end{verbatim} \newpage Se há a necessidade de escrever uma solução numérica obtida pelo solver para um arquivo, deve-se usar o seguinte comando: \begin{verbatim} glpsol --model foo.mod --output foo.sol \end{verbatim} \noindent neste caso, a solução é escrita no arquivo \verb|foo.sol| em formato de texto plano, viável para análise visual. A lista completa de opções do \verb|glpsol| pode ser encontrada no manual de referência do GLPK incluída na distribuição do GLPK. % The GLPK package\footnote{{\tt http://www.gnu.org/software/glpk/}} % includes the program {\tt glpsol}, a stand-alone LP/MIP solver. This % program can be launched from the command line or from the shell to % solve models written in the GNU MathProg modeling language. % % To tell the solver that the input file contains a model description you % need to specify the option \verb|--model| in the command line. % For example: % % \begin{verbatim} % glpsol --model foo.mod % \end{verbatim} % % Sometimes it is necessary to use the data section placed in a separate % file, in which case you may use the following command: % % \begin{verbatim} % glpsol --model foo.mod --data foo.dat % \end{verbatim} % % \noindent Note that if the model file also contains the data section, % that section is ignored. % % It is also allowed to specify more than one file containing the data % section, for example: % % \begin{verbatim} % glpsol --model foo.mod --data foo1.dat --data foo2.dat % \end{verbatim} % % If the model description contains some display and/or printf % statements, by default the output is sent to the terminal. If you need % to redirect the output to a file, you may use the following command: % % \begin{verbatim} % glpsol --model foo.mod --display foo.out % \end{verbatim} % % If you need to look at the problem, which has been generated by the % model translator, you may use the option \verb|--wlp| as follows: % % \begin{verbatim} % glpsol --model foo.mod --wlp foo.lp % \end{verbatim} % % \noindent In this case the problem data is written to file % \verb|foo.lp| in CPLEX LP format suitable for visual analysis. % % Sometimes it is needed merely to check the model description not % solving the generated problem instance. In this case you may specify % the option \verb|--check|, for example: % % \begin{verbatim} % glpsol --check --model foo.mod --wlp foo.lp % \end{verbatim} % % \newpage % % If you need to write a numeric solution obtained by the solver to % a file, you may use the following command: % % \begin{verbatim} % glpsol --model foo.mod --output foo.sol % \end{verbatim} % % \noindent in which case the solution is written to file \verb|foo.sol| % in a plain text format suitable for visual analysis. % % The complete list of the \verb|glpsol| options can be found in the % GLPK reference manual included in the GLPK distribution. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Exemplo de descrição de modelo} \section{Descrição de modelo escrito em MathProg} Este é um exemplo completo de descrição de modelo escrito na linguagem de modelagem GNU MathProg. \bigskip \begin{verbatim} # UM PROBLEMA DE TRANSPORTE # # Este problema encontra a logística de custo mínimo que atende das demandas # de mercado e as ofertas das fábricas. # # Referência: # Dantzig G B, "Linear Programming and Extensions." # Princeton University Press, Princeton, New Jersey, 1963, # Chapter 3-3. set I; /* fábricas de enlatados*/ set J; /* mercados */ param a{i in I}; /* capacidade da fábrica i, em caixas */ param b{j in J}; /* demanda no mercado j, em caixas */ param d{i in I, j in J}; /* distância, em milhares de milhas */ param f; /* frete, em dólares por caixa a cada mil milhas */ param c{i in I, j in J} := f * d[i,j] / 1000; /* custo de transporte, em milhares de dólares por caixa */ var x{i in I, j in J} >= 0; /* quantidade enviada, em caixas */ minimize custo: sum{i in I, j in J} c[i,j] * x[i,j]; /* custo total de transporte, em milhares de dólares */ s.t. suprimento{i in I}: sum{j in J} x[i,j] <= a[i]; /* observa o limite de suprimento na fábrica i */ s.t. demanda{j in J}: sum{i in I} x[i,j] >= b[j]; /* satisfaz a demanda do mercado j */ data; set I := Seattle San-Diego; set J := New-York Chicago Topeka; param a := Seattle 350 San-Diego 600; param b := New-York 325 Chicago 300 Topeka 275; param d : New-York Chicago Topeka := Seattle 2.5 1.7 1.8 San-Diego 2.5 1.8 1.4 ; param f := 90; end; \end{verbatim} % Below here is a complete example of the model description written in % the GNU MathProg modeling language. % % \bigskip % % \begin{verbatim} % # A TRANSPORTATION PROBLEM % # % # This problem finds a least cost shipping schedule that meets % # requirements at markets and supplies at factories. % # % # References: % # Dantzig G B, "Linear Programming and Extensions." % # Princeton University Press, Princeton, New Jersey, 1963, % # Chapter 3-3. % % set I; % /* canning plants */ % % set J; % /* markets */ % % param a{i in I}; % /* capacity of plant i in cases */ % % param b{j in J}; % /* demand at market j in cases */ % % param d{i in I, j in J}; % /* distance in thousands of miles */ % % param f; % /* freight in dollars per case per thousand miles */ % % param c{i in I, j in J} := f * d[i,j] / 1000; % /* transport cost in thousands of dollars per case */ % % var x{i in I, j in J} >= 0; % /* shipment quantities in cases */ % % minimize cost: sum{i in I, j in J} c[i,j] * x[i,j]; % /* total transportation costs in thousands of dollars */ % % s.t. supply{i in I}: sum{j in J} x[i,j] <= a[i]; % /* observe supply limit at plant i */ % % s.t. demand{j in J}: sum{i in I} x[i,j] >= b[j]; % /* satisfy demand at market j */ % % data; % % set I := Seattle San-Diego; % % set J := New-York Chicago Topeka; % % param a := Seattle 350 % San-Diego 600; % % param b := New-York 325 % Chicago 300 % Topeka 275; % % param d : New-York Chicago Topeka := % Seattle 2.5 1.7 1.8 % San-Diego 2.5 1.8 1.4 ; % % param f := 90; % % end; % \end{verbatim} \newpage \section{Instância gerada do problema de PL} Este é o resultado da tradução do modelo de exemplo produzido pelo solver \verb|glpsol| e escrito no formato CPLEX LP com a opção \verb|--wlp|. \medskip \begin{verbatim} \* Problem: transporte *\ Minimize custo: + 0.225 x(Seattle,New~York) + 0.153 x(Seattle,Chicago) + 0.162 x(Seattle,Topeka) + 0.225 x(San~Diego,New~York) + 0.162 x(San~Diego,Chicago) + 0.126 x(San~Diego,Topeka) Subject To suprimento(Seattle): + x(Seattle,New~York) + x(Seattle,Chicago) + x(Seattle,Topeka) <= 350 suprimento(San~Diego): + x(San~Diego,New~York) + x(San~Diego,Chicago) + x(San~Diego,Topeka) <= 600 demanda(New~York): + x(Seattle,New~York) + x(San~Diego,New~York) >= 325 demanda(Chicago): + x(Seattle,Chicago) + x(San~Diego,Chicago) >= 300 demanda(Topeka): + x(Seattle,Topeka) + x(San~Diego,Topeka) >= 275 End \end{verbatim} \section{solução ótima do problema de PL} Esta é a solução ótima da instância gerada do problema de PL encontrada pelo solver \verb|glpsol| e escrita em formato de texto plano com a opção\verb|--output|. \medskip \begin{footnotesize} \begin{verbatim} Problem: transporte Rows: 6 Columns: 6 Non-zeros: 18 Status: OPTIMAL Objective: custo = 153.675 (MINimum) No. Row name St Activity Lower bound Upper bound Marginal ------ ------------ -- ------------- ------------- ------------- ------------- 1 cust B 153.675 2 suprimento[Seattle] NU 350 350 < eps 3 suprimento[San-Diego] B 550 600 4 demanda[New-York] NL 325 325 0.225 5 demanda[Chicago] NL 300 300 0.153 6 demanda[Topeka] NL 275 275 0.126 No. Column name St Activity Lower bound Upper bound Marginal ------ ------------ -- ------------- ------------- ------------- ------------- 1 x[Seattle,New-York] B 50 0 2 x[Seattle,Chicago] B 300 0 3 x[Seattle,Topeka] NL 0 0 0.036 4 x[San-Diego,New-York] B 275 0 5 x[San-Diego,Chicago] NL 0 0 0.009 6 x[San-Diego,Topeka] B 275 0 End of output \end{verbatim} \end{footnotesize} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newpage \section*{Agradecimentos} \addcontentsline{toc}{chapter}{Agradecimentos} Os autores gostariam de agradecer as seguintes pessoas que gentilmente leram, comentaram e corrigiram o rascunho deste documento: \noindent Juan Carlos Borras \verb|| \noindent Harley Mackenzie \verb|| \noindent Robbie Morrison \verb|| \end{document}