Here is a test of another parameterization, a simple piecewise function.


In [1]:
# Routine

# This line configures matplotlib to show figures embedded in the notebook, 
# instead of opening a new window for each figure. More about that later. 
# If you are using an old version of IPython, try using '%pylab inline' instead.
%matplotlib inline
%load_ext snakeviz

import numpy as np
from scipy.optimize import minimize
from scipy.optimize import rosen, differential_evolution
from scipy.special import expit
import matplotlib.pyplot as plt
import scipy

from matplotlib.lines import Line2D

import timeit

import pandas as pd

import plotly.plotly as py
from plotly.graph_objs import *
import plotly.tools as tls

In [2]:
# For test use. This is some random structure.

array12 = np.asarray(np.split(np.random.rand(1,60)[0],12))

In [3]:
# Here is the activation function
# Using sigmoid

def act(x):
    x = np.asarray(x, dtype=float)
    # np.piecewise complexity
    if not x.shape:
        x = np.asarray([x])
        
    return np.piecewise(x, [x<=-1.0, (x>-1.0)&(x<1.0), x>=1.0], [0.0, lambda x: x+1.0, 2.0])

def actp(x):
    x = np.asarray(x, dtype=float)
    # np.piecewise complexity
    if not x.shape:
        x = np.asarray([x])
    return np.piecewise(x, [x<=-1.0,(x>-1.0)&(x<1.0), x>=1.0], [0.0, 1.0, 0.0])

Here comes the density matrix


In [4]:
# Density matrix in the forms that I wrote down on my Neutrino Physics notebook
# x is a real array of 12 arrays.

init = np.array([1.0,0.0,0.0,0.0])

def rho(x,ti,initialCondition):
    
    elem = np.ones(4)
    
    for i in np.linspace(0,3,4):
        elem[i] = np.sum(ti*x[i*3]*act(ti*x[i*3+1] + x[i*3+2]) )
    
    return init + elem

In [5]:
xtest = np.linspace(-5, 5, 10)
#np.piecewise(xtest, [xtest < 0,  0 <= xtest , xtest< 10], [lambda x: -x, 0,lambda x: x])
#[act(i) for i in xtest]
print act(xtest), actp(xtest),act(np.linspace(-5, 5, 10))


[ 0.          0.          0.          0.          0.44444444  1.55555556
  2.          2.          2.          2.        ] [ 0.  0.  0.  0.  1.  1.  0.  0.  0.  0.] [ 0.          0.          0.          0.          0.44444444  1.55555556
  2.          2.          2.          2.        ]

In [6]:
# Hamiltonian of the problem, in terms of four real components

hamil = np.array( [  np.cos(2.0),np.sin(2.0) ] )
print hamil


[-0.41614684  0.90929743]

In [7]:
def rhop(x,ti,initialCondition):
    
    rhoprime = np.zeros(4)
    
    for i in np.linspace(0,3,4):
        rhoprime[i] = np.sum(x[i*3] * (act(ti*x[i*3+1] + x[i*3+2]) ) ) +  np.sum( ti*x[i*3]* (actp(ti*x[i*3+1] + x[i*3+2]) ) * x[i*3+1]  )
        
    return rhoprime

def costi(x,ti,initialCondition):
    
    rhoi = rho(x,ti,initialCondition)
    rhopi = rhop(x,ti,initialCondition)
    
    costTemp = np.zeros(4)
    
    costTemp[0] = ( rhopi[0] - 2.0*rhoi[3]*hamil[1] )**2
    costTemp[1] = ( rhopi[1] + 2.0*rhoi[3]*hamil[1] )**2
    costTemp[2] = ( rhopi[2] - 2.0*rhoi[3]*hamil[0] )**2
    costTemp[3] = ( rhopi[3] + 2.0*rhoi[2]*hamil[0] - hamil[1] * (rhoi[1] - rhoi[0] ) )**2
    
    return np.sum(costTemp)# + 2.0*(rhoi[0]+rhoi[1]-1.0)**2

In [8]:
costi(array12,0,init)


Out[8]:
75.248234503210085

In [9]:
def cost(x,t,initialCondition):
    
    costTotal = map(lambda t: costi(x,t,initialCondition),t)
    
    return 0.5*np.sum(costTotal)

