title: Using optim to find minimization while also forcing the parameters to sum to 1
body: <p>I am trying to use R and optim to calculate mixing proportions. So, for example, let's say I have a rock composition, 60% SiO2 and 40% CaO. I want to know how much of two different phases I have to mix to produce my rock. Let's say phase2 is 35% SiO2 and 65% CaO and Phase2 80% SiO2 and 20% CaO.</p>
  
  <p>***Edits: I have updated the code to include a 3rd phase, and my attempt at using compositions package.I also have attempted to set bounds on the optim search range.</p>
  
  <pre><code>#Telling R the composition of both phases and the target rock
  
  library(compositions)
  
  Phase1 &lt;- c(35, 65)
  Phase2 &lt;- c(80, 20)
  Phase3 &lt;- c(10, 90)
  Target_Composition &lt;- c(60, 40)
  
  #My function to minimize
  my.function &lt;- function(n){
      n &lt;- clo(n) #I though this would make 1 = n[1] + n[2] + n[3]
      (Target_Composition[1] - (n[1]*Phase1[1] + n[2]*Phase2[1] + n[3]*Phase3[1]))^2 + 
      (Target_Composition[2] - (n[1]*Phase1[2] + n[2]*Phase2[2] + n[3]*Phase3[2]))^2 
  }
  </code></pre>
  
  <p>I then run this in optim using:</p>
  
  <pre><code>optim(c(.54,.46), my.function)
  </code></pre>
  
  <p>When I run this, I get 0.536 and 0.487, which is indeed a minimum, but, I neeed to set an additional parameter that n[1] + n[2] = 1 . Is there anyway to do this using optim? That's what's puzzling me. As a side note, the actual problem I want to solve has many more phases and each phase is more complicated, but, I will scale up once I get this part working.</p>
  
  <p>I now use:</p>
  
  <pre><code>optim(c(.5, .4, .1), my.function, lower=0, upper=1, method="L-BFGS-B")
  </code></pre>
  
  <p>I now get 0.4434595, 0.4986680, and 0.2371141 as results, which do not sum to 1. How can I fix this? Also, Is my new method of setting the search range between 0 and 1 going to work?</p>
  
  <p>Thanks for your help.</p>