├── Screenshot from 2024-09-12 14-25-22.png
├── Screenshot from 2024-09-12 14-26-29.png
├── Non-Linear Optimization [Python]
├── docs
│ ├── error.png
│ ├── gradient.png
│ └── results
└── src
│ ├── steepest_descent.py
│ ├── newton.py
│ ├── conjugate_gradient.py
│ ├── quasi_newton.py
│ ├── line_search.py
│ └── rosenbrock.py
├── QuadraticEstimationMethod.py
├── GradientDecentMethod.m
├── ExhaustiveSearchMethod.py
├── GoldenSectionSearchMethod.py
├── QuadraticEstimationMethod.m
├── IntervalHalvingMethod.py
├── FibonacciSearchMethod.py
├── BisectionMethod.py
├── NewtonRaphsonMethod.py
├── SecantMethod.py
├── ExhaustiveSearchMethod.m
├── GoldenSectionSearchMethod.m
├── BisectionMethod.m
├── BoundingPhaseMethod.py
├── IntervalHalvingMethod.m
├── NewtonRaphsonMethod.m
├── SuccessiveQuadraticEstimationMethod.py
├── fibonacci_search_method.m
├── SuccessiveQuadraticEstimationMethod.m
├── BoundingPhaseMethod.m
├── CubicSearchMethod.py
├── CubicSearchMethod.m
├── README.md
├── LICENSE
└── KKT_optimization
├── infill-dphi-focus.ipynb
└── .ipynb_checkpoints
└── infill-dphi-focus-checkpoint.ipynb
/Screenshot from 2024-09-12 14-25-22.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Soumyabrata111/Optimization-Techniques/HEAD/Screenshot from 2024-09-12 14-25-22.png
--------------------------------------------------------------------------------
/Screenshot from 2024-09-12 14-26-29.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Soumyabrata111/Optimization-Techniques/HEAD/Screenshot from 2024-09-12 14-26-29.png
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/docs/error.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Soumyabrata111/Optimization-Techniques/HEAD/Non-Linear Optimization [Python]/docs/error.png
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/docs/gradient.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Soumyabrata111/Optimization-Techniques/HEAD/Non-Linear Optimization [Python]/docs/gradient.png
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/docs/results:
--------------------------------------------------------------------------------
1 | Method Iterations Result
2 | CG 11 (0.9995053, 0.9990086)
3 | Newton 14 (1.0000000, 1.0000000)
4 | Quasi Newton 21 (1.0000000, 1.0000000)
5 |
6 |
--------------------------------------------------------------------------------
/QuadraticEstimationMethod.py:
--------------------------------------------------------------------------------
1 | # Quadratic Estimation Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 |
6 | a=1 #Lower bound
7 | b=5 #Upper bound
8 | c=(a+b)/2 # Mid point of the search space
9 |
10 | # Equation to be minimized
11 | def f(x):
12 | return 2*x**2+16/x
13 |
14 | x=np.linspace(a,b,1000)
15 |
16 | a0=f(a)
17 | a1=(f(b)-f(a))/(b-a)
18 | a2=(1/(c-b))*(((f(c)-f(a))/(c-a))-((f(b)-f(a))/(b-a)))
19 |
20 | # Approximate point for minimum function value
21 | x_bar=(a+b)/2-(a1/(2*a2))
22 |
23 | # Approximate minimum function value
24 | f_bar=f(x_bar)
25 |
26 | print(f"The approximate minimum function value is {f_bar}, and it is located at {x_bar}")
27 |
28 | # Plot the function
29 | plt.plot(x,f(x))
30 | plt.xlabel("x",fontweight='bold')
31 | plt.ylabel("f(x)",fontweight='bold')
32 | plt.grid(which='major',axis='both',linestyle='dashed')
33 | plt.title('Exhaustive Search Method',fontweight='bold')
34 | plt.scatter(x_bar,f_bar, color='red', label='Approximate Minimum Point')
35 | plt.legend()
36 | plt.savefig('Quadratic Estimation Method.png',dpi=300)
37 | plt.show()
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/src/steepest_descent.py:
--------------------------------------------------------------------------------
1 | '''
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | '''
15 | from numpy import *
16 | from line_search import find_step_length
17 |
18 | def steepest_descent(f, fd, x, max_iterations, precision, callback):
19 | for i in range(0, max_iterations):
20 | direction = - fd(x)
21 | alpha = find_step_length(f, fd, x, 1.0, direction, c2=0.9)
22 | x = x + alpha*direction
23 | callback(i, direction, alpha, x)
24 | if linalg.norm(direction) < precision:
25 | break
26 | return x
27 |
--------------------------------------------------------------------------------
/GradientDecentMethod.m:
--------------------------------------------------------------------------------
1 | % Gradient (Steepest) DEcent Method as Explained in https://www.youtube.com/watch?v=x7YMV5xcMc8
2 | % Matlab version R2018b
3 | % Date: 22nd October, 2018
4 | clc
5 | clear
6 | %% Taking thefunction as input from user
7 | sc = inputdlg('Type an expression that is a function of x & y ' ); % Taking the equation as input from the user
8 | s = sc{:}; % Function String
9 | f = str2func(['@(x,y) ' s])
10 | x = input ('Enter the initial guess of x: ');
11 | y = input ('Enter the initial guess of y: ');
12 | a = input ('Enter the learning rate: ');
13 | %% Starting the algorithm
14 | for i=1:100000
15 | z = feval (f,x,y);
16 | x1 = x + .000001 * x;
17 | y1 = y + .000001 * y;
18 | zx = feval (f,x1,y);
19 | zy = feval(f,x,y1);
20 | del_fx = (zx-z)/(.000001*x); % The partial derivative w.r.t x at the chosen point of the user
21 | del_fy = (zy-z)/(.000001*y); % The partial derivative w.r.t y at the chosen point of the user
22 | x_new = x - a*del_fx;
23 | y_new = y - a*del_fy;
24 | x = x_new;
25 | y = y_new;
26 | end
27 | fprintf('The minimum values of the variables x & y are respectively: %f & %f \n',x,y);
28 |
--------------------------------------------------------------------------------
/ExhaustiveSearchMethod.py:
--------------------------------------------------------------------------------
1 | # Exhaustive Search Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 |
6 | a=0.1 #Lower bound
7 | b=14 #Upper bound
8 | n = 1000 #Number of divisions
9 | dx=(b-a)/n #Length of each division
10 |
11 | # Equation to be minimized
12 | def f(x):
13 | return x**2+54/x
14 |
15 | # Initialization
16 | x1=a
17 | x2=x1+dx
18 | x3=x2+dx
19 | x_min=x2
20 | f_min =f(x_min)
21 |
22 | while x3<=b:
23 | if f(x2)<=f(x1) and f(x2)<=f(x3):
24 | print('The approx minimum point is: '+str(x2))
25 | print('The approx minimum function value is: '+str(f(x2)))
26 | x_min=x2
27 | f_min=f(x_min)
28 |
29 | x1=x2
30 | x2=x1+dx
31 | x3=x2+dx
32 |
33 | # Store the points to where the function is to be evaluated
34 | x = np.linspace(a,b,n)
35 |
36 | # Plot the function
37 | plt.plot(x,f(x))
38 | plt.xlabel("x",fontweight='bold')
39 | plt.ylabel("f(x)",fontweight='bold')
40 | plt.grid(which='major',axis='both',linestyle='dashed')
41 | plt.title('Exhaustive Search Method',fontweight='bold')
42 | plt.scatter(x_min,f_min, color='red', label='Minimum Point')
43 | plt.legend()
44 | plt.savefig('Exhaustive Search Method.png',dpi=300)
45 | plt.show()
--------------------------------------------------------------------------------
/GoldenSectionSearchMethod.py:
--------------------------------------------------------------------------------
1 | # Golden Section Search Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | a = 0.1 # Lower bound
6 | b = 14 # Upper bound
7 | eps = 1e-8 # Desired accuracy
8 | gr = (1 + 5 ** 0.5) / 2 # Golden Ratio
9 |
10 | def f(x):
11 | return x ** 2 + 54 / x
12 |
13 | x = np.linspace(a,b,1000)
14 |
15 | # Initialization
16 | x1 = a + (b - a) / gr
17 | x2 = b - (b - a) / gr
18 |
19 | while abs(b - a) > eps:
20 | f1 = f(x1)
21 | f2 = f(x2)
22 | if f1 > f2:
23 | b = x2
24 | x2 = x1
25 | x1 = a + (b - a) / gr
26 | else:
27 | a = x1
28 | x1 = x2
29 | x2 = b - (b - a) / gr
30 | x_min = (a+b)/2
31 | f_min = f(x_min)
32 | print (f"The approximate minimum point and the value respectively are: {x_min} and {f_min}")
33 |
34 |
35 | # Plot the function
36 | plt.plot(x,f(x))
37 | plt.xlabel("x",fontweight='bold')
38 | plt.ylabel("f(x)",fontweight='bold')
39 | plt.grid(which='major',axis='both',linestyle='dashed')
40 | plt.title('Golden Section Search Method',fontweight='bold')
41 | plt.scatter(x_min,f_min, color='red', label='Minimum Point')
42 | plt.legend()
43 | plt.savefig('Golden Section Search Method.png',dpi=300)
44 | plt.show()
45 |
--------------------------------------------------------------------------------
/QuadraticEstimationMethod.m:
--------------------------------------------------------------------------------
1 | % Quadratic Estimation Method
2 |
3 | clear all
4 | clc
5 |
6 | a = 1; % Lower bound
7 | b = 5; % Upper bound
8 | c=(a+b)/2; % Mid point of the search space
9 |
10 | % Function to be minimized
11 | f = @(x) 2*x.^2 + 16./x;
12 |
13 | x_values=linspace(a,b,1000);
14 | y_values=f(x_values);
15 |
16 | a0=f(a);
17 | a1=(f(b)-f(a))/(b-a);
18 | a2=(1/(c-b))*(((f(c)-f(a))/(c-a))-((f(b)-f(a))/(b-a)));
19 |
20 | % Approximate point for minimum function value
21 | x_bar=(a+b)/2-(a1/(2*a2));
22 |
23 | % Approximate minimum function value
24 | f_bar=f(x_bar);
25 |
26 | fprintf("The approximate minimum function value is %f, and it is located at %f",f_bar,x_bar)
27 |
28 | % Plot the function
29 | figure;
30 | plot(x_values, y_values);
31 | xlabel('x', 'fontweight', 'bold');
32 | ylabel('f(x)', 'fontweight', 'bold');
33 | grid on;
34 | title('Quadratic Estimation Method', 'fontweight', 'bold');
35 | hold on;
36 | scatter(x_bar, f_bar, 'red', 'filled');
37 | legend(func2str(f), 'Approximate Minimum Point');
38 |
39 | % Set x-axis ticks to be whole numbers
40 | xticks(a:b);
41 |
42 | % Adjust x-axis limits
43 | ax = gca;
44 | ax.XLim = [a b]; % Update here
45 |
46 | saveas(gcf, 'Quadratic_Estimation_Method.png', 'png');
47 |
--------------------------------------------------------------------------------
/IntervalHalvingMethod.py:
--------------------------------------------------------------------------------
1 | # Interval Halving Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | a = 0.1 # Lower bound
6 | b = 14 # Upper bound
7 | eps = 1e-5 # Desired accuracy
8 |
9 | # Function to minimize
10 | def f(x):
11 | return x**2+54/x
12 |
13 | # Initialization
14 | xm = (a+b)/2 # Mid point
15 | L = b - a # Length of search space
16 | x1 = a + L/4 # Left intermediary point
17 | x2 = b - L/4 # Right intermediary point
18 |
19 | f1 = f(x1)
20 | f2 = f(x2)
21 | fm = f(xm)
22 | x = np.linspace(a,b,1000)
23 |
24 |
25 | while abs(L)>eps:
26 | if f1.
14 | '''
15 | from numpy import *
16 | from line_search import find_step_length
17 |
18 | def newton(f, fd, fdd, x, max_iterations, precision, callback):
19 | for i in range(1, max_iterations):
20 | gradient = fd(x)
21 | hessian = fdd(x)
22 |
23 | direction = -linalg.solve(hessian, gradient)
24 | alpha = find_step_length(f, fd, x, 1.0, direction, c2=0.9)
25 | x_prev = x
26 | x = x + alpha*direction
27 |
28 | callback(i, direction, alpha, x)
29 |
30 | if linalg.norm(x - x_prev) < precision:
31 | break
32 | return x
33 |
--------------------------------------------------------------------------------
/FibonacciSearchMethod.py:
--------------------------------------------------------------------------------
1 | # Fibonacci Search Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 |
6 | a=0.1 #Lower bound
7 | b=14 #Upper bound
8 | n = 2000 #Number of times function is to be evaluated
9 |
10 | # Function to calculate n-th Fibonacci number
11 | def F(n):
12 | fi = []
13 | fi.append(0)
14 | fi.append(1)
15 |
16 | for i in range(2, n+1):
17 | fi.append(fi[i-1] + fi[i-2])
18 | return fi[n]
19 |
20 | # Function to be minimized
21 | def f(x):
22 | return x**2+54/x
23 |
24 | # Initialization
25 | k=2
26 | L=b-a # Length of search space
27 | L_ks=(F(n-k+1)/F(n+1))*L
28 | x1=a+L_ks
29 | x2=b-L_ks
30 | f1=f(x1)
31 | f2=f(x2)
32 | x=np.linspace(a,b,1000)
33 |
34 | while k<=n:
35 | if f20.01:
19 | return 0.01*abs(x)
20 | else:
21 | return 0.0001
22 |
23 | # Function to calculate first derivative of the function
24 | def fdx(x):
25 | return ((f(x+dx(x))-f(x-dx(x)))/(2*dx(x)))
26 |
27 | x1=a # Beginning of search space
28 | x2=b # End of search space
29 | z=0.5*(x1+x2) # Mid-point of the search space
30 |
31 | # Initialization
32 | fx1=f(x1)
33 | fx2=f(x2)
34 | fz=f(z)
35 | fdz=fdx(z)
36 |
37 | while abs(fdz)>eps:
38 | if fdz<0:
39 | x1=z
40 | elif fdz>0:
41 | x2=z
42 | z=0.5*(x1+x2)
43 | fx1=f(x1)
44 | fx2=f(x2)
45 | fz=f(z)
46 | fdz=fdx(z)
47 |
48 | print (f"The approximate minimum point and the value respectively are: {z} and {fz}")
49 |
50 | # Plot the function
51 | plt.plot(x_p,f(x_p))
52 | plt.xlabel("x",fontweight='bold')
53 | plt.ylabel("f(x)",fontweight='bold')
54 | plt.grid(which='major',axis='both',linestyle='dashed')
55 | plt.title('Bisection Method',fontweight='bold')
56 | plt.scatter(z,fz, color='red', label='Approximate Minimum Point')
57 | plt.legend()
58 | plt.savefig('Bisection Method.png',dpi=300)
59 | plt.show()
--------------------------------------------------------------------------------
/NewtonRaphsonMethod.py:
--------------------------------------------------------------------------------
1 | # Newton-Raphson Method
2 |
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 |
6 | a = 0.1 # Lower bound
7 | b = 15 # Upper bound
8 |
9 | x_p = np.linspace(a,b,1000) # points for plotting the function
10 |
11 | # Function to minimize
12 | def f(x):
13 | return x**2+54/x
14 |
15 | # Function to determine the value of 'dx'
16 | def dx(x):
17 | if abs(x)>0.01:
18 | return 0.01*abs(x)
19 | else:
20 | return 0.0001
21 |
22 | # Function to calculate first derivative of the function
23 | def fdx(x):
24 | return ((f(x+dx(x))-f(x-dx(x)))/(2*dx(x)))
25 |
26 | # Function to calculate second derivative of the function
27 | def fddx(x):
28 | return ((f(x+dx(x))-2*f(x)+f(x-dx(x)))/((dx(x))**2))
29 |
30 | # Initialization
31 | x=a # Initial guess
32 | eps=1e-5 # Small number to check convergency
33 | k=1 # Counter
34 | max_iterations = 1000 # Maximum number of iterations
35 |
36 | xn = x-(fdx(x)/fddx(x))
37 | fn = f(xn)
38 |
39 | while fn>eps and k <= max_iterations:
40 | k=k+1
41 | x = xn
42 | xn = x-(fdx(x)/fddx(x))
43 | fn = f(xn)
44 | print (f"The approximate minimum point and the value respectively are: {xn} and {fn}")
45 |
46 | # Plot the function
47 | plt.plot(x_p,f(x_p))
48 | plt.xlabel("x",fontweight='bold')
49 | plt.ylabel("f(x)",fontweight='bold')
50 | plt.grid(which='major',axis='both',linestyle='dashed')
51 | plt.title('Newton-Raphson Method',fontweight='bold')
52 | plt.scatter(xn,fn, color='red', label='Approximate Minimum Point')
53 | plt.legend()
54 | plt.savefig('Newton-Raphson Method.png',dpi=300)
55 | plt.show()
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/src/conjugate_gradient.py:
--------------------------------------------------------------------------------
1 | '''
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | '''
15 | from numpy import *
16 | from line_search import find_step_length
17 |
18 | def conjugate_gradient(f, fd, x, max_iterations, precision, callback):
19 | direction = -fd(x)
20 | gradient = None
21 | gradient_next = matrix(fd(x)).T
22 | x_prev = None
23 |
24 | for i in range(1, max_iterations):
25 | alpha = find_step_length(f, fd, x, 1.0, direction, c2=0.1)
26 | x_prev = x
27 | x = x + alpha*direction
28 |
29 | callback(i, direction, alpha, x)
30 |
31 | gradient = gradient_next
32 | gradient_next = matrix(fd(x)).T
33 |
34 | if linalg.norm(x - x_prev) < precision:
35 | break
36 |
37 | BFR = (gradient_next.T * gradient_next) / (gradient.T * gradient)
38 | BFR = squeeze(asarray(BFR))
39 |
40 | direction = -squeeze(asarray(gradient_next)) + BFR*direction
41 | return x
42 |
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/src/quasi_newton.py:
--------------------------------------------------------------------------------
1 | '''
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | '''
15 | from numpy import *
16 | from line_search import find_step_length
17 |
18 | def quasi_newton(f, fd, x, max_iterations, precision, callback):
19 | I = identity(x.size)
20 | H = I
21 | x_prev = x
22 | f_prev = f
23 | fd_prev = fd
24 |
25 | for i in range(1, max_iterations):
26 | gradient = fd(x)
27 | direction = -H * matrix(gradient).T
28 | direction = squeeze(asarray(direction))
29 |
30 | alpha = find_step_length(f, fd, x, 1.0, direction, c2=0.9)
31 | x_prev = x
32 | x = x + alpha*direction
33 |
34 | callback(i, direction, alpha, x)
35 |
36 | if linalg.norm(x - x_prev) < precision:
37 | break
38 |
39 | s = matrix(x - x_prev).T
40 | y = matrix(fd(x) - fd(x_prev)).T
41 | rho = float(1 / (y.T*s))
42 | H = (I - rho*s*y.T)*H*(I - rho*y*s.T) + rho*s*s.T
43 | return x
44 |
--------------------------------------------------------------------------------
/SecantMethod.py:
--------------------------------------------------------------------------------
1 | # Secant Method
2 |
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 |
6 | a = 0.1 # Lower bound
7 | b = 15 # Upper bound
8 | eps=1e-3 # Small number
9 |
10 | x_p = np.linspace(a,b,1000) # points for plotting the function
11 |
12 | # Function to minimize
13 | def f(x):
14 | return x**2+54/x
15 |
16 | # Function to determine the value of 'dx'
17 | def dx(x):
18 | if abs(x)>0.01:
19 | return 0.01*abs(x)
20 | else:
21 | return 0.0001
22 |
23 | # Function to calculate first derivative of the function
24 | def fdx(x):
25 | return ((f(x+dx(x))-f(x-dx(x)))/(2*dx(x)))
26 |
27 | x1=a # Beginning of search space
28 | x2=b # End of search space
29 | z=x2-(fdx(x2))/((fdx(x2)-fdx(x1))/(x2-x1)) # Mid-point of the search space
30 |
31 | # Initialization
32 | fx1=f(x1)
33 | fx2=f(x2)
34 | fz=f(z)
35 | fdz=fdx(z)
36 |
37 | while abs(fdz)>eps:
38 | if fdz<0:
39 | x1=z
40 | elif fdz>0:
41 | x2=z
42 | z=z=x2-(fdx(x2))/((fdx(x2)-fdx(x1))/(x2-x1))
43 | fx1=f(x1)
44 | fx2=f(x2)
45 | fz=f(z)
46 | fdz=fdx(z)
47 |
48 | print (f"The approximate minimum point and the value respectively are: {z} and {fz}")
49 |
50 | # Plot the function
51 | plt.plot(x_p,f(x_p))
52 | plt.xlabel("x",fontweight='bold')
53 | plt.ylabel("f(x)",fontweight='bold')
54 | plt.grid(which='major',axis='both',linestyle='dashed')
55 | plt.title('Secant Method',fontweight='bold')
56 | plt.scatter(z,fz, color='red', label='Approximate Minimum Point')
57 | plt.legend()
58 | plt.savefig('Secant Method.png',dpi=300)
59 | plt.show()
--------------------------------------------------------------------------------
/ExhaustiveSearchMethod.m:
--------------------------------------------------------------------------------
1 | % Exhaustive Search Method as Explained in the book
2 | %"Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2022b
5 | % Date: 14th October, 2018
6 | % Date: 25th October, 2023 (Updated)
7 | % Date: 27th October, 2023 (Updated)
8 |
9 | clear all
10 | clc
11 | a=0.1; %Lower bound
12 | b=14; % Upper bound
13 | n = 1000; %Number of divisions
14 | dx=(b-a)/n; %Length of each division
15 |
16 | % Equation to be minimized
17 | f=@(x) x.^2+54./x;
18 |
19 | % Initialization
20 | x1=a;
21 | x2=x1+dx;
22 | x3=x2+dx;
23 | x_min=x2;
24 | f_min=f(x_min);
25 |
26 | while x3<=b
27 | if f(x2)<=f(x1) && f(x2)<=f(x3)
28 | disp(['The approx minimum point is: ' num2str(x2)])
29 | disp(['The approx minimum function value is: ' num2str(f(x2))])
30 | x_min=x2;
31 | f_min=f(x_min);
32 | end
33 | x1=x2;
34 | x2=x1+dx;
35 | x3=x2+dx;
36 |
37 | end
38 |
39 |
40 | % Plotting
41 | x = linspace(a,b,n);
42 | plot(x,f(x),'LineWidth',2,'DisplayName',func2str(f));
43 | xlabel('x',FontWeight='bold');
44 | ylabel('f(x)','FontWeight','bold')
45 | grid on;
46 | title('Exhaustive Search Method','FontWeight','bold');
47 |
48 | hold on;
49 |
50 | % Scatter plot for the minimum point
51 | scatter(x_min, f_min, 100, 'red', 'filled', 'DisplayName', 'Minimum Point');
52 |
53 | % Adding Legend
54 | legend('Location','best')
55 | legend('show')
56 |
57 | % Save the figure as a PNG file
58 | saveas(gcf, 'Exhaustive Search Method.png');
59 |
60 | % Display the plot
61 | hold off;
62 |
--------------------------------------------------------------------------------
/GoldenSectionSearchMethod.m:
--------------------------------------------------------------------------------
1 | % Exhaustive Search Method as Explained in the book
2 | %"Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2022b
5 | % Date: 14th October, 2018
6 | % Date: 27th October, 2023 (Updated)
7 |
8 | clear all
9 | clc
10 | a = 0.1; % Lower bound
11 | b = 14 ; % Upper bound
12 | eps = 1e-8; % Desired accuracy
13 | gr = (1 + 5^0.5) / 2; % Golden Ratio
14 |
15 | f=@(x) x.^2+54./x;
16 |
17 | x = linspace(a,b,1000);
18 |
19 | % Initialization
20 | x1 = a + (b - a) / gr;
21 | x2 = b - (b - a) / gr;
22 |
23 | while abs(b - a) > eps
24 | f1 = f(x1);
25 | f2 = f(x2);
26 | if f1 > f2
27 | b = x2;
28 | x2 = x1;
29 | x1 = a + (b - a) / gr;
30 | else
31 | a = x1;
32 | x1 = x2;
33 | x2 = b - (b - a) / gr;
34 | end
35 | end
36 | x_min = (a+b)/2;
37 | f_min = f(x_min);
38 | disp(['The approx minimum point is: ',num2str(x_min)])
39 | disp(['The approx minimum function value is: ',num2str(f_min)])
40 |
41 | % Plotting
42 | plot(x,f(x),'LineWidth',2,'DisplayName',func2str(f));
43 | xlabel('x',FontWeight='bold');
44 | ylabel('f(x)','FontWeight','bold')
45 | grid on;
46 | title('Golden Section Search Method','FontWeight','bold');
47 |
48 | hold on;
49 |
50 | % Scatter plot for the minimum point
51 | scatter(x_min, f_min, 100, 'red', 'filled', 'DisplayName', 'Minimum Point');
52 |
53 | % Adding Legend
54 | legend('Location','best')
55 | legend('show')
56 |
57 | % Save the figure as a PNG file
58 | saveas(gcf, 'Golden Section Search Method.png');
59 |
60 | % Display the plot
61 | hold off;
62 |
--------------------------------------------------------------------------------
/BisectionMethod.m:
--------------------------------------------------------------------------------
1 | % Bisection Method
2 | % Matlab version R2018b and R2022a
3 | % Date: 27th October, 2018
4 | % Date: 5th November, 2023
5 | clc
6 | clear
7 | % Bisection Method
8 |
9 | a = 0.1; % Lower bound
10 | b = 15; % Upper bound
11 | eps = 1e-3; % Small number
12 |
13 | x_p = linspace(a, b, 1000); % points for plotting the function
14 |
15 | % Function to minimize
16 | f = @(x) x.^2 + 54./x;
17 |
18 | % Function to determine the value of 'dx'
19 | dx = @(x) abs(x) > 0.01 .* 0.01 .* abs(x) + (abs(x) <= 0.01) .* 0.0001;
20 |
21 | % Function to calculate first derivative of the function
22 | fdx = @(x) (f(x + dx(x)) - f(x - dx(x))) ./ (2 .* dx(x));
23 |
24 | x1 = a; % Beginning of search space
25 | x2 = b; % End of search space
26 | z = 0.5 .* (x1 + x2); % Mid-point of the search space
27 |
28 | % Initialization
29 | fx1 = f(x1);
30 | fx2 = f(x2);
31 | fz = f(z);
32 | fdz = fdx(z);
33 |
34 | while abs(fdz) > eps
35 | if fdz < 0
36 | x1 = z;
37 | elseif fdz > 0
38 | x2 = z;
39 | end
40 | z = 0.5 .* (x1 + x2);
41 | fx1 = f(x1);
42 | fx2 = f(x2);
43 | fz = f(z);
44 | fdz = fdx(z);
45 | end
46 |
47 | fprintf('The approximate minimum point and the value respectively are: %f and %f\n', z, fz);
48 |
49 | % Plot the function
50 | figure;
51 | plot(x_p, f(x_p), 'b', 'LineWidth', 1.5,'DisplayName', func2str (f));
52 | xlabel('x', 'FontWeight', 'bold');
53 | ylabel('f(x)', 'FontWeight', 'bold');
54 | grid on;
55 | title('Bisection Method', 'FontWeight', 'bold');
56 | hold on;
57 | scatter(z, fz, 50, 'red', 'filled', 'DisplayName', 'Approximate Minimum Point');
58 | legend('Location', 'Best');
59 | saveas(gcf, 'Bisection_Method.png', 'png');
60 |
--------------------------------------------------------------------------------
/BoundingPhaseMethod.py:
--------------------------------------------------------------------------------
1 | # Bounding Phase Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | a = 0.1 # Lower bound
6 | b = 14 # Upper bound
7 | dx=1e-5 # Step-size parameter
8 |
9 | # Function to be minimized
10 | def f(x):
11 | return x ** 2 + 54 / x
12 |
13 | # Initialization
14 | x_mid=a+dx*(b-a) # Initial guess
15 | x_lb=x_mid-dx # Current lower bound
16 | x_ub=x_mid+dx # Current upper bound
17 | f_mid = f(x_mid)
18 | f_lb=f(x_lb)
19 | f_ub=f(x_ub)
20 | k=0 # Value will be iterated
21 | x = np.linspace(a,b,1000)
22 |
23 | # Check whether the function is unimodal
24 |
25 | while x_ub<=b and x_lb >=a:
26 | if f_mid>=f_lb and f_mid>=f_ub:
27 | print(f_lb,f_mid,f_ub)
28 | print("The function is not unimodal")
29 | elif f_lb>=f_mid and f_mid>=f_ub:
30 | dx=abs(dx)
31 | print(f"dx: {dx}")
32 | else:
33 | dx=-abs(dx)
34 | print(f"dx: {dx}")
35 | k=k+1
36 | x_mid_new = x_mid + 2**k*dx
37 | f_mid_new = f(x_mid_new)
38 | if f_mid_new > f_mid:
39 | break
40 | x_mid = x_mid_new
41 | x_lb=x_mid-dx
42 | x_ub=x_mid+dx
43 | f_mid = f_mid_new
44 | f_lb=f(x_lb)
45 | f_ub=f(x_ub)
46 | print(f"k={k},x_mid={x_mid},x_lb={x_lb},x_ub={x_ub}")
47 | print (f"The approximate minimum point and the value respectively are: {x_mid} and {f_mid}")
48 |
49 | # Plot the function
50 | plt.plot(x,f(x))
51 | plt.xlabel("x",fontweight='bold')
52 | plt.ylabel("f(x)",fontweight='bold')
53 | plt.grid(which='major',axis='both',linestyle='dashed')
54 | plt.title('Bounding Phase Method',fontweight='bold')
55 | plt.scatter(x_mid,f_mid, color='red', label='Minimum Point')
56 | plt.legend()
57 | plt.savefig('Bounding Phase Method.png',dpi=300)
58 | plt.show()
59 |
--------------------------------------------------------------------------------
/IntervalHalvingMethod.m:
--------------------------------------------------------------------------------
1 | % Interval Halving Method as Explained in the book
2 | %"Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2022a
5 | % Date: 16th October, 2018
6 | % Date: 31st October, 2023 (updated)
7 | clc
8 | clear
9 | % Interval Halving Method
10 |
11 | a = 0.1; % Lower bound
12 | b = 14; % Upper bound
13 | eps = 1e-5; % Desired accuracy
14 |
15 | % Function to minimize
16 | f = @(x) x.^2 + 54./x;
17 |
18 | % Initialization
19 | xm = (a + b) / 2; % Mid point
20 | L = b - a; % Length of search space
21 | x1 = a + L / 4; % Left intermediary point
22 | x2 = b - L / 4; % Right intermediary point
23 |
24 | f1 = f(x1);
25 | f2 = f(x2);
26 | fm = f(xm);
27 | x_vals = linspace(a, b, 1000);
28 | y_vals = f(x_vals);
29 |
30 | while abs(L) > eps
31 | if f1 < fm
32 | b = xm;
33 | xm = x1;
34 | elseif f2 < fm
35 | a = xm;
36 | xm = x2;
37 | else
38 | a = x1;
39 | b = x2;
40 | end
41 |
42 | L = b - a;
43 | x1 = a + L / 4;
44 | x2 = b - L / 4;
45 | f1 = f(x1);
46 | f2 = f(x2);
47 | fm = f(xm);
48 | end
49 |
50 | fprintf('The minimum point lies between %.8f and %.8f\n', x1, x2);
51 |
52 | % Plot the function
53 | plot(x_vals, y_vals);
54 | xlabel('x', 'FontWeight', 'bold');
55 | ylabel('f(x)', 'FontWeight', 'bold');
56 | grid on;
57 | title('Interval Halving Method', 'FontWeight', 'bold');
58 |
59 | hold on;
60 | scatter(xm, fm, 100, 'red', 'filled', 'MarkerEdgeColor', 'black', 'LineWidth', 1.5, 'DisplayName', 'Approximate Minimum Point');
61 | legend('show');
62 | hold off;
63 |
64 | saveas(gcf, 'Interval_Halving_Method.png', 'png');
65 |
--------------------------------------------------------------------------------
/NewtonRaphsonMethod.m:
--------------------------------------------------------------------------------
1 | % Newton-Raphson Method as Explained in the book
2 | %"Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2022a
5 | % Date: 16th October, 2018
6 | % Date: 4th November, 2023
7 | clc
8 | clear
9 | % Newton-Raphson Method
10 |
11 | a = 0.1; % Lower bound
12 | b = 15; % Upper bound
13 |
14 | x_p = linspace(a, b, 1000); % points for plotting the function
15 |
16 | % Function to minimize
17 | f = @(x) x^2 + 54/x;
18 |
19 | % Function to determine the value of 'dx'
20 | dx = @(x) 0.01 * abs(x);
21 | dx = @(x) max(dx(x), 0.0001);
22 |
23 | % Function to calculate first derivative of the function
24 | fdx = @(x) (f(x + dx(x)) - f(x - dx(x))) / (2 * dx(x));
25 |
26 | % Function to calculate second derivative of the function
27 | fddx = @(x) (f(x + dx(x)) - 2 * f(x) + f(x - dx(x))) / (dx(x)^2);
28 |
29 | % Initialization
30 | x = a; % Initial guess
31 | eps = 1e-5; % Small number to check convergency
32 | max_iterations = 1000; % Maximum number of iterations
33 |
34 | xn = x - (fdx(x) / fddx(x));
35 | fn = f(xn);
36 |
37 | k = 1; % Counter
38 |
39 | while fn > eps && k <= max_iterations
40 | k = k + 1;
41 | x = xn;
42 | xn = x - (fdx(x) / fddx(x));
43 | fn = f(xn);
44 | end
45 |
46 | fprintf('The approximate minimum point and the value respectively are: %.4f and %.4f\n', xn, fn);
47 |
48 | % Plot the function
49 | figure;
50 | plot(x_p, arrayfun(f, x_p),'DisplayName', func2str (f));
51 | xlabel('x', 'FontWeight', 'bold');
52 | ylabel('f(x)', 'FontWeight', 'bold');
53 | grid on;
54 | title('Newton-Raphson Method', 'FontWeight', 'bold');
55 | hold on;
56 | scatter(xn, fn, 'r', 'filled', 'DisplayName', 'Approximate Minimum Point');
57 | legend('Location', 'Best');
58 | saveas(gcf, 'NewtonRaphsonMethod.png', 'png');
59 |
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/src/line_search.py:
--------------------------------------------------------------------------------
1 | '''
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | '''
15 | import numpy
16 |
17 | def find_step_length(f, fd, x, alpha, direction, c2):
18 | g = lambda alpha: f(x+alpha*direction)
19 | gd = lambda alpha: numpy.dot(fd(x + alpha*direction), direction)
20 | return interpolation(g, gd, alpha, c2)
21 |
22 | def wolf1(f, fd, alpha):
23 | c1 = 1e-4
24 | return f(alpha) <= f(0) + c1*alpha*fd(alpha)
25 |
26 | def wolf_strong(f, fd, alpha, c2):
27 | return abs(fd(alpha)) <= -c2*fd(0)
28 |
29 | def simple_backtracking(f, fd, alpha, c2):
30 | rate = 0.5
31 | while not (wolf1(f, fd, alpha) or wolf_strong(f, fd, alpha, c2)):
32 | alpha = rate*alpha
33 | return alpha
34 |
35 | def interpolation(f, fd, alpha, c2):
36 | lo = 0.0
37 | hi = 1.0
38 |
39 | for i in range(0, 20):
40 | if wolf1(f, fd, alpha):
41 | if wolf_strong(f, fd, alpha, c2):
42 | return alpha
43 |
44 | half = (lo+hi)/2.0
45 | alpha = - (fd(lo)*hi*hi) / (2*(f(hi)-f(lo)-fd(lo)*hi))
46 |
47 | if alpha < lo or alpha > hi: # quadratic interpolation failed. reduce by half instead
48 | alpha = half
49 | if fd(alpha) > 0:
50 | hi = alpha
51 | elif fd(alpha) <= 0:
52 | lo = alpha
53 | return alpha
54 |
--------------------------------------------------------------------------------
/SuccessiveQuadraticEstimationMethod.py:
--------------------------------------------------------------------------------
1 | # Successive Quadratic Estimation Method
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 |
6 | a=0.1 #Lower bound
7 | b=14 #Upper bound
8 | dx=1e-5 # Step size
9 | fcp=1e-8 # Convergence parameter for function evaluation
10 |
11 | # Equation to be minimized
12 | def f(x):
13 | # return 2*x**2+16/x
14 | return x**2+54/x
15 |
16 | x=np.linspace(a,b,1000)
17 |
18 | #Initialization
19 |
20 | x1=a
21 | x2=x1+dx
22 | f1=f(x1)
23 | f2=f(x2)
24 |
25 | if f1>f2:
26 | x3=x1+2*dx
27 | elif f1<=f2:
28 | x3=x1-dx
29 | f3=f(x3)
30 |
31 | # Detemine minimum function value for the initial step
32 | f_min=min({f1,f2,f3})
33 |
34 | # Determine x-value corresponding to minimum funtion value
35 | if f_min==f1:
36 | x_min=x1
37 | elif f_min==f2:
38 | x_min=x2
39 | elif f_min==f3:
40 | x_min=x3
41 |
42 | # Determine x_bar
43 | a1=(f2-f1)/(x2-x1)
44 |
45 | a2=(1/(x3-x2))*(((f3-f1)/(x3-x1))-((f2-f1)/(x2-x1)))
46 | x_bar=0.5*((x1+x2)-(a1/a2))
47 |
48 | f_bar=f(x_bar)
49 |
50 | while abs(f_min-f_bar)>fcp:
51 | x2=(x_min+x_bar)/2
52 | x1=x2-dx
53 | x3=x1+2*dx
54 | f1=f(x1)
55 | f2=f(x2)
56 | f3=f(x3)
57 | f_min=min({f1,f2,f3})
58 | if f_min==f1:
59 | x_min=x1
60 | elif f_min==f2:
61 | x_min=x2
62 | elif f_min==f3:
63 | x_min=x3
64 | a1=(f2-f1)/(x2-x1)
65 | a2=(1/(x3-x2))*(((f3-f1)/(x3-x1))-((f2-f1)/(x2-x1)))
66 | x_bar=0.5*((x1+x2)-(a1/a2))
67 | f_bar=f(x_bar)
68 |
69 | print(f'The approximate minimum function value is {f_min}, at {x_min}')
70 |
71 | # Plot the function
72 | plt.plot(x,f(x))
73 | plt.xlabel("x",fontweight='bold')
74 | plt.ylabel("f(x)",fontweight='bold')
75 | plt.grid(which='major',axis='both',linestyle='dashed')
76 | plt.title('Exhaustive Search Method',fontweight='bold')
77 | plt.scatter(x_min,f_min, color='red', label='Approximate Minimum Point')
78 | plt.legend()
79 | plt.savefig('Successive Quadratic Estimation Method.png',dpi=300)
80 | plt.show()
81 |
--------------------------------------------------------------------------------
/fibonacci_search_method.m:
--------------------------------------------------------------------------------
1 | % Fibonacci Search Method
2 | % Matlab version R2018b
3 | % Date: 10th February, 2019 (started)
4 | % Date: 2nd November, 2023 (updated)
5 |
6 | clc
7 | clear
8 | a = 0.1; % Lower bound
9 | b = 14; % Upper bound
10 | n = 1000; % Number of times function is to be evaluated
11 | b_p=b;
12 | a_p=a;
13 |
14 | % Function to be minimized
15 | f = @(x) x.^2 + 54./x;
16 |
17 | % Initialization
18 | k = 2;
19 | L = b - a; % Length of search space
20 | L_ks = (F(n-k+1)/F(n+1)) * L;
21 | x1 = a + L_ks;
22 | x2 = b - L_ks;
23 | f1 = f(x1);
24 | f2 = f(x2);
25 |
26 | while k <= n
27 | if f2 < f1
28 | a = x1;
29 | else
30 | b = x2;
31 | end
32 | L = b - a;
33 | L_ks = (F(n - k + 1) / F(n + 1)) * L; % Recalculate L_ks
34 | x1 = a + L_ks;
35 | x2 = b - L_ks;
36 | f1 = f(x1);
37 | f2 = f(x2);
38 | k = k + 1;
39 | end
40 |
41 | x_min = (x1 + x2) / 2;
42 | f_min = f((x1 + x2) / 2);
43 |
44 | fprintf('The approximate minimum point and the value respectively are: %f and %f\n', x_min, f_min);
45 |
46 | % Plot the function
47 | x_values = linspace(0, b_p, 1000); % Update here
48 | y_values = f(x_values);
49 | figure;
50 | plot(x_values, y_values);
51 | xlabel('x', 'fontweight', 'bold');
52 | ylabel('f(x)', 'fontweight', 'bold');
53 | grid on;
54 | title('Fibonacci Search Method', 'fontweight', 'bold');
55 | hold on;
56 | scatter(x_min, f_min, 'red', 'filled');
57 | legend(func2str(f), 'Approximate Minimum Point');
58 |
59 | % Set x-axis ticks to be whole numbers
60 | xticks(a_p:b_p);
61 |
62 | % Adjust x-axis limits
63 | ax = gca;
64 | ax.XLim = [a_p b_p]; % Update here
65 |
66 | saveas(gcf, 'Fibonacci_Search_Method.png', 'png');
67 |
68 | % Function to generate n-th Fibonacci number
69 | function result = F(n)
70 | fi = zeros(1, n+1);
71 | fi(1) = 0;
72 | fi(2) = 1;
73 |
74 | for i = 3:n+1
75 | fi(i) = fi(i-1) + fi(i-2);
76 | end
77 |
78 | result = fi(n+1);
79 | end
80 |
--------------------------------------------------------------------------------
/SuccessiveQuadraticEstimationMethod.m:
--------------------------------------------------------------------------------
1 | % Successive Quadratic Estimation Method
2 |
3 | a = 0.1; % Lower bound
4 | b = 14; % Upper bound
5 | dx = 1e-5; % Step size
6 | fcp = 1e-8; % Convergence parameter for function evaluation
7 |
8 | % Equation to be minimized
9 | f = @(x) x^2 + 54/x;
10 |
11 | x = linspace(a, b, 1000);
12 |
13 | % Initialization
14 | x1 = a;
15 | x2 = x1 + dx;
16 | f1 = f(x1);
17 | f2 = f(x2);
18 |
19 | if f1 > f2
20 | x3 = x1 + 2*dx;
21 | elseif f1 <= f2
22 | x3 = x1 - dx;
23 | end
24 | f3 = f(x3);
25 |
26 | % Determine minimum function value for the initial step
27 | f_min = min([f1, f2, f3]);
28 |
29 | % Determine x-value corresponding to minimum function value
30 | if f_min == f1
31 | x_min = x1;
32 | elseif f_min == f2
33 | x_min = x2;
34 | elseif f_min == f3
35 | x_min = x3;
36 | end
37 |
38 | % Determine x_bar
39 | a1 = (f2 - f1) / (x2 - x1);
40 | a2 = (1 / (x3 - x2)) * (((f3 - f1) / (x3 - x1)) - ((f2 - f1) / (x2 - x1)));
41 | x_bar = 0.5 * ((x1 + x2) - (a1 / a2));
42 | f_bar = f(x_bar);
43 |
44 | while abs(f_min - f_bar) > fcp
45 | x2 = (x_min + x_bar) / 2;
46 | x1 = x2 - dx;
47 | x3 = x1 + 2*dx;
48 | f1 = f(x1);
49 | f2 = f(x2);
50 | f3 = f(x3);
51 | f_min = min([f1, f2, f3]);
52 | if f_min == f1
53 | x_min = x1;
54 | elseif f_min == f2
55 | x_min = x2;
56 | elseif f_min == f3
57 | x_min = x3;
58 | end
59 | a1 = (f2 - f1) / (x2 - x1);
60 | a2 = (1 / (x3 - x2)) * (((f3 - f1) / (x3 - x1)) - ((f2 - f1) / (x2 - x1)));
61 | x_bar = 0.5 * ((x1 + x2) - (a1 / a2));
62 | f_bar = f(x_bar);
63 | end
64 |
65 | fprintf('The approximate minimum function value is %.8f, at %.8f\n', f_min, x_min);
66 |
67 | % Plot the function
68 | x_values = linspace(a, b, 1000);
69 | y_values = arrayfun(f, x_values);
70 |
71 | figure;
72 | plot(x_values, y_values,'DisplayName', func2str (f));
73 | xlabel('x', 'FontWeight', 'bold');
74 | ylabel('f(x)', 'FontWeight', 'bold');
75 | grid on;
76 | title('Successive Quadratic Estimation Method', 'FontWeight', 'bold');
77 | hold on;
78 | scatter(x_min, f_min, 'red', 'filled', 'DisplayName', 'Approximate Minimum Point');
79 | legend('Location', 'Best');
80 | saveas(gcf, 'Successive_Quadratic_Estimation_Method.png');
81 |
--------------------------------------------------------------------------------
/BoundingPhaseMethod.m:
--------------------------------------------------------------------------------
1 | % Bounding Phase Method as Explained in the book
2 | %"ENGINEERING OPTIMIZATION Methods and Applications" SECOND EDITION by A. Ravindran, K. M. Ragsdell and G. V. Reklaitis
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2022a
5 | % Date: 15th October, 2018
6 | % Date: 30th October, 2023 (updated)
7 |
8 | clc
9 | clear all
10 | % Bounding Phase Method
11 |
12 | a = 0.1; % Lower bound
13 | b = 14; % Upper bound
14 | dx = 1e-5; % Step-size parameter
15 |
16 | % Function to be minimized
17 | f = @(x) x.^2 + 54./x;
18 |
19 | % Initialization
20 | x_mid = a + dx*(b-a); % Initial guess
21 | x_lb = x_mid - dx; % Current lower bound
22 | x_ub = x_mid + dx; % Current upper bound
23 | f_mid = f(x_mid);
24 | f_lb = f(x_lb);
25 | f_ub = f(x_ub);
26 | k = 0; % Value will be iterated
27 | x = linspace(a, b, 1000);
28 |
29 | % Check whether the function is unimodal
30 | while x_ub <= b && x_lb >= a
31 | if f_mid >= f_lb && f_mid >= f_ub
32 | disp([f_lb, f_mid, f_ub]);
33 | disp('The function is not unimodal');
34 | elseif f_lb >= f_mid && f_mid >= f_ub
35 | dx = abs(dx);
36 | disp(['dx: ', num2str(dx)]);
37 | else
38 | dx = -abs(dx);
39 | disp(['dx: ', num2str(dx)]);
40 | end
41 | k = k + 1;
42 | x_mid_new = x_mid + 2^k*dx;
43 | f_mid_new = f(x_mid_new);
44 | if f_mid_new > f_mid
45 | break;
46 | end
47 | x_mid = x_mid_new;
48 | x_lb = x_mid - dx;
49 | x_ub = x_mid + dx;
50 | f_mid = f_mid_new;
51 | f_lb = f(x_lb);
52 | f_ub = f(x_ub);
53 | disp(['k=', num2str(k), ',x_mid=', num2str(x_mid), ',x_lb=', num2str(x_lb), ',x_ub=', num2str(x_ub)]);
54 | disp(['The approximate minimum point and the value respectively are: ', num2str(x_mid), ' and ', num2str(f_mid)]);
55 | end
56 |
57 | % Plot the function
58 | x_values = linspace(a, b, 1000);
59 | f_values = f(x_values);
60 |
61 | figure;
62 | plot(x_values, f_values,'DisplayName', func2str(f));
63 | xlabel('x', 'FontWeight', 'bold');
64 | ylabel('f(x)', 'FontWeight', 'bold');
65 | grid on;
66 | title('Bounding Phase Method', 'FontWeight', 'bold');
67 | hold on;
68 | scatter(x_mid, f_mid, 100, 'red', 'filled', 'DisplayName', 'Minimum Point');
69 | legend('show');
70 | saveas(gcf, 'Bounding_Phase_Method.png');
71 |
--------------------------------------------------------------------------------
/Non-Linear Optimization [Python]/src/rosenbrock.py:
--------------------------------------------------------------------------------
1 | '''
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | '''
15 | from numpy import *
16 | from newton import *
17 | from quasi_newton import *
18 | from steepest_descent import *
19 | from conjugate_gradient import *
20 |
21 | if __name__ == '__main__':
22 | def f(x): return 100 * math.pow(x[1] - math.pow(x[0], 2), 2) + math.pow(1 - x[0], 2)
23 | def df_dx1(x): return 400*math.pow(x[0], 3) - 400*x[0]*x[1] + 2*x[0] - 2
24 | def df_dx2(x): return 200*x[1] - 200*math.pow(x[0], 2)
25 | def fd(x): return array([ df_dx1(x), df_dx2(x) ])
26 |
27 | def df_dx1_dx1(x): return 1200*math.pow(x[0], 2) - 400*x[1] + 2
28 | def df_dx1_dx2(x): return-400*x[0]
29 |
30 | def fdd(x):
31 | return array([
32 | [df_dx1_dx1(x), df_dx1_dx2(x)],
33 | [df_dx1_dx2(x), 200]])
34 |
35 | def print_error(i, direction, alpha, x):
36 | opt = f(array([1,1]))
37 | print("%d, %.20f" % (i, f(x)-opt))
38 |
39 | def print_gradient(i, direction, alpha, x):
40 | print("%d, %.20f" % (i, linalg.norm(fd(x))))
41 |
42 | def print_all(i, direction, alpha, x):
43 | print("iteration %d: \t direction: %s \t alpha: %.7f \t x: %s"
44 | % (i, ["%.7f" % _ for _ in direction], alpha, ["%.7f" % _ for _ in x]))
45 |
46 | x = array([0, 0])
47 | precision = 10e-6
48 | max_iterations = 100
49 | callback = print_all
50 |
51 | print("steepest descent:")
52 | steepest_descent(f, fd, x, max_iterations, precision, callback)
53 |
54 | print("\nnewton:")
55 | newton(f, fd, fdd, x, max_iterations, precision, callback)
56 |
57 | print("\nquasi newton:")
58 | quasi_newton(f, fd, x, max_iterations, precision, callback)
59 |
60 | print("\nconjugate gradient:")
61 | conjugate_gradient(f, fd, x, max_iterations, precision, callback)
62 |
63 |
--------------------------------------------------------------------------------
/CubicSearchMethod.py:
--------------------------------------------------------------------------------
1 | # Cubic Search Method
2 |
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 |
6 | a = 0.1 # Lower bound
7 | b = 14 # Upper bound
8 |
9 | # Function to minimize
10 | def f(x):
11 | return x**2 + 54/x
12 |
13 | # Function to calculate first derivative of the function
14 | def fdx(x):
15 | dx = 1e-6 # Small value for differentiation
16 | return ((f(x+dx) - f(x-dx)) / (2*dx))
17 |
18 | # Initialize
19 | x0 = 1
20 | dx = 0.06 # Step size
21 | x_bar = 0
22 | x_k = x0
23 | k = 0
24 | x_p=np.linspace(a,b,1000)
25 |
26 | eps1 = 1e-3
27 | eps2 = 1e-3
28 |
29 | prev_f_bar = float('inf')
30 |
31 | while True:
32 | fdx0 = fdx(x_k)
33 | if fdx0 < 0:
34 | dx = abs(dx)
35 | else:
36 | dx = -abs(dx)
37 |
38 | x_k1 = x_k + 2**k*dx
39 |
40 | fdx_k = fdx(x_k)
41 | fdx_k1 = fdx(x_k1)
42 |
43 | if (fdx_k * fdx_k1) > 0:
44 | x_k = x_k + 2**k*dx
45 | else:
46 | x1 = min(x_k, x_k1)
47 | x2 = max(x_k, x_k1)
48 | f1 = f(x1)
49 | f2 = f(x2)
50 | fd1 = fdx(x1)
51 | fd2 = fdx(x2)
52 | z = (3*(f1-f2)/(x2-x1)) + fd1 + fd2
53 |
54 | if x1 < x2:
55 | w = np.sqrt(z**2 - fd1*fd2)
56 | else:
57 | w = -np.sqrt(z**2 - fd1*fd2)
58 |
59 | mu = (fd2 + w - z) / (fd2 + fd1 + 2*w)
60 |
61 | if mu == 0:
62 | x_bar = x2
63 | elif 0 < mu <= 1:
64 | x_bar = x2 - mu * (x2 - x1)
65 | else:
66 | x_bar = x1
67 |
68 | f_bar = f(x_bar)
69 | f1 = f(x1)
70 |
71 | if f_bar > f1:
72 | x_bar = x_bar - (x_bar - x1) / 2
73 | x1 = x1 + 2**k*dx
74 | k = k + 1
75 | f_bar = f(x_bar)
76 | f1 = f(x1)
77 | else:
78 | fdx_bar = fdx(x_bar)
79 | fdx1 = fdx(x1)
80 |
81 | if abs(fdx_bar) <= eps1 and abs((x_bar - x1) / x_bar) <= eps2:
82 | if f_bar < prev_f_bar: # Check if it's an improvement
83 | best_x_bar = x_bar
84 | best_f_bar = f_bar
85 | break
86 |
87 | if fdx_bar * fdx1 < 0:
88 | x2 = x_bar
89 | x1 = x_bar
90 | f1 = f(x1)
91 | f2 = f(x2)
92 | fd1 = fdx(x1)
93 | fd2 = fdx(x2)
94 | z = (3*(f1-f2)/(x2-x1)) + fd1 + fd2
95 |
96 | if x1 < x2:
97 | w = np.sqrt(z**2 - fd1*fd2)
98 | else:
99 | w = -np.sqrt(z**2 - fd1*fd2)
100 |
101 | mu = (fd2 + w - z) / (fd2 + fd1 + 2*w)
102 |
103 | if mu == 0:
104 | x_bar = x2
105 | elif 0 < mu <= 1:
106 | x_bar = x2 - mu * (x2 - x1)
107 | else:
108 | x_bar = x1
109 |
110 | if f_bar < prev_f_bar: # Check if it's an improvement
111 | best_x_bar = x_bar
112 | best_f_bar = f_bar
113 |
114 | if f_bar > prev_f_bar: # If current f_bar is worse, stop
115 | break
116 |
117 | prev_f_bar = f_bar
118 |
119 | k += 1
120 |
121 |
122 | print(f"The approximate minimum function value is {best_f_bar}, and it is located at {best_x_bar}")
123 |
124 | # Plot the function
125 | plt.plot(x_p,f(x_p))
126 | plt.xlabel("x",fontweight='bold')
127 | plt.ylabel("f(x)",fontweight='bold')
128 | plt.grid(which='major',axis='both',linestyle='dashed')
129 | plt.title('Cubic Search Method',fontweight='bold')
130 | plt.scatter(x_bar,f_bar, color='red', label='Approximate Minimum Point')
131 | plt.legend()
132 | plt.savefig('Cubic Search Method.png',dpi=300)
133 | plt.show()
--------------------------------------------------------------------------------
/CubicSearchMethod.m:
--------------------------------------------------------------------------------
1 | % Cubic Search Method as Explained in the book
2 | %"Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb
3 | % Code developed by Sri. Soumyabrata Bhattacharjee
4 | % Matlab version R2018b, R2022a
5 | % Date: 3rd November, 2018
6 | % Date: 5th November, 2023 (updated)
7 |
8 | clc
9 | clear
10 | a = 0.1; % Lower bound
11 | b = 14; % Upper bound
12 |
13 | % Function to minimize
14 | f = @(x) x.^2 + 54./x;
15 |
16 | % Function to calculate first derivative of the function
17 | fdx = @(x) (f(x + 1e-6) - f(x - 1e-6)) / (2e-6);
18 |
19 | % Initialize
20 | x0 = 1;
21 | dx = 0.06; % Step size
22 | x_bar = 0;
23 | x_k = x0;
24 | k = 0;
25 | x_p = linspace(a, b, 1000);
26 |
27 | eps1 = 1e-3;
28 | eps2 = 1e-3;
29 |
30 | prev_f_bar = inf;
31 |
32 | while true
33 | fdx0 = fdx(x_k);
34 | if fdx0 < 0
35 | dx = abs(dx);
36 | else
37 | dx = -abs(dx);
38 | end
39 |
40 | x_k1 = x_k + 2^k * dx;
41 |
42 | fdx_k = fdx(x_k);
43 | fdx_k1 = fdx(x_k1);
44 |
45 | if (fdx_k * fdx_k1) > 0
46 | x_k = x_k + 2^k * dx;
47 | else
48 | x1 = min(x_k, x_k1);
49 | x2 = max(x_k, x_k1);
50 | f1 = f(x1);
51 | f2 = f(x2);
52 | fd1 = fdx(x1);
53 | fd2 = fdx(x2);
54 | z = (3*(f1-f2)/(x2-x1)) + fd1 + fd2;
55 |
56 | if x1 < x2
57 | w = sqrt(z^2 - fd1*fd2);
58 | else
59 | w = -sqrt(z^2 - fd1*fd2);
60 | end
61 |
62 | mu = (fd2 + w - z) / (fd2 + fd1 + 2*w);
63 |
64 | if mu == 0
65 | x_bar = x2;
66 | elseif 0 < mu && mu <= 1
67 | x_bar = x2 - mu * (x2 - x1);
68 | else
69 | x_bar = x1;
70 | end
71 |
72 | f_bar = f(x_bar);
73 | f1 = f(x1);
74 |
75 | if f_bar > f1
76 | x_bar = x_bar - (x_bar - x1) / 2;
77 | x1 = x1 + 2^k * dx;
78 | k = k + 1;
79 | f_bar = f(x_bar);
80 | f1 = f(x1);
81 | else
82 | fdx_bar = fdx(x_bar);
83 | fdx1 = fdx(x1);
84 |
85 | if abs(fdx_bar) <= eps1 && abs((x_bar - x1) / x_bar) <= eps2
86 | if f_bar < prev_f_bar % Check if it's an improvement
87 | best_x_bar = x_bar;
88 | best_f_bar = f_bar;
89 | end
90 | break;
91 | end
92 |
93 | if fdx_bar * fdx1 < 0
94 | x2 = x_bar;
95 | x1 = x_bar;
96 | f1 = f(x1);
97 | f2 = f(x2);
98 | fd1 = fdx(x1);
99 | fd2 = fdx(x2);
100 | z = (3*(f1-f2)/(x2-x1)) + fd1 + fd2;
101 |
102 | if x1 < x2
103 | w = sqrt(z^2 - fd1*fd2);
104 | else
105 | w = -sqrt(z^2 - fd1*fd2);
106 | end
107 |
108 | mu = (fd2 + w - z) / (fd2 + fd1 + 2*w);
109 |
110 | if mu == 0
111 | x_bar = x2;
112 | elseif 0 < mu && mu <= 1
113 | x_bar = x2 - mu * (x2 - x1);
114 | else
115 | x_bar = x1;
116 | end
117 | end
118 | end
119 |
120 | if f_bar < prev_f_bar % Check if it's an improvement
121 | best_x_bar = x_bar;
122 | best_f_bar = f_bar;
123 | end
124 |
125 | if f_bar > prev_f_bar % If current f_bar is worse, stop
126 | break;
127 | end
128 |
129 | prev_f_bar = f_bar;
130 | end
131 |
132 | k = k + 1;
133 | end
134 |
135 | fprintf('The approximate minimum function value is %.6f, and it is located at %.6f\n', best_f_bar, best_x_bar);
136 |
137 | % Plot the function
138 | x_p = linspace(a, b, 1000);
139 | figure;
140 | plot(x_p, f(x_p), 'LineWidth', 1.5,'DisplayName',func2str (f));
141 | hold on;
142 | xlabel('x', 'FontWeight', 'bold');
143 | ylabel('f(x)', 'FontWeight', 'bold');
144 | grid on;
145 | title('Cubic Search Method', 'FontWeight', 'bold');
146 | scatter(best_x_bar, best_f_bar, 100, 'r', 'filled', 'DisplayName', 'Approximate Minimum Point');
147 | legend('Location', 'Best');
148 | saveas(gcf, 'Cubic_Search_Method.png', 'png');
149 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Optimization Techniques
2 |
3 | This repository contains implementations of various optimization techniques outlined in the book "Optimization of Engineering Design: Algorithms and Examples" by Prof. Kalyanmoy Deb. Each technique provides a visual representation by plotting both the function and the approximate minimum point (marked as 'o').
4 |
5 | ## Techniques Included
6 |
7 | 1. **Exhaustive Search Method**
8 | - Description: The exhaustive search method is a brute-force approach to finding the minimum of a function within a specified range.
9 | - Versions available for both Python and MATLAB:
10 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/ExhaustiveSearchMethod.py)
11 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/ExhaustiveSearchMethod.m)
12 |
13 | 2. **Golden Section Search**
14 | - Description: The Golden Section Search is an iterative method that narrows down the search space to find the minimum of an unimodal function.
15 | - Versions available for both Python and MATLAB:
16 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/GoldenSectionSearchMethod.py)
17 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/GoldenSectionSearchMethod.m)
18 |
19 | 3. **Bounding Phase Method**
20 | - Description: The Bounding Phase Method is an optimization technique that involves narrowing down the search interval to find the minimum of an unimodal function.
21 | - Versions available for both Python and MATLAB:
22 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/BoundingPhaseMethod.py)
23 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/BoundingPhaseMethod.m)
24 |
25 | 4. **Interval Halving Method**
26 | - Description: The Interval Halving Method is an iterative approach for finding the minimum of a function within a specified interval.
27 | - Versions available for both Python and MATLAB:
28 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/IntervalHalvingMethod.py)
29 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/IntervalHalvingMethod.m)
30 | 5. **Fibonacci Search Method**
31 | - Description: The Fibonacci Search Method is another iterative approach for finding the minimum of a function within a specified interval.
32 | - Version available for Python:
33 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/FibonacciSearchMethod.py)
34 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/fibonacci_search_method.m)
35 | 6. **Quadratic Estimation Method**
36 | - Description: The Quadratic Estimation Method is the simplest of all the polynomial interpolation approaches for finding the minimum of a function within a specified interval.
37 | - Version available for Python:
38 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/QuadraticEstimationMethod.py)
39 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/QuadraticEstimationMethod.m)
40 | 7. **Successive Quadratic Estimation Method**
41 | - Description: It is the more refined form of the Quadratic Estimation Method, which iteratively finds the minimum of a function within a specified interval.
42 | - Version available for Python:
43 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/SuccessiveQuadraticEstimationMethod.py)
44 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/SuccessiveQuadraticEstimationMethod.m)
45 | 8. **Newton-Raphson Method**
46 | - Description: It is a very simple gradient-based method, suitable for unconstrained optimization problems.
47 | - Version available for Python:
48 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/NewtonRaphsonMethod.py)
49 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/NewtonRaphsonMethod.m)
50 | 9. **Bisection Method**
51 | - Description: This version of the Bisection Method, does not need the two endpoints, of the search space to have function values of opposite values. Rather, the algorithm is based on the function's first derivative within the search space. The search space reduces with every iteration.
52 | - Version available for Python:
53 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/BisectionMethod.py)
54 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/BisectionMethod.m)
55 | 10. **Secant Method**
56 | - Description: The Secant Method is a modification of the Bisection Method. Here, the point 'z' of the search space is not the mid-point; rather, it depends on the values of the first derivative of the function.
57 | - Version available for Python:
58 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/SecantMethod.py)
59 | 11. **Cubic Search Method**
60 | - Description: The Cubic Search Method is used to find the minimum of an unimodal function iteratively. It is similar to the successive quadratic point estimation method.
61 | - Versions available for both Python and MATLAB:
62 | - [Python Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/CubicSearchMethod.py)
63 | - [MATLAB Code](https://github.com/Soumyabrata111/Optimization-Techniques/blob/master/CubicSearchMethod.m)
64 |
65 | ## About the Author
66 |
67 | I am pursuing my PhD from the Department of Mechanical Engineering, Indian Institute of Technology Indore. I am also available for freelancing in Optimization Algorithms, Machine Learning, and Deep Learning. My current research work is in time series analysis and classification algorithms. A list of my publications is available at [Google Scholar](https://scholar.google.co.in/citations?user=-ZM_QRcAAAAJ&hl=en)
68 |
69 | ## Get the Latest MATLAB Files
70 |
71 | [](https://in.mathworks.com/matlabcentral/fileexchange/69108-optimization-techniques)
72 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/KKT_optimization/infill-dphi-focus.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {
7 | "collapsed": false
8 | },
9 | "outputs": [
10 | {
11 | "name": "stderr",
12 | "output_type": "stream",
13 | "text": [
14 | "/home/p2admin/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
15 | " from ._conv import register_converters as _register_converters\n"
16 | ]
17 | }
18 | ],
19 | "source": [
20 | "import numpy as np\n",
21 | "import tensorflow as tf\n",
22 | "import matplotlib.pyplot as plt\n",
23 | "import scipy.io as sio\n",
24 | "from tensorflow.contrib import rnn\n",
25 | "import math\n",
26 | "import time\n",
27 | "import os\n",
28 | "from datetime import datetime\n",
29 | "import dateutil.tz\n",
30 | "# from utils.utils import *\n",
31 | "\n",
32 | "\n",
33 | "def xavier_init(size):\n",
34 | " in_dim = size[0]\n",
35 | " xavier_stddev = 1. / tf.sqrt(in_dim / 2.)\n",
36 | " return tf.random_normal(shape=size, stddev=xavier_stddev)\n",
37 | "\n",
38 | "def creat_dir(network_type):\n",
39 | " \"\"\"code from on InfoGAN\"\"\"\n",
40 | " now = datetime.now(dateutil.tz.tzlocal())\n",
41 | " timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')\n",
42 | " root_log_dir = \"logs/\" + network_type\n",
43 | " exp_name = network_type + \"_%s\" % timestamp\n",
44 | " log_dir = os.path.join(root_log_dir, exp_name)\n",
45 | "\n",
46 | " now = datetime.now(dateutil.tz.tzlocal())\n",
47 | " timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')\n",
48 | " root_model_dir = \"models/\" + network_type\n",
49 | " exp_name = network_type + \"_%s\" % timestamp\n",
50 | " model_dir = os.path.join(root_model_dir, exp_name)\n",
51 | "\n",
52 | " for path in [log_dir, model_dir]:\n",
53 | " if not os.path.exists(path):\n",
54 | " os.makedirs(path)\n",
55 | " return log_dir, model_dir\n",
56 | "\n",
57 | "tic = time.clock()\n",
58 | "\n",
59 | "E0 = 1\n",
60 | "Emin = 1e-9\n",
61 | "nu = 0.3\n",
62 | "batch_size = 3\n",
63 | "\n",
64 | "'Input'\n",
65 | "nelx, nely, alpha, alpha2, gamma, rmin, density_r = 12*4, 4*4, 0.6, 0.6, 3.0, 3.0, 6.0\n",
66 | "\n",
67 | "'Algorithm parameters'\n",
68 | "p, nn, epsilon_al, epsilon_opt = 16,nely * nelx, 1, 1e-3\n",
69 | "\n",
70 | "'Prepare filter'\n",
71 | "r = rmin\n",
72 | "Range = np.arange(-r, r + 1)\n",
73 | "X = np.array([Range] * len(Range))\n",
74 | "Y = np.array([Range] * len(Range)).T\n",
75 | "X_temp = X.T.reshape(len(Range) ** 2, 1)\n",
76 | "Y_temp = Y.T.reshape(len(Range) ** 2, 1)\n",
77 | "neighbor = np.concatenate((X_temp, Y_temp), 1)\n",
78 | "D = np.sum(neighbor ** 2, 1)\n",
79 | "rn = sum(D <= r ** 2) - sum(D == 0)\n",
80 | "\n",
81 | "pattern_index = []\n",
82 | "for i in range(len(D)):\n",
83 | " if D[i] <= r ** 2 and D[i] != 0:\n",
84 | " pattern_index.append(i)\n",
85 | "pattern = neighbor[pattern_index]\n",
86 | "\n",
87 | "locX = np.asarray([np.arange(1, nelx + 1)] * nely)\n",
88 | "locY = np.asarray([np.arange(1, nely + 1)] * nelx).T\n",
89 | "loc = np.asarray([locY.T.reshape(-1), locX.T.reshape(-1)]).T\n",
90 | "\n",
91 | "M = np.zeros([nn, rn])\n",
92 | "for i in range(nn):\n",
93 | " for j in range(rn):\n",
94 | " locc = loc[i, :] + pattern[j, :]\n",
95 | " count_true = 0\n",
96 | " if locc[0] > nely: count_true = count_true + 1\n",
97 | " if locc[1] > nelx: count_true = count_true + 1\n",
98 | "\n",
99 | " if sum(locc < 1) + count_true == 0:\n",
100 | " M[i, j] = locc[0] + (locc[1] - 1) * nely\n",
101 | " else:\n",
102 | " M[i, j] = 'NaN'\n",
103 | "\n",
104 | "iH = np.ones([int(nelx * nely * (2 * (np.ceil(rmin) - 1) + 1) ** 2), 1], dtype=int)\n",
105 | "jH = np.ones(iH.shape, dtype=int)\n",
106 | "sH = np.zeros(iH.shape)\n",
107 | "k = 0\n",
108 | "for i1 in range(nelx):\n",
109 | " for j1 in range(nely):\n",
110 | " e1 = (i1) * nely + (j1 + 1)\n",
111 | " for i2 in np.arange(int(max(i1 + 1 - (np.ceil(rmin) - 1), 1)),\n",
112 | " int(min(i1 + 1 + (np.ceil(rmin) - 1), nelx)) + 1):\n",
113 | " for j2 in np.arange(int(max(j1 + 1 - (np.ceil(rmin) - 1), 1)),\n",
114 | " int(min(j1 + 1 + (np.ceil(rmin) - 1), nely)) + 1):\n",
115 | " e2 = (i2 - 1) * nely + j2\n",
116 | " iH[k] = e1\n",
117 | " jH[k] = e2\n",
118 | " sH[k] = max(0, rmin - np.sqrt((i1 + 1 - i2) ** 2 + (j1 + 1 - j2) ** 2))\n",
119 | " k = k + 1\n",
120 | "\n",
121 | "iH = iH.reshape(-1) - 1\n",
122 | "jH = jH.reshape(-1) - 1\n",
123 | "sH = sH.reshape(-1)\n",
124 | "\n",
125 | "import scipy.sparse as sps\n",
126 | "\n",
127 | "H = sps.csc_matrix((sH, (iH, jH))).toarray()\n",
128 | "Hs = np.sum(H, 1)\n",
129 | "bigM = H > 0\n",
130 | "\n",
131 | "'create neighbourhood index for N'\n",
132 | "r = density_r\n",
133 | "Range = np.arange(-r, r + 1)\n",
134 | "mesh = Range\n",
135 | "X = np.asarray([Range] * len(Range))\n",
136 | "Y = np.asarray([Range] * len(Range)).T\n",
137 | "neighbor = np.array([X.T.reshape(-1), Y.T.reshape(-1)]).T\n",
138 | "D = np.sum(neighbor ** 2, 1)\n",
139 | "rn = np.sum(D <= r ** 2)\n",
140 | "pattern = neighbor[D <= r ** 2, :]\n",
141 | "locX = np.asarray([np.arange(1, nelx + 1)] * nely)\n",
142 | "locY = np.asarray([np.arange(1, nely + 1)] * nelx).T\n",
143 | "loc = np.asarray([locY.T.reshape(-1), locX.T.reshape(-1)]).T\n",
144 | "N = np.zeros([nn, rn])\n",
145 | "for i in range(nn):\n",
146 | " for j in range(rn):\n",
147 | " locc = loc[i, :] + pattern[j, :]\n",
148 | " count_true = 0\n",
149 | " if locc[0] > nely: count_true = count_true + 1\n",
150 | " if locc[1] > nelx: count_true = count_true + 1\n",
151 | "\n",
152 | " if sum(locc < 1) + count_true == 0:\n",
153 | " N[i, j] = locc[0] + (locc[1] - 1) * nely\n",
154 | " else:\n",
155 | " N[i, j] = 'NaN'\n",
156 | "\n",
157 | "idx_temp = (np.array([np.arange(nn)] * rn).T).reshape(-1).reshape(nn * rn, 1)\n",
158 | "N_t = N.T\n",
159 | "idy = []\n",
160 | "idx = []\n",
161 | "import math\n",
162 | "\n",
163 | "k = 0\n",
164 | "for i in range(N_t.shape[1]):\n",
165 | " for j in range(N_t.shape[0]):\n",
166 | " if not math.isnan(N_t[j, i]):\n",
167 | " idy.append(N_t[j, i])\n",
168 | " idx.append(idx_temp[k])\n",
169 | " k = k + 1\n",
170 | "idy = np.asarray(idy).reshape(len(idy), 1) - 1\n",
171 | "idx = np.asarray(idx)\n",
172 | "bigN = sps.coo_matrix((np.ones(len(idx)), (idx.reshape(-1), idy.reshape(-1)))).toarray()\n",
173 | "N_count = np.sum(~np.isnan(N), axis=1)\n",
174 | "\n",
175 | "'Material Properties'\n",
176 | "E0, Emin, nu = 1, 1e-9, 0.3\n",
177 | "\n",
178 | "'PREPARE FINITE ELEMENT ANALYSIS'\n",
179 | "A11 = np.array([[12, 3, -6, -3], [3, 12, 3, 0], [-6, 3, 12, -3], [-3, 0, -3, 12]])\n",
180 | "A12 = np.array([[-6, -3, 0, 3], [-3, -6, -3, -6], [0, -3, -6, 3], [3, -6, 3, -6]])\n",
181 | "B11 = np.array([[-4, 3, -2, 9], [3, -4, -9, 4], [-2, -9, -4, -3], [9, 4, -3, -4]])\n",
182 | "B12 = np.array([[2, -3, 4, -9], [-3, 2, 9, -2], [4, 9, 2, 3], [-9, -2, 3, 2]])\n",
183 | "\n",
184 | "A1 = np.concatenate((A11, A12), axis=1)\n",
185 | "A2 = np.concatenate((A12.T, A11), axis=1)\n",
186 | "A = np.concatenate((A1, A2))\n",
187 | "\n",
188 | "B1 = np.concatenate((B11, B12), axis=1)\n",
189 | "B2 = np.concatenate((B12.T, B11), axis=1)\n",
190 | "B = np.concatenate((B1, B2))\n",
191 | "\n",
192 | "KE = 1 / (1 - nu ** 2) / 24. * (A + nu * B)\n",
193 | "nodenrs = np.arange((1 + nelx) * (1 + nely)).reshape(1 + nelx, 1 + nely).T\n",
194 | "edofVec = (2 * (nodenrs[0:-1, 0:-1] + 1)).reshape(nelx * nely, 1, order='F')\n",
195 | "edofMat = np.asarray([edofVec.reshape(-1)] * 8).T + \\\n",
196 | " np.asarray(([0, 1, 2 * nely + 2, 2 * nely + 3, 2 * nely + 0, 2 * nely + 1, -2, -1]) * nelx * nely).reshape(\n",
197 | " nelx * nely, 8)\n",
198 | "\n",
199 | "iK = np.zeros([edofMat.shape[0] * 8, edofMat.shape[1] * 1])\n",
200 | "for i in range(edofMat.shape[0]):\n",
201 | " for j in range(edofMat.shape[1]):\n",
202 | " iK[i * 8:(i + 1) * 8, j] = np.asarray(edofMat[i, j] * np.ones([8, 1])).reshape(-1)\n",
203 | "iK = (iK.astype(np.int32).T).reshape(64 * nelx * nely, 1, order='F')\n",
204 | "\n",
205 | "jK = np.zeros([edofMat.shape[0] * 1, edofMat.shape[1] * 8])\n",
206 | "for i in range(edofMat.shape[0]):\n",
207 | " for j in range(edofMat.shape[1]):\n",
208 | " jK[i, j * 8:(j + 1) * 8] = np.asarray(edofMat[i, j] * np.ones([1, 8])).reshape(-1)\n",
209 | "jK = (jK.astype(np.int32).T).reshape(64 * nelx * nely, 1, order='F')\n",
210 | "\n",
211 | "'DEFINE LOADS AND SUPPORTS (HALF MBB-BEAM)'\n",
212 | "# F = np.zeros([2 * (nely + 1) * (nelx + 1), 1])\n",
213 | "# F[((nely + 1) * nelx) * 2 + nely + 1, 0] = -1\n",
214 | "F = tf.placeholder(tf.float32, shape=([2*(nely+1)*(nelx+1),batch_size]))\n",
215 | "\n",
216 | "\n",
217 | "# F=sps.coo_matrix(F)\n",
218 | "U = np.zeros([2 * (nely + 1) * (nelx + 1), 1])\n",
219 | "# fixeddofs=(np.arange(0,2*(nely+1),2).tolist());fixeddofs.append(2*(nelx+1)*(nely+1)-1)\n",
220 | "# fixeddofs=np.asarray(fixeddofs).reshape(1,len(fixeddofs))\n",
221 | "# alldofs = np.arange(2*(nely+1)*(nelx+1)).reshape(1,2*(nely+1)*(nelx+1))\n",
222 | "\n",
223 | "fixeddofs = np.asarray(np.arange(0, 2 * (nely + 1), 1).tolist())\n",
224 | "fixeddofs = fixeddofs.reshape(1, len(fixeddofs))\n",
225 | "alldofs = np.arange(2 * (nely + 1) * (nelx + 1)).reshape(1, 2 * (nely + 1) * (nelx + 1))\n",
226 | "\n",
227 | "freedofs = np.setdiff1d(alldofs, fixeddofs)\n",
228 | "\n",
229 | "'prepare some stuff to reduce cost'\n",
230 | "dphi_idphi = (H / sum(H)).T\n",
231 | "\n",
232 | "'Start Iteration'\n",
233 | "# phi = alpha*np.ones([nn,1])\n",
234 | "\n",
235 | "\n",
236 | "\n",
237 | "\n",
238 | "z_dim, h_dim_1, h_dim_2, h_dim_3, h_dim_4, h_dim_5 = 2, 100, 100, 100, 100, 100\n",
239 | "\n",
240 | "# r_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
241 | "# r_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
242 | "# lamda_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
243 | "# lamda_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
244 | "\n",
245 | "F_input = tf.placeholder(tf.float32, shape=([batch_size, z_dim]))\n",
246 | "# F = tf.placeholder(tf.float32, shape=([2*(nely+1)*(nelx+1),batch_size]))\n",
247 | "\n",
248 | "W1 = tf.Variable(xavier_init([z_dim, h_dim_1]))\n",
249 | "b1 = tf.Variable(tf.zeros(shape=[h_dim_1]))\n",
250 | "\n",
251 | "W2 = tf.Variable(xavier_init([h_dim_1, h_dim_2]))\n",
252 | "b2 = tf.Variable(tf.zeros(shape=[h_dim_2]))\n",
253 | "\n",
254 | "W3 = tf.Variable(xavier_init([h_dim_2, h_dim_3]))\n",
255 | "b3 = tf.Variable(tf.zeros(shape=[h_dim_3]))\n",
256 | "\n",
257 | "W4 = tf.Variable(xavier_init([h_dim_3, h_dim_4]))\n",
258 | "b4 = tf.Variable(tf.zeros(shape=[h_dim_4]))\n",
259 | "\n",
260 | "W5 = tf.Variable(xavier_init([h_dim_4, nn]))\n",
261 | "b5 = tf.Variable(tf.zeros(shape=[nn]))\n",
262 | "\n",
263 | "# W6 = tf.Variable(xavier_init([h_dim_5, nn]))\n",
264 | "# b6 = tf.Variable(tf.zeros(shape=[nn]))\n",
265 | "\n",
266 | "h1 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(F_input, W1) + b1),scale=True)\n",
267 | "h2 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h1, W2) + b2),scale=True)\n",
268 | "h3 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h2, W3) + b3),scale=True)\n",
269 | "h4 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h3, W4) + b4),scale=True)\n",
270 | "# h5 = tf.nn.relu(tf.matmul(h4, W5) + b5)\n",
271 | " \n",
272 | "phi_ = tf.sigmoid(tf.matmul(h4, W5) + b5)\n",
273 | "phi = tf.reshape(phi_, [nn, batch_size])\n",
274 | "\n",
275 | "# phi = (tf.Variable(alpha * np.ones([nn, 1]), dtype='float32'))\n",
276 | "\n",
277 | "loop = 0\n",
278 | "# delta = 1.0\n",
279 | "\n",
280 | "# while beta < 1000:\n",
281 | "loop = loop + 1\n",
282 | "loop2 = 0\n",
283 | "'augmented lagrangian parameters'\n",
284 | "# r_lag = 1\n",
285 | "# r_lag2 = 0.001\n",
286 | "# lamda_lag = 0\n",
287 | "# lamda_lag2 = 0\n",
288 | "\n",
289 | "eta = 0.1\n",
290 | "eta2 = 0.1\n",
291 | "epsilon = 1\n",
292 | "dphi = 1e6\n",
293 | "\n",
294 | "r_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
295 | "r_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
296 | "lamda_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
297 | "lamda_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
298 | "beta = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
299 | "################################################################\n",
300 | "'get initial g and c'\n",
301 | "\n",
302 | "import time\n",
303 | "\n",
304 | "W1_fake = tf.Variable(xavier_init([z_dim, h_dim_1]), trainable=False)\n",
305 | "b1_fake = tf.Variable(tf.zeros(shape=[h_dim_1]), trainable=False)\n",
306 | "W1_fake = W1_fake.assign(W1)\n",
307 | "b1_fake = b1_fake.assign(b1)\n",
308 | "\n",
309 | "W2_fake = tf.Variable(xavier_init([h_dim_1, h_dim_2]), trainable=False)\n",
310 | "b2_fake = tf.Variable(tf.zeros(shape=[h_dim_2]), trainable=False)\n",
311 | "W2_fake = W2_fake.assign(W2)\n",
312 | "b2_fake = b2_fake.assign(b2)\n",
313 | "\n",
314 | "W3_fake = tf.Variable(xavier_init([h_dim_2, h_dim_3]), trainable=False)\n",
315 | "b3_fake = tf.Variable(tf.zeros(shape=[h_dim_3]), trainable=False)\n",
316 | "W3_fake = W3_fake.assign(W3)\n",
317 | "b3_fake = b3_fake.assign(b3)\n",
318 | "\n",
319 | "W4_fake = tf.Variable(xavier_init([h_dim_3, h_dim_4]), trainable=False)\n",
320 | "b4_fake = tf.Variable(tf.zeros(shape=[h_dim_4]), trainable=False)\n",
321 | "W4_fake = W4_fake.assign(W4)\n",
322 | "b4_fake = b4_fake.assign(b4)\n",
323 | "\n",
324 | "W5_fake = tf.Variable(xavier_init([h_dim_4, nn]), trainable=False)\n",
325 | "b5_fake = tf.Variable(tf.zeros(shape=[nn]), trainable=False)\n",
326 | "W5_fake = W5_fake.assign(W5)\n",
327 | "b5_fake = b5_fake.assign(b5)\n",
328 | "\n",
329 | "# W6_fake = tf.Variable(xavier_init([h_dim_5, nn]), trainable=False)\n",
330 | "# b6_fake = tf.Variable(tf.zeros(shape=[nn]), trainable=False)\n",
331 | "# W6_fake = W6_fake.assign(W6)\n",
332 | "# b6_fake = b6_fake.assign(b6)\n",
333 | "\n",
334 | "h1_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(F_input, W1_fake) + b1_fake),scale=True,trainable=False)\n",
335 | "h2_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h1_fake, W2_fake) + b2_fake),scale=True,trainable=False)\n",
336 | "h3_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h2_fake, W3_fake) + b3_fake),scale=True,trainable=False)\n",
337 | "h4_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h3_fake, W4_fake) + b4_fake),scale=True,trainable=False)\n",
338 | "# h5_fake = tf.nn.relu(tf.matmul(h4_fake, W5_fake) + b5_fake)\n",
339 | "\n",
340 | "phi_temp_fake = tf.sigmoid(tf.matmul(h4_fake, W5_fake) + b5_fake)\n",
341 | "phi_fake = tf.reshape(phi_temp_fake,[nn,batch_size])\n"
342 | ]
343 | },
344 | {
345 | "cell_type": "code",
346 | "execution_count": null,
347 | "metadata": {
348 | "collapsed": true
349 | },
350 | "outputs": [],
351 | "source": [
352 | "sep_grad_store,error_store,dphi_store,dobj_store=[],[],[],[]\n",
353 | "c,g,global_density=[],[],[]\n",
354 | "c_fake,g_fake,global_density_fake=[],[],[]\n",
355 | "rho,rho_fake=[],[]\n",
356 | "dphi_fake=[]\n",
357 | "\n",
358 | "tic=time.clock()\n",
359 | "\n",
360 | "learning_rate_fake = tf.placeholder(tf.float32,shape=([batch_size,1]))\n",
361 | "g_old = [tf.Variable(0, dtype='float32',trainable=False)]*batch_size\n",
362 | "global_density_old = [tf.Variable([[0]], dtype='float32',trainable=False)]*batch_size\n",
363 | "c_old = [tf.Variable(0, dtype='float32',trainable=False)]*batch_size\n",
364 | "tic=time.clock()\n",
365 | "\n",
366 | "for i in range(batch_size):\n",
367 | " phi_til = tf.matmul(tf.cast(H, tf.float32), phi[:,i:i+1]) / Hs.reshape(nn, 1)\n",
368 | " rho.append((tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0)))\n",
369 | "\n",
370 | " sK_temp = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
371 | " tf.reshape(Emin + tf.reshape(rho[i], [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
372 | " sK = tf.reshape(sK_temp, [8 * 8 * nelx * nely, 1])\n",
373 | "\n",
374 | " ###################\n",
375 | " indices_m = np.stack((iK.reshape(-1), jK.reshape(-1)), axis=1)\n",
376 | " values_m = tf.reshape(sK, [-1])\n",
377 | "\n",
378 | " linearized_m = tf.matmul(indices_m, [[10000], [1]])\n",
379 | " y_m, idx_m = tf.unique(tf.squeeze(linearized_m))\n",
380 | "\n",
381 | " idx_m_sort, ind_m_sort = tf.nn.top_k(idx_m, k=nelx * nely * 64)\n",
382 | " idx_m_sort = tf.reverse(idx_m_sort, [0])\n",
383 | " ind_m_sort = tf.reverse(ind_m_sort, [0])\n",
384 | "\n",
385 | " # values_m_test = values_m\n",
386 | " values_m = tf.gather(values_m, ind_m_sort)\n",
387 | " values_m = tf.segment_sum(values_m, idx_m_sort)\n",
388 | "\n",
389 | " y_m = tf.expand_dims(y_m, 1)\n",
390 | " indices_m = tf.concat([y_m // 10000, y_m % 10000], axis=1)\n",
391 | " #####################\n",
392 | "\n",
393 | " #####################\n",
394 | " K_sp = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
395 | " tf.reshape(tf.cast(values_m, tf.float32), [-1]),\n",
396 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
397 | " K_sp = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp)\n",
398 | " K_dense = (K_sp + tf.transpose(K_sp)) / 2\n",
399 | " #####################\n",
400 | "\n",
401 | " K_temp = tf.gather(K_dense, freedofs.astype(np.int32))\n",
402 | " K_free = tf.transpose(tf.gather(tf.transpose(K_temp), freedofs.astype(np.int32)))\n",
403 | " \n",
404 | " F_RHS=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
405 | " tf.float32)\n",
406 | " chol = tf.cholesky(K_free+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
407 | " U_pre = tf.cholesky_solve(chol,F_RHS)\n",
408 | " \n",
409 | "# U_pre = tf.matmul(tf.matrix_inverse(tf.cast(K_free, tf.float32)),\n",
410 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
411 | "# tf.float32))\n",
412 | "\n",
413 | " U = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
414 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
415 | " tf.reshape(tf.cast(U_pre, tf.float32), [-1]), [(nelx + 1) * (nely + 1) * 2]))\n",
416 | "\n",
417 | " 'Objective Function and Sensitivity Analysis'\n",
418 | " ce = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U, edofMat.astype(np.int32)), edofMat.shape),\n",
419 | " KE.astype(np.float32)), tf.gather(U, edofMat.astype(np.int32))), axis=1)\n",
420 | " ce = tf.reshape(ce, [nn, 1])\n",
421 | " c.append(tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho[i] ** gamma, (E0 - Emin)), tf.float32), ce)))\n",
422 | " rho_bar = tf.divide(tf.matmul(tf.cast(bigN, tf.float32), rho[i]), N_count.reshape(nn, 1))\n",
423 | " g.append((tf.reduce_sum(rho_bar ** p) / nely / nelx) ** (1.0 / p) / alpha - 1.0)\n",
424 | " global_density.append(tf.matmul(tf.transpose(rho[i]), tf.ones([nn, 1])) / nn - alpha2)\n",
425 | " ###################################################################\n",
426 | "\n",
427 | " # if ((max(abs(dphi)))2) or (loo2>100):\n",
428 | "\n",
429 | "\n",
430 | " dc_drho = -gamma * rho[i] ** (gamma - 1) * (E0 - Emin) * ce\n",
431 | " drho_dphi = beta[i][0] * (1 - tf.tanh(beta[i][0] * (phi[:,i:i+1] - 0.5)) ** 2) / 2.0 / tf.tanh(beta[i][0] / 2.)\n",
432 | " dc_dphi = tf.reduce_sum(bigM * (dphi_idphi * (dc_drho * drho_dphi)), axis=0)\n",
433 | " dg_drhobar = 1.0 / alpha / nn * (1.0 / nn * tf.reduce_sum(rho_bar ** p)) ** (1.0 / p - 1) * rho_bar ** (p - 1)\n",
434 | " dg_dphi = tf.reduce_sum(bigM * (dphi_idphi * (tf.matmul(tf.cast(bigN, tf.float32),\n",
435 | " (dg_drhobar / N_count.reshape(nn, 1))) * drho_dphi)), axis=0)\n",
436 | "\n",
437 | " dphi = dc_dphi + tf.cast(lamda_lag[i][0] * dg_dphi * tf.reduce_sum(tf.cast(g[i] > 0, tf.float32)), tf.float32) + \\\n",
438 | " tf.cast(2.0 / r_lag[i][0] * g[i] * dg_dphi * tf.reduce_sum(tf.cast(g[i] > 0, tf.float32)), tf.float32) + \\\n",
439 | " lamda_lag2[i][0] * tf.ones(nn, 1) / nn * (tf.reduce_sum(tf.cast(global_density[i] > 0, tf.float32))) + \\\n",
440 | " tf.reshape(2.0 / r_lag2[i][0] * global_density[i] / nn / nn * tf.ones([nn, 1]) * (\n",
441 | " tf.reduce_sum(tf.cast(global_density[i] > 0, tf.float32))), [-1])\n",
442 | " \n",
443 | " dphi_store.append(dphi)\n",
444 | " \n",
445 | "\n",
446 | " \n",
447 | "############################################################################################################\n",
448 | "\n",
449 | " 'get initial g and c'\n",
450 | " phi_til_fake = tf.matmul(tf.cast(H, tf.float32), phi_fake[:,i:i+1]) / Hs.reshape(nn, 1)\n",
451 | " rho_fake.append((tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til_fake - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0)))\n",
452 | "\n",
453 | " sK_temp_fake = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
454 | " tf.reshape(Emin + tf.reshape(rho_fake[i], [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
455 | " sK_fake = tf.reshape(sK_temp_fake, [8 * 8 * nelx * nely, 1])\n",
456 | "\n",
457 | " ###################\n",
458 | " indices_m = np.stack((iK.reshape(-1), jK.reshape(-1)), axis=1)\n",
459 | " values_m_fake = tf.reshape(sK_fake, [-1])\n",
460 | "\n",
461 | " linearized_m = tf.matmul(indices_m, [[10000], [1]])\n",
462 | " y_m, idx_m = tf.unique(tf.squeeze(linearized_m))\n",
463 | "\n",
464 | " idx_m_sort, ind_m_sort = tf.nn.top_k(idx_m, k=nelx * nely * 64)\n",
465 | " idx_m_sort = tf.reverse(idx_m_sort, [0])\n",
466 | " ind_m_sort = tf.reverse(ind_m_sort, [0])\n",
467 | "\n",
468 | " values_m_fake = tf.gather(values_m_fake, ind_m_sort)\n",
469 | " values_m_fake = tf.segment_sum(values_m_fake, idx_m_sort)\n",
470 | "\n",
471 | " y_m = tf.expand_dims(y_m, 1)\n",
472 | " indices_m = tf.concat([y_m // 10000, y_m % 10000], axis=1)\n",
473 | " #####################\n",
474 | "\n",
475 | " #####################\n",
476 | " K_sp_fake = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
477 | " tf.reshape(tf.cast(values_m_fake, tf.float32), [-1]),\n",
478 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
479 | " K_sp_fake = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp_fake)\n",
480 | " K_dense_fake = (K_sp_fake + tf.transpose(K_sp_fake)) / 2.0\n",
481 | " #####################\n",
482 | "\n",
483 | " K_temp_fake = tf.gather(K_dense_fake, freedofs.astype(np.int32))\n",
484 | " K_free_fake = tf.transpose(tf.gather(tf.transpose(K_temp_fake), freedofs.astype(np.int32)))\n",
485 | "\n",
486 | " F_RHS_fake=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
487 | " tf.float32)\n",
488 | " chol_fake = tf.cholesky(K_free_fake+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
489 | " U_pre_fake = tf.cholesky_solve(chol_fake,F_RHS_fake)\n",
490 | " \n",
491 | "# U_pre_fake = tf.matmul(tf.matrix_inverse(tf.cast(K_free_fake, tf.float32)),\n",
492 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
493 | "# tf.float32))\n",
494 | "\n",
495 | " U_fake = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
496 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
497 | " tf.reshape(tf.cast(U_pre_fake, tf.float32), [-1]),\n",
498 | " [(nelx + 1) * (nely + 1) * 2]))\n",
499 | "\n",
500 | " 'Objective Function and Sensitivity Analysis'\n",
501 | " ce_fake = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U_fake, edofMat.astype(np.int32)), edofMat.shape),\n",
502 | " KE.astype(np.float32)), tf.gather(U_fake, edofMat.astype(np.int32))),\n",
503 | " axis=1)\n",
504 | " ce_fake = tf.reshape(ce_fake, [nn, 1])\n",
505 | " c_fake.append(tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho_fake[i] ** gamma, (E0 - Emin)), tf.float32), ce_fake)))\n",
506 | " rho_bar_fake=tf.divide(tf.matmul(tf.cast(bigN, tf.float32), rho_fake[i]), N_count.reshape(nn, 1))\n",
507 | " g_fake.append((tf.reduce_sum(rho_bar_fake ** p) / nely / nelx) ** (1. / p) / alpha - 1.0)\n",
508 | " global_density_fake.append(tf.matmul(tf.transpose(rho_fake[i]), tf.ones([nn, 1])) / nn - alpha2)\n",
509 | " ###################################################################\n",
510 | "\n",
511 | " # if ((max(abs(dphi)))2) or (loo2>100):\n",
512 | "\n",
513 | "\n",
514 | " dc_drho_fake = -gamma * rho_fake[i] ** (gamma - 1) * (E0 - Emin) * ce_fake\n",
515 | " drho_dphi_fake = beta[i][0] * (1 - tf.tanh(beta[i][0] * (phi_fake[:,i:i+1] - 0.5)) ** 2) / 2.0 / tf.tanh(beta[i][0] / 2.)\n",
516 | " dc_dphi_fake = tf.reduce_sum(bigM * (dphi_idphi * (dc_drho_fake * drho_dphi_fake)), axis=0)\n",
517 | " dg_drhobar_fake = 1.0 / alpha / nn * (1.0 / nn * tf.reduce_sum(rho_bar_fake ** p)) ** (1.0 / p - 1) * rho_bar_fake ** (\n",
518 | " p - 1)\n",
519 | " dg_dphi_fake = tf.reduce_sum(bigM * (dphi_idphi * (tf.matmul(tf.cast(bigN, tf.float32),\n",
520 | " (dg_drhobar_fake / N_count.reshape(nn,\n",
521 | " 1))) * drho_dphi_fake)),\n",
522 | " axis=0)\n",
523 | "\n",
524 | " A = dc_dphi_fake + tf.cast(lamda_lag[i][0] * dg_dphi_fake * tf.reduce_sum(tf.cast(g_fake[i] > 0, tf.float32)), tf.float32) + \\\n",
525 | " tf.cast(2.0 / r_lag[i][0] * g_fake[i] * dg_dphi_fake * tf.reduce_sum(tf.cast(g_fake[i] > 0, tf.float32)), tf.float32)\n",
526 | "\n",
527 | " B = lamda_lag2[i][0] * tf.ones(nn, 1) / nn * (tf.reduce_sum(tf.cast(global_density_fake[i] > 0, tf.float32))) + \\\n",
528 | " 2.0 / r_lag2[i][0] * global_density_fake[i] / nn / nn * tf.ones([nn]) * (tf.reduce_sum(tf.cast(global_density_fake[i] > 0, tf.float32)))\n",
529 | "\n",
530 | " dphi_fake.append(A + B)\n",
531 | " \n",
532 | " \n",
533 | " error_sep = tf.reduce_sum(((tf.reshape(dphi_fake[i], [nn, 1]) * phi[:,i:i+1])))\n",
534 | " error_store.append(error_sep)\n",
535 | " \n",
536 | " sep_grad=tf.reduce_sum(tf.abs(tf.gradients((tf.reshape(dphi_fake[i], [nn, 1]) * phi[:,i:i+1]),W1)))\n",
537 | " sep_grad_store.append(sep_grad)\n",
538 | " \n",
539 | "############################################################################################\n",
540 | "# g_old = tf.Variable(0, dtype='float32',trainable=False)\n",
541 | "# global_density_old = tf.Variable([[0]], dtype='float32',trainable=False)\n",
542 | "# c_old = tf.Variable(0, dtype='float32',trainable=False)\n",
543 | "\n",
544 | " g_old[i] = g_old[i].assign(g[i])\n",
545 | " global_density_old[i] = global_density_old[i].assign(global_density[i])\n",
546 | " c_old[i] = c_old[i].assign(c[i])\n",
547 | "\n",
548 | "# assign_g=tf.assign(g_old[i],g[i])\n",
549 | "# assign_gd=tf.assign(global_density_old[i],global_density[i])\n",
550 | "# assign_c=tf.assign(c_old[i],c[i])\n",
551 | "\n",
552 | " 'learning rate adjusting'\n",
553 | " delta = -dphi_fake[i] * learning_rate_fake[i][0]\n",
554 | " phi_temp = phi_fake[:,i:i+1] + tf.reshape(delta, [nn, 1])\n",
555 | "\n",
556 | " # assign_phi = tf.assign(phi,phi_temp)\n",
557 | "\n",
558 | " # phi_temp=tf.Variable(np.ones([nn,1]), dtype='float32')\n",
559 | " # phi_temp=phi_temp.assign(phi)\n",
560 | "\n",
561 | " phi_til_temp = tf.matmul(tf.cast(H, tf.float32), phi_temp) / tf.reshape(tf.cast(Hs, tf.float32), [nn, 1])\n",
562 | " rho_temp = (tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til_temp - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0))\n",
563 | " rho_bar_temp = (tf.matmul(tf.cast(bigN, tf.float32), rho_temp) / tf.reshape(tf.cast(N_count, tf.float32), [nn, 1]))\n",
564 | " g_temp = (tf.reduce_sum(rho_bar_temp ** p) / nn) ** (1.0 / p) / alpha - 1.0\n",
565 | " global_density_temp = tf.matmul(tf.transpose(rho_temp), tf.ones([nn, 1])) / nn - alpha2\n",
566 | "\n",
567 | " sK_temp_fake2 = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
568 | " tf.reshape(Emin + tf.reshape(rho_temp, [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
569 | " sK_fake2 = tf.reshape(sK_temp_fake2, [8 * 8 * nelx * nely, 1])\n",
570 | "\n",
571 | " ###################\n",
572 | " values_m_fake2 = tf.reshape(sK_fake2, [-1])\n",
573 | " values_m_fake2 = tf.gather(values_m_fake2, ind_m_sort)\n",
574 | " values_m_fake2 = tf.segment_sum(values_m_fake2, idx_m_sort)\n",
575 | " ###################\n",
576 | "\n",
577 | " ###################\n",
578 | " K_sp_fake2 = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
579 | " tf.reshape(tf.cast(values_m_fake2, tf.float32), [-1]),\n",
580 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
581 | " K_sp_fake2 = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp_fake2)\n",
582 | " K_dense_fake2 = (K_sp_fake2 + tf.transpose(K_sp_fake2)) / 2.0\n",
583 | " ###################\n",
584 | "\n",
585 | " K_temp_fake2 = tf.gather(K_dense_fake2, freedofs.astype(np.int32))\n",
586 | " K_free_fake2 = tf.transpose(tf.gather(tf.transpose(K_temp_fake2), freedofs.astype(np.int32)))\n",
587 | " \n",
588 | " F_RHS_fake2=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
589 | " tf.float32)\n",
590 | " chol_fake2 = tf.cholesky(K_free_fake2+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
591 | " U_pre_fake2 = tf.cholesky_solve(chol_fake2,F_RHS_fake2)\n",
592 | " \n",
593 | "# U_pre_fake2 = tf.matmul(tf.matrix_inverse(tf.cast(K_free_fake2, tf.float32)+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-15).tolist()[0])),\n",
594 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),tf.float32))\n",
595 | "\n",
596 | " U_fake2 = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
597 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
598 | " tf.reshape(tf.cast(U_pre_fake2, tf.float32), [-1]),\n",
599 | " [(nelx + 1) * (nely + 1) * 2]))\n",
600 | "\n",
601 | " ce_temp = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U_fake2, edofMat.astype(np.int32)), edofMat.shape),\n",
602 | " KE.astype(np.float32)), tf.gather(U_fake2, edofMat.astype(np.int32))),axis=1)\n",
603 | " \n",
604 | " ce_temp = tf.reshape(ce_temp, [nn, 1])\n",
605 | " c_temp = tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho_temp ** gamma, (E0 - Emin)), tf.float32), ce_temp))\n",
606 | "\n",
607 | " A2 = (c_temp + lamda_lag[i][0] * g_temp * (tf.reduce_sum(tf.cast(g_temp > 0, tf.float32))) + 1.0 / r_lag[i][0] * g_temp ** 2 * (\n",
608 | " tf.reduce_sum(tf.cast(g_temp > 0, tf.float32))) + \\\n",
609 | " 1.0 / r_lag2[i][0] * global_density_temp ** 2 * (tf.reduce_sum(tf.cast(global_density_temp > 0, tf.float32))))\n",
610 | "\n",
611 | " B2 = (c_old[i] + lamda_lag[i][0] * g_old[i] * (tf.reduce_sum(tf.cast(g_old[i] > 0, tf.float32))) + 1.0 / r_lag[i][0] * g_old[i] ** 2 * (\n",
612 | " tf.reduce_sum(tf.cast(g_old[i] > 0, tf.float32))) + \\\n",
613 | " 1.0 / r_lag2[i][0] * global_density_old[i] ** 2 * (tf.reduce_sum(tf.cast(global_density_old[i] > 0, tf.float32))))\n",
614 | " dobj = A2 - B2\n",
615 | " dobj_store.append(dobj)\n",
616 | " \n",
617 | "toc=time.clock()\n",
618 | "print(toc-tic)"
619 | ]
620 | },
621 | {
622 | "cell_type": "code",
623 | "execution_count": null,
624 | "metadata": {
625 | "collapsed": true
626 | },
627 | "outputs": [],
628 | "source": [
629 | "global_step = tf.Variable(0, trainable=False)\n",
630 | "starter_learning_rate = 0.001\n",
631 | "learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,\n",
632 | " 1000, 1.0, staircase=True)\n",
633 | "\n",
634 | "solver0 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[0], global_step=global_step)\n",
635 | "solver1 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[1], global_step=global_step)\n",
636 | "solver2 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[2], global_step=global_step)\n",
637 | "\n",
638 | "sess = tf.Session()\n",
639 | "sess.run(tf.global_variables_initializer())"
640 | ]
641 | },
642 | {
643 | "cell_type": "code",
644 | "execution_count": null,
645 | "metadata": {
646 | "collapsed": true
647 | },
648 | "outputs": [],
649 | "source": [
650 | "force=-1\n",
651 | "F_batch=np.zeros([batch_size,z_dim])\n",
652 | "\n",
653 | "# alpha=1.5\n",
654 | "theta = np.linspace(np.pi*0.,2.0*np.pi/5.,batch_size)\n",
655 | "\n",
656 | "count=0\n",
657 | "for i in range(batch_size-1,-1,-1):\n",
658 | "# theta = 2*(i+1)*np.pi/10.#+i*np.pi/9*alpha\n",
659 | " print theta[i]\n",
660 | "# theta = (i+1)*np.pi/10\n",
661 | " Fx = force*np.sin(theta[i])\n",
662 | " Fy = force*np.cos(theta[i])\n",
663 | " \n",
664 | " # up-right corner\n",
665 | " F_batch[count,0]=Fx\n",
666 | " F_batch[count,1]=Fy\n",
667 | " count=count+1 \n",
668 | "\n",
669 | "count=0\n",
670 | "F_sp=np.zeros([2*(nely+1)*(nelx+1),batch_size])\n",
671 | "for i in range(batch_size-1,-1,-1):\n",
672 | "# theta = 2*(i+1)*np.pi/10.#+i*np.pi/9*alpha\n",
673 | "# theta = (i+1)*np.pi/5\n",
674 | " Fx = force*np.sin(theta[i])\n",
675 | " Fy = force*np.cos(theta[i]) \n",
676 | " F_sp[(nely+1)*2*nelx+nely, count] = Fx\n",
677 | " F_sp[(nely+1)*2*nelx+nely+1, count] = Fy\n",
678 | " count=count+1\n",
679 | "\n",
680 | "print F_batch"
681 | ]
682 | },
683 | {
684 | "cell_type": "code",
685 | "execution_count": null,
686 | "metadata": {
687 | "collapsed": true
688 | },
689 | "outputs": [],
690 | "source": [
691 | "lamda_value = np.zeros([batch_size, 1])\n",
692 | "lamda_value2 = np.zeros([batch_size, 1])\n",
693 | "r_value = np.ones([batch_size, 1]) * 1\n",
694 | "r_value2 = np.ones([batch_size, 1]) * 0.001\n",
695 | "eta = np.ones([batch_size, 1]) * 0.1\n",
696 | "eta2 = np.ones([batch_size, 1]) * 0.1\n",
697 | "j, j2 = 0, 0\n",
698 | "\n",
699 | "k_j = np.ones([batch_size, 1])\n",
700 | "thre_range = 0.02\n",
701 | "agg = 0\n",
702 | "total_E_pre = 1e20\n",
703 | "count_k = 0\n",
704 | "count = 0\n",
705 | "drho=1e6\n",
706 | "it=0\n",
707 | "beta_value=np.ones([batch_size,1])*10\n",
708 | "learning_rate_fake_value=np.ones([batch_size,1])*0.001"
709 | ]
710 | },
711 | {
712 | "cell_type": "code",
713 | "execution_count": null,
714 | "metadata": {
715 | "collapsed": true
716 | },
717 | "outputs": [],
718 | "source": [
719 | "import os\n",
720 | "import time\n",
721 | "timestr = time.strftime(\"%Y%m%d-%H%M%S_bn\")\n",
722 | "if not os.path.exists(timestr):\n",
723 | " os.makedirs(timestr)"
724 | ]
725 | },
726 | {
727 | "cell_type": "code",
728 | "execution_count": null,
729 | "metadata": {
730 | "collapsed": true
731 | },
732 | "outputs": [],
733 | "source": [
734 | "####################\n",
735 | "# logdir,modeldir=creat_dir('infill_var')\n",
736 | "# summary_writer = tf.summary.FileWriter(logdir)\n",
737 | "# summary_op_train = tf.summary.merge([tf.summary.scalar(\"train/error\",error_total)])\n",
738 | "####################\n",
739 | "\n",
740 | "# for it in range(100000):\n",
741 | "it=0\n",
742 | "drho_total_store=[]\n",
743 | "\n",
744 | "while min(beta_value)<11:\n",
745 | " it=it+1\n",
746 | " # sess.run([assign_phi_fake,assign_c,assign_g,assign_gd], feed_dict={learning_rate_fake: starter_learning_rate, lamda_lag: lamda_value,\n",
747 | " # lamda_lag2: lamda_value2,\n",
748 | " # r_lag: r_value,\n",
749 | " # r_lag2: r_value2})\n",
750 | " \n",
751 | "# total_E, g_value, gd, dphi_fake_value, dobj_value, lr, phi_fake_value,rho_value = sess.run([error_store, g,\n",
752 | "# global_density, dphi_fake, dobj_store,\n",
753 | "# learning_rate,phi_fake,rho],\n",
754 | "# feed_dict={learning_rate_fake: learning_rate_fake_value,\n",
755 | "# lamda_lag:lamda_value,\n",
756 | "# lamda_lag2:lamda_value2,\n",
757 | "# r_lag:r_value,\n",
758 | "# r_lag2:r_value2,\n",
759 | "# F_input:F_batch,\n",
760 | "# F:F_sp, \n",
761 | "# learning_rate:starter_learning_rate,beta:beta_value})\n",
762 | "\n",
763 | " \n",
764 | " \n",
765 | " loop2=0\n",
766 | " \n",
767 | " while 1:\n",
768 | "# try:\n",
769 | " g_value_temp,dphi_fake_value,rho_pre = sess.run([g,dphi_fake,rho], \n",
770 | " feed_dict={learning_rate_fake: learning_rate_fake_value,\n",
771 | " lamda_lag:lamda_value,lamda_lag2:lamda_value2,\n",
772 | " r_lag:r_value,r_lag2:r_value2,F_input: F_batch,\n",
773 | " F:F_sp,learning_rate:starter_learning_rate,\n",
774 | " beta:beta_value})\n",
775 | "# except:\n",
776 | "# stop=1\n",
777 | "\n",
778 | " \n",
779 | " dphi_fake_value_max=max(max(abs(np.array(dphi_fake_value[0])).reshape(-1)),\n",
780 | " max(abs(np.array(dphi_fake_value[1])).reshape(-1)),\n",
781 | " max(abs(np.array(dphi_fake_value[2])).reshape(-1)))\n",
782 | " \n",
783 | " \n",
784 | " if (dphi_fake_value_max < 1*batch_size and max(g_value_temp) < 0.01 and loop2 > 0) or (loop2 > 100):\n",
785 | "\n",
786 | "# if (drho < 0.05 and max(g_value_temp) < 0.005 and loop2 > 0) or (loop2 > 100):\n",
787 | " # print('wrong')\n",
788 | " lamda_value = np.zeros([batch_size, 1])\n",
789 | " lamda_value2 = np.zeros([batch_size, 1])\n",
790 | " r_value = np.ones([batch_size, 1]) * 1\n",
791 | " r_value2 = np.ones([batch_size, 1]) * 0.001\n",
792 | " eta = np.ones([batch_size, 1]) * 0.1\n",
793 | " eta2 = np.ones([batch_size, 1]) * 0.1\n",
794 | " dphi_fake_value=np.array([1e6]*batch_size)\n",
795 | " drho=np.array([1e6]*batch_size)\n",
796 | " break\n",
797 | "\n",
798 | " loop2 = loop2 + 1\n",
799 | " j, j2 = 0, 0\n",
800 | " loop3 = np.array([0]*batch_size)\n",
801 | " dphi_fake_value = np.array([1e6]*batch_size)\n",
802 | " drho = np.array([1e6]*batch_size)\n",
803 | " \n",
804 | "\n",
805 | "\n",
806 | " while (max(max(abs(np.array(dphi_fake_value[0])).reshape(-1)),\n",
807 | " max(abs(np.array(dphi_fake_value[1])).reshape(-1)),\n",
808 | " max(abs(np.array(dphi_fake_value[2])).reshape(-1)))) > epsilon and min(loop3) < 1000:\n",
809 | " \n",
810 | "# rho_value_pre = sess.run(rho, feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
811 | "# F_input: F_batch,F:F_sp,learning_rate:starter_learning_rate,beta:beta_value})\n",
812 | "\n",
813 | " \n",
814 | " for i in range(batch_size):\n",
815 | " if count>=4000:\n",
816 | " break\n",
817 | " if loop3[i]>1000:\n",
818 | " continue\n",
819 | "# dphi_fake_value[i] = np.array([1e6])\n",
820 | "# g_value = g_value_temp[i]\n",
821 | "\n",
822 | " starter_learning_rate = 0.001\n",
823 | " learning_rate_fake_value[i]=0.001\n",
824 | " loop3[i] = loop3[i] + 1\n",
825 | " loop4 = np.asarray([0]*batch_size)\n",
826 | "\n",
827 | " tic=time.clock()\n",
828 | " while loop4[i] < 10:\n",
829 | " try:\n",
830 | " dphi_fake_value, dobj_value,rho_value = sess.run([dphi_fake, dobj_store,rho],\n",
831 | " feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
832 | " lamda_lag2:lamda_value2, r_lag:r_value,\n",
833 | " r_lag2:r_value2,F_input:F_batch,\n",
834 | " F:F_sp,learning_rate:learning_rate_fake_value[i][0],\n",
835 | " beta:beta_value})\n",
836 | " except:\n",
837 | " starter_learning_rate = starter_learning_rate*0.5\n",
838 | " learning_rate_fake_value[i] = learning_rate_fake_value[i]*0.5\n",
839 | " \n",
840 | "\n",
841 | "\n",
842 | " if dobj_value[i] > 0:\n",
843 | " starter_learning_rate = starter_learning_rate * 0.5\n",
844 | " learning_rate_fake_value[i] = learning_rate_fake_value[i]*0.5\n",
845 | " loop4[i] = loop4[i] + 1\n",
846 | " if loop4[i] == 10:\n",
847 | " loop3[i] = 10000\n",
848 | " dphi_fake_value[i] = np.array([0])\n",
849 | " drho[i] = np.array([0])\n",
850 | " # break\n",
851 | " else:\n",
852 | " if i == 0:\n",
853 | " try:\n",
854 | " sess.run([solver0],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
855 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
856 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
857 | "\n",
858 | " except:\n",
859 | " print('jump0')\n",
860 | " \n",
861 | " if i == 1:\n",
862 | " try:\n",
863 | " sess.run([solver1],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
864 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
865 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
866 | "\n",
867 | " except:\n",
868 | " print('jump1')\n",
869 | " \n",
870 | " if i == 2:\n",
871 | " try:\n",
872 | " sess.run([solver2],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
873 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
874 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
875 | " except:\n",
876 | " print('jump2')\n",
877 | " \n",
878 | " break\n",
879 | "\n",
880 | " toc=time.clock()\n",
881 | " count = count + 1\n",
882 | "# try:\n",
883 | " g_value,c_value,sep_grad_value,error_total_value,phi_value,rho_curr=sess.run([g,c,sep_grad_store,error_store,phi,rho], \n",
884 | " feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,\n",
885 | " lamda_lag2: lamda_value2,r_lag: r_value,\n",
886 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: learning_rate_fake_value[i][0],\n",
887 | " beta: beta_value})\n",
888 | "# except:\n",
889 | "# print('jump3')\n",
890 | "\n",
891 | " drho[i]=sum(abs(rho_curr[i]-rho_pre[i]).reshape(-1))\n",
892 | " drho_total=sum(abs(np.array(rho_curr)-np.array(rho_pre)).reshape(-1))\n",
893 | " drho_total_store.append(drho_total)\n",
894 | " print('iteration:{}'.format(it))\n",
895 | " print('updating_case:{}'.format(i))\n",
896 | " print('num_update:{}'.format(count))\n",
897 | " print('total_error:{}'.format(np.sum(np.array(error_total_value))))\n",
898 | " print('g_value:{}'.format(g_value))\n",
899 | " print('c_value:{}'.format(c_value))\n",
900 | " print('log_r:{}'.format(np.log(r_value)))\n",
901 | "# print('max_abs_dphi:{}'.format(max(abs(dphi_fake_value.reshape(-1)))))\n",
902 | " print('gradient_W1:{}'.format(sep_grad_value))\n",
903 | " print('dobj_value:{}'.format(dobj_value))\n",
904 | " # r_lag2:r_value2,F_input: F_batch,F:F_sp,learning_rate:starter_learning_rate,beta:beta_value})))\n",
905 | " print('dphi_fake_value_max:{}'.format((max(abs(dphi_fake_value[i].reshape(-1))))))\n",
906 | "# print('drho_fake_value_max:{}'.format(max(abs(rho_value[i].reshape(-1)-rho_value_pre[i].reshape(-1)))))\n",
907 | " print('drho:{}'.format(drho))\n",
908 | " print('loop3:{}'.format(loop3))\n",
909 | " print\n",
910 | " print('running time:{}'.format(toc-tic))\n",
911 | " print()\n",
912 | " if count%500 == 0:\n",
913 | " sio.savemat('{}/c_value.mat'.format(timestr), mdict={'c': np.array(c_value)})\n",
914 | " sio.savemat('{}/rho.mat'.format(timestr), mdict={'rho': np.array(rho_curr)})\n",
915 | " sio.savemat('{}/drho.mat'.format(timestr), mdict={'drho': np.array(drho_total_store)})\n",
916 | " fig, axs = plt.subplots(2, 5, figsize=(15, 4), facecolor='w', edgecolor='k')\n",
917 | " fig.subplots_adjust(hspace=.1, wspace=.001)\n",
918 | "\n",
919 | " axs = axs.ravel()\n",
920 | "\n",
921 | " for i in range(batch_size):\n",
922 | " axs[i].imshow(1 - rho_curr[i].reshape([nelx, nely]).T, 'gray')\n",
923 | " axs[i].set_title('c={}'.format(c_value[i]))\n",
924 | " plt.savefig('{}/opt_{}.png'.format(timestr, str(count)))\n",
925 | " plt.close()\n",
926 | " if count >= 4000:\n",
927 | " break\n",
928 | "# drho1=max(rho_value_cur[0].reshape(-1)-rho_value_pre[0].reshape(-1))\n",
929 | "# drho2=max(rho_value_cur[1].reshape(-1)-rho_value_pre[1].reshape(-1))\n",
930 | "# drho3=max(rho_value_cur[2].reshape(-1)-rho_value_pre[2].reshape(-1))\n",
931 | "# drho=max(drho1,drho2,drho3)\n",
932 | " \n",
933 | " \n",
934 | "# g_value, gd, rho_value_cur = sess.run([g, global_density,rho], \n",
935 | "# feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
936 | "# lamda_lag2:lamda_value2,r_lag:r_value,\n",
937 | "# r_lag2:r_value2,F_input: F_batch,F:F_sp,\n",
938 | "# learning_rate:starter_learning_rate,beta:beta_value})\n",
939 | " for i in range(batch_size): \n",
940 | " g_value, gd= sess.run([g, global_density], \n",
941 | " feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
942 | " lamda_lag2:lamda_value2,r_lag:r_value,\n",
943 | " r_lag2:r_value2,F_input: F_batch,F:F_sp,\n",
944 | " learning_rate:learning_rate_fake_value[i][0],beta:beta_value}) \n",
945 | " if g_value[i] < eta[i]:\n",
946 | " lamda_value[i] = lamda_value[i] + 2 * g_value[i] / r_value[i]\n",
947 | " j = j + 1\n",
948 | " eta[i] = eta[i] * 0.5\n",
949 | " else:\n",
950 | " r_value[i] = r_value[i] * 0.5\n",
951 | " j = 0\n",
952 | "\n",
953 | " if gd[i] < eta2[i]:\n",
954 | " lamda_value2[i] = lamda_value2[i] + 2 * gd[i][0] / r_value2[i]\n",
955 | " j2 = j2 + 1\n",
956 | " eta2[i] = eta2[i] * 0.5\n",
957 | " else:\n",
958 | " r_value2[i] = r_value2[i] * 0.5\n",
959 | " j2 = 0\n",
960 | " \n",
961 | " for i in range(batch_size):\n",
962 | " beta_value[i] = 1.5 * beta_value[i]\n",
963 | "\n",
964 | "phi_value, rho_value = sess.run([phi, rho],feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,lamda_lag2: lamda_value2,r_lag: r_value,\n",
965 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: starter_learning_rate, beta: beta_value})\n",
966 | "\n",
967 | "print('finished')\n",
968 | "# sio.savemat('result/infill_phi_{}.mat'.format(count), mdict={'phi': phi_value})\n",
969 | "# sio.savemat('result/infill_rho_{}.mat'.format(count), mdict={'rho': rho_value})"
970 | ]
971 | },
972 | {
973 | "cell_type": "code",
974 | "execution_count": null,
975 | "metadata": {
976 | "collapsed": true
977 | },
978 | "outputs": [],
979 | "source": [
980 | "# import os\n",
981 | "# import time\n",
982 | "# timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n",
983 | "# if not os.path.exists(timestr):\n",
984 | "# os.makedirs(timestr)\n",
985 | "\n",
986 | "sio.savemat('{}/c_value.mat'.format(timestr), mdict={'c': np.array(c_value)})\n",
987 | "sio.savemat('{}/rho.mat'.format(timestr), mdict={'rho': np.array(rho_curr)})\n",
988 | "sio.savemat('{}/drho.mat'.format(timestr), mdict={'drho': np.array(drho_total_store)})"
989 | ]
990 | },
991 | {
992 | "cell_type": "code",
993 | "execution_count": null,
994 | "metadata": {
995 | "collapsed": true
996 | },
997 | "outputs": [],
998 | "source": [
999 | "phi_value, rho_value = sess.run([phi, rho],feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,lamda_lag2: lamda_value2,r_lag: r_value,\n",
1000 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: starter_learning_rate, beta: beta_value})\n",
1001 | "\n",
1002 | "sio.savemat('result/infill_phi_{}.mat'.format(count), mdict={'phi': phi_value})\n",
1003 | "sio.savemat('result/infill_rho_{}.mat'.format(count), mdict={'rho': rho_value})"
1004 | ]
1005 | },
1006 | {
1007 | "cell_type": "code",
1008 | "execution_count": null,
1009 | "metadata": {
1010 | "collapsed": true
1011 | },
1012 | "outputs": [],
1013 | "source": [
1014 | "'training result'\n",
1015 | "%matplotlib inline\n",
1016 | "fig, axs = plt.subplots(2,5, figsize=(15, 4), facecolor='w', edgecolor='k')\n",
1017 | "fig.subplots_adjust(hspace = .1, wspace=.001)\n",
1018 | "\n",
1019 | "axs = axs.ravel()\n",
1020 | "\n",
1021 | "for i in range(batch_size):\n",
1022 | " axs[i].imshow(1-rho_value[i].reshape([nelx,nely]).T,'gray')\n",
1023 | "# axs[i].set_title(str(250+i))"
1024 | ]
1025 | },
1026 | {
1027 | "cell_type": "code",
1028 | "execution_count": null,
1029 | "metadata": {
1030 | "collapsed": true
1031 | },
1032 | "outputs": [],
1033 | "source": []
1034 | }
1035 | ],
1036 | "metadata": {
1037 | "kernelspec": {
1038 | "display_name": "Python 2",
1039 | "language": "python",
1040 | "name": "python2"
1041 | },
1042 | "language_info": {
1043 | "codemirror_mode": {
1044 | "name": "ipython",
1045 | "version": 2
1046 | },
1047 | "file_extension": ".py",
1048 | "mimetype": "text/x-python",
1049 | "name": "python",
1050 | "nbconvert_exporter": "python",
1051 | "pygments_lexer": "ipython2",
1052 | "version": "2.7.13"
1053 | }
1054 | },
1055 | "nbformat": 4,
1056 | "nbformat_minor": 2
1057 | }
1058 |
--------------------------------------------------------------------------------
/KKT_optimization/.ipynb_checkpoints/infill-dphi-focus-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {
7 | "collapsed": false
8 | },
9 | "outputs": [
10 | {
11 | "name": "stderr",
12 | "output_type": "stream",
13 | "text": [
14 | "/home/p2admin/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
15 | " from ._conv import register_converters as _register_converters\n"
16 | ]
17 | }
18 | ],
19 | "source": [
20 | "import numpy as np\n",
21 | "import tensorflow as tf\n",
22 | "import matplotlib.pyplot as plt\n",
23 | "import scipy.io as sio\n",
24 | "from tensorflow.contrib import rnn\n",
25 | "import math\n",
26 | "import time\n",
27 | "import os\n",
28 | "from datetime import datetime\n",
29 | "import dateutil.tz\n",
30 | "# from utils.utils import *\n",
31 | "\n",
32 | "\n",
33 | "def xavier_init(size):\n",
34 | " in_dim = size[0]\n",
35 | " xavier_stddev = 1. / tf.sqrt(in_dim / 2.)\n",
36 | " return tf.random_normal(shape=size, stddev=xavier_stddev)\n",
37 | "\n",
38 | "def creat_dir(network_type):\n",
39 | " \"\"\"code from on InfoGAN\"\"\"\n",
40 | " now = datetime.now(dateutil.tz.tzlocal())\n",
41 | " timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')\n",
42 | " root_log_dir = \"logs/\" + network_type\n",
43 | " exp_name = network_type + \"_%s\" % timestamp\n",
44 | " log_dir = os.path.join(root_log_dir, exp_name)\n",
45 | "\n",
46 | " now = datetime.now(dateutil.tz.tzlocal())\n",
47 | " timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')\n",
48 | " root_model_dir = \"models/\" + network_type\n",
49 | " exp_name = network_type + \"_%s\" % timestamp\n",
50 | " model_dir = os.path.join(root_model_dir, exp_name)\n",
51 | "\n",
52 | " for path in [log_dir, model_dir]:\n",
53 | " if not os.path.exists(path):\n",
54 | " os.makedirs(path)\n",
55 | " return log_dir, model_dir\n",
56 | "\n",
57 | "tic = time.clock()\n",
58 | "\n",
59 | "E0 = 1\n",
60 | "Emin = 1e-9\n",
61 | "nu = 0.3\n",
62 | "batch_size = 3\n",
63 | "\n",
64 | "'Input'\n",
65 | "nelx, nely, alpha, alpha2, gamma, rmin, density_r = 12*4, 4*4, 0.6, 0.6, 3.0, 3.0, 6.0\n",
66 | "\n",
67 | "'Algorithm parameters'\n",
68 | "p, nn, epsilon_al, epsilon_opt = 16,nely * nelx, 1, 1e-3\n",
69 | "\n",
70 | "'Prepare filter'\n",
71 | "r = rmin\n",
72 | "Range = np.arange(-r, r + 1)\n",
73 | "X = np.array([Range] * len(Range))\n",
74 | "Y = np.array([Range] * len(Range)).T\n",
75 | "X_temp = X.T.reshape(len(Range) ** 2, 1)\n",
76 | "Y_temp = Y.T.reshape(len(Range) ** 2, 1)\n",
77 | "neighbor = np.concatenate((X_temp, Y_temp), 1)\n",
78 | "D = np.sum(neighbor ** 2, 1)\n",
79 | "rn = sum(D <= r ** 2) - sum(D == 0)\n",
80 | "\n",
81 | "pattern_index = []\n",
82 | "for i in range(len(D)):\n",
83 | " if D[i] <= r ** 2 and D[i] != 0:\n",
84 | " pattern_index.append(i)\n",
85 | "pattern = neighbor[pattern_index]\n",
86 | "\n",
87 | "locX = np.asarray([np.arange(1, nelx + 1)] * nely)\n",
88 | "locY = np.asarray([np.arange(1, nely + 1)] * nelx).T\n",
89 | "loc = np.asarray([locY.T.reshape(-1), locX.T.reshape(-1)]).T\n",
90 | "\n",
91 | "M = np.zeros([nn, rn])\n",
92 | "for i in range(nn):\n",
93 | " for j in range(rn):\n",
94 | " locc = loc[i, :] + pattern[j, :]\n",
95 | " count_true = 0\n",
96 | " if locc[0] > nely: count_true = count_true + 1\n",
97 | " if locc[1] > nelx: count_true = count_true + 1\n",
98 | "\n",
99 | " if sum(locc < 1) + count_true == 0:\n",
100 | " M[i, j] = locc[0] + (locc[1] - 1) * nely\n",
101 | " else:\n",
102 | " M[i, j] = 'NaN'\n",
103 | "\n",
104 | "iH = np.ones([int(nelx * nely * (2 * (np.ceil(rmin) - 1) + 1) ** 2), 1], dtype=int)\n",
105 | "jH = np.ones(iH.shape, dtype=int)\n",
106 | "sH = np.zeros(iH.shape)\n",
107 | "k = 0\n",
108 | "for i1 in range(nelx):\n",
109 | " for j1 in range(nely):\n",
110 | " e1 = (i1) * nely + (j1 + 1)\n",
111 | " for i2 in np.arange(int(max(i1 + 1 - (np.ceil(rmin) - 1), 1)),\n",
112 | " int(min(i1 + 1 + (np.ceil(rmin) - 1), nelx)) + 1):\n",
113 | " for j2 in np.arange(int(max(j1 + 1 - (np.ceil(rmin) - 1), 1)),\n",
114 | " int(min(j1 + 1 + (np.ceil(rmin) - 1), nely)) + 1):\n",
115 | " e2 = (i2 - 1) * nely + j2\n",
116 | " iH[k] = e1\n",
117 | " jH[k] = e2\n",
118 | " sH[k] = max(0, rmin - np.sqrt((i1 + 1 - i2) ** 2 + (j1 + 1 - j2) ** 2))\n",
119 | " k = k + 1\n",
120 | "\n",
121 | "iH = iH.reshape(-1) - 1\n",
122 | "jH = jH.reshape(-1) - 1\n",
123 | "sH = sH.reshape(-1)\n",
124 | "\n",
125 | "import scipy.sparse as sps\n",
126 | "\n",
127 | "H = sps.csc_matrix((sH, (iH, jH))).toarray()\n",
128 | "Hs = np.sum(H, 1)\n",
129 | "bigM = H > 0\n",
130 | "\n",
131 | "'create neighbourhood index for N'\n",
132 | "r = density_r\n",
133 | "Range = np.arange(-r, r + 1)\n",
134 | "mesh = Range\n",
135 | "X = np.asarray([Range] * len(Range))\n",
136 | "Y = np.asarray([Range] * len(Range)).T\n",
137 | "neighbor = np.array([X.T.reshape(-1), Y.T.reshape(-1)]).T\n",
138 | "D = np.sum(neighbor ** 2, 1)\n",
139 | "rn = np.sum(D <= r ** 2)\n",
140 | "pattern = neighbor[D <= r ** 2, :]\n",
141 | "locX = np.asarray([np.arange(1, nelx + 1)] * nely)\n",
142 | "locY = np.asarray([np.arange(1, nely + 1)] * nelx).T\n",
143 | "loc = np.asarray([locY.T.reshape(-1), locX.T.reshape(-1)]).T\n",
144 | "N = np.zeros([nn, rn])\n",
145 | "for i in range(nn):\n",
146 | " for j in range(rn):\n",
147 | " locc = loc[i, :] + pattern[j, :]\n",
148 | " count_true = 0\n",
149 | " if locc[0] > nely: count_true = count_true + 1\n",
150 | " if locc[1] > nelx: count_true = count_true + 1\n",
151 | "\n",
152 | " if sum(locc < 1) + count_true == 0:\n",
153 | " N[i, j] = locc[0] + (locc[1] - 1) * nely\n",
154 | " else:\n",
155 | " N[i, j] = 'NaN'\n",
156 | "\n",
157 | "idx_temp = (np.array([np.arange(nn)] * rn).T).reshape(-1).reshape(nn * rn, 1)\n",
158 | "N_t = N.T\n",
159 | "idy = []\n",
160 | "idx = []\n",
161 | "import math\n",
162 | "\n",
163 | "k = 0\n",
164 | "for i in range(N_t.shape[1]):\n",
165 | " for j in range(N_t.shape[0]):\n",
166 | " if not math.isnan(N_t[j, i]):\n",
167 | " idy.append(N_t[j, i])\n",
168 | " idx.append(idx_temp[k])\n",
169 | " k = k + 1\n",
170 | "idy = np.asarray(idy).reshape(len(idy), 1) - 1\n",
171 | "idx = np.asarray(idx)\n",
172 | "bigN = sps.coo_matrix((np.ones(len(idx)), (idx.reshape(-1), idy.reshape(-1)))).toarray()\n",
173 | "N_count = np.sum(~np.isnan(N), axis=1)\n",
174 | "\n",
175 | "'Material Properties'\n",
176 | "E0, Emin, nu = 1, 1e-9, 0.3\n",
177 | "\n",
178 | "'PREPARE FINITE ELEMENT ANALYSIS'\n",
179 | "A11 = np.array([[12, 3, -6, -3], [3, 12, 3, 0], [-6, 3, 12, -3], [-3, 0, -3, 12]])\n",
180 | "A12 = np.array([[-6, -3, 0, 3], [-3, -6, -3, -6], [0, -3, -6, 3], [3, -6, 3, -6]])\n",
181 | "B11 = np.array([[-4, 3, -2, 9], [3, -4, -9, 4], [-2, -9, -4, -3], [9, 4, -3, -4]])\n",
182 | "B12 = np.array([[2, -3, 4, -9], [-3, 2, 9, -2], [4, 9, 2, 3], [-9, -2, 3, 2]])\n",
183 | "\n",
184 | "A1 = np.concatenate((A11, A12), axis=1)\n",
185 | "A2 = np.concatenate((A12.T, A11), axis=1)\n",
186 | "A = np.concatenate((A1, A2))\n",
187 | "\n",
188 | "B1 = np.concatenate((B11, B12), axis=1)\n",
189 | "B2 = np.concatenate((B12.T, B11), axis=1)\n",
190 | "B = np.concatenate((B1, B2))\n",
191 | "\n",
192 | "KE = 1 / (1 - nu ** 2) / 24. * (A + nu * B)\n",
193 | "nodenrs = np.arange((1 + nelx) * (1 + nely)).reshape(1 + nelx, 1 + nely).T\n",
194 | "edofVec = (2 * (nodenrs[0:-1, 0:-1] + 1)).reshape(nelx * nely, 1, order='F')\n",
195 | "edofMat = np.asarray([edofVec.reshape(-1)] * 8).T + \\\n",
196 | " np.asarray(([0, 1, 2 * nely + 2, 2 * nely + 3, 2 * nely + 0, 2 * nely + 1, -2, -1]) * nelx * nely).reshape(\n",
197 | " nelx * nely, 8)\n",
198 | "\n",
199 | "iK = np.zeros([edofMat.shape[0] * 8, edofMat.shape[1] * 1])\n",
200 | "for i in range(edofMat.shape[0]):\n",
201 | " for j in range(edofMat.shape[1]):\n",
202 | " iK[i * 8:(i + 1) * 8, j] = np.asarray(edofMat[i, j] * np.ones([8, 1])).reshape(-1)\n",
203 | "iK = (iK.astype(np.int32).T).reshape(64 * nelx * nely, 1, order='F')\n",
204 | "\n",
205 | "jK = np.zeros([edofMat.shape[0] * 1, edofMat.shape[1] * 8])\n",
206 | "for i in range(edofMat.shape[0]):\n",
207 | " for j in range(edofMat.shape[1]):\n",
208 | " jK[i, j * 8:(j + 1) * 8] = np.asarray(edofMat[i, j] * np.ones([1, 8])).reshape(-1)\n",
209 | "jK = (jK.astype(np.int32).T).reshape(64 * nelx * nely, 1, order='F')\n",
210 | "\n",
211 | "'DEFINE LOADS AND SUPPORTS (HALF MBB-BEAM)'\n",
212 | "# F = np.zeros([2 * (nely + 1) * (nelx + 1), 1])\n",
213 | "# F[((nely + 1) * nelx) * 2 + nely + 1, 0] = -1\n",
214 | "F = tf.placeholder(tf.float32, shape=([2*(nely+1)*(nelx+1),batch_size]))\n",
215 | "\n",
216 | "\n",
217 | "# F=sps.coo_matrix(F)\n",
218 | "U = np.zeros([2 * (nely + 1) * (nelx + 1), 1])\n",
219 | "# fixeddofs=(np.arange(0,2*(nely+1),2).tolist());fixeddofs.append(2*(nelx+1)*(nely+1)-1)\n",
220 | "# fixeddofs=np.asarray(fixeddofs).reshape(1,len(fixeddofs))\n",
221 | "# alldofs = np.arange(2*(nely+1)*(nelx+1)).reshape(1,2*(nely+1)*(nelx+1))\n",
222 | "\n",
223 | "fixeddofs = np.asarray(np.arange(0, 2 * (nely + 1), 1).tolist())\n",
224 | "fixeddofs = fixeddofs.reshape(1, len(fixeddofs))\n",
225 | "alldofs = np.arange(2 * (nely + 1) * (nelx + 1)).reshape(1, 2 * (nely + 1) * (nelx + 1))\n",
226 | "\n",
227 | "freedofs = np.setdiff1d(alldofs, fixeddofs)\n",
228 | "\n",
229 | "'prepare some stuff to reduce cost'\n",
230 | "dphi_idphi = (H / sum(H)).T\n",
231 | "\n",
232 | "'Start Iteration'\n",
233 | "# phi = alpha*np.ones([nn,1])\n",
234 | "\n",
235 | "\n",
236 | "\n",
237 | "\n",
238 | "z_dim, h_dim_1, h_dim_2, h_dim_3, h_dim_4, h_dim_5 = 2, 100, 100, 100, 100, 100\n",
239 | "\n",
240 | "# r_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
241 | "# r_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
242 | "# lamda_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
243 | "# lamda_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
244 | "\n",
245 | "F_input = tf.placeholder(tf.float32, shape=([batch_size, z_dim]))\n",
246 | "# F = tf.placeholder(tf.float32, shape=([2*(nely+1)*(nelx+1),batch_size]))\n",
247 | "\n",
248 | "W1 = tf.Variable(xavier_init([z_dim, h_dim_1]))\n",
249 | "b1 = tf.Variable(tf.zeros(shape=[h_dim_1]))\n",
250 | "\n",
251 | "W2 = tf.Variable(xavier_init([h_dim_1, h_dim_2]))\n",
252 | "b2 = tf.Variable(tf.zeros(shape=[h_dim_2]))\n",
253 | "\n",
254 | "W3 = tf.Variable(xavier_init([h_dim_2, h_dim_3]))\n",
255 | "b3 = tf.Variable(tf.zeros(shape=[h_dim_3]))\n",
256 | "\n",
257 | "W4 = tf.Variable(xavier_init([h_dim_3, h_dim_4]))\n",
258 | "b4 = tf.Variable(tf.zeros(shape=[h_dim_4]))\n",
259 | "\n",
260 | "W5 = tf.Variable(xavier_init([h_dim_4, nn]))\n",
261 | "b5 = tf.Variable(tf.zeros(shape=[nn]))\n",
262 | "\n",
263 | "# W6 = tf.Variable(xavier_init([h_dim_5, nn]))\n",
264 | "# b6 = tf.Variable(tf.zeros(shape=[nn]))\n",
265 | "\n",
266 | "h1 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(F_input, W1) + b1),scale=True)\n",
267 | "h2 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h1, W2) + b2),scale=True)\n",
268 | "h3 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h2, W3) + b3),scale=True)\n",
269 | "h4 = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h3, W4) + b4),scale=True)\n",
270 | "# h5 = tf.nn.relu(tf.matmul(h4, W5) + b5)\n",
271 | " \n",
272 | "phi_ = tf.sigmoid(tf.matmul(h4, W5) + b5)\n",
273 | "phi = tf.reshape(phi_, [nn, batch_size])\n",
274 | "\n",
275 | "# phi = (tf.Variable(alpha * np.ones([nn, 1]), dtype='float32'))\n",
276 | "\n",
277 | "loop = 0\n",
278 | "# delta = 1.0\n",
279 | "\n",
280 | "# while beta < 1000:\n",
281 | "loop = loop + 1\n",
282 | "loop2 = 0\n",
283 | "'augmented lagrangian parameters'\n",
284 | "# r_lag = 1\n",
285 | "# r_lag2 = 0.001\n",
286 | "# lamda_lag = 0\n",
287 | "# lamda_lag2 = 0\n",
288 | "\n",
289 | "eta = 0.1\n",
290 | "eta2 = 0.1\n",
291 | "epsilon = 1\n",
292 | "dphi = 1e6\n",
293 | "\n",
294 | "r_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
295 | "r_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
296 | "lamda_lag = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
297 | "lamda_lag2 = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
298 | "beta = tf.placeholder(tf.float32, shape=([batch_size,1]))\n",
299 | "################################################################\n",
300 | "'get initial g and c'\n",
301 | "\n",
302 | "import time\n",
303 | "\n",
304 | "W1_fake = tf.Variable(xavier_init([z_dim, h_dim_1]), trainable=False)\n",
305 | "b1_fake = tf.Variable(tf.zeros(shape=[h_dim_1]), trainable=False)\n",
306 | "W1_fake = W1_fake.assign(W1)\n",
307 | "b1_fake = b1_fake.assign(b1)\n",
308 | "\n",
309 | "W2_fake = tf.Variable(xavier_init([h_dim_1, h_dim_2]), trainable=False)\n",
310 | "b2_fake = tf.Variable(tf.zeros(shape=[h_dim_2]), trainable=False)\n",
311 | "W2_fake = W2_fake.assign(W2)\n",
312 | "b2_fake = b2_fake.assign(b2)\n",
313 | "\n",
314 | "W3_fake = tf.Variable(xavier_init([h_dim_2, h_dim_3]), trainable=False)\n",
315 | "b3_fake = tf.Variable(tf.zeros(shape=[h_dim_3]), trainable=False)\n",
316 | "W3_fake = W3_fake.assign(W3)\n",
317 | "b3_fake = b3_fake.assign(b3)\n",
318 | "\n",
319 | "W4_fake = tf.Variable(xavier_init([h_dim_3, h_dim_4]), trainable=False)\n",
320 | "b4_fake = tf.Variable(tf.zeros(shape=[h_dim_4]), trainable=False)\n",
321 | "W4_fake = W4_fake.assign(W4)\n",
322 | "b4_fake = b4_fake.assign(b4)\n",
323 | "\n",
324 | "W5_fake = tf.Variable(xavier_init([h_dim_4, nn]), trainable=False)\n",
325 | "b5_fake = tf.Variable(tf.zeros(shape=[nn]), trainable=False)\n",
326 | "W5_fake = W5_fake.assign(W5)\n",
327 | "b5_fake = b5_fake.assign(b5)\n",
328 | "\n",
329 | "# W6_fake = tf.Variable(xavier_init([h_dim_5, nn]), trainable=False)\n",
330 | "# b6_fake = tf.Variable(tf.zeros(shape=[nn]), trainable=False)\n",
331 | "# W6_fake = W6_fake.assign(W6)\n",
332 | "# b6_fake = b6_fake.assign(b6)\n",
333 | "\n",
334 | "h1_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(F_input, W1_fake) + b1_fake),scale=True,trainable=False)\n",
335 | "h2_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h1_fake, W2_fake) + b2_fake),scale=True,trainable=False)\n",
336 | "h3_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h2_fake, W3_fake) + b3_fake),scale=True,trainable=False)\n",
337 | "h4_fake = tf.contrib.layers.batch_norm(tf.nn.relu(tf.matmul(h3_fake, W4_fake) + b4_fake),scale=True,trainable=False)\n",
338 | "# h5_fake = tf.nn.relu(tf.matmul(h4_fake, W5_fake) + b5_fake)\n",
339 | "\n",
340 | "phi_temp_fake = tf.sigmoid(tf.matmul(h4_fake, W5_fake) + b5_fake)\n",
341 | "phi_fake = tf.reshape(phi_temp_fake,[nn,batch_size])\n"
342 | ]
343 | },
344 | {
345 | "cell_type": "code",
346 | "execution_count": null,
347 | "metadata": {
348 | "collapsed": true
349 | },
350 | "outputs": [],
351 | "source": [
352 | "sep_grad_store,error_store,dphi_store,dobj_store=[],[],[],[]\n",
353 | "c,g,global_density=[],[],[]\n",
354 | "c_fake,g_fake,global_density_fake=[],[],[]\n",
355 | "rho,rho_fake=[],[]\n",
356 | "dphi_fake=[]\n",
357 | "\n",
358 | "tic=time.clock()\n",
359 | "\n",
360 | "learning_rate_fake = tf.placeholder(tf.float32,shape=([batch_size,1]))\n",
361 | "g_old = [tf.Variable(0, dtype='float32',trainable=False)]*batch_size\n",
362 | "global_density_old = [tf.Variable([[0]], dtype='float32',trainable=False)]*batch_size\n",
363 | "c_old = [tf.Variable(0, dtype='float32',trainable=False)]*batch_size\n",
364 | "tic=time.clock()\n",
365 | "\n",
366 | "for i in range(batch_size):\n",
367 | " phi_til = tf.matmul(tf.cast(H, tf.float32), phi[:,i:i+1]) / Hs.reshape(nn, 1)\n",
368 | " rho.append((tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0)))\n",
369 | "\n",
370 | " sK_temp = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
371 | " tf.reshape(Emin + tf.reshape(rho[i], [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
372 | " sK = tf.reshape(sK_temp, [8 * 8 * nelx * nely, 1])\n",
373 | "\n",
374 | " ###################\n",
375 | " indices_m = np.stack((iK.reshape(-1), jK.reshape(-1)), axis=1)\n",
376 | " values_m = tf.reshape(sK, [-1])\n",
377 | "\n",
378 | " linearized_m = tf.matmul(indices_m, [[10000], [1]])\n",
379 | " y_m, idx_m = tf.unique(tf.squeeze(linearized_m))\n",
380 | "\n",
381 | " idx_m_sort, ind_m_sort = tf.nn.top_k(idx_m, k=nelx * nely * 64)\n",
382 | " idx_m_sort = tf.reverse(idx_m_sort, [0])\n",
383 | " ind_m_sort = tf.reverse(ind_m_sort, [0])\n",
384 | "\n",
385 | " # values_m_test = values_m\n",
386 | " values_m = tf.gather(values_m, ind_m_sort)\n",
387 | " values_m = tf.segment_sum(values_m, idx_m_sort)\n",
388 | "\n",
389 | " y_m = tf.expand_dims(y_m, 1)\n",
390 | " indices_m = tf.concat([y_m // 10000, y_m % 10000], axis=1)\n",
391 | " #####################\n",
392 | "\n",
393 | " #####################\n",
394 | " K_sp = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
395 | " tf.reshape(tf.cast(values_m, tf.float32), [-1]),\n",
396 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
397 | " K_sp = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp)\n",
398 | " K_dense = (K_sp + tf.transpose(K_sp)) / 2\n",
399 | " #####################\n",
400 | "\n",
401 | " K_temp = tf.gather(K_dense, freedofs.astype(np.int32))\n",
402 | " K_free = tf.transpose(tf.gather(tf.transpose(K_temp), freedofs.astype(np.int32)))\n",
403 | " \n",
404 | " F_RHS=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
405 | " tf.float32)\n",
406 | " chol = tf.cholesky(K_free+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
407 | " U_pre = tf.cholesky_solve(chol,F_RHS)\n",
408 | " \n",
409 | "# U_pre = tf.matmul(tf.matrix_inverse(tf.cast(K_free, tf.float32)),\n",
410 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
411 | "# tf.float32))\n",
412 | "\n",
413 | " U = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
414 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
415 | " tf.reshape(tf.cast(U_pre, tf.float32), [-1]), [(nelx + 1) * (nely + 1) * 2]))\n",
416 | "\n",
417 | " 'Objective Function and Sensitivity Analysis'\n",
418 | " ce = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U, edofMat.astype(np.int32)), edofMat.shape),\n",
419 | " KE.astype(np.float32)), tf.gather(U, edofMat.astype(np.int32))), axis=1)\n",
420 | " ce = tf.reshape(ce, [nn, 1])\n",
421 | " c.append(tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho[i] ** gamma, (E0 - Emin)), tf.float32), ce)))\n",
422 | " rho_bar = tf.divide(tf.matmul(tf.cast(bigN, tf.float32), rho[i]), N_count.reshape(nn, 1))\n",
423 | " g.append((tf.reduce_sum(rho_bar ** p) / nely / nelx) ** (1.0 / p) / alpha - 1.0)\n",
424 | " global_density.append(tf.matmul(tf.transpose(rho[i]), tf.ones([nn, 1])) / nn - alpha2)\n",
425 | " ###################################################################\n",
426 | "\n",
427 | " # if ((max(abs(dphi)))2) or (loo2>100):\n",
428 | "\n",
429 | "\n",
430 | " dc_drho = -gamma * rho[i] ** (gamma - 1) * (E0 - Emin) * ce\n",
431 | " drho_dphi = beta[i][0] * (1 - tf.tanh(beta[i][0] * (phi[:,i:i+1] - 0.5)) ** 2) / 2.0 / tf.tanh(beta[i][0] / 2.)\n",
432 | " dc_dphi = tf.reduce_sum(bigM * (dphi_idphi * (dc_drho * drho_dphi)), axis=0)\n",
433 | " dg_drhobar = 1.0 / alpha / nn * (1.0 / nn * tf.reduce_sum(rho_bar ** p)) ** (1.0 / p - 1) * rho_bar ** (p - 1)\n",
434 | " dg_dphi = tf.reduce_sum(bigM * (dphi_idphi * (tf.matmul(tf.cast(bigN, tf.float32),\n",
435 | " (dg_drhobar / N_count.reshape(nn, 1))) * drho_dphi)), axis=0)\n",
436 | "\n",
437 | " dphi = dc_dphi + tf.cast(lamda_lag[i][0] * dg_dphi * tf.reduce_sum(tf.cast(g[i] > 0, tf.float32)), tf.float32) + \\\n",
438 | " tf.cast(2.0 / r_lag[i][0] * g[i] * dg_dphi * tf.reduce_sum(tf.cast(g[i] > 0, tf.float32)), tf.float32) + \\\n",
439 | " lamda_lag2[i][0] * tf.ones(nn, 1) / nn * (tf.reduce_sum(tf.cast(global_density[i] > 0, tf.float32))) + \\\n",
440 | " tf.reshape(2.0 / r_lag2[i][0] * global_density[i] / nn / nn * tf.ones([nn, 1]) * (\n",
441 | " tf.reduce_sum(tf.cast(global_density[i] > 0, tf.float32))), [-1])\n",
442 | " \n",
443 | " dphi_store.append(dphi)\n",
444 | " \n",
445 | "\n",
446 | " \n",
447 | "############################################################################################################\n",
448 | "\n",
449 | " 'get initial g and c'\n",
450 | " phi_til_fake = tf.matmul(tf.cast(H, tf.float32), phi_fake[:,i:i+1]) / Hs.reshape(nn, 1)\n",
451 | " rho_fake.append((tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til_fake - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0)))\n",
452 | "\n",
453 | " sK_temp_fake = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
454 | " tf.reshape(Emin + tf.reshape(rho_fake[i], [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
455 | " sK_fake = tf.reshape(sK_temp_fake, [8 * 8 * nelx * nely, 1])\n",
456 | "\n",
457 | " ###################\n",
458 | " indices_m = np.stack((iK.reshape(-1), jK.reshape(-1)), axis=1)\n",
459 | " values_m_fake = tf.reshape(sK_fake, [-1])\n",
460 | "\n",
461 | " linearized_m = tf.matmul(indices_m, [[10000], [1]])\n",
462 | " y_m, idx_m = tf.unique(tf.squeeze(linearized_m))\n",
463 | "\n",
464 | " idx_m_sort, ind_m_sort = tf.nn.top_k(idx_m, k=nelx * nely * 64)\n",
465 | " idx_m_sort = tf.reverse(idx_m_sort, [0])\n",
466 | " ind_m_sort = tf.reverse(ind_m_sort, [0])\n",
467 | "\n",
468 | " values_m_fake = tf.gather(values_m_fake, ind_m_sort)\n",
469 | " values_m_fake = tf.segment_sum(values_m_fake, idx_m_sort)\n",
470 | "\n",
471 | " y_m = tf.expand_dims(y_m, 1)\n",
472 | " indices_m = tf.concat([y_m // 10000, y_m % 10000], axis=1)\n",
473 | " #####################\n",
474 | "\n",
475 | " #####################\n",
476 | " K_sp_fake = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
477 | " tf.reshape(tf.cast(values_m_fake, tf.float32), [-1]),\n",
478 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
479 | " K_sp_fake = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp_fake)\n",
480 | " K_dense_fake = (K_sp_fake + tf.transpose(K_sp_fake)) / 2.0\n",
481 | " #####################\n",
482 | "\n",
483 | " K_temp_fake = tf.gather(K_dense_fake, freedofs.astype(np.int32))\n",
484 | " K_free_fake = tf.transpose(tf.gather(tf.transpose(K_temp_fake), freedofs.astype(np.int32)))\n",
485 | "\n",
486 | " F_RHS_fake=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
487 | " tf.float32)\n",
488 | " chol_fake = tf.cholesky(K_free_fake+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
489 | " U_pre_fake = tf.cholesky_solve(chol_fake,F_RHS_fake)\n",
490 | " \n",
491 | "# U_pre_fake = tf.matmul(tf.matrix_inverse(tf.cast(K_free_fake, tf.float32)),\n",
492 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
493 | "# tf.float32))\n",
494 | "\n",
495 | " U_fake = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
496 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
497 | " tf.reshape(tf.cast(U_pre_fake, tf.float32), [-1]),\n",
498 | " [(nelx + 1) * (nely + 1) * 2]))\n",
499 | "\n",
500 | " 'Objective Function and Sensitivity Analysis'\n",
501 | " ce_fake = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U_fake, edofMat.astype(np.int32)), edofMat.shape),\n",
502 | " KE.astype(np.float32)), tf.gather(U_fake, edofMat.astype(np.int32))),\n",
503 | " axis=1)\n",
504 | " ce_fake = tf.reshape(ce_fake, [nn, 1])\n",
505 | " c_fake.append(tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho_fake[i] ** gamma, (E0 - Emin)), tf.float32), ce_fake)))\n",
506 | " rho_bar_fake=tf.divide(tf.matmul(tf.cast(bigN, tf.float32), rho_fake[i]), N_count.reshape(nn, 1))\n",
507 | " g_fake.append((tf.reduce_sum(rho_bar_fake ** p) / nely / nelx) ** (1. / p) / alpha - 1.0)\n",
508 | " global_density_fake.append(tf.matmul(tf.transpose(rho_fake[i]), tf.ones([nn, 1])) / nn - alpha2)\n",
509 | " ###################################################################\n",
510 | "\n",
511 | " # if ((max(abs(dphi)))2) or (loo2>100):\n",
512 | "\n",
513 | "\n",
514 | " dc_drho_fake = -gamma * rho_fake[i] ** (gamma - 1) * (E0 - Emin) * ce_fake\n",
515 | " drho_dphi_fake = beta[i][0] * (1 - tf.tanh(beta[i][0] * (phi_fake[:,i:i+1] - 0.5)) ** 2) / 2.0 / tf.tanh(beta[i][0] / 2.)\n",
516 | " dc_dphi_fake = tf.reduce_sum(bigM * (dphi_idphi * (dc_drho_fake * drho_dphi_fake)), axis=0)\n",
517 | " dg_drhobar_fake = 1.0 / alpha / nn * (1.0 / nn * tf.reduce_sum(rho_bar_fake ** p)) ** (1.0 / p - 1) * rho_bar_fake ** (\n",
518 | " p - 1)\n",
519 | " dg_dphi_fake = tf.reduce_sum(bigM * (dphi_idphi * (tf.matmul(tf.cast(bigN, tf.float32),\n",
520 | " (dg_drhobar_fake / N_count.reshape(nn,\n",
521 | " 1))) * drho_dphi_fake)),\n",
522 | " axis=0)\n",
523 | "\n",
524 | " A = dc_dphi_fake + tf.cast(lamda_lag[i][0] * dg_dphi_fake * tf.reduce_sum(tf.cast(g_fake[i] > 0, tf.float32)), tf.float32) + \\\n",
525 | " tf.cast(2.0 / r_lag[i][0] * g_fake[i] * dg_dphi_fake * tf.reduce_sum(tf.cast(g_fake[i] > 0, tf.float32)), tf.float32)\n",
526 | "\n",
527 | " B = lamda_lag2[i][0] * tf.ones(nn, 1) / nn * (tf.reduce_sum(tf.cast(global_density_fake[i] > 0, tf.float32))) + \\\n",
528 | " 2.0 / r_lag2[i][0] * global_density_fake[i] / nn / nn * tf.ones([nn]) * (tf.reduce_sum(tf.cast(global_density_fake[i] > 0, tf.float32)))\n",
529 | "\n",
530 | " dphi_fake.append(A + B)\n",
531 | " \n",
532 | " \n",
533 | " error_sep = tf.reduce_sum(((tf.reshape(dphi_fake[i], [nn, 1]) * phi[:,i:i+1])))\n",
534 | " error_store.append(error_sep)\n",
535 | " \n",
536 | " sep_grad=tf.reduce_sum(tf.abs(tf.gradients((tf.reshape(dphi_fake[i], [nn, 1]) * phi[:,i:i+1]),W1)))\n",
537 | " sep_grad_store.append(sep_grad)\n",
538 | " \n",
539 | "############################################################################################\n",
540 | "# g_old = tf.Variable(0, dtype='float32',trainable=False)\n",
541 | "# global_density_old = tf.Variable([[0]], dtype='float32',trainable=False)\n",
542 | "# c_old = tf.Variable(0, dtype='float32',trainable=False)\n",
543 | "\n",
544 | " g_old[i] = g_old[i].assign(g[i])\n",
545 | " global_density_old[i] = global_density_old[i].assign(global_density[i])\n",
546 | " c_old[i] = c_old[i].assign(c[i])\n",
547 | "\n",
548 | "# assign_g=tf.assign(g_old[i],g[i])\n",
549 | "# assign_gd=tf.assign(global_density_old[i],global_density[i])\n",
550 | "# assign_c=tf.assign(c_old[i],c[i])\n",
551 | "\n",
552 | " 'learning rate adjusting'\n",
553 | " delta = -dphi_fake[i] * learning_rate_fake[i][0]\n",
554 | " phi_temp = phi_fake[:,i:i+1] + tf.reshape(delta, [nn, 1])\n",
555 | "\n",
556 | " # assign_phi = tf.assign(phi,phi_temp)\n",
557 | "\n",
558 | " # phi_temp=tf.Variable(np.ones([nn,1]), dtype='float32')\n",
559 | " # phi_temp=phi_temp.assign(phi)\n",
560 | "\n",
561 | " phi_til_temp = tf.matmul(tf.cast(H, tf.float32), phi_temp) / tf.reshape(tf.cast(Hs, tf.float32), [nn, 1])\n",
562 | " rho_temp = (tf.tanh(beta[i][0] / 2.0) + tf.tanh(beta[i][0] * (phi_til_temp - 0.5))) / (2 * tf.tanh(beta[i][0] / 2.0))\n",
563 | " rho_bar_temp = (tf.matmul(tf.cast(bigN, tf.float32), rho_temp) / tf.reshape(tf.cast(N_count, tf.float32), [nn, 1]))\n",
564 | " g_temp = (tf.reduce_sum(rho_bar_temp ** p) / nn) ** (1.0 / p) / alpha - 1.0\n",
565 | " global_density_temp = tf.matmul(tf.transpose(rho_temp), tf.ones([nn, 1])) / nn - alpha2\n",
566 | "\n",
567 | " sK_temp_fake2 = tf.transpose((KE.reshape(KE.shape[0] * KE.shape[1], 1) * \\\n",
568 | " tf.reshape(Emin + tf.reshape(rho_temp, [-1]) ** (gamma) * (E0 - Emin), [1, nelx * nely])))\n",
569 | " sK_fake2 = tf.reshape(sK_temp_fake2, [8 * 8 * nelx * nely, 1])\n",
570 | "\n",
571 | " ###################\n",
572 | " values_m_fake2 = tf.reshape(sK_fake2, [-1])\n",
573 | " values_m_fake2 = tf.gather(values_m_fake2, ind_m_sort)\n",
574 | " values_m_fake2 = tf.segment_sum(values_m_fake2, idx_m_sort)\n",
575 | " ###################\n",
576 | "\n",
577 | " ###################\n",
578 | " K_sp_fake2 = tf.SparseTensor(tf.cast(indices_m, tf.int64),\n",
579 | " tf.reshape(tf.cast(values_m_fake2, tf.float32), [-1]),\n",
580 | " [(nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2])\n",
581 | " K_sp_fake2 = tf.sparse_add(tf.zeros(((nely + 1) * (nelx + 1) * 2, (nely + 1) * (nelx + 1) * 2)), K_sp_fake2)\n",
582 | " K_dense_fake2 = (K_sp_fake2 + tf.transpose(K_sp_fake2)) / 2.0\n",
583 | " ###################\n",
584 | "\n",
585 | " K_temp_fake2 = tf.gather(K_dense_fake2, freedofs.astype(np.int32))\n",
586 | " K_free_fake2 = tf.transpose(tf.gather(tf.transpose(K_temp_fake2), freedofs.astype(np.int32)))\n",
587 | " \n",
588 | " F_RHS_fake2=tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),\n",
589 | " tf.float32)\n",
590 | " chol_fake2 = tf.cholesky(K_free_fake2+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-8).tolist()[0]))\n",
591 | " U_pre_fake2 = tf.cholesky_solve(chol_fake2,F_RHS_fake2)\n",
592 | " \n",
593 | "# U_pre_fake2 = tf.matmul(tf.matrix_inverse(tf.cast(K_free_fake2, tf.float32)+np.diag((np.ones([1,(nelx+1)*(nely+1)*2-len(fixeddofs[0])])*1e-15).tolist()[0])),\n",
594 | "# tf.cast(tf.gather(tf.reshape(F[:,i:i+1], [(nelx + 1) * (nely + 1) * 2, 1]), freedofs.astype(np.int64)),tf.float32))\n",
595 | "\n",
596 | " U_fake2 = tf.sparse_add(tf.zeros(((nelx + 1) * (nely + 1) * 2)),\n",
597 | " tf.SparseTensor(freedofs.reshape((nelx + 1) * (nely + 1) * 2 - (nely + 1) * 2, 1),\n",
598 | " tf.reshape(tf.cast(U_pre_fake2, tf.float32), [-1]),\n",
599 | " [(nelx + 1) * (nely + 1) * 2]))\n",
600 | "\n",
601 | " ce_temp = tf.reduce_sum(tf.multiply(tf.matmul(tf.reshape(tf.gather(U_fake2, edofMat.astype(np.int32)), edofMat.shape),\n",
602 | " KE.astype(np.float32)), tf.gather(U_fake2, edofMat.astype(np.int32))),axis=1)\n",
603 | " \n",
604 | " ce_temp = tf.reshape(ce_temp, [nn, 1])\n",
605 | " c_temp = tf.reduce_sum(tf.multiply(tf.cast(tf.multiply(rho_temp ** gamma, (E0 - Emin)), tf.float32), ce_temp))\n",
606 | "\n",
607 | " A2 = (c_temp + lamda_lag[i][0] * g_temp * (tf.reduce_sum(tf.cast(g_temp > 0, tf.float32))) + 1.0 / r_lag[i][0] * g_temp ** 2 * (\n",
608 | " tf.reduce_sum(tf.cast(g_temp > 0, tf.float32))) + \\\n",
609 | " 1.0 / r_lag2[i][0] * global_density_temp ** 2 * (tf.reduce_sum(tf.cast(global_density_temp > 0, tf.float32))))\n",
610 | "\n",
611 | " B2 = (c_old[i] + lamda_lag[i][0] * g_old[i] * (tf.reduce_sum(tf.cast(g_old[i] > 0, tf.float32))) + 1.0 / r_lag[i][0] * g_old[i] ** 2 * (\n",
612 | " tf.reduce_sum(tf.cast(g_old[i] > 0, tf.float32))) + \\\n",
613 | " 1.0 / r_lag2[i][0] * global_density_old[i] ** 2 * (tf.reduce_sum(tf.cast(global_density_old[i] > 0, tf.float32))))\n",
614 | " dobj = A2 - B2\n",
615 | " dobj_store.append(dobj)\n",
616 | " \n",
617 | "toc=time.clock()\n",
618 | "print(toc-tic)"
619 | ]
620 | },
621 | {
622 | "cell_type": "code",
623 | "execution_count": null,
624 | "metadata": {
625 | "collapsed": true
626 | },
627 | "outputs": [],
628 | "source": [
629 | "global_step = tf.Variable(0, trainable=False)\n",
630 | "starter_learning_rate = 0.001\n",
631 | "learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,\n",
632 | " 1000, 1.0, staircase=True)\n",
633 | "\n",
634 | "solver0 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[0], global_step=global_step)\n",
635 | "solver1 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[1], global_step=global_step)\n",
636 | "solver2 = tf.train.AdamOptimizer(learning_rate).minimize(error_store[2], global_step=global_step)\n",
637 | "\n",
638 | "sess = tf.Session()\n",
639 | "sess.run(tf.global_variables_initializer())"
640 | ]
641 | },
642 | {
643 | "cell_type": "code",
644 | "execution_count": null,
645 | "metadata": {
646 | "collapsed": true
647 | },
648 | "outputs": [],
649 | "source": [
650 | "force=-1\n",
651 | "F_batch=np.zeros([batch_size,z_dim])\n",
652 | "\n",
653 | "# alpha=1.5\n",
654 | "theta = np.linspace(np.pi*0.,2.0*np.pi/5.,batch_size)\n",
655 | "\n",
656 | "count=0\n",
657 | "for i in range(batch_size-1,-1,-1):\n",
658 | "# theta = 2*(i+1)*np.pi/10.#+i*np.pi/9*alpha\n",
659 | " print theta[i]\n",
660 | "# theta = (i+1)*np.pi/10\n",
661 | " Fx = force*np.sin(theta[i])\n",
662 | " Fy = force*np.cos(theta[i])\n",
663 | " \n",
664 | " # up-right corner\n",
665 | " F_batch[count,0]=Fx\n",
666 | " F_batch[count,1]=Fy\n",
667 | " count=count+1 \n",
668 | "\n",
669 | "count=0\n",
670 | "F_sp=np.zeros([2*(nely+1)*(nelx+1),batch_size])\n",
671 | "for i in range(batch_size-1,-1,-1):\n",
672 | "# theta = 2*(i+1)*np.pi/10.#+i*np.pi/9*alpha\n",
673 | "# theta = (i+1)*np.pi/5\n",
674 | " Fx = force*np.sin(theta[i])\n",
675 | " Fy = force*np.cos(theta[i]) \n",
676 | " F_sp[(nely+1)*2*nelx+nely, count] = Fx\n",
677 | " F_sp[(nely+1)*2*nelx+nely+1, count] = Fy\n",
678 | " count=count+1\n",
679 | "\n",
680 | "print F_batch"
681 | ]
682 | },
683 | {
684 | "cell_type": "code",
685 | "execution_count": null,
686 | "metadata": {
687 | "collapsed": true
688 | },
689 | "outputs": [],
690 | "source": [
691 | "lamda_value = np.zeros([batch_size, 1])\n",
692 | "lamda_value2 = np.zeros([batch_size, 1])\n",
693 | "r_value = np.ones([batch_size, 1]) * 1\n",
694 | "r_value2 = np.ones([batch_size, 1]) * 0.001\n",
695 | "eta = np.ones([batch_size, 1]) * 0.1\n",
696 | "eta2 = np.ones([batch_size, 1]) * 0.1\n",
697 | "j, j2 = 0, 0\n",
698 | "\n",
699 | "k_j = np.ones([batch_size, 1])\n",
700 | "thre_range = 0.02\n",
701 | "agg = 0\n",
702 | "total_E_pre = 1e20\n",
703 | "count_k = 0\n",
704 | "count = 0\n",
705 | "drho=1e6\n",
706 | "it=0\n",
707 | "beta_value=np.ones([batch_size,1])*10\n",
708 | "learning_rate_fake_value=np.ones([batch_size,1])*0.001"
709 | ]
710 | },
711 | {
712 | "cell_type": "code",
713 | "execution_count": null,
714 | "metadata": {
715 | "collapsed": true
716 | },
717 | "outputs": [],
718 | "source": [
719 | "import os\n",
720 | "import time\n",
721 | "timestr = time.strftime(\"%Y%m%d-%H%M%S_bn\")\n",
722 | "if not os.path.exists(timestr):\n",
723 | " os.makedirs(timestr)"
724 | ]
725 | },
726 | {
727 | "cell_type": "code",
728 | "execution_count": null,
729 | "metadata": {
730 | "collapsed": true
731 | },
732 | "outputs": [],
733 | "source": [
734 | "####################\n",
735 | "# logdir,modeldir=creat_dir('infill_var')\n",
736 | "# summary_writer = tf.summary.FileWriter(logdir)\n",
737 | "# summary_op_train = tf.summary.merge([tf.summary.scalar(\"train/error\",error_total)])\n",
738 | "####################\n",
739 | "\n",
740 | "# for it in range(100000):\n",
741 | "it=0\n",
742 | "drho_total_store=[]\n",
743 | "\n",
744 | "while min(beta_value)<11:\n",
745 | " it=it+1\n",
746 | " # sess.run([assign_phi_fake,assign_c,assign_g,assign_gd], feed_dict={learning_rate_fake: starter_learning_rate, lamda_lag: lamda_value,\n",
747 | " # lamda_lag2: lamda_value2,\n",
748 | " # r_lag: r_value,\n",
749 | " # r_lag2: r_value2})\n",
750 | " \n",
751 | "# total_E, g_value, gd, dphi_fake_value, dobj_value, lr, phi_fake_value,rho_value = sess.run([error_store, g,\n",
752 | "# global_density, dphi_fake, dobj_store,\n",
753 | "# learning_rate,phi_fake,rho],\n",
754 | "# feed_dict={learning_rate_fake: learning_rate_fake_value,\n",
755 | "# lamda_lag:lamda_value,\n",
756 | "# lamda_lag2:lamda_value2,\n",
757 | "# r_lag:r_value,\n",
758 | "# r_lag2:r_value2,\n",
759 | "# F_input:F_batch,\n",
760 | "# F:F_sp, \n",
761 | "# learning_rate:starter_learning_rate,beta:beta_value})\n",
762 | "\n",
763 | " \n",
764 | " \n",
765 | " loop2=0\n",
766 | " \n",
767 | " while 1:\n",
768 | "# try:\n",
769 | " g_value_temp,dphi_fake_value,rho_pre = sess.run([g,dphi_fake,rho], \n",
770 | " feed_dict={learning_rate_fake: learning_rate_fake_value,\n",
771 | " lamda_lag:lamda_value,lamda_lag2:lamda_value2,\n",
772 | " r_lag:r_value,r_lag2:r_value2,F_input: F_batch,\n",
773 | " F:F_sp,learning_rate:starter_learning_rate,\n",
774 | " beta:beta_value})\n",
775 | "# except:\n",
776 | "# stop=1\n",
777 | "\n",
778 | " \n",
779 | " dphi_fake_value_max=max(max(abs(np.array(dphi_fake_value[0])).reshape(-1)),\n",
780 | " max(abs(np.array(dphi_fake_value[1])).reshape(-1)),\n",
781 | " max(abs(np.array(dphi_fake_value[2])).reshape(-1)))\n",
782 | " \n",
783 | " \n",
784 | " if (dphi_fake_value_max < 1*batch_size and max(g_value_temp) < 0.01 and loop2 > 0) or (loop2 > 100):\n",
785 | "\n",
786 | "# if (drho < 0.05 and max(g_value_temp) < 0.005 and loop2 > 0) or (loop2 > 100):\n",
787 | " # print('wrong')\n",
788 | " lamda_value = np.zeros([batch_size, 1])\n",
789 | " lamda_value2 = np.zeros([batch_size, 1])\n",
790 | " r_value = np.ones([batch_size, 1]) * 1\n",
791 | " r_value2 = np.ones([batch_size, 1]) * 0.001\n",
792 | " eta = np.ones([batch_size, 1]) * 0.1\n",
793 | " eta2 = np.ones([batch_size, 1]) * 0.1\n",
794 | " dphi_fake_value=np.array([1e6]*batch_size)\n",
795 | " drho=np.array([1e6]*batch_size)\n",
796 | " break\n",
797 | "\n",
798 | " loop2 = loop2 + 1\n",
799 | " j, j2 = 0, 0\n",
800 | " loop3 = np.array([0]*batch_size)\n",
801 | " dphi_fake_value = np.array([1e6]*batch_size)\n",
802 | " drho = np.array([1e6]*batch_size)\n",
803 | " \n",
804 | "\n",
805 | "\n",
806 | " while (max(max(abs(np.array(dphi_fake_value[0])).reshape(-1)),\n",
807 | " max(abs(np.array(dphi_fake_value[1])).reshape(-1)),\n",
808 | " max(abs(np.array(dphi_fake_value[2])).reshape(-1)))) > epsilon and min(loop3) < 1000:\n",
809 | " \n",
810 | "# rho_value_pre = sess.run(rho, feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
811 | "# F_input: F_batch,F:F_sp,learning_rate:starter_learning_rate,beta:beta_value})\n",
812 | "\n",
813 | " \n",
814 | " for i in range(batch_size):\n",
815 | " if count>=4000:\n",
816 | " break\n",
817 | " if loop3[i]>1000:\n",
818 | " continue\n",
819 | "# dphi_fake_value[i] = np.array([1e6])\n",
820 | "# g_value = g_value_temp[i]\n",
821 | "\n",
822 | " starter_learning_rate = 0.001\n",
823 | " learning_rate_fake_value[i]=0.001\n",
824 | " loop3[i] = loop3[i] + 1\n",
825 | " loop4 = np.asarray([0]*batch_size)\n",
826 | "\n",
827 | " tic=time.clock()\n",
828 | " while loop4[i] < 10:\n",
829 | " try:\n",
830 | " dphi_fake_value, dobj_value,rho_value = sess.run([dphi_fake, dobj_store,rho],\n",
831 | " feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
832 | " lamda_lag2:lamda_value2, r_lag:r_value,\n",
833 | " r_lag2:r_value2,F_input:F_batch,\n",
834 | " F:F_sp,learning_rate:learning_rate_fake_value[i][0],\n",
835 | " beta:beta_value})\n",
836 | " except:\n",
837 | " starter_learning_rate = starter_learning_rate*0.5\n",
838 | " learning_rate_fake_value[i] = learning_rate_fake_value[i]*0.5\n",
839 | " \n",
840 | "\n",
841 | "\n",
842 | " if dobj_value[i] > 0:\n",
843 | " starter_learning_rate = starter_learning_rate * 0.5\n",
844 | " learning_rate_fake_value[i] = learning_rate_fake_value[i]*0.5\n",
845 | " loop4[i] = loop4[i] + 1\n",
846 | " if loop4[i] == 10:\n",
847 | " loop3[i] = 10000\n",
848 | " dphi_fake_value[i] = np.array([0])\n",
849 | " drho[i] = np.array([0])\n",
850 | " # break\n",
851 | " else:\n",
852 | " if i == 0:\n",
853 | " try:\n",
854 | " sess.run([solver0],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
855 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
856 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
857 | "\n",
858 | " except:\n",
859 | " print('jump0')\n",
860 | " \n",
861 | " if i == 1:\n",
862 | " try:\n",
863 | " sess.run([solver1],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
864 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
865 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
866 | "\n",
867 | " except:\n",
868 | " print('jump1')\n",
869 | " \n",
870 | " if i == 2:\n",
871 | " try:\n",
872 | " sess.run([solver2],feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
873 | " lamda_lag2:lamda_value2,r_lag:r_value,r_lag2:r_value2,\n",
874 | " F_input: F_batch,F:F_sp,learning_rate:learning_rate_fake_value[i][0],beta:beta_value})\n",
875 | " except:\n",
876 | " print('jump2')\n",
877 | " \n",
878 | " break\n",
879 | "\n",
880 | " toc=time.clock()\n",
881 | " count = count + 1\n",
882 | "# try:\n",
883 | " g_value,c_value,sep_grad_value,error_total_value,phi_value,rho_curr=sess.run([g,c,sep_grad_store,error_store,phi,rho], \n",
884 | " feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,\n",
885 | " lamda_lag2: lamda_value2,r_lag: r_value,\n",
886 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: learning_rate_fake_value[i][0],\n",
887 | " beta: beta_value})\n",
888 | "# except:\n",
889 | "# print('jump3')\n",
890 | "\n",
891 | " drho[i]=sum(abs(rho_curr[i]-rho_pre[i]).reshape(-1))\n",
892 | " drho_total=sum(abs(np.array(rho_curr)-np.array(rho_pre)).reshape(-1))\n",
893 | " drho_total_store.append(drho_total)\n",
894 | " print('iteration:{}'.format(it))\n",
895 | " print('updating_case:{}'.format(i))\n",
896 | " print('num_update:{}'.format(count))\n",
897 | " print('total_error:{}'.format(np.sum(np.array(error_total_value))))\n",
898 | " print('g_value:{}'.format(g_value))\n",
899 | " print('c_value:{}'.format(c_value))\n",
900 | " print('log_r:{}'.format(np.log(r_value)))\n",
901 | "# print('max_abs_dphi:{}'.format(max(abs(dphi_fake_value.reshape(-1)))))\n",
902 | " print('gradient_W1:{}'.format(sep_grad_value))\n",
903 | " print('dobj_value:{}'.format(dobj_value))\n",
904 | " # r_lag2:r_value2,F_input: F_batch,F:F_sp,learning_rate:starter_learning_rate,beta:beta_value})))\n",
905 | " print('dphi_fake_value_max:{}'.format((max(abs(dphi_fake_value[i].reshape(-1))))))\n",
906 | "# print('drho_fake_value_max:{}'.format(max(abs(rho_value[i].reshape(-1)-rho_value_pre[i].reshape(-1)))))\n",
907 | " print('drho:{}'.format(drho))\n",
908 | " print('loop3:{}'.format(loop3))\n",
909 | " print\n",
910 | " print('running time:{}'.format(toc-tic))\n",
911 | " print()\n",
912 | " if count%500 == 0:\n",
913 | " sio.savemat('{}/c_value.mat'.format(timestr), mdict={'c': np.array(c_value)})\n",
914 | " sio.savemat('{}/rho.mat'.format(timestr), mdict={'rho': np.array(rho_curr)})\n",
915 | " sio.savemat('{}/drho.mat'.format(timestr), mdict={'drho': np.array(drho_total_store)})\n",
916 | " fig, axs = plt.subplots(2, 5, figsize=(15, 4), facecolor='w', edgecolor='k')\n",
917 | " fig.subplots_adjust(hspace=.1, wspace=.001)\n",
918 | "\n",
919 | " axs = axs.ravel()\n",
920 | "\n",
921 | " for i in range(batch_size):\n",
922 | " axs[i].imshow(1 - rho_curr[i].reshape([nelx, nely]).T, 'gray')\n",
923 | " axs[i].set_title('c={}'.format(c_value[i]))\n",
924 | " plt.savefig('{}/opt_{}.png'.format(timestr, str(count)))\n",
925 | " plt.close()\n",
926 | " if count >= 4000:\n",
927 | " break\n",
928 | "# drho1=max(rho_value_cur[0].reshape(-1)-rho_value_pre[0].reshape(-1))\n",
929 | "# drho2=max(rho_value_cur[1].reshape(-1)-rho_value_pre[1].reshape(-1))\n",
930 | "# drho3=max(rho_value_cur[2].reshape(-1)-rho_value_pre[2].reshape(-1))\n",
931 | "# drho=max(drho1,drho2,drho3)\n",
932 | " \n",
933 | " \n",
934 | "# g_value, gd, rho_value_cur = sess.run([g, global_density,rho], \n",
935 | "# feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
936 | "# lamda_lag2:lamda_value2,r_lag:r_value,\n",
937 | "# r_lag2:r_value2,F_input: F_batch,F:F_sp,\n",
938 | "# learning_rate:starter_learning_rate,beta:beta_value})\n",
939 | " for i in range(batch_size): \n",
940 | " g_value, gd= sess.run([g, global_density], \n",
941 | " feed_dict={learning_rate_fake: learning_rate_fake_value,lamda_lag:lamda_value,\n",
942 | " lamda_lag2:lamda_value2,r_lag:r_value,\n",
943 | " r_lag2:r_value2,F_input: F_batch,F:F_sp,\n",
944 | " learning_rate:learning_rate_fake_value[i][0],beta:beta_value}) \n",
945 | " if g_value[i] < eta[i]:\n",
946 | " lamda_value[i] = lamda_value[i] + 2 * g_value[i] / r_value[i]\n",
947 | " j = j + 1\n",
948 | " eta[i] = eta[i] * 0.5\n",
949 | " else:\n",
950 | " r_value[i] = r_value[i] * 0.5\n",
951 | " j = 0\n",
952 | "\n",
953 | " if gd[i] < eta2[i]:\n",
954 | " lamda_value2[i] = lamda_value2[i] + 2 * gd[i][0] / r_value2[i]\n",
955 | " j2 = j2 + 1\n",
956 | " eta2[i] = eta2[i] * 0.5\n",
957 | " else:\n",
958 | " r_value2[i] = r_value2[i] * 0.5\n",
959 | " j2 = 0\n",
960 | " \n",
961 | " for i in range(batch_size):\n",
962 | " beta_value[i] = 1.5 * beta_value[i]\n",
963 | "\n",
964 | "phi_value, rho_value = sess.run([phi, rho],feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,lamda_lag2: lamda_value2,r_lag: r_value,\n",
965 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: starter_learning_rate, beta: beta_value})\n",
966 | "\n",
967 | "print('finished')\n",
968 | "# sio.savemat('result/infill_phi_{}.mat'.format(count), mdict={'phi': phi_value})\n",
969 | "# sio.savemat('result/infill_rho_{}.mat'.format(count), mdict={'rho': rho_value})"
970 | ]
971 | },
972 | {
973 | "cell_type": "code",
974 | "execution_count": null,
975 | "metadata": {
976 | "collapsed": true
977 | },
978 | "outputs": [],
979 | "source": [
980 | "# import os\n",
981 | "# import time\n",
982 | "# timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n",
983 | "# if not os.path.exists(timestr):\n",
984 | "# os.makedirs(timestr)\n",
985 | "\n",
986 | "sio.savemat('{}/c_value.mat'.format(timestr), mdict={'c': np.array(c_value)})\n",
987 | "sio.savemat('{}/rho.mat'.format(timestr), mdict={'rho': np.array(rho_curr)})\n",
988 | "sio.savemat('{}/drho.mat'.format(timestr), mdict={'drho': np.array(drho_total_store)})"
989 | ]
990 | },
991 | {
992 | "cell_type": "code",
993 | "execution_count": null,
994 | "metadata": {
995 | "collapsed": true
996 | },
997 | "outputs": [],
998 | "source": [
999 | "phi_value, rho_value = sess.run([phi, rho],feed_dict={learning_rate_fake: learning_rate_fake_value, lamda_lag: lamda_value,lamda_lag2: lamda_value2,r_lag: r_value,\n",
1000 | " r_lag2: r_value2, F_input: F_batch, F: F_sp, learning_rate: starter_learning_rate, beta: beta_value})\n",
1001 | "\n",
1002 | "sio.savemat('result/infill_phi_{}.mat'.format(count), mdict={'phi': phi_value})\n",
1003 | "sio.savemat('result/infill_rho_{}.mat'.format(count), mdict={'rho': rho_value})"
1004 | ]
1005 | },
1006 | {
1007 | "cell_type": "code",
1008 | "execution_count": null,
1009 | "metadata": {
1010 | "collapsed": true
1011 | },
1012 | "outputs": [],
1013 | "source": [
1014 | "'training result'\n",
1015 | "%matplotlib inline\n",
1016 | "fig, axs = plt.subplots(2,5, figsize=(15, 4), facecolor='w', edgecolor='k')\n",
1017 | "fig.subplots_adjust(hspace = .1, wspace=.001)\n",
1018 | "\n",
1019 | "axs = axs.ravel()\n",
1020 | "\n",
1021 | "for i in range(batch_size):\n",
1022 | " axs[i].imshow(1-rho_value[i].reshape([nelx,nely]).T,'gray')\n",
1023 | "# axs[i].set_title(str(250+i))"
1024 | ]
1025 | },
1026 | {
1027 | "cell_type": "code",
1028 | "execution_count": null,
1029 | "metadata": {
1030 | "collapsed": true
1031 | },
1032 | "outputs": [],
1033 | "source": []
1034 | }
1035 | ],
1036 | "metadata": {
1037 | "kernelspec": {
1038 | "display_name": "Python 2",
1039 | "language": "python",
1040 | "name": "python2"
1041 | },
1042 | "language_info": {
1043 | "codemirror_mode": {
1044 | "name": "ipython",
1045 | "version": 2
1046 | },
1047 | "file_extension": ".py",
1048 | "mimetype": "text/x-python",
1049 | "name": "python",
1050 | "nbconvert_exporter": "python",
1051 | "pygments_lexer": "ipython2",
1052 | "version": "2.7.13"
1053 | }
1054 | },
1055 | "nbformat": 4,
1056 | "nbformat_minor": 2
1057 | }
1058 |
--------------------------------------------------------------------------------