Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(tidyverse)
- library(plotly)
- #library(NlcOptim)
- #library(Rsolnp)
- ## define set curve function ----
- outerSolve <- function(x, a){
- a[1] * (1 - innerSolve(x, a) * (x - 1))
- }
- # part of the curve function
- innerSolve <- function(x, a){
- a[2] * x ^ a[3]
- }
- # check if constraint is fulfilled
- checkConstraint <- function(a){
- if(Vcon[2] / (1 - innerSolve(xcon[2], a) * (xcon[2] - 1)) <=
- Vcon[1] / (1 - innerSolve(xcon[1], a) * (xcon[1] - 1))) {
- return(TRUE)
- } else {
- return(FALSE)
- }
- }
- # create sample data
- sampleData <- (function(){
- # set x range
- x = seq(50, 800, 5)
- # set coefficents
- setCoef <- c(80, 0.004, -0.3)
- # calculate y with some noise and create dataframe
- set.seed(123)
- tmpDF <- tibble(
- x = x,
- y = outerSolve(x, setCoef) + rnorm(length(x), 0, 0.02)
- )
- p <- plot_ly(x = ~ x, y = ~ y, data = tmpDF, type = 'scatter', mode = 'markers')
- return(list(setCoef = setCoef, raw = tmpDF, plot = p))
- })()
- # start values for target coefficents
- startCoef <- c(max(sampleData$raw$y), 0.0001, -0.1)
- # curve fitting with nls
- refCurveFitting <- (function(){
- tmpModel = nls(
- y ~ outerSolve(x, c(find.a1, find.a2, find.a3)),
- data = sampleData$raw,
- start = c(
- find.a1 = startCoef[1],
- find.a2 = startCoef[2],
- find.a3 = startCoef[3]
- ),
- trace = TRUE,
- control = nls.control(maxiter = 100)
- )
- return(list(model = tmpModel, gof = tibble(AIC = AIC(refCurveFitting$model),
- BIC = BIC(refCurveFitting$model))
- )
- )
- })()
- # set constraint values
- Vcon <- c(150, 130)
- xcon <- c(50, 300)
- checkConstraint(sampleData$setCoef)
- [1] FALSE
- minFunction <- function(a){
- sampleData$raw %>%
- mutate(predicted.y = outerSolve(x, a),
- squaredRes = (y - predicted.y) ^ 2
- ) %>%
- summarise(sum.squaredRes = sum(squaredRes)) %>%
- pull(sum.squaredRes)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement