Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. library(tidyverse)
  2. library(plotly)
  3. #library(NlcOptim)
  4. #library(Rsolnp)
  5.  
  6. ## define set curve function ----
  7. outerSolve <- function(x, a){
  8.  
  9. a[1] * (1 - innerSolve(x, a) * (x - 1))
  10.  
  11. }
  12.  
  13. # part of the curve function
  14. innerSolve <- function(x, a){
  15.  
  16. a[2] * x ^ a[3]
  17.  
  18. }
  19.  
  20. # check if constraint is fulfilled
  21. checkConstraint <- function(a){
  22.  
  23. if(Vcon[2] / (1 - innerSolve(xcon[2], a) * (xcon[2] - 1)) <=
  24. Vcon[1] / (1 - innerSolve(xcon[1], a) * (xcon[1] - 1))) {
  25.  
  26. return(TRUE)
  27.  
  28. } else {
  29.  
  30. return(FALSE)
  31. }
  32.  
  33.  
  34. }
  35.  
  36. # create sample data
  37. sampleData <- (function(){
  38.  
  39. # set x range
  40. x = seq(50, 800, 5)
  41.  
  42. # set coefficents
  43. setCoef <- c(80, 0.004, -0.3)
  44.  
  45. # calculate y with some noise and create dataframe
  46. set.seed(123)
  47. tmpDF <- tibble(
  48. x = x,
  49. y = outerSolve(x, setCoef) + rnorm(length(x), 0, 0.02)
  50. )
  51.  
  52. p <- plot_ly(x = ~ x, y = ~ y, data = tmpDF, type = 'scatter', mode = 'markers')
  53.  
  54. return(list(setCoef = setCoef, raw = tmpDF, plot = p))
  55.  
  56. })()
  57.  
  58. # start values for target coefficents
  59. startCoef <- c(max(sampleData$raw$y), 0.0001, -0.1)
  60.  
  61. # curve fitting with nls
  62. refCurveFitting <- (function(){
  63.  
  64. tmpModel = nls(
  65. y ~ outerSolve(x, c(find.a1, find.a2, find.a3)),
  66. data = sampleData$raw,
  67. start = c(
  68. find.a1 = startCoef[1],
  69. find.a2 = startCoef[2],
  70. find.a3 = startCoef[3]
  71. ),
  72. trace = TRUE,
  73. control = nls.control(maxiter = 100)
  74. )
  75.  
  76. return(list(model = tmpModel, gof = tibble(AIC = AIC(refCurveFitting$model),
  77. BIC = BIC(refCurveFitting$model))
  78. )
  79. )
  80.  
  81. })()
  82.  
  83. # set constraint values
  84. Vcon <- c(150, 130)
  85. xcon <- c(50, 300)
  86.  
  87. checkConstraint(sampleData$setCoef)
  88. [1] FALSE
  89.  
  90. minFunction <- function(a){
  91. sampleData$raw %>%
  92. mutate(predicted.y = outerSolve(x, a),
  93. squaredRes = (y - predicted.y) ^ 2
  94. ) %>%
  95. summarise(sum.squaredRes = sum(squaredRes)) %>%
  96. pull(sum.squaredRes)
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement