R/tst.model.R

Defines functions tst.model

#' Generating a tst.models
#' 
#' Generate an tst model from a text file and an eventual database. The
#' function generates the model and checks it.
#' 
#' The left hand side (LHS) of an equation should contain only one variable
#' which is considered as endogenous. If the right hand side (RHS) part of the
#' equation contains only a number, this number is set as the initial value
#' (resp. fixed value) for endogenous (resp. exogenous) variable contained in
#' the LHS part of the equation. Each equation might preceded by a description
#' of the equation. The timeline of the model is specified with the reserved
#' keyword 'timeline' and two dates separated by spaces.  #Disposable income yd
#' = w*n - t timeline 1945 2010 The format of the data file (respecting csv
#' format, 'white space' separator and "." decimal) is as follows: Names of
#' each variable should be in the first line, years in the first column.
#' 
#' @param fileName The path to the filename containing the equations. See
#' details hereunder for a description of the format of the text file
#' @param dataFile Optional. The path to the file containing the values for the
#' variables (endogenous) and (exogenous) of the model. See details hereunder
#' for a description of the format of the data file
#' @param modelName Optional, default="tst.model". Specifies the name of the
#' model.
#' @param fill Optional, default FALSE. Wether the check of the model offers to
#' fill the lacks found in the model. See tst.check for more details.
#' @return An object of the class "tst" representing a model
#' @note %% ~~further notes~~
#' @author Adam Elderfield
#' @seealso %% ~~objects to See Also as \code{\link{help}}, ~~~
#' @references %% here is where the references go
#' @keywords ~kwd1 ~kwd2
#' 

tst.model <-function(fileName,dataFile=NA,modelName="tst.model",fill=F,
                     smpl = NA){
  
  ## FOR TESTING PURPOSES - delete later
   #directory <- getwd()
   #mymod <- paste0(directory,"/","test",".txt")
   #fileName <-mymod 
   #model<-tst.create("a")
   #dataFile <- dat
   #data <- dataFile[dataFile$Date>="2019-03-01",]
   #smpl = "2019-03-01 2025-06-01 quarter"
  
  if(!is.na(smpl)){ # create start sample if present
    
    SimuStart <- substr(smpl, start = 1, stop = 10)

  }
  
  options(warn=-1) # Supress warnings
  
  model<-tst.create(modelName)  # Create empty model
   
  if(!is.na(dataFile)){
    
    data <- dataFile[which(dataFile$Date == SimuStart)-1,] # Find the last historical data point
    
    variablesName <- names(data)
    
    for(i in 2:length(data[i,])){
      
      model<-tst.addVar(model,var=variablesName[i],init=as.numeric(data[1,i]),desc="") 
      
    }
    
    model<-tst.setDate(model,as.Date(data[1,1]),as.Date(data[length(data[,1]),1]), f =  "quarter")
  }
  
  options(warn=-1)
  
  modelFile <- file(fileName)  # Open the textfile that contains the model
  
  modelText <- readLines(modelFile, n = -1) # Read the text file
  
  close(modelFile) # Close file
  
  firstEquation=TRUE
  
  # This loop goes through eah line of the model text and fills parts of the model list 
  for (i in 1:length(modelText)) {
  
    lineText = modelText[i]  # line i
    
    lineText <- sub("#.*", "", lineText) ## Remove any comments
    
    if (!grepl("^[[:blank:]]*$", lineText)) { ## If line has text in it, then execute loop
      
      if(grepl("timeline", lineText)){
        
        myTable = strsplit(lineText, " ")
        
        startDate=myTable[[1]][2]
        
        endDate=myTable[[1]][3]
        
        freq = myTable[[1]][4]
            
        model<-tst.setDate(model,startDate,endDate, freq)
        
      }else{
      
        # This section works with the model equations
        myTable = strsplit(lineText, "=") # Splits string, before and after =
        
      #This is to manage the case when there are other = in the equation (use of logical operators)
        if(length(myTable[[1]])>2){
          
          tempStr<-myTable[[1]][2]
          
          for(iter in 3:length(myTable[[1]])){
            
            tempStr<-paste(tempStr,myTable[[1]][3],sep="=")
            
            myTable[[1]]=myTable[[1]][-3]
          }
          myTable[[1]][2]=tempStr
        }
        
        #Replacing all reseverved words, for now only in-> inv
        nameEnd = myTable[[1]][1]  # the endogenous variable name (LHS of the =)
        
        equation = myTable[[1]][2] # the equation (RHS of the =)
        
        equation<-trim(equation) # remove white space
        
        value<-as.double(equation) # check equation is not a parameter
        
        # This loop works with the paremterts
        if(!is.na(value)){
          
          nameEndSearch = gsub("\\bin\\b","inv",nameEnd)
          
          nameEndSearch<-trim(nameEndSearch)
          
          indEnd<-tst.getIndex(model,end=nameEndSearch) # finds the index of the variable in th model, returns negative 1, if not endogenour
          
          if(indEnd>0){
            
            model<-tst.editEnd(model,ind=indEnd,init=value)
          
            }else{
            
              indVar<-tst.getIndex(model,var=nameEndSearch) # Finds index for variable in the model
            
              if(indVar>0){
              
                model<-tst.editVar(model,ind=indVar,init=value)
            
                }else{
              
                  if(grepl("#",modelText[i-1])){
                
                    display=substring(modelText[i-1],2)
              
                    }else{
                
                      display=""
              
                      }			
              
                  model<-tst.addVar(model,var=nameEnd,init=value,desc=display)
            
                  }
          }
          
        }else{
          
          if(grepl("#",modelText[i-1])){
            
            displayEquation=substring(modelText[i-1],2)
            
          }else{
            
            displayEquation=""
          }
          
          model<-tst.addEqu(model,nameEnd,equation,displayEquation) # Adds equation to the model
        }
      } # Back to the check if it has text in linetext
    }
  }
  
  options(warn=0)

  model<-tst.check(model,fill=fill)
  
  model$dat <- dataFile
  
  return(model)
}
AdamElderfield/tst_package documentation built on Dec. 5, 2019, 2:08 a.m.