In [10]:
cost(array12,np.array([0,1,2]),init)


Out[10]:
942.33067356593722

In [ ]:

Opt


In [26]:
# with ramdom initial guess. TO make it more viable, I used (-5,5)

#initGuess = np.asarray(np.split(10.0*(np.random.rand(1,60)[0] - 0.5),12))
initGuess = np.split(np.zeros(60),12)
endpoint = 2
tlin = np.linspace(0,endpoint,11)

def costF(x):
    return cost(x,tlin,init)

start = timeit.default_timer()
costvFResult = minimize(costF,initGuess,method="Nelder-Mead",tol=1e-20,options={"maxiter":100000,"maxfev":1000000})
stop = timeit.default_timer()

print stop - start

print costvFResult


8204.57799911
  status: 2
    nfev: 796059
 success: False
     fun: 0.55048662297676554
       x: array([-0.44429739, -0.00212607, -0.22919247,  0.25493155, -0.00370533,
        0.3433715 ,  0.1347531 , -0.12684036,  0.42430059, -0.43595558,
       -0.55826255,  0.20597159, -0.02883053, -0.02197778, -0.19546828,
       -0.21163043, -0.16319202,  0.26262914, -0.02733229,  0.30356311,
        0.0124602 , -0.12825455,  0.08702593,  0.23938438, -0.17535952,
        0.02183636,  0.11126804, -0.29032986, -0.05515277,  0.15178409,
        0.260206  , -0.18296184,  0.1258358 ,  0.04233165,  0.03956137,
        0.07693995,  0.04351908, -0.31694182, -0.03798371,  0.2781894 ,
       -0.29749896, -0.35077587,  0.0607649 ,  0.49677765, -0.0648979 ,
        0.3081725 ,  0.20479714,  0.10042806,  0.066708  , -0.20250059,
       -0.1936218 ,  0.11052159,  0.21896106,  0.14451482, -0.19880874,
        0.11017775, -0.00226545, -0.1397491 , -0.21052389, -0.00143826])
 message: 'Maximum number of iterations has been exceeded.'
     nit: 100000

In [27]:
xresult = costvFResult.x

In [28]:
plttlin=np.linspace(0,endpoint,100)
pltdata11 = np.array([])
for i in plttlin:
    pltdata11 = np.append(pltdata11 ,rho(xresult,i,init)[0] )
    
print pltdata11

plt.figure(figsize=(16,9.36))
plt.ylabel('P')
plt.xlabel('Time')
plt.plot(np.linspace(0,2,10),1-(np.sin(2.0)**2)*(np.sin(0.5*np.linspace(0,2,10)) )**2,"r-")
plt.plot(plttlin,pltdata11,"b4-",label="vac_rho11")
plt.show()
#py.iplot_mpl(plt.gcf(),filename="MMA-rho11-Vac-80-60")


[ 1.          0.99308184  0.98616446  0.97924785  0.972332    0.96541693
  0.95850263  0.9515891   0.94467635  0.93776436  0.93085314  0.9239427
  0.91703302  0.91012412  0.90321599  0.89630863  0.88940204  0.88249622
  0.87559117  0.86868689  0.86178339  0.85488065  0.84797869  0.8410775
  0.83417707  0.82727742  0.82037854  0.81348044  0.8065831   0.79968653
  0.79279074  0.78589571  0.77900146  0.77210797  0.76521526  0.75832332
  0.75143215  0.74454175  0.73765213  0.73076327  0.72387519  0.71698787
  0.71010133  0.70321556  0.69633056  0.68944632  0.68256287  0.67568018
  0.66879826  0.66191711  0.65503674  0.64815714  0.6412783   0.63440024
  0.62752295  0.62064643  0.61377068  0.6068957   0.6000215   0.59314806
  0.5862754   0.5794035   0.57253238  0.56566203  0.55879245  0.55192364
  0.5450556   0.53818833  0.53132184  0.52445611  0.51759116  0.51072697
  0.50386356  0.49700092  0.49013905  0.48327795  0.47641762  0.46955806
  0.46269928  0.45584126  0.44898402  0.44212754  0.43527184  0.42841691
  0.42156275  0.41470936  0.40785674  0.4010049   0.39415382  0.38730352
  0.38045398  0.37360522  0.36675723  0.35991001  0.35306356  0.34621788
  0.33937297  0.33252883  0.32568547  0.31884287]

