Sunday 9 July 2017

How To Deal With Missing Data In Stata Forex


Base R navios com um monte de funcionalidade útil para séries de tempo, em especial no pacote stats. Isto é complementado por muitos pacotes no CRAN, que são brevemente resumidos abaixo. Há também uma considerável sobreposição entre as ferramentas para séries temporais e aquelas nas vistas de tarefas de Econometria e Finanças. Os pacotes nesta visualização podem ser estruturados grosso modo nos seguintes tópicos. Se você acha que algum pacote está faltando na lista, entre em contato conosco. A infraestrutura . Base R contém infra-estrutura substancial para representar e analisar dados de séries temporais. A classe fundamental é quottsquot que pode representar séries temporais regularmente espaçadas (usando carimbos de tempo numéricos). Assim, é particularmente adequado para dados anuais, mensais, trimestrais, etc. As médias móveis são computadas por ma da previsão. E rollmean do zoológico. Este último também proporciona uma função geral rollapply. Juntamente com outras funções de estatísticas de rolamento específicas. Roll fornece funções paralelas para computar estatísticas de rolagem. Gráficos . As parcelas de séries temporais são obtidas com plot () aplicado aos objetos ts. (Parciais) funções de autocorrelação são implementadas em acf () e pacf (). Versões alternativas são fornecidas por Acf () e Pacf () na previsão. Juntamente com uma exibição de combinação usando tsdisplay (). SDD fornece diagramas de dependência de série mais gerais, enquanto dCovTS calcula e traça as funções de covariância e correlação de distância de séries temporais. Exibições sazonais são obtidas usando monthplot () nas estatísticas e seasonplot na previsão. Wats implementa wrap-around gráficos de série de tempo. Ggseas fornece gráficos ggplot2 para séries ajustadas sazonalmente e estatísticas de rolamento. Dygraphs fornece uma interface para o Dygraphs interativo série de tempo gráfico de biblioteca. ZRA traça objetos de previsão do pacote de previsão usando dígrafos. As parcelas dos ventiladores básicos das distribuições de previsão são fornecidas por previsão e vars. As parcelas de ventiladores mais flexíveis de quaisquer distribuições seqüenciais são implementadas em fanplot. Class quottsquot só pode lidar com carimbos de tempo numéricos, mas muitas mais classes estão disponíveis para armazenar informações de data / hora e computação com ele. Para uma visão geral, consulte R Help Desk: Classes de data e hora em R de Gabor Grothendieck e Thomas Petzoldt em R News 4 (1). 29-32. Classes quotyearmonquot e quotyearqtrquot do zoológico permitem computação mais conveniente com observações mensais e trimestrais, respectivamente. Classe quotDatequot do pacote base é a classe básica para lidar com datas em dados diários. As datas são internamente armazenadas como o número de dias desde 1970-01-01. O pacote cron fornece classes para datas (). Horas () e data / hora (intra-dia) em cron (). Não há suporte para fusos horários e horário de verão. Internamente, os objetos quotchronquot são dias (fracionários) desde 1970-01-01. Classes quotPOSIXctquot e quotPOSIXltquot implementam o padrão POSIX para informações de data / hora (intra-dia) e também suportam fusos horários e horário de verão. No entanto, os cálculos de fuso horário exigem algum cuidado e podem depender do sistema. Internamente, quotPOSIXctquot objetos são o número de segundos desde 1970-01-01 00:00:00 GMT. O pacote lubridate fornece funções que facilitam determinados cálculos baseados em POSIX. A classe quottimeDatequot é fornecida no pacote timeDate (anteriormente: fCalendar). Destina-se a informações de data / hora financeira e trata de fusos horários e horários de verão através de um novo conceito de centros financeiros. Internamente, ele armazena todas as informações em quotPOSIXctquot e faz todos os cálculos em GMT apenas. Funcionalidade do calendário, p. Incluindo informações sobre fins de semana e feriados para várias bolsas de valores, também está incluído. O pacote tis fornece a classe quottiquot para informações de hora / data. A classe quotmondatequot do pacote mondate facilita a computação com datas em termos de meses. O pacote tempdisagg inclui métodos para desagregação temporal e interpolação de uma série temporal de baixa freqüência para uma série de freqüências mais altas. TimeProjection extrai componentes de tempo útil de um objeto de data, como dia da semana, fim de semana, feriado, dia do mês, etc, e colocá-lo em um quadro de dados. Como mencionado acima, quotts ​​é a classe básica para séries temporais regularmente espaçadas usando carimbos de tempo numéricos. O pacote do zoológico fornece infra-estrutura para séries temporais regular e irregularmente espaçadas usando classes arbitrárias para os carimbos de tempo (ou seja, permitindo que todas as classes da seção anterior). Ele é projetado para ser o mais consistente possível com quottsquot. Coerção de e para quotzooquot está disponível para todas as outras classes mencionadas nesta seção. O pacote xts baseia-se no zoológico e fornece tratamento uniforme de Rs diferentes classes de dados baseadas no tempo. Vários pacotes implementam séries temporais irregulares baseadas em quotPOSIXctquot selos de tempo, destinados especialmente para aplicações financeiras. Estes incluem quotits de sua. Citações de tseries. E quotftsquot de fts. A classe quottimeSeriesquot em timeSeries (anteriormente: fSeries) implementa séries de tempo com selos de tempo quottimeDatequot. A classe quottisquot in tis implementa séries temporais com selos de tempo quottiquot. O pacote tframe contém infra-estrutura para definir intervalos de tempo em diferentes formatos. Previsão e Modelagem Univariada O pacote de previsão fornece uma classe e métodos para previsões de séries de tempo univariadas e fornece muitas funções implementando diferentes modelos de previsão incluindo todos aqueles no pacote de estatísticas. Suavização exponencial. HoltWinters () em estatísticas fornece alguns modelos básicos com otimização parcial, ets () do pacote de previsão fornece um conjunto maior de modelos e instalações com otimização completa. O pacote MAPA combina modelos exponenciais de suavização em diferentes níveis de agregação temporal para melhorar a precisão das previsões. Smooth implementa algumas generalizações de suavização exponencial. O método theta é implementado na função thetaf do pacote de previsão. Uma implementação alternativa e estendida é fornecida no forectheta. Modelos auto-regressivos. Ar () nas estatísticas (com seleção do modelo) e FitAR para os modelos do subconjunto AR. Modelos ARIMA. Arima () em stats é a função básica dos modelos ARIMA, SARIMA, ARIMAX e subconjunto ARIMA. Ele é aprimorado no pacote de previsão através da função Arima () juntamente com auto. arima () para a seleção de ordem automática. Arma () no pacote tseries fornece algoritmos diferentes para modelos ARMA e subconjunto ARMA. O FitARMA implementa um algoritmo MLE rápido para modelos ARMA. O pacote gsarima contém funcionalidade para a simulação da série de tempo SARIMA generalizada. O pacote mar1s processa AR multiplicativo (1) com processos sazonais. TSTutorial fornece um tutorial interativo para Box-Jenkins modelagem. Os intervalos de previsão melhorados para ARIMA e modelos de séries temporais estruturais são fornecidos pelo tsPI. Modelos ARMA periódicos. Pear e partsm para modelos periódicos de séries temporais autorregressivas e perARMA para modelagem periódica ARMA e outros procedimentos para análise periódica de séries temporais. Modelos ARFIMA. Algumas instalações para modelos ARFIMA fraccionados diferenciados são fornecidas no pacote fracdiff. O pacote arfima possui recursos mais avançados e gerais para modelos ARFIMA e ARIMA, incluindo modelos de regressão dinâmica (função de transferência). ArmaFit () do pacote fArma é uma interface para modelos ARIMA e ARFIMA. Ruído gaussiano fracionário e modelos simples para séries de tempo de decaimento hiperbólico são tratados no pacote FGN. Os modelos de função de transferência são fornecidos pela função arimax no pacote TSA ea função arfima no pacote arfima. Outlier detecção após a Chen-Liu abordagem é fornecida por tsoutliers. Modelos estruturais são implementados em StructTS () em stats, e em stsm e stsm. class. KFKSDS fornece uma implementação ingênua do filtro de Kalman e alisadores para modelos de espaço de estados univariados. Os modelos de séries temporais estruturais bayesianas são implementados em séries temporais não gaussianas podem ser manipuladas com modelos de espaço de estado GLARMA via glarma. E usando modelos Generalized Autoregressive Score no pacote GAS. Modelos condicionais de Auto-Regressão utilizando métodos Monte Carlo Likelihood são implementados em mclcar. Modelos GARCH. Garch () do tseries se encaixa modelos GARCH básicos. Muitas variações em modelos de GARCH são fornecidas pelo rugarch. Outros pacotes GARCH univariados incluem fGarch que implementa modelos ARIMA com uma ampla classe de inovações GARCH. Existem muitos outros pacotes GARCH descritos na vista de tarefas Financeiro. Modelos de volatilidade estocástica são manipulados por stochvol em uma estrutura bayesiana. Modelos de série de tempo de contagem são manipulados nos pacotes tscount e acp. O ZIM fornece modelos Zero-Inflated para séries de tempo de contagem. Tsintermittent implementa vários modelos para analisar e prever séries de tempo de demanda intermitente. As séries temporais censuradas podem ser modeladas usando centavos e carx. Testes Portmanteau são fornecidos através de Box. test () no pacote stats. Testes adicionais são dados por portes e WeightedPortTest. A detecção de ponto de mudança é fornecida no strucchange (usando modelos de regressão linear), na tendência (usando testes não paramétricos) e em wbsts (usando segmentação binária selvagem). O pacote de ponto de mudança fornece muitos métodos de ponto de troca populares, e ecp faz detecção de ponto de mudança não paramétrico para séries univariadas e multivariadas. A detecção de ponto de mudança online para séries temporais univariadas e multivariadas é fornecida pelo onlineCPD. O InspectChangepoint usa projeção esparsa para estimar pontos de mudança em séries temporais de alta dimensão. A imputação de séries temporais é fornecida pelo pacote imputeTS. Alguns recursos mais limitados estão disponíveis usando na. interp () do pacote de previsão. As previsões podem ser combinadas usando ForecastCombinations que suporta os métodos mais usados ​​para combinar previsões. ForecastHybrid fornece funções para previsões de conjuntos, combinando abordagens do pacote de previsão. Opera tem facilidades para previsões on-line com base em combinações de previsões fornecidas pelo usuário. A avaliação da previsão é fornecida na função accuracy () da previsão. A avaliação de previsão distribucional usando regras de pontuação está disponível no scoringRules Miscellaneous. Ltsa contém métodos para análise de séries temporais lineares, timsac para análise e controle de séries temporais e tsbugs para modelos BUGS de séries temporais. A estimativa da densidade espectral é fornecida pelo espectro () no pacote stats, incluindo o periodograma, o periodograma suavizado e as estimativas de AR. A inferência espectral bayesiana é fornecida por bspec. O quantspec inclui métodos para calcular e traçar periodogramas de Laplace para séries temporais univariadas. O periodograma Lomb-Scargle para séries temporais amostradas de forma desigual é calculado por lomb. O espectro utiliza transformadas de Fourier e Hilbert para filtragem espectral. Psd produz estimativas de densidade espectral adaptativas, seno-multitaper. Kza fornece Kolmogorov-Zurbenko Adaptive Filters incluindo detecção de quebra, análise espectral, wavelets e KZ Fourier transformações. Multitaper também fornece algumas ferramentas de análise espectral multitaper. Métodos Wavelet. O pacote de wavelets inclui computar filtros wavelet, transformadas wavelet e análises multiresolução. Os métodos wavelet para a análise de séries temporais baseados em Percival e Walden (2000) são dados em wmtsa. WaveletComp fornece algumas ferramentas para a análise baseada em wavelet de séries temporais univariadas e bivariadas incluindo cross-wavelets, diferença de fase e testes significativos. Biwavelet pode ser usado para plotar e calcular os espectros wavelet, espectros de wavelet cruzado e coerência wavelet de séries temporais não-estacionárias. Ele também inclui funções para agrupar séries temporais baseadas nas (des) similaridades em seu espectro. Testes de ruído branco usando wavelets são fornecidos por hwwntest. Métodos Wavelet adicionais podem ser encontrados no brainwaver pacotes. Rwt. Waveslim Wavethresh e mvcwt. A regressão harmônica usando termos de Fourier é implementada em HarmonicRegression. O pacote de previsão também fornece algumas facilidades simples de regressão harmônica através da função fourier. Decomposição e filtragem Filtros e suavização. O filtro () em stats fornece filtragem linear média auto-regressiva e móvel de séries temporais univariadas múltiplas. O pacote robfilter fornece vários filtros robustos de séries temporais, enquanto o mFilter inclui diversos filtros de séries temporais úteis para suavizar e extrair componentes tendenciais e cíclicos. Smooth () do pacote de estatísticas computa Tukeys executando mediana smoothers, 3RS3R, 3RSS, 3R, etc sleekts calcula o 4253H duas vezes método de suavização. Decomposição. A decomposição sazonal é discutida abaixo. A decomposição baseada em auto-regressão é fornecida pelo ArDec. O rmaf usa um filtro refinado de média móvel para decomposição. Análise de Espectro Singular é implementada em Rssa e métodos espectrais. A decomposição do modo empírico (EMD) ea análise espectral de Hilbert são fornecidas por EMD. Ferramentas adicionais, incluindo EMD conjunto, estão disponíveis em hht. Uma implementação alternativa do conjunto EMD e sua variante completa estão disponíveis em Rlibeemd. Decomposição sazonal. O pacote stats fornece decomposição clássica em decompose (). E decomposição STL em stl (). A decomposição STL melhorada está disponível em stlplus. StR fornece a decomposição Seasonal-Trend baseada na regressão. X12 fornece um wrapper para os binários X12 que devem ser instalados primeiro. X12GUI fornece uma interface gráfica do usuário para x12. Os binários X-13-ARIMA-SEATS são fornecidos no pacote x13binary, com o fornecimento sazonal de uma interface R. Análise da sazonalidade. O pacote bfast fornece métodos para detectar e caracterizar mudanças abruptas dentro da tendência e componentes sazonais obtidos a partir de uma decomposição. Npst fornece uma generalização do teste de sazonalidade Hewitts. estação. Análise sazonal de dados de saúde, incluindo modelos de regressão, crossover caso-estratificado tempo, funções de traçado e verificações residuais. Mares Análise sazonal e gráficos, especialmente para climatologia. Dessazonalizar Otimização da dessazonalização para séries geofísicas usando o encaixe AR. Estacionaridade, Unidade de Raízes e Cointegração Estacionaridade e raízes unitárias. Tseries fornece vários testes de estacionaridade e raiz unitária, incluindo Dickey-Fuller aumentado, Phillips-Perron e KPSS. Implementações alternativas dos testes ADF e KPSS estão no pacote urca, que também inclui métodos adicionais como os testes Elliott-Rothenberg-Stock, Schmidt-Phillips e Zivot-Andrews. O pacote fUnitRoots também fornece o teste MacKinnon, enquanto o uroot fornece testes de raiz unitária sazonais. O CADFtest fornece implementações tanto do ADF padrão como de um teste de ADF (CADF) com covariável. Estacionaridade local. Localiza um teste de estacionaridade local e calcula a autocovariância localizada. A determinação da determinação da costeração de séries temporais é fornecida por costat. LSTS tem funções para análise de séries temporais localmente estacionárias. Modelos de wavelet estacionariamente estacionários para séries temporais não-estacionárias são implementados em wavethresh (incluindo estimativa, plotagem e simulação para espectros que variam no tempo). Cointegração. O método Engle-Granger de dois passos com o teste de cointegração Phillips-Ouliaris é implementado em tseries e urca. Este último contém adicionalmente funcionalidade para os testes Johansen trace e lambda-max. TsDyn fornece Johansens teste e AIC / BIC seleção simultânea rank-lag. O CommonTrend fornece ferramentas para extrair e traçar tendências comuns de um sistema de cointegração. A estimação e inferência de parâmetros em uma regressão de cointegração são implementadas em cointReg. Análise não linear de séries temporais Auto-regressão não-linear. Várias formas de auto-regressão não linear estão disponíveis em tsDyn incluindo AR aditivo, redes neurais, modelos SETAR e LSTAR, limiar VAR e VECM. A auto-regressão da rede neural também é fornecida no GMDH. O bentcableAR implementa a autorregressão Bent-Cable. BAYSTAR fornece a análise bayesiana de modelos autorregressivos de limiar. TseriesChaos fornece uma implementação R dos algoritmos do projeto TISEAN. Autoregression Os modelos de comutação de Markov são fornecidos em MSwM. Enquanto que as misturas dependentes de modelos de Markov latentes são dadas em depmix e depmixS4 para séries temporais categóricas e contínuas. Testes. Vários testes de não-linearidade são fornecidos em fNonlinear. TseriesEntropy testes de dependência serial não linear com base em métricas de entropia. Funções adicionais para séries temporais não-lineares estão disponíveis em nlts e nonlinearTseries. A modelagem da série de tempo do Fractal e a análise são fornecidas pelo fractal. Fractalrock gera séries de tempo fractal com distribuições de retornos não-normais. Modelos dinâmicos de regressão Modelos dinâmicos lineares. Uma interface conveniente para ajustar modelos de regressão dinâmica via OLS está disponível no dynlm uma abordagem avançada que também funciona com outras funções de regressão e mais séries de séries temporais é implementada em dyn. Equações mais avançadas do sistema dinâmico podem ser montadas usando dse. Os modelos de espaço de estados lineares gaussianos podem ser ajustados usando dlm (via máxima verossimilhança, filtragem / alisamento de Kalman e métodos Bayesianos), ou usando bsts que usa MCMC. As funções para a modelação não-linear de atraso distribuído são fornecidas em dlnm. Modelos de parâmetros variáveis ​​no tempo podem ser ajustados usando o pacote tpr. OrderedLasso ajusta um modelo linear esparso com uma restrição de ordem sobre os coeficientes, a fim de lidar com regressores defasados ​​onde os coeficientes decadência como o lag aumenta. Modelos dinâmicos de vários tipos estão disponíveis em dynr incluindo tempo discreto e contínuo, modelos lineares e não-lineares e diferentes tipos de variáveis ​​latentes. Modelos de séries temporais multivariadas Modelos VAR (Vector Autoregressive) são fornecidos via ar () no pacote stats básico incluindo a seleção de pedidos via AIC. Estes modelos são restritos para ser estacionário. O MTS é um conjunto de ferramentas para análise de séries temporais multivariadas, incluindo VAR, VARMA, VARMA sazonal, modelos VAR com variáveis ​​exógenas, regressão multivariada com erros de séries temporais e muito mais. Possivelmente modelos VAR não estacionários são montados no pacote mAr, o que também permite modelos VAR no espaço do componente principal. Sparsevar permite a estimação de modelos VAR e VECM esparsos, ecm fornece funções para a construção de modelos VECM, enquanto BigVAR estima modelos VAR e VARX com penalidades laço estruturado. Os modelos e redes VAR automatizados estão disponíveis no autovarCore. Modelos mais elaborados são fornecidos em pacotes vars. TsDyn. EstVARXls () em dse. E uma abordagem bayesiana está disponível em MSBVAR. Outra implementação com intervalos de previsão bootstrap é dada em VAR. etp. MlVAR fornece auto-regressão vectorial multi-nível. VARsignR fornece rotinas para identificar choques estruturais em modelos VAR usando restrições de sinal. Os modelos VARIMA e modelos de espaço de estado são fornecidos no pacote dse. EvalEst facilita experiências de Monte Carlo para avaliar os métodos de estimação associados. Modelos de correção de erros vetoriais estão disponíveis através da urca. Vars e pacotes tsDyn, incluindo versões com restrições estruturais e thresholding. Análise de componentes de séries temporais. A análise fatorial de séries temporais é fornecida em tsfa. O ForeCA implementa uma análise de componentes que pode ser pesquisada procurando as melhores transformações lineares que tornam uma série de tempo multivariada o mais previsível possível. PCA4TS encontra uma transformação linear de uma série de tempo multivariada dando subseries de menor dimensão que não estão correlacionadas entre si. Modelos de espaço de estados multivariados são implementados no pacote FKF (Fast Kalman Filter). Isso fornece modelos de espaço de estados relativamente flexíveis através da função fkf (): os parâmetros de espaço de estado podem variar em função do tempo e as interceptações são incluídas em ambas as equações. Uma implementação alternativa é fornecida pelo pacote KFAS que fornece um filtro de Kalman multivariado rápido, mais suave, simulação mais suave e previsão. Ainda outra implementação é dada no pacote dlm que também contém ferramentas para converter outros modelos multivariados em forma de espaço de estado. Dlmodeler fornece uma interface unificada para dlm. KFAS e FKF. O MARSS se ajusta a modelos de estados-espaço autoregressivos multivariados restritos e não restringidos usando um algoritmo EM. Todos esses pacotes assumem que os termos de erro observacional e de estado não estão correlacionados. Os processos de Markov parcialmente observados são uma generalização dos modelos de espaço de estados multivariados lineares usuais, permitindo modelos não-Gaussianos e não-lineares. Estes são implementados no pacote pompa. Modelos de volatilidade estocástica multivariada (usando fatores latentes) são fornecidos por fatores tochvol. Análise de grandes grupos de séries temporais O agrupamento em séries temporais é implementado em TSclust. Dtwclust. BNPTSclust e pdc. TSdist fornece medidas de distância para dados de séries temporais. O jmotif implementa ferramentas baseadas na discretização simbólica de séries temporais para encontrar motivos em séries temporais e facilita a classificação de séries temporais interpretáveis. Métodos para traçar e prever coleções de séries temporais hierárquicas e agrupadas são fornecidos por hts. Ladrão usa métodos hierárquicos para conciliar previsões de séries temporais temporais agregadas. Uma abordagem alternativa para conciliar previsões de séries temporais hierárquicas é fornecida por gtop. Ladrão Modelos de tempo contínuo Modelagem autorregressiva de tempo contínuo é fornecida em cts. Sim. DiffProc simula e modela equações diferenciais estocásticas. A simulação ea inferência para equações diferenciais estocásticas são fornecidas por sde e yuima. Bootstrapping. O pacote de inicialização fornece a função tsboot () para bootstrapping de série de tempo, incluindo bootstrap de bloco com várias variantes. Tsbootstrap () do tseries fornece bootstrapping rápido estacionário e de bloco. O bootstrap entropy máximo para a série de tempo está disponível no meboot. Timesboot calcula o CI de bootstrap para o ACF e o periodograma da amostra. O BootPR calcula os intervalos de previsão corrigidos por bias e boostrap para séries temporais autorregressivas. Dados de Makridakis, Wheelwright e Hyndman (1998) Previsão: métodos e aplicações são fornecidos no pacote fma. Dados de Hyndman, Koehler, Ord e Snyder (2008) As previsões com suavização exponencial estão no pacote expsmooth. Dados de Hyndman e Athanasopoulos (2013) Previsão: princípios e práticas estão no pacote fpp. Os dados da competição M e competição M3 são fornecidos no pacote Mcomp. Os dados da competição M4 são dados em M4comp. Enquanto a Tcomp fornece dados da Competição de Previsão de Turismo IJF 2010. Pdfetch fornece facilidades para baixar séries econômicas e financeiras de fontes públicas. Dados do portal on-line do Quandl para conjuntos de dados financeiros, econômicos e sociais podem ser consultados interativamente usando o pacote Quandl. Os dados do portal on-line do Datamarket podem ser obtidos usando o pacote rdatamarket. Os dados de Cryer e Chan (2010) estão no pacote TSA. Os dados de Shumway e Stoffer (2011) estão no pacote astsa. Dados de Tsay (2005) A análise de séries de tempo financeiras está no pacote FinTS, juntamente com algumas funções e arquivos de script necessários para trabalhar alguns dos exemplos. TSdbi fornece uma interface comum para bancos de dados de séries temporais. Fama fornece uma interface para bases de dados de séries de tempo FAME AER e Ecdat ambos contêm muitos conjuntos de dados (incluindo dados de séries temporais) de muitos livros de econometria dtw. Algoritmos dinâmicos do warping do tempo para computar e traçar alinhamentos pairwise entre séries de tempo. EnsembleBMA. Modelo Bayesiano Averaging para criar previsões probabilísticas a partir de previsões de conjunto e observações meteorológicas. Earlywarnings. Avisos iniciais sinalizam caixa de ferramentas para detectar transições críticas em eventos de séries temporais. Transforma dados de eventos extraídos por máquina em séries de tempo multivariadas agregadas regulares. FeedbackTS. Análise da direcionalidade temporal fragmentada para investigar feedback em séries temporais. LPStimeSeries pretende encontrar similaridade de padrão quotlearned para séries de tempo. MAR1 fornece ferramentas para preparar dados de séries temporais de comunidades ecológicas para modelagem de AR multivariada. Redes Rotinas para a estimativa de redes de correlação parciais esparsas de longo prazo para dados de séries temporais. PaleoTS. Modelagem da evolução em séries temporais paleontológicas. Pastecs. Regulação, decomposição e análise de séries espaço-temporais. Ptw. Comprimento de tempo paramétrico. RGENERATE fornece ferramentas para gerar séries de vetores. RMAWGEN é um conjunto de funções S3 e S4 para a geração estocástica espacial multi-site de séries de tempo diárias de temperatura e precipitação, fazendo uso de modelos VAR. O pacote pode ser utilizado em climatologia e hidrologia estatística. RSEIS. Ferramentas sísmicas de análise de séries temporais. Rts. Análise de séries temporais de rasterização (por exemplo, séries temporais de imagens de satélite). Sae2. Modelos de séries temporais para estimativa de área pequena. SpTimer. Modelagem bayesiana espacial-temporal. vigilância. Modelação temporal e espaço-temporal e monitoramento de fenômenos epidêmicos. TED. Turbulência de séries temporais Detecção e classificação de eventos. Marés Funções para calcular características de séries temporais quase periódicas, e. Níveis de água nos estuários. tigre. Grupos temporariamente resolvidos de diferenças típicas (erros) entre duas séries temporais são determinados e visualizados. TSMining. Motivos Univariados e Multivariados em Dados de Série de Tempo. TsModel. Modelagem de séries temporais para poluição do ar e saúde. Pacotes CRAN: Links relacionados: Referência ILE RPG do WebSphere (R) Development Studio Além disso, alguns tipos de dados permitem diferentes formatos de dados. Este capítulo descreve a diferença entre formatos de dados internos e externos, descreve cada formato e como especificá-los. Os campos numérico, de caractere, data, hora e carimbo de data / hora têm um formato interno que é independente do formato externo. O formato interno é a forma como os dados são armazenados no programa. O formato externo é a maneira como os dados são armazenados em arquivos. Você precisa estar ciente do formato interno quando: Passando parâmetros por referência Sobreposição de subcampos em estruturas de dados Além disso, você pode querer considerar o formato interno de campos numéricos, quando o desempenho em tempo de execução de operações aritméticas é importante. Para obter mais informações, consulte Considerações sobre desempenho. Existe um formato interno e externo predefinido para os tipos de dados numéricos e de data / hora. Você pode especificar um formato interno para um campo específico em uma especificação de definição. Da mesma forma, você pode especificar um formato externo para um campo descrito no programa na especificação de entrada ou saída correspondente. Para campos em um arquivo descrito externamente, o formato de dados externo é especificado nas especificações de descrição de dados na posição 35. Você não pode alterar o formato externo de campos descritos externamente, com uma exceção. Se você especificar EXTBININT em uma especificação de controle, qualquer campo binário com zero posições decimais será tratado como tendo um formato externo inteiro. Para subcampos em estruturas de dados descritas externamente, os formatos de dados especificados na descrição externa são utilizados como formatos internos dos subcampos pelo compilador. O formato interno padrão para campos numéricos standalone é empacotado-decimal. O formato interno padrão para sub-campos de estrutura de dados numéricos é zoned-decimal. Para especificar um formato interno diferente, especifique o formato desejado na posição 40 na especificação de definição para o campo ou subcampo. O formato padrão para os campos de data, hora e carimbo de data / hora é ISO. Em geral, recomenda-se que você use o formato ISO interno padrão, especialmente se você tiver uma mistura de tipos de formatos externos. Para campos de data, hora e carimbo de data / hora, você pode usar as palavras-chave DATFMT e TIMFMT na especificação de controle para alterar o formato interno padrão, se desejado, para todos os campos de data e hora no programa. Você pode usar a palavra-chave DATFMT ou TIMFMT em uma especificação de definição para substituir o formato interno padrão de um campo de data e hora individual. Se você tiver campos numéricos, de caractere ou de data e hora em arquivos descritos no programa, você pode especificar seu formato externo. O formato externo não afeta a forma como um campo é processado. No entanto, você pode ser capaz de melhorar o desempenho de operações aritméticas, dependendo do formato interno especificado. Para obter mais informações, consulte Considerações sobre desempenho. A tabela a seguir mostra como especificar o formato externo dos campos descritos pelo programa. Para obter mais informações sobre cada tipo de formato, consulte a seção apropriada no restante deste capítulo. P Comprimido decimal S Zoned decimal O formato externo padrão para dados numéricos flutuantes é chamado de representação de exibição externa. O formato para dados de float de 4 bytes é: O formato para dados de float de 8 bytes é: Note que um valor de float de 4 bytes ocupa 14 posições e um valor de float de 8 bytes ocupa 23 posições. Para dados numéricos diferentes de float, o formato externo padrão é zonal decimal. O formato externo para matrizes e tabelas de compilação-tempo deve ser zoned-decimal, left-sign ou right-sign. Para float compilação-tempo matrizes e tabelas, os dados de tempo de compilação são especificados como um literal numérico ou um literal float. Cada elemento de uma matriz de float de 4 bytes requer 14 posições no registro de origem cada elemento de uma matriz de float de 8 bytes requer 23 posições. Os campos numéricos não float definidos em especificações de entrada, especificações de cálculo ou especificações de saída sem definição correspondente em uma especificação de definição são armazenados internamente em formato decimal compactado. Para qualquer um dos campos de entrada e saída na Tabela 11. especifique um dos seguintes formatos de dados externos válidos: A Caractere (válido para dados de caracteres e indicadores) N Indicador (válido para dados de caracteres e indicadores) G Gráfico (válido para dados gráficos) C UCS-2 (válido para dados UCS-2) A palavra-chave EXTFMT pode ser usada para especificar os dados para uma matriz ou tabela no formato UCS-2. Especifique o atributo de dados VAR nas posições 31-34 em uma especificação de entrada e nas posições 53-80 em uma especificação de saída para dados de caracteres, gráficos ou UCS-2 de comprimento variável. Se você tiver campos de data, hora e carimbo de data / hora em arquivos descritos no programa, então você deve especificar seu formato externo. Você pode especificar um formato externo padrão para todos os campos de data, hora e carimbo de data / hora em um arquivo descrito no programa usando as palavras-chave DATFMT e TIMFMT em uma especificação de descrição de arquivo. Você também pode especificar um formato externo para um determinado campo. Especifique o formato desejado nas posições 31-34 em uma especificação de entrada. Especifique a palavra-chave e o formato apropriados nas posições 53-80 em uma especificação de saída. Para obter mais informações sobre cada tipo de formato, consulte a seção apropriada no restante deste capítulo. O tipo de dados de caractere representa valores de caractere e pode ter qualquer um dos seguintes formatos: Os dados de caractere podem conter um ou mais caracteres de um ou dois bytes, dependendo do formato especificado. Os campos de caracteres, gráficos e UCS-2 também podem ter um formato fixo ou de comprimento variável. A tabela a seguir resume os diferentes formatos de tipo de dados de caracteres. Tipo de dados de caractere Número de bytes O formato de caracteres de comprimento fixo é um ou mais bytes de comprimento com um comprimento definido. Você define um campo de caractere especificando A na entrada Data-Type da especificação apropriada. You can also define one using the LIKE keyword on the definition specification where the parameter is a character field. The default initialization value is blanks. The indicator format is a special type of character data. Indicators are all one byte long and can only contain the character values 0 (off) and 1 (on). They are generally used to indicate the result of an operation or to condition (control) the processing of an operation. The default value of indicators is 0. You define an indicator field by specifying N in the Data-Type entry of the appropriate specification. You can also define an indicator field using the LIKE keyword on the definition specification where the parameter is an indicator field. Indicator fields are also defined implicitly with the COMMIT keyword on the file description specification. A special set of predefined RPG IV indicators (INxx) is also available. For a description of these indicators, see RPG IV Indicators. The rules for defining indicator variables are: Indicators can be defined as standalone fields, subfields, prototyped parameters, and procedure return values. If an indicator variable is defined as a prerun-time or compile-time array or table, the initialization data must consist of only 0s and 1s. Note: If an indicator contains a value other than 0 or 1 at runtime, the results are unpredictable. If the keyword INZ is specified, the value must be one of 0, OFF, 1, or ON. The keyword VARYING cannot be specified for an indicator field. The rules for using indicator variables are: The default initialization value for indicator fields is 0. Operation code CLEAR sets an indicator variable to 0. Blank-after function applied to an indicator variable sets it to 0. If an array of indicators is specified as the result of a MOVEA(P) operation, the padding character is 0. Indicators are implicitly defined with ALTSEQ(NONE). This means that the alternate collating sequence is not used for comparisons involving indicators. Indicators may be used as key-fields where the external key is a character of length 1. The graphic format is a character string where each character is represented by 2 bytes. Fields defined as graphic data do not contain shift-out (SO) or shift-in (SI) characters. The difference between single byte character and double byte graphic data is shown in the following figure: The length of a graphic field, in bytes, is two times the number of graphic characters in the field. The fixed-length graphic format is a character string with a set length where each character is represented by 2 bytes. You define a graphic field by specifying G in the Data-Type entry of the appropriate specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a graphic field. The default initialization value for graphic data is X4040. The value of HIVAL is XFFFF, and the value of LOVAL is X0000. The Universal Character Set (UCS-2) format is a character string where each character is represented by 2 bytes. This character set can encode the characters for many written languages. Fields defined as UCS-2 data do not contain shift-out (SO) or shift-in (SI) characters. The length of a UCS-2 field, in bytes, is two times the number of UCS-2 characters in the field. The fixed-length UCS-2 format is a character string with a set length where each character is represented by 2 bytes. You define a UCS-2 field by specifying C in the Data-Type entry of the appropriate specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a UCS-2 field. The default initialization value for UCS-2 data is X0020. The value of HIVAL is XFFFF, LOVAL is X0000, and the value of BLANKS is X0020. For more information on the UCS-2 format, see the iSeries Information Center globalization topic. Variable-length character fields have a declared maximum length and a current length that can vary while a program is running. The length is measured in single bytes for the character format and in double bytes for the graphic and UCS-2 formats. The storage allocated for variable-length character fields is 2 bytes longer than the declared maximum length. The leftmost 2 bytes are an unsigned integer field containing the current length in characters, graphic characters or UCS-2 characters. The actual character data starts at the third byte of the variable-length field. Figure 80 shows how variable-length character fields are stored: Figure 81 shows how variable-length graphic fields are stored. UCS-2 fields are stored similarly. You define a variable-length character data field by specifying A (character), G (graphic), or C (UCS-2) and the keyword VARYING on a definition specification. It can also be defined using the LIKE keyword on a definition specification where the parameter is a variable-length character field. You can refer to external variable-length fields, on an input or output specification, with the VAR data attribute. A variable-length field is initialized by default to have a current length of zero. The following rules apply when defining variable-length fields: The declared length of the field can be from 1 to 65535 single-byte characters and from 1 to 16383 double-byte graphic or UCS-2 characters. The current length may be any value from 0 to the maximum declared length for the field. The field may be initialized using keyword INZ. The initial value is the exact value specified and the initial length of the field is the length of the initial value. The field is padded with blanks for initialization, but the blanks are not included in the length. In all cases except subfields defined using positional notation, the length entry (positions 33-39 on the definition specifications) contains the maximum length of the field not including the 2-byte length. For subfields defined using positional notation, the length includes the 2-byte length. As a result, a variable-length subfield may be 32769 single bytes long or 16384 double bytes long for an unnamed data structure. The keyword VARYING cannot be specified for a data structure. For variable-length prerun-time arrays, the initialization data in the file is stored in variable format, including the 2-byte length prefix. Since prerun-time array data is read from a file and files have a maximum record length of 32766, variable-length prerun-time arrays have a maximum size of 32764 single-byte characters, or 16382 double-byte graphic or UCS-2 characters. A variable-length array or table may be defined with compile-time data. The trailing blanks in the field of data are not significant. The length of the data is the position of the last non-blank character in the field. This is different from prerun-time initialization since the length prefix cannot be stored in compile-time data. LIKE DEFINE cannot be used to define a field like a variable-length field. The following is an example of defining variable-length character fields: The following is an example of defining variable-length graphic and UCS-2 fields: The default initialization value for numeric fields is zero. Binary format means that the sign (positive or negative) is in the leftmost bit of the field and the numeric value is in the remaining bits of the field. Positive numbers have a zero in the sign bit negative numbers have a one in the sign bit and are in twos complement form. A binary field can be from one to nine digits in length and can be defined with decimal positions. If the length of the field is from one to four digits, the compiler assumes a binary field length of 2 bytes. If the length of the field is from five to nine digits, the compiler assumes a binary field length of 4 bytes. Every input field read in binary format is assigned a field length (number of digits) by the compiler. A length of 4 is assigned to a 2-byte binary field a length of 9 is assigned to a 4-byte binary field, if the field is not defined elsewhere in the program. Because of these length restrictions, the highest decimal value that can be assigned to a 2-byte binary field is 9999 and the highest decimal value that can be assigned to a 4-byte binary field is 999 999 999. In general, a binary field of n digits can have a maximum value of n 9s. This discussion assumes zero decimal positions. Because a 2-byte field in binary format is converted by the compiler to a decimal field with 1 to 4 digits, the input value may be too large. If it is, the leftmost digit of the number is dropped. For example, if a four digit binary input field has a binary value of hexadecimal 6000, the compiler converts this to 24 576 in decimal. The 2 is dropped and the result is 4576. Similarly, the input value may be too large for a 4-byte field in binary format. If the binary fields have zero (0) decimal positions, then you can avoid this conversion problem by defining integer fields instead of binary fields. Note: Binary input fields cannot be defined as match or control fields. The number of digits of a binary field is exactly the same as the length in the DDS description. For example, if you define a binary field in your DDS specification as having 7 digits and 0 decimal positions, the RPG IVcompiler handles the data like this: The field is defined as a 4-byte binary field in the input specification A Packed(7,0) field is generated for the field in the RPG IV program. If you want to retain the complete binary field information, redefine the field as a binary subfield in a data structure or as a binary stand-alone field. Note that an externally described binary field may have a value outside of the range allowed by RPG IV binary fields. If the externally described binary field has zero (0) decimal positions then you can avoid this problem. To do so, you define the externally described binary field on a definition specification and specify the EXTBININT keyword on the control specification. This will change the external format of the externally described field to that of a signed integer. The float format consists of two parts: the mantissa and the exponent. The value of a floating-point field is the result of multiplying the mantissa by 10 raised to the power of the exponent. For example, if 1.2345 is the mantissa and 5 is the exponent then the value of the floating-point field is: You define a floating-point field by specifying F in the data type entry of the appropriate specification. The decimal positions must be left blank. However, floating-point fields are considered to have decimal positions. As a result, float variables may not be used in any place where a numeric value without decimal places is required, such as an array index, do loop index, etc. The default initialization and CLEAR value for a floating point field is 0E0. The length of a floating point field is defined in terms of the number of bytes. It must be specified as either 4 or 8 bytes. The range of values allowed for a floating-point field are: 4-byte float (8 digits) -3.4028235E38 to -1.1754944E-38, 0.0E0, 1.1754944E-38 to 3.4028235E38 8-byte float (16 digits) -1.797693134862315E308 to -2.225073858507201E-308, 0.0E0, 2.225073858507201E-308 to 1.797693134862315E308 Note: Float variables conform to the IEEE standard as supported by the OS/400 operating system. Since float variables are intended to represent scientific values, a numeric value stored in a float variable may not represent the exact same value as it would in a packed variable. Float should not be used when you need to represent numbers exactly to a specific number of decimal places, such as monetary amounts. See Specifying an External Format for a Numeric Field for a general description of external display representation. The external display representation of float values applies for the following: Output of float data with Data-Format entry blank. Input of float data with Data-Format entry blank. External format of compile-time and prerun-time arrays and tables (when keyword EXTFMT is omitted). Display and input of float values using operation code DSPLY. Output of float values on a dump listing. Result of built-in function EDITFLT. When outputting float values, the external representation uses a format similar to float literals, except that: Values are always written with the character E and the signs for both mantissa and exponent. Values are either 14 or 23 characters long (for 4F and 8F respectively). Values are normalized. That is, the decimal point immediately follows the most significant digit. The decimal separator character is either period or comma depending on the parameter for Control Specification keyword DECEDIT. Here are some examples of how float values are presented: When inputting float values, the value is specified just like a float literal. The value does not have to be normalized or adjusted in the field. When float values are defined as array/table initialization data, they are specified in fields either 14 or 23 characters long (for 4F and 8F respectively). Note the following about float fields: Alignment of float fields may be desired to improve the performance of accessing float subfields. You can use the ALIGN keyword to align float subfields defined on a definition specification. 4-byte float subfields are aligned on a 4-byte boundary and 8-byte float subfields are aligned along a 8-byte boundary. For more information on aligning float subfields, see ALIGN. Length adjustment is not allowed when the LIKE keyword is used to define a field like a float field. Float input fields cannot be defined as match or control fields. The integer format is similar to the binary format with two exceptions: The integer format allows the full range of binary values The number of decimal positions for an integer field is always zero. You define an integer field by specifying I in the Data-Type entry of the appropriate specification. You can also define an integer field using the LIKE keyword on a definition specification where the parameter is an integer field. The length of an integer field is defined in terms of number of digits it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage a 5-digit field takes up 2 bytes of storage a 10-digit field takes up 4 bytes a 20-digit field takes up 8 bytes. The range of values allowed for an integer field depends on its length. Field length Range of Allowed Values 3-digit integer -128 to 127 5-digit integer -32768 to 32767 10-digit integer -2147483648 to 2147483647 20-digit integer -9223372036854775808 to 9223372036854775807 Note the following about integer fields: Alignment of integer fields may be desired to improve the performance of accessing integer subfields. You can use the ALIGN keyword to align integer subfields defined on a definition specification. 2-byte integer subfields are aligned on a 2-byte boundary 4-byte integer subfields are aligned along a 4-byte boundary 8-byte integer subfields are aligned along an 8-byte boundary. For more information on aligning integer subfields, see ALIGN. If the LIKE keyword is used to define a field like an integer field, the Length entry may contain a length adjustment in terms of number of digits. The adjustment value must be such that the resulting number of digits for the field is 3, 5, 10, or 20. Integer input fields cannot be defined as match or control fields. Packed-decimal format means that each byte of storage (except for the low order byte) can contain two decimal numbers. The low-order byte contains one digit in the leftmost portion and the sign (positive or negative) in the rightmost portion. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. The packed-decimal format looks like this: The sign portion of the low-order byte indicates whether the numeric value represented in the digit portions is positive or negative. Figure 89 shows what the decimal number 21544 looks like in packed-decimal format. Use the following formula to find the length in digits of a packed-decimal field: This formula gives you the maximum number of digits you can represent in packed-decimal format the upper limit is 31. Packed fields can be up to 16 bytes long. Table 12 shows the packed equivalents for zoned-decimal fields up to 31 digits long: Zoned-Decimal Length in Digits Number of Bytes Used in Packed-Decimal Field For example, an input field read in packed-decimal format has a length of five bytes (as specified on the input or definition specifications). The number of digits in this field equals 2(5) - 1 or 9. Therefore, when the field is used in the calculation specifications, the result field must be nine positions long. The PACKEVEN keyword on the definition specification can be used to indicate which of the two possible sizes you want when you specify a packed subfield using from and to positions rather than number of digits. The unsigned integer format is like the integer format except that the range of values does not include negative numbers. You should use the unsigned format only when non-negative integer data is expected. You define an unsigned field by specifying U in the Data-Type entry of the appropriate specification. You can also define an unsigned field using the LIKE keyword on the definition specification where the parameter is an unsigned field. The length of an unsigned field is defined in terms of number of digits it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage a 5-digit field takes up 2 bytes of storage a 10-digit field takes up 4 bytes a 20-digit field takes up 8 bytes. The range of values allowed for an unsigned field depends on its length. Field length Range of Allowed Values 3-digit unsigned 0 to 255 5-digit unsigned 0 to 65535 10-digit unsigned 0 to 4294967295 20-digit unsigned 0 to 18446744073709551615 For other considerations regarding the use of unsigned fields, including information on alignment, see Integer Format. Zoned-decimal format means that each byte of storage can contain one digit or one character. In the zoned-decimal format, each byte of storage is divided into two portions: a 4-bit zone portion and a 4-bit digit portion. The zoned-decimal format looks like this: The zone portion of the low-order byte indicates the sign (positive or negative) of the decimal number. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. In zoned-decimal format, each digit in a decimal number includes a zone portion however, only the low-order zone portion serves as the sign. Figure 89 shows what the number 21544 looks like in zoned-decimal format. You must consider the change in field length when coding the end position in positions 40 through 43 of the Output specifications and the field is to be output in packed format. To find the length of the field after it has been packed, use the following formula: You can specify an alternative sign format for zoned-decimal format. In the alternative sign format, the numeric field is immediately preceded or followed by a or - sign. A plus sign is a hexadecimal 4E, and a minus sign is a hexadecimal 60. When an alternative sign format is specified, the field length (specified on the input specification) must include an additional position for the sign. For example, if a field is 5 digits long and the alternative sign format is specified, a field length of 6 positions must be specified. Keep in mind the following when defining numeric fields: When coding the end position in positions 47 through 51 of the output specifications, be sure to use the external format when calculating the number of bytes to be occupied by the output field. For example, a packed field with 5 digits is stored in 3 bytes, but when output in zoned format, it requires 5 bytes. When output in integer format, it only requires 2 bytes. If you move a character field to a zoned numeric, the sign of the character field is fixed to zoned positive or zoned negative. The zoned portion of the other bytes will be forced to F. However, if the digit portion of one of the bytes in the character field does not contain a valid digit a decimal data error will occur. When numeric fields are written out with no editing, the sign is not printed as a separate character the last digit of the number will include the sign. This can produce surprising results for example, when -625 is written out, the zoned decimal value is XF6F2D5 which appears as 62N. You should specify the integer or unsigned format for fields when: Performance of arithmetic is important With certain arithmetic operations, it may be important that the value used be an integer. Some examples where performance may be improved include array index computations and arguments for the built-in function SUBST. Interacting with routines written in other languages that support an integer data type, such as ILE C. Using fields in file feedback areas that are defined as integer and that may contain values above 9999 or 999999999. Packed, zoned, and binary formats should be specified for fields when: Using values that have implied decimal positions, such currency values Manipulating values having more than 19 digits Ensuring a specific number of digits for a field is important Float format should be specified for fields when: The same variable is needed to hold very small and/or very large values that cannot be represented in packed or zoned values. Note: Overflow is more likely to occur with arithmetic operations performed using the integer or unsigned format, especially when integer arithmetic occurs in free-form expressions. This is because the intermediate results are kept in integer or unsigned format rather than a temporary decimal field of sufficient size. Figure 89 shows what the decimal number 21544 looks like in various formats. Note the following about the representations in the figure. To obtain the numeric value of a positive binary or integer number, unsigned number, add the values of the bits that are on (1), but do not include the sign bit (if present). For an unsigned number, add the values of the bits that are on, including the leftmost bit. The value 21544 cannot be represented in a 2-byte binary field even though it only uses bits in the low-order two bytes. A 2-byte binary field can only hold up to 4 digits, and 21544 has 5 digits. Figure 90 shows the number -21544 in integer format. Date fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all date data. Date constants or variables used in comparisons or assignments do not have to be in the same format or use the same separators. Also, dates used for I/O operations such as input fields, output fields or key fields are also converted (if required) to the necessary format for the operation. The default internal format for date variables is ISO. This default internal format can be overridden globally by the control specification keyword DATFMT and individually by the definition specification keyword DATFMT. The hierarchy used when determining the internal date format and separator for a date field is From the DATFMT keyword specified on the definition specification From the DATFMT keyword specified on the control specification ISO There are three kinds of date data formats, depending on the range of years that can be represented. This leads to the possibility of a date overflow or underflow condition occurring when the result of an operation is a date outside the valid range for the target field. The formats and ranges are as follows: Number of Digits in Year 2 (YMD, DMY, MDY, JUL) Several formats are also supported for fields used by the MOVE, MOVEL, and TEST operations only. This support is provided for compatibility with externally defined values that are already in a 3-digit year format and the 4-digit year LONGJUL format. It also applies to the 2-digit year formats when JOBRUN is specified. JOBRUN should be used when the field which it is describing is known to have the attributes from the job. For instance, a 12-digit numeric result of a TIME operation will be in the job date format. Table 15 lists the valid externally defined date formats that can be used in Factor 1 of a MOVE, MOVEL, and TEST operation. Format (Default Separator) 2-Digit Year Formats Determined at runtime from the DATFMT, or DATSEP job values. 3-Digit Year Formats 2 4-Digit Year Formats JOBRUN is valid only for character or numeric dates with a 2-digit year since the run-time job attribute for DATFMT can only be MDY, YMD, DMY or JUL. Valid values for the century character c are: When coding a date format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code date formats without separators see MOVE (Move). MOVEL (Move Left) and TEST (Test Date/Time/Timestamp). To initialize the Date field to the system date at runtime, specify INZ(SYS) on the definition specification. To initialize the Date field to the job date at runtime, specify INZ(JOB) on the definition specification. SYS or JOB cannot be used with a field that is exported. The Date field can also be initialized to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. Time fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all time data. Time constants or variables used in comparisons or assignments do not have to be in the same format or use the same separators. Also, times used for I/O operations such as input fields, output fields or key fields are also converted (if required) to the necessary format for the operation. The default internal format for time variables is ISO. This default internal format can be overridden globally by the control specification keyword TIMFMT and individually by the definition specification keyword TIMFMT. The hierarchy used when determining the internal time format and separator for a time field is From the TIMFMT keyword specified on the definition specification From the TIMFMT keyword specified on the control specification ISO Table 16 shows the time formats supported and their separators. RPG Format Name When coding a time format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code time formats without separators see MOVE (Move). To initialize the Time field to the system time at runtime, specify INZ(SYS) on the definition specification. SYS cannot be used with a field that is exported. The Time field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. A special value of JOBRUN can be used in Factor 1 of a MOVE, MOVEL or TEST operation. This indicates that the separator of the field being described is based on the run-time job attributes, TIMSEP. Timestamp fields have a predetermined size and format. They can be defined on the definition specification. Timestamp data must be in the format Microseconds (.mmmmmm) are optional for timestamp literals and if not provided will be padded on the right with zeros. Leading zeros are required for all timestamp data. The default initialization value for a timestamp is midnight of January 1, 0001 (0001-01-01-00.00.00.000000). The HIVAL value for a timestamp is 9999-12-31-24.00.00.000000. The LOVAL value for timestamp is 0001-01-01-00.00.00.000000. When coding the timestamp format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify ISO0. For an example of how ISO is used without separators see TEST (Test Date/Time/Timestamp). To initialize the Timestamp field to the system date at runtime, specify INZ(SYS) on the definition specification. SYS cannot be used with a field that is exported. The Timestamp field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. The object data type allows you to define a Java object. You specify the object data type as follows: In position 40, you specify data type O. In the keyword section, you specify the CLASS keyword to indicate the class of the object. Specify JAVA for the environment, and the class name. If the object is the return type of a Java constructor, the class of the returned object is the same as the class of the method so you do not specify the CLASS keyword. Instead, you specify the EXTPROC keyword with environment JAVA, the class name, and procedure name CONSTRUCTOR. An object cannot be based. It also cannot be a subfield of a data structure. If an object is an array or table, it must be loaded at runtime. Pre-run and compile-time arrays and tables of type Object are not allowed. Every object is initialized to NULL, which means that the object is not associated with an instance of its class. To change the contents of an object, you must use method calls. You cannot directly access the storage used by the object. Classes are resolved at runtime. The compiler does not check that a class exists or that it is compatible with other objects. You can use an object field in the following situations: Free-Form Evaluation You can use the EVAL operation to assign one Object item (field or prototyped procedure) to a field of type Object. Free-Form Comparison You can compare one object to another object. You can specify any comparison, but only the following comparisons are meaningful: Equality or inequality with another object. Two objects are equal only if they represent exactly the same object. Two different objects with the same value are not equal. If you want to test for equality of the value of two objects, use the Java equals method as follows: Equality or inequality with NULL. An object is equal to NULL if it is not associated with a particular instance of its class. Free-Form Call Parameter You can code an object as a parameter in a call operation if the parameter in the prototype is an object. Objects are not valid as input or output fields. Assignment validity is not checked. For example, RPG would allow you to assign an object of class Number to an object variable defined with class String. If this was not correct, a Java error would occur when you tried to use the String variable. Basing pointers are used to locate the storage for based variables. The storage is accessed by defining a field, array, or data structure as based on a particular basing pointer variable and setting the basing pointer variable to point to the required storage location. For example, consider the based variable MYFIELD, a character field of length 5, which is based on the pointer PTR1. The based variable does not have a fixed location in storage. You must use a pointer to indicate the current location of the storage for the variable. Suppose that the following is the layout of some area of storage: If we set pointer PTR1 to point to the G, If MYFIELD is now changed by an EVAL statement to HELLO, the storage starting at the J would change: Use the BASED keyword on the definition specification (see BASED(basingpointername) ) to define a basing pointer for a field. Basing pointers have the same scope as the based field. The length of the basing pointer field must be 16 bytes long and must be aligned on a 16 byte boundary. This requirement for boundary alignment can cause a pointer subfield of a data structure not to follow the preceding field directly, and can cause multiple occurrence data structures to have non-contiguous occurrences. For more information on the alignment of subfields, see Aligning Data Structure Subfields. The default initialization value for basing pointers is NULL. Note: When coding basing pointers, you must be sure that you set the pointer to storage that is large enough and of the correct type for the based field. Figure 96 shows some examples of how not to code basing pointers. Note: You can add or subtract an offset from a pointer in an expression, for example EVAL ptr ptr offset. When doing pointer arithmetic be aware that it is your responsibility to ensure that you are still pointing within the storage of the item you are pointing to. In most cases no exception will be issued if you point before or after the item. When subtracting two pointers to determine the offset between them, the pointers must be pointing to the same space, or the same type of storage. For example, you can subtract two pointers in static storage, or two pointers in automatic storage, or two pointers within the same user space. You set or change the location of the based variable by setting or changing the basing pointer in one of the following ways: Initializing with INZ(ADDR(FLD)) where FLD is a non-based variable Assigning the pointer to the result of ADDR(X) where X is any variable Assigning the pointer to the value of another pointer Using ALLOC or REALLOC (see ALLOC (Allocate Storage). REALLOC (Reallocate Storage with New Length). and the WebSphere Development Studio: ILE RPG Programmers Guide for examples) Moving the pointer forward or backward in storage using pointer arithmetic: (offset is the distance in bytes that the pointer is moved)Section Menu Welcome Background to BUGS The BUGS ( B ayesian inference U sing G ibbs S ampling) project is concerned with flexible software for the Bayesian analysis of complex statistical models using Markov chain Monte Carlo (MCMC) methods. The project began in 1989 in the MRC Biostatistics Unit, Cambridge, and led initially to the Classic BUGS program, and then onto the WinBUGS software developed jointly with the Imperial College School of Medicine at St Marys, London. Development is now focussed on the OpenBUGS project. WinBUGS 1.4.3 This site at the MRC Biostatistics Unit is primarily concerned with the stand-alone WinBUGS 1.4.3 package. Features a graphical user interface and on-line monitoring and convergence diagnostics. Over 30000 downloads, and a huge number of applications and links. WinBUGS development site includes facilities to add distributions, functions, and includes add-ons for pharmacokinetic modelling, differential equations, and reversible jump MCMC. Can be called from R with R2WinBUGS . WinBUGS 1.4.3 is a stable version which is recommended for standard use. However many developments are now taking place using OpenBUGS. Note: The preferred reference for citing WinBUGS in scientific papers is: Lunn, D. J. Thomas, A. Best, N. and Spiegelhalter, D. (2000) WinBUGS -- a Bayesian modelling framework: concepts, structure, and extensibility. Statistics and Computing . 10 :325--337. OpenBUGS The OpenBUGS project can be found here . Open-source version of the core BUGS code with a variety of interfaces. Runs under Windows with a very similar graphical interface to WinBUGS. Runs on Linux with a plain-text interface. Can be embedded in R as BRugs . Different architecture from WinBUGS 1.4.3: this means that WinBUGS 1.4 add-ons on the WinBUGS development site will not yet run in OpenBUGS. OpenBUGS is the main development platform and is currently experimental, but will eventually become the standard version. The aim is then to transfer new 1.4 functionality to OpenBUGS. Similar software JAGS (Just Another Gibbs Sampler) by Martyn Plummer is an open source program which was developed independently of the BUGS project. JAGS uses essentially the same model description language, but it has been completely re-written. This runs natively on Windows, Mac, Linux and several other varieties of Unix. Stan is another program for general Bayesian analysis, developed even more recently at Columbia University. It uses a modelling language inspired by BUGS and superficially similar, but it is conceptually different in many ways. NIMBLE can also be used to fit general models written in the BUGS language, and includes the ability to write novel sampling algorithms. Health warning The programs are reasonably easy to use and come with a wide range of examples. There is, however, a need for caution. A knowledge of Bayesian statistics is assumed, including recognition of the potential importance of prior distributions, and MCMC is inherently less robust than analytic statistical methods. There is no in-built protection against misuse. copy2016 MRC Biostatistics Unit. Cambridge Biomedical Campus. Cambridge Institute of Public Health. Forvie Site. Robinson Way. Cambridge CB2 0SR. UK. 01223 330366

No comments:

Post a Comment