Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F80654404
optimizer.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Sun, Sep 1, 22:11
Size
2 KB
Mime Type
text/x-python
Expires
Tue, Sep 3, 22:11 (2 d)
Engine
blob
Format
Raw Data
Handle
20416286
Attached To
R7561 SP4E_HW1
optimizer.py
View Options
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 12:31:42 2018
@author: alessia
"""
import
numpy
as
np
import
scipy.optimize
as
sopt
from
mpl_toolkits.mplot3d
import
Axes3D
import
matplotlib.pyplot
as
plt
from
matplotlib
import
cm
from
matplotlib.ticker
import
LinearLocator
,
FormatStrFormatter
import
sys
import
argparse
def
S
(
x
):
x1
=
x
[
0
]
x2
=
x
[
1
]
return
2.
*
(
x1
**
2
)
+
3.
/
2.
*
(
x2
**
2
)
+
x1
*
x2
-
x1
-
2
*
x2
+
6
path
=
[]
def
getIterationSteps
(
x
):
path
.
append
(
x
)
def
plotFunc
(
S
,
path
):
fig
=
plt
.
figure
()
ax
=
fig
.
gca
(
projection
=
'3d'
)
# Plot the surface.
X1
=
np
.
arange
(
-
3
,
3
,
0.01
)
X2
=
np
.
arange
(
-
3
,
3
,
0.01
)
X1
,
X2
=
np
.
meshgrid
(
X1
,
X2
)
X3
=
S
((
X1
,
X2
))
surf
=
ax
.
plot_surface
(
X1
,
X2
,
X3
,
cmap
=
cm
.
coolwarm
,
linewidth
=
0
,
antialiased
=
False
)
#ax.contour(X1, X2, X3, 20, colors='k', linewidths=1)
# Plot the path.
path
=
np
.
array
(
path
)
x1
=
path
[:,
0
]
x2
=
path
[:,
1
]
x3
=
S
((
x1
,
x2
))
ax
.
plot
(
x1
,
x2
,
x3
,
'--ko'
)
plt
.
xlabel
(
'x'
)
plt
.
ylabel
(
'y'
)
ax
.
view_init
(
45
,
140
)
fig
.
colorbar
(
surf
,
shrink
=
0.5
,
aspect
=
5
)
plt
.
show
()
#-------------------------------------------------------------------------------------------------------------------
if
__name__
==
'__main__'
:
parser
=
argparse
.
ArgumentParser
(
description
=
"optimizer.py finds the minimum of a given function with different methods"
)
group
=
parser
.
add_mutually_exclusive_group
()
group
.
add_argument
(
"-BFGS"
,
"--BFGS"
,
action
=
"store_true"
,
help
=
"minimize with BFGS method"
)
group
.
add_argument
(
"-CG"
,
"--CG"
,
action
=
"store_true"
,
help
=
"minimize with Conjugate Gradient method"
)
args
=
parser
.
parse_args
()
if
args
.
BFGS
:
min_method
=
'BFGS'
if
args
.
CG
:
min_method
=
'CG'
else
:
sys
.
stderr
.
write
(
"Choose a minimization method between BFGS and CG"
)
x
=
(
np
.
random
.
rand
(
2
)
+
2
)
path
.
append
(
x
)
minimum
=
sopt
.
minimize
(
S
,
x
,
method
=
min_method
,
tol
=
1e-14
,
callback
=
getIterationSteps
)
plotFunc
(
S
,
path
)
Event Timeline
Log In to Comment