In [ ]:


In [19]:
# with ramdom initial guess
# %snakeviz

devoendpoint = 3
devotlin = np.linspace(0,devoendpoint,11)

devocostF = lambda x: cost(x,devotlin,init)

bounds=np.zeros([60,2])
for i in range(60):
    bounds[i,0]=-1.0
    bounds[i,1]=1.0
#print bounds

startdevo = timeit.default_timer()
devo = differential_evolution(devocostF,bounds,strategy='best1bin',tol=1e-10,maxiter=10000,polish=True)
stopdevo = timeit.default_timer()

print stopdevo - startdevo

print devo


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-19-4a57520306b7> in <module>()
     14 
     15 startdevo = timeit.default_timer()
---> 16 devo = differential_evolution(devocostF,bounds,strategy='best1bin',tol=1e-10,maxiter=10000,polish=True)
     17 stopdevo = timeit.default_timer()
     18 

/Library/Python/2.7/site-packages/scipy/optimize/_differentialevolution.pyc in differential_evolution(func, bounds, args, strategy, maxiter, popsize, tol, mutation, recombination, seed, callback, disp, polish, init)
    200                                          disp=disp,
    201                                          init=init)
--> 202     return solver.solve()
    203 
    204 

/Library/Python/2.7/site-packages/scipy/optimize/_differentialevolution.pyc in solve(self)
    493                 parameters = self._scale_parameters(trial)
    494 
--> 495                 energy = self.func(parameters, *self.args)
    496                 nfev += 1
    497 

<ipython-input-19-4a57520306b7> in <lambda>(x)
      5 devotlin = np.linspace(0,devoendpoint,11)
      6 
----> 7 devocostF = lambda x: cost(x,devotlin,init)
      8 
      9 bounds=np.zeros([60,2])

<ipython-input-9-d2e557ab8f90> in cost(x, t, initialCondition)
      1 def cost(x,t,initialCondition):
      2 
----> 3     costTotal = map(lambda t: costi(x,t,initialCondition),t)
      4 
      5     return 0.5*np.sum(costTotal)

<ipython-input-9-d2e557ab8f90> in <lambda>(t)
      1 def cost(x,t,initialCondition):
      2 
----> 3     costTotal = map(lambda t: costi(x,t,initialCondition),t)
      4 
      5     return 0.5*np.sum(costTotal)

<ipython-input-7-c4d7c90b3035> in costi(x, ti, initialCondition)
     11 
     12     rhoi = rho(x,ti,initialCondition)
---> 13     rhopi = rhop(x,ti,initialCondition)
     14 
     15     costTemp = np.zeros(4)

<ipython-input-7-c4d7c90b3035> in rhop(x, ti, initialCondition)
      4 
      5     for i in np.linspace(0,3,4):
----> 6         rhoprime[i] = np.sum(x[i*3] * (act(ti*x[i*3+1] + x[i*3+2]) ) ) +  np.sum( ti*x[i*3]* (actp(ti*x[i*3+1] + x[i*3+2]) ) * x[i*3+1]  )
      7 
      8     return rhoprime

KeyboardInterrupt: 

In [ ]:
devoxresult = devo.x

devoplttlin=np.linspace(0,devoendpoint,100)
devopltdata11 = np.array([])
for i in devoplttlin:
    devopltdata11 = np.append(devopltdata11 ,rho(devoxresult,i,init)[0] )
    
print devopltdata11

plt.figure(figsize=(16,9.36))
plt.ylabel('P')
plt.xlabel('Time')
plt.plot(np.linspace(0,2,10),1-(np.sin(2.0)**2)*(np.sin(0.5*np.linspace(0,2,10)) )**2,"r-")
plt.plot(devoplttlin,devopltdata11,"b4-",label="vac_rho11")
plt.show()
#py.iplot_mpl(plt.gcf(),filename="MMA-rho11-Vac-80-60")

In [ ]: