Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • s7603593/dune-microstructure
  • s7603593/dune-microstructure-backup
2 results
Show changes
Showing
with 13658 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<addOn>
<identifier>e5698820-4a80-11e4-9553-005056977bd0</identifier>
<displayType>Function</displayType>
<translatedDisplayType>
<en_US>Function</en_US>
<ja_JP>関数</ja_JP>
<ko_KR>함수</ko_KR>
<zh_CN>函数</zh_CN>
</translatedDisplayType>
<name>Red Blue Colormap</name>
<author>Adam Auton</author>
<version>1.0.0.0</version>
<downloadUrl>https://www.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/25536/versions/1/download/zip?src=addons_ml_desktop_install&amp;profile_id=14169257&amp;license=40758619&amp;release_family=R2020b</downloadUrl>
<licenseUrl>https://addons.mathworks.com/registry/v1/e5698820-4a80-11e4-9553-005056977bd0/1.0.0.0/-/license</licenseUrl>
<previewImageUrl>https://www.mathworks.com/responsive_image/160/120/0/0/0/cache/matlabcentral/mlc-downloads/downloads/submissions/25536/versions/1/screenshot.png</previewImageUrl>
<releaseNotesUrl>https://www.mathworks.com/add-ons/e5698820-4a80-11e4-9553-005056977bd0/d1034754-ea44-08f8-b658-22b590dfae7e/releaseNotes</releaseNotesUrl>
<installationFolder>Functions</installationFolder>
</addOn>
Matlab-Programs/resources/previewImage.png

18.8 KiB

File added
Matlab-Programs/resources/screenshot.png

17 KiB

function [G, angle, Type, kappa] = symMinimization(print_Input,print_statPoint,print_Output,make_FunctionPlot, InputPath) %(Q_hom,B_eff)
syms v1 v2 q1 q2 q3 q12 b1 b2 b3
% -------- Options ----------
% % print_Input = false; %effective quantities
% print_Input = true;
% % print_statPoint = false;
% print_statPoint = true;
% print_Minimizer = true;
% % make_FunctionPlot = false;
% make_FunctionPlot = true;
print_Uniqueness = false;
check_StationaryPoints = false; % could be added to Input-Parameters..
compare_with_Classification = false; %maybe added later ---
%fprintf('Functions to be minimized:')
f_plus(v1,v2,q1,q2,q3,q12,b1,b2,b3) = q1*v1^4 + q2*v2^4+2*q3*v1^2*v2^2-2*(q1*b1*v1^2+ q2*b2*v2^2+sqrt(2)*q3*b3*v1*v2)...
+ q12*(v1^2*v2^2-b2*v1^2-b1*v2^2+b1*b2);
f_minus(v1,v2,q1,q2,q3,q12,b1,b2,b3) = q1*v1^4 + q2*v2^4+2*q3*v1^2*v2^2+2*(q1*b1*v1^2+ q2*b2*v2^2+sqrt(2)*q3*b3*v1*v2)...
+ q12*(v1^2*v2^2+b2*v1^2+b1*v2^2+b1*b2);
% ---- Fix parameters
% Epsilon used:
epsilon = 1e-8;
if ~exist('InputPath','var')
% third parameter does not exist, so default it to something
absPath = "/home/klaus/Desktop/DUNE/dune-microstructure/outputs";
end
% 1. Import effective quantities from CellSolver-Code:
%read as sparse Matrix...
try %absolutePath
Qmat = spconvert(load(absPath + '' + "/QMatrix.txt"));
Bmat = spconvert(load(absPath + '' + "/BMatrix.txt"));
% fprintf('Use absolute Path')
catch ME % use relativePath
Qmat = spconvert(load('../outputs/QMatrix.txt'));
Bmat = spconvert(load('../outputs/BMatrix.txt'));
% fprintf('Use relative Path')
end
%convert to full matrix...
Qmat = full(Qmat);
Bmat = full(Bmat);
% --- TODO CHECK: assert if Q is orthotropic ??? check ifq13=q31=q23=q32= 0 ?
if print_Input
fprintf('effective quadratic form:')
Qmat
fprintf('effective prestrain')
Bmat
% check if Q is (close to..) symmetric
% könnte Anti-symmetric part berechnen und schauen dass dieser klein?
% Test: issymmetric(Qmat) does not work for float matrices?
% symmetric part 0.5*(Qmat+Qmat')
% anti-symmetric part 0.5*(Qmat-Qmat')
if norm(0.5*(Qmat-Qmat'),'fro') < 1e-8
fprintf('Qmat (close to) symmetric \n')
norm(0.5*(Qmat-Qmat'),'fro') % TEST
else
fprintf('Qmat not symmetric \n')
end
% Check if B_eff is diagonal this is equivalent to b3 == 0
if abs(Bmat(3)) < 1e-8
fprintf('B_eff is diagonal (b3 == 0) \n')
else
fprintf('B_eff is NOT diagonal (b3 != 0) \n')
end
end
% CAST VALUES TO SYM FIRST? This is done anyway..
% % Substitute effective quantitites
f_plus = subs(f_plus,{q1, q2, q3, q12, b1, b2, b3}, {Qmat(1,1), Qmat(2,2), Qmat(3,3), Qmat(1,2), ...
Bmat(1), Bmat(2), Bmat(3)});
f_minus = subs(f_minus,{q1, q2, q3, q12, b1, b2, b3}, {Qmat(1,1), Qmat(2,2), Qmat(3,3), Qmat(1,2), ...
Bmat(1), Bmat(2), Bmat(3)});
% Compute the Gradients
df_plusx = diff(f_plus,v1);
df_plusy = diff(f_plus,v2);
df_minusx = diff(f_minus,v1);
df_minusy = diff(f_minus,v2);
% Setup Equations Grad(f) = 0
eq1 = df_plusx == 0;
eq2 = df_plusy == 0;
eqns_plus = [eq1, eq2];
eq3 = df_minusx == 0;
eq4 = df_minusy == 0;
eqns_minus = [eq3, eq4];
% ------- Symbolically Solve Equations:
% More robust (works even for values b_3 ~ 1e-08 ):
S_plus = solve(eqns_plus,v1,v2,'MaxDegree' , 5);
S_minus = solve(eqns_minus,v1,v2,'MaxDegree' , 5);
A_plus = S_plus.v1;
B_plus = S_plus.v2;
A_minus = S_minus.v1;
B_minus = S_minus.v2;
if check_StationaryPoints
%---------- TEST if Grad(f) = 0 ---------------------
fprintf('Testing equation grad(f) = 0 with stationary points')
for i = 1:size(A_plus,1)
fprintf('Testing %d.point (f_plus): ',i )
[ double(subs(subs(df_plusx,v1,A_plus(i)),v2,B_plus(i))), double(subs(subs(df_plusy,v1,A_plus(i)),v2,B_plus(i))) ]
end
for i = 1:size(A_minus,1)
fprintf('Testing %d.point (f_minus): ',i )
[double(subs(subs(df_minusx,v1,A_minus(i)),v2,B_minus(i))), double(subs(subs(df_minusy,v1,A_minus(i)),v2,B_minus(i)))]
end
% ------------------------------------
end
% --- Extract only Real-Solutions
% fprintf('real stationary points of f_plus:')
tmp1 = A_plus(imag(double(A_plus))==0 & imag(double(B_plus)) == 0);
tmp2 = B_plus(imag(double(A_plus))==0 & imag(double(B_plus)) == 0);
A_plus = tmp1;
B_plus = tmp2;
SP_plus = [A_plus,B_plus];
% fprintf('real stationary points of f_minus:')
tmp1 = A_minus(imag(double(A_minus))==0 & imag(double(B_minus)) == 0);
tmp2 = B_minus(imag(double(A_minus))==0 & imag(double(B_minus)) == 0);
A_minus = tmp1;
B_minus = tmp2;
SP_minus = [A_minus,B_minus];
% TODO one should use f_plus.subs(A_plus..) to compute function value symbolically?
% in the end only the stationaryPoints are used.. should be ok to compare function values numerically
% Determine global Minimizer from stationary points:
% fprintf('function values at stationary points (f_plus):')
T_plus = arrayfun(@(v1,v2) double(f_plus(v1,v2,q1,q2,q3,q12,b1,b2,b3)),A_plus,B_plus,'UniformOutput', false);
T_plus = cell2mat(T_plus);
%Test: use Substitution
% subs(f_plus,{v1, v2}, {A_plus,B_plus})
% fprintf('function values at stationary points (f_minus):')
T_minus = arrayfun(@(v1,v2) double(f_minus(v1,v2,q1,q2,q3,q12,b1,b2,b3)),A_minus,B_minus,'UniformOutput', false);
T_minus = cell2mat(T_minus);
%Test: use Substitution
% T_minus = subs(f_minus,{v1, v2}, {A_minus,B_minus})
% double(T_minus)
if print_statPoint
fprintf('real stationary points of f_plus: ')
% SP_Plus %alternative: output as symbolic (can be unwieldy)
double(SP_plus)
fprintf('real stationary points of f_minus:')
% SP_Minus %alternative: output as symbolic (can be unwieldy)
double(SP_minus)
fprintf('function values at stationary points (f_plus):')
T_plus
fprintf('function values at stationary points (f_minus):')
T_minus
end
% --- Find Stationary Point(s) with minimum Value
[Min_plus,MinIdx_plus] = min(T_plus, [], 'all', 'linear'); %find one min...
[Min_minus,MinIdx_minus] = min(T_minus, [], 'all', 'linear');
% [Min_minus,MinIdx_minus] = min(T_minus) % works with symbolic too
% Compare Minimizers of f_plus & f_minus
[globalMinimizerValue,GlobalIdx] = min([Min_plus,Min_minus]);
if GlobalIdx == 1 %Min_plus % i.e. Global Minimizer is given by f_plus
GlobalMinimizer = SP_plus(MinIdx_plus,:);
sign = 1.0;
elseif GlobalIdx == 2 %Min_minus % i.e. Global Minimizer is given by f_minus
GlobalMinimizer = SP_minus(MinIdx_minus,:);
sign = -1.0;
end
% ------ Check if there are more SP with the same value...
MinIndices_minus = find(T_minus(:) == globalMinimizerValue); % Find indices of All Minima
MinIndices_plus = find(T_plus(:) == globalMinimizerValue); % Find indices of All Minima
numMinSP_minus = size(MinIndices_minus,1); % One of these is always >= 2 due to the structure of the roots..
numMinSP_plus = size(MinIndices_plus,1);
% AllMinSP_minus = SP_minus(MinIndices_minus,:)
% AllMinSP_minus = double(SP_minus(MinIndices_minus,:))
% AllMin = T_minus(MinIndices) %bereits klar dass diese selben funktionswert haben..
Minimizer = sign*(GlobalMinimizer'*GlobalMinimizer); % global minimizing Matrix G*
MinimizerCount = 1;
% different Stationary Points might correspond to the same minimizing
% Matrix G*... check this:
% Compare only with other StationaryPoints/Minimizers
% remove Index of Minimizer
if GlobalIdx == 1
MinIndices_plus = MinIndices_plus(MinIndices_plus~=MinIdx_plus);
elseif GlobalIdx == 2
MinIndices_minus = MinIndices_minus(MinIndices_minus~=MinIdx_minus);
end
MinIndices = cat(1,MinIndices_plus,MinIndices_minus); %[Minimizers-Indices f_plus, Minimizer-Indices f_minus]
for i = 1:(numMinSP_minus+numMinSP_plus-1) % -1: dont count Minimizer itself..
idx = MinIndices(i);
if i > numMinSP_plus
SP = SP_minus(idx,:);
else
SP = SP_plus(idx,:);
end
% SP_value = T_minus(idx) % not needed?
Matrix = sign*(SP'*SP);
if norm(double(Matrix-Minimizer),'fro') < 1e-8 %check is this sufficient here?
% fprintf('both StationaryPoints correspond to the same(Matrix-)Minimizer')
else
% fprintf('StationaryPoint corresponds to a different (Matrix-)Minimizer')
MinimizerCount = MinimizerCount + 1;
end
end
% ----------------------------------------------------------------------------------------------------------------
% Output Uniqueness of Minimizers:
if print_Uniqueness
if MinimizerCount == 1
fprintf('Unique Minimzier')
elseif MinimizerCount == 2
fprintf('Two Minimziers')
else
fprintf('1-Parameter family of Minimziers')
end
end
% --- determine the angle of the Minimizer
% a1 = Minimizer(1,1)
% a2 = Minimizer(2,2)
a1 = double(Minimizer(1,1));
a2 = double(Minimizer(2,2));
% compute the angle <(e,e_1) where Minimizer = kappa* (e (x) e)
e = [sqrt((a1/(a1+a2))), sqrt((a2/(a1+a2)))]; % always positive under sqrt here .. basically takes absolute value here
angle = atan2(e(2), e(1));
% compute curvature kappa
kappa = (a1 + a2);
% % CHeck off diagonal entries:
% sqrt(a1*a2);
% double(Minimizer);
G = double(Minimizer);
% --- "Classification" / Determine the TYPE of Minimizer by using
% the number of solutions (Uniqueness?)
% the angle (axial- or non-axial Minimizer)
% (Alternative compute det[GlobalMinimizer' e1'] where e1 = [1 0] ?)
% Check Uniqueness -- Options: unique/twoMinimizers/1-ParameterFamily
if MinimizerCount == 1
% fprintf('Unique Minimzier')
% Check if Minimizer is axial or non-axial:
if (abs(angle-pi/2) < 1e-8 || abs(angle) < 1e-8) % axial Minimizer
Type = 3;
else % non-axial Minimizer
Type = 1;
end
elseif MinimizerCount == 2
% fprintf('Two Minimziers')
% Check if Minimizer is axial or non-axial:
if (abs(angle-pi/2) < 1e-8 || abs(angle) < 1e-8) % axial Minimizer
Type = 3;
else % non-axial Minimizer
fprintf('ERROR: Two non-axial Minimizers cannot happen!')
end
else
% fprintf('1-Parameter family of Minimziers')
% Check if Minimizer is axial or non-axial:
if (abs(angle-pi/2) < 1e-8 || abs(angle) < 1e-8) % axial Minimizer
% fprintf('ERROR: axial Minimizers cannot happen for 1-Parameter Family!')
else % non-axial Minimizer
Type = 2;
end
end
% ------------------------------------------------------------------------------------------------------
if print_Output
fprintf(' --------- Output symMinimization --------')
fprintf('Global Minimizer v: (%d,%d) \n', GlobalMinimizer(1),GlobalMinimizer(2) )
fprintf('Global Minimizer Value f(v): %d \n', sym(globalMinimizerValue) ) %cast to symbolic
% fprintf('Global Minimizer Value : %d', globalMinimizerValue )
fprintf('Global Minimizer G: \n' )
G
fprintf("Angle = %d \n", angle)
fprintf("Curvature = %d \n", kappa)
fprintf("Type = %i \n", Type)
fprintf(' --------- -------------------- --------')
end
if make_FunctionPlot
fsurf(@(x,y) f_plus(x,y,q1,q2,q3,q12,b1,b2,b3)) % Plot functions
hold on
plot3(double(A_plus),double(B_plus),T_plus,'g*')
%Plot GlobalMinimizer:
hold on
plot3(double(GlobalMinimizer(1)),double(GlobalMinimizer(2)),globalMinimizerValue, 'o', 'Color','c')
% view(90,0)
% view(2)
figure
fsurf(@(x,y) f_minus(x,y,q1,q2,q3,q12,b1,b2,b3))
hold on
plot3(double(A_minus),double(B_minus),T_minus,'g*')
hold on
plot3(double(GlobalMinimizer(1)), double(GlobalMinimizer(2)),globalMinimizerValue, 'o', 'Color','c')
end
return
% Write symbolic solution to txt-File in Latex format
% fileID = fopen('txt.txt','w');
% fprintf(fileID,'%s' , latex(S_plus.v1));
% fclose(fileID);
syms q1 q2 q3 q12 b1 b2 a1 a2
% eqn1 = q1 * a1 + (q3 + (q12/2)) *a2 == -2*q1*b1 - q12*b2
%
% eqn2 = (q3 + (q12/2)) * a1 + q2 *a2 == -2*q2*b2 - q12*b1
eqn1 = q1 * a1 + (q3 + (q12/2)) *a2 == q1*b1 + (q12*b2/2)
eqn2 = (q3 + (q12/2)) * a1 + q2 *a2 == q2*b2 + (q12*b1/2)
[A,B] = equationsToMatrix([eqn1, eqn2], [a1,a2])
X = linsolve(A,B)
% check special case
fprintf('special case q12 = 0 ')
subs(X,q12,0)
\ No newline at end of file
Colormap: Cool-to-Warm
Representation: Point-Gaussian
Opacity: 0.01
PointSize: 2
Gaussian-radius: 0.0075
Shader-Preset: Plain-Circle
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# Extra packages :
# from HelperFunctions import *
# from ClassifyMin import *
# from subprocess import Popen, PIPE
#import sys
###################### Documentation #########################
#..... add description here
###########################################################
def rot(v,alpha):
#rotate about axis v with degree deg in radians:
tmp = np.array([ [v[0]**2*(1-np.cos(alpha))+np.cos(alpha), v[0]*v[1]*(1-np.cos(alpha))-v[2]*np.sin(alpha), v[0]*v[2]*(1-np.cos(alpha))+ v[1]*np.sin(alpha) ],
[v[0]*v[1]*(1-np.cos(alpha))+v[2]*np.sin(alpha), v[1]**2*(1-np.cos(alpha))+np.cos(alpha), v[1]*v[2]*(1-np.cos(alpha))+v[0]*np.sin(alpha) ],
[v[2]*v[0]*(1-np.cos(alpha))-v[1]*np.sin(alpha), v[2]*v[1]*(1-np.cos(alpha))+v[0]*np.sin(alpha) , v[2]**2*(1-np.cos(alpha))+np.cos(alpha) ] ])
return tmp
def rotate_data(X, R):
#rotate about axis v with degree deg in radians:
# X : DataSet
# R : RotationMatrix
print('ROTATE DATA FUNCTION ---------------')
rot_matrix = R
# print('rot_matrix:', rot_matrix)
# print('rot_matrix.shape:', rot_matrix.shape)
# print('X', X)
# print('shape of X[0]', X.shape[0])
B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
# print('shape of B', B.shape)
# print('B',B)
# print('B[0,:]', B[0,:])
# print('B[0,:].shape', B[0,:].shape)
Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
print('shape of Out', Out.shape)
return Out
# def rotate_data(X, v,alpha): #(Old Version)
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
# rot_matrix = rot(v,alpha)
# # print('rot_matrix:', rot_matrix)
# # print('rot_matrix.shape:', rot_matrix.shape)
#
# # print('X', X)
# # print('shape of X[0]', X.shape[0])
# B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
#
# # print('shape of B', B.shape)
# # print('B',B)
# # print('B[0,:]', B[0,:])
# # print('B[0,:].shape', B[0,:].shape)
# Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
# print('shape of Out', Out.shape)
#
# return Out
# def translate_data(X, v): ...
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
#
# print('X', X)
# print('shape of X[0]', X.shape[0])
#
# Out = X + v
# return Out
def u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp for u',tmp)
if kappa == 0 :
tmp = np.array([0*x[0], x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1] ])
else :
tmp = np.array([-(1/kappa)*np.cos(tmp)+(1/kappa), (1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0] ])
return tmp
def grad_u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp',tmp)
grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# print('produkt', grad_u.dot(e) )
mapped_e = grad_u.dot(e)
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
# mapped_e = mapped_e.transpose()
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
return mapped_e
def compute_normal(x,kappa,e):
tmp = (x.dot(e))*kappa
partial1_u = np.array([ np.sin(tmp)*e[0] ,np.cos(tmp)*e[0], -e[1] ])
partial2_u = np.array([ np.sin(tmp)*e[1], np.cos(tmp)*e[1], e[0] ])
normal = np.cross(partial1_u,partial2_u)
# print('normal=',normal)
return normal
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
print('T:', T)
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
e_container = []
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
e_container.append(e)
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
G_container = np.array(G_container)
abar_container = np.array(abar_container)
e_container = np.array(e_container)
print('G_container', G_container)
print('G_container.shape', G_container.shape)
# idx_1 = np.where(alphas == np.pi/4)
idx_1 = np.where(np.round(alphas,2) == round(np.pi/3,2))
idx_2 = np.where(np.round(alphas,2) == 0.0)
idx_3 = np.where(np.round(alphas,2) == round(np.pi/4,2))
# idx_3 = np.where(alphas == 0)
print('Index idx_1:', idx_1)
print('Index idx_2:', idx_2)
print('Index idx_3:', idx_3)
print('Index idx_1[0][0]:', idx_1[0][0])
print('Index idx_2[0][0]:', idx_2[0][0])
print('Index idx_3[0][0]:', idx_3[0][0])
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('kappas:',kappas)
# print('alphas:',alphas)
print('min alpha:', min(alphas))
print('min kappa:', min(kappas))
print('G_container[idx_1[0][0]]', G_container[idx_1[0][0]])
print('G_container[idx_2[0][0]]', G_container[idx_2[0][0]])
print('G_container[idx_3[0][0]]', G_container[idx_3[0][0]])
print('e_container[idx_1[0][0]]', e_container[idx_1[0][0]])
print('e_container[idx_2[0][0]]', e_container[idx_2[0][0]])
print('e_container[idx_3[0][0]]', e_container[idx_3[0][0]])
idx = 2
e = e_container[idx_1[0][0]]
e = e_container[idx_2[0][0]]
# e = e_container[idx_3[0][0]]
kappa = kappas[idx_1[0][0]]
kappa = kappas[idx_2[0][0]]
# kappa = kappas[idx_3[0][0]]
angle = alphas[idx_1[0][0]]
angle = alphas[idx_2[0][0]]
# angle = alphas[idx_3[0][0]]
# kappa = kappa*2
print('kappa:',kappa)
print('angle:',angle)
#### TEST apply reflection
#
# G_tmp = G_container[idx_1[0][0]]
#
# print('G_tmp', G_tmp)
#
# # Basis:
# G_1 = np.array([[1.0,0.0], [0.0,0.0]])
# G_2 = np.array([[0.0,0.0], [0.0,1.0]])
# G_3 = (1/np.sqrt(2))*np.array([[0.0,1.0], [1.0,0.0]])
# print('G_1', G_1)
# print('G_2', G_2)
# print('G_3', G_3)
#
# G = G_tmp[0] * G_1 + G_tmp[1]*G_2 + G_tmp[2]*G_3
# print('G:', G )
#
# T = np.array([[1.0 , -1.0] , [-1.0,1.0]])
#
# TG = np.multiply(T,G)
# print('TG', TG)
#
#
#
# v = np.array([np.sqrt(TG[0][0]),np.sqrt(TG[1][1]) ])
# print('v', v)
# print('norm(v):', np.linalg.norm(v))
# norm_v = np.linalg.norm(v)
#
# kappa = norm_v**2
#
# e = (1/norm_v)*v
# print('e:', e)
# print('kappa:', kappa)
reflected_e = np.array([e[0], -1*e[1]])
e = reflected_e # Correct?! Reflect e on x-Axis ??!
print('reflected_e:', reflected_e)
############################################################################################################################################
####################################################################### KAPPA NEGATIVE ####################################################
############################################################################################################################################
# kappa = -2
num_Points = 200
num_Points = 100
# e = np.array([1,0])
# e = np.array([0,1])
# e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e = np.array([1/2,np.sqrt(3)/2])
# e = np.array([np.sqrt(3)/2,1/2])
# e = np.array([-1,0])
# e = np.array([0,-1])
###--- Creating dataset
x = np.linspace(-2,2,num_Points)
x = np.linspace(-3,3,num_Points)
# x = np.linspace(-4,4,num_Points)
# x = np.linspace(-1.5,1.5,num_Points)
# x = np.linspace(-1,1,num_Points)
y = np.linspace(-1/2,1/2,num_Points)
y = np.linspace(-1/4,1/4,num_Points)
print('type of x', type(x))
print('max of x:', max(x))
print('max of y:', max(y))
# print('x:', x)
x1, x2 = np.meshgrid(x,y)
zero = 0*x1
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# print('np.size(u1)',np.size(u1))
# print('u1.shape',u1.shape)
# colorfunction=(u1**2+u2**2)
# print('colofunction',colorfunction)
# print('u1.size:',np.size(u1))
# tmp = np.ones(np.size(u1))*kappa
# print('np.size(tmp)',np.size(tmp))
B = np.full_like(u1, 1)
# colorfunction=(u3) # TODO Color by angle
# colorfunction=(np.ones(np.size(u1))*kappa)
colorfunction=(B*kappa)
# print('colofunction',colorfunction)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# -----------------------------------------------------
# Display the mesh
fig = plt.figure()
width = 6.28 *0.5
width = 6.28 * 0.333
height = width / 1.618
height = width / 2.5
height = width
ax = plt.axes(projection ='3d', adjustable='box')
###---TEST MAP e-vectprs!
# e1 = np.array([1,0])
# e2 = np.array([0,1])
# e3 = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e1 = np.array([0,1])
# e2 = np.array([-1,0])
# e3 = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# e1_mapped = u(e1,kappa,e1)
# e2_mapped = u(e2,kappa,e2)
# e3_mapped = u(e3,kappa,e3)
# print('e1 mapped:',e1_mapped)
# print('e2 mapped:',e2_mapped)
# print('e3 mapped:',e3_mapped)
### -----------------------------------
#--e1 :
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([0,1,0])
#--e2:
Rotation_angle = np.pi/2
Rotation_vector = np.array([1,0,0])
###--e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([1,0,0])
# #2te rotation :
# Rotation_angle = np.pi/4
# Rotation_vector = np.array([0,0,1])
Rotation_angle = -np.pi/2
Rotation_angle = 0
# Rotation_angle = np.pi/2
Rotation_vector = np.array([0,1,0])
Rotation_vector = np.array([1,0,0])
# rot(np.array([0,1,0]),np.pi/2)
# ZERO ROTATION
Rotation = rot(np.array([0,1,0]),0)
# TEST :
#DETERMINE ANGLE:
angle = math.atan2(e[1], e[0])
print('angle:', angle)
## GENERAL TRANSFORMATION / ROTATION:
Rotation = rot(np.array([0,0,1]),angle).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
### if e1:
# Rotation = rot(np.array([0,0,1]),-np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Add another rotation around z-axis:
# Rotation = rot(np.array([0,0,1]),+np.pi).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/8).dot(Rotation)
#e3 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),np.pi/4)
# Rotation = rot(np.array([1,0,0]),np.pi/4)
#### if e1 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
#### if e2:
# Rotation = rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2))
# # #### if e3 :
# zufall dass np.pi/4 genau dem Winkel angle alpha entspricht?:
# (würde) bei e_2 keinen Unterschied machen um z achse zu rotieren?!
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([1,0,0]),np.pi/2)
# Rotation_vector = e3_mapped #TEST
# Rotation_vector = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_vector = np.array([0,0,1])
# v = np.array([1,0,0])
# X = np.array([u1,u2,u3])
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 2, cstride = 2, facecolors=cm.brg(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.viridis(colorfunction), alpha=.4, zorder=4)
###---- PLOT PARAMETER-PLANE:
# ax.plot_surface(x1,x2,zero,color = 'w', rstride = 1, cstride = 1 )
print('------------------ Kappa : ', kappa)
#midpoint:
midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
print('midpoint',midpoint)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
# mapped_e = Rotation.dot(mapped_e)
# normal = Rotation.dot(normal)
# Plot Mapped_midPoint
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=4) # line width
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [mapped_e[0]], [mapped_e[1]], [mapped_e[2]], color="red")
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [normal[0]], [normal[1]], [normal[2]], color="blue")
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 2,
# ec ='green',
# zorder=3)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 2,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 3)
###-- TEST Rotation :
# v = np.array([1,0,0])
# t = np.array([0,1,0])
#
# ax.arrow3D(0,0,0,
# t[0],t[1],t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
#
# # e_extend
#
# rotM = rot(v,np.pi/2)
#
# print('rotM:', rotM)
#
# rot_t = rotM.dot(t)
#
# print('rot_t:', rot_t)
#
# ax.arrow3D(0,0,0,
# rot_t[0],rot_t[1],rot_t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
### -------------------------------------------
############################################################################################################################################
####################################################################### KAPPA POSITIVE ####################################################
############################################################################################################################################
# kappa = (-1)*kappa
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.3) ##This one!
# T = rotate_data(X,Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=False)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 2, cstride = 2, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, facecolors=cm.brg(colorfunction), alpha=.8, zorder=4)
ax.plot_surface(T[0], T[1], T[2], rstride = 5, cstride = 5, color='orange', alpha=.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color='blue', alpha=.8, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=0.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=1, zorde5r=5)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
# print('midpoint',midpoint)
print('------------------ Kappa : ', kappa)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# Plot MIDPOINT:
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
# mapped_e = grad_u(midpoint,kappa,e)
# normal = compute_normal(midpoint,kappa,e)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
############################################################################################################################################
####################################################################### KAPPA ZERO #########################################################
############################################################################################################################################
kappa = 0
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, rstride = 1, cstride = 1, color = 'white', alpha=0.85)
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride =1 , cstride = 1, color = 'white', alpha=0.55, zorder=3)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.5, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color = 'white', alpha=0.55, zorder=2)
ax.plot_surface(T[0], T[1], T[2], rstride = 20, cstride = 20, color = 'gray', alpha=0.35, zorder=1, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'white', alpha=0.55, zorder=2)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
mapped_e = grad_u(midpoint,kappa,e)
normal_zeroCurv = compute_normal(midpoint,kappa,e)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
##----- PLOT MAPPED MIDPOINT :::
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# # linestyle='--', # line style will be dash line
# linewidth=1,
# zorder=5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='red',
# ec ='red')
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal_zeroCurv[0],normal_zeroCurv[1],normal_zeroCurv[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
##---------- PLOT MAPPED ORIGIN :::
# origin = np.array([0,0])
# origin_mapped = u(origin,kappa,e)
# print('origin_mapped', origin_mapped)
#
# ax.plot(origin_mapped[0],origin_mapped[1],origin_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='green', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#
# # rotate mapped origin
# # v = np.array([1,0,0])
# # alpha = Rotation_angle
#
# rotM = rot(Rotation_vector,Rotation_angle)
# # origin_mRot = rotate_data(origin_mapped,v,alpha)
# origin_mRot = rotM.dot(origin_mapped)
# print('origin_mapped Rotated', origin_mRot)
#
# # --- Compute Distance to Origin 3D
# origin_3D=np.array([0,0,0])
# distance = origin_mapped-origin_3D
# print('distance', distance)
## --------------------------------------------------------
# COMPUTE ANGLE WITH Z AXIS
z = np.array([0,0,1])
print('test', normal_zeroCurv*z)
angle_z = np.arccos(normal_zeroCurv.dot(z) /( (np.linalg.norm(z)*np.linalg.norm(normal_zeroCurv) ) ))
print('angle between normal and z-axis', angle_z)
## unfinished...
###------------------------------------- PLOT :
plt.axis('off')
# plt.axis('tight')
# ADD colorbar
# scamap = plt.cm.ScalarMappable(cmap='inferno')
# fig.colorbar(scamap)
# ax.colorbar()
# ax.axis('auto')
# ax.set_title(r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e))
# ax.set_title(r'Cylindrical minimizer' + '_$e$=' + str(e))
ax.set_xlabel(r"x-axis")
ax.set_ylabel(r"y-axis")
ax.set_zlabel(r"z-axis")
# TEST :
# ax.annotate3D('point 1', (0, 0, 0), xytext=(3, 3), textcoords='offset points')
# ax.annotate3D('point 2', (0, 1, 0),
# xytext=(-30, -30),
# textcoords='offset points',
# arrowprops=dict(ec='black', fc='white', shrink=2.5))
# ax.annotate3D('point 3', (0, 0, 1),
# xytext=(30, -30),
# textcoords='offset points',
# bbox=dict(boxstyle="round", fc="lightyellow"),
# arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))
#######################################################################################################################
u1 = T[0]
u2 = T[1]
u3 = T[2]
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /3
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /12
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /8
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /6
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /2
mid_u1 = (u1.max()+u1.min()) * 0.5
mid_u2 = (u2.max()+u2.min()) * 0.5
mid_u3 = (u3.max()+u3.min()) * 0.5
ax.set_xlim(mid_u1 - max_range, mid_u1 + max_range)
ax.set_ylim(mid_u2 - max_range, mid_u2 + max_range)
ax.set_zlim(mid_u3 - max_range, mid_u3 + max_range)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-1.5, (mid_u2 + max_range)+1.5)
# ax.autoscale(tight=True)
##----- CHANGE CAMERA POSITION:
# ax.view_init(elev=10., azim=0)
# ax.view_init(elev=38, azim=90)
# ax.view_init(elev=38, azim=120)
# ax.view_init(elev=38)
# if e1 ::
# ax.view_init(elev=44)
# ax.view_init(elev=38, azim=-90)
# ax.view_init(elev=38, azim=0)
ax.view_init(elev=25, azim=-30)
# if e3 ::
# ax.view_init(elev=25)
# ax.set_xlim3d(-2, 2)
# ax.set_ylim3d(-1.0,3.0)
# ax.set_zlim3d(-1.5,2.5)
# ax.set_ylim3d(-10,10)
# ax.set_xlim(mid_u1 - max_range-0.2, mid_u1 + max_range+0.2)
# ax.set_zlim(mid_u3 - max_range-0.2, mid_u3 + max_range+0.2)
# ax.set_ylim(mid_u2 - max_range-0.2, mid_u2 + max_range+0.2)
# width = 6.28 *0.5
# height = width / 1.618
# # height = width / 2.5
# fig.set_size_inches(width, height)
# fig.savefig('Test-Cylindrical.pdf')
# Figurename = r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e)
# Figurename = r'Cylindrical minimizer' + '_$e$=' + str(e)
Figurename = r'1-ParFamMinimizer_idx' + str(idx)
# plt.savefig("test.png", bbox_inches='tight')
# plt.figure().set_size_inches(width, height)
# plt.set_size_inches(width, height)
fig.set_size_inches(width, height)
fig.savefig(Figurename+".pdf")
plt.savefig(Figurename+".png", bbox_inches='tight')
# plt.savefig(Figurename+".png")
plt.show()
# #---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# Extra packages :
# from HelperFunctions import *
# from ClassifyMin import *
# from subprocess import Popen, PIPE
#import sys
###################### Documentation #########################
#..... add description here
###########################################################
def rot(v,alpha):
#rotate about axis v with degree deg in radians:
tmp = np.array([ [v[0]**2*(1-np.cos(alpha))+np.cos(alpha), v[0]*v[1]*(1-np.cos(alpha))-v[2]*np.sin(alpha), v[0]*v[2]*(1-np.cos(alpha))+ v[1]*np.sin(alpha) ],
[v[0]*v[1]*(1-np.cos(alpha))+v[2]*np.sin(alpha), v[1]**2*(1-np.cos(alpha))+np.cos(alpha), v[1]*v[2]*(1-np.cos(alpha))+v[0]*np.sin(alpha) ],
[v[2]*v[0]*(1-np.cos(alpha))-v[1]*np.sin(alpha), v[2]*v[1]*(1-np.cos(alpha))+v[0]*np.sin(alpha) , v[2]**2*(1-np.cos(alpha))+np.cos(alpha) ] ])
return tmp
def rotate_data(X, R):
#rotate about axis v with degree deg in radians:
# X : DataSet
# R : RotationMatrix
print('ROTATE DATA FUNCTION ---------------')
rot_matrix = R
# print('rot_matrix:', rot_matrix)
# print('rot_matrix.shape:', rot_matrix.shape)
# print('X', X)
# print('shape of X[0]', X.shape[0])
B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
# print('shape of B', B.shape)
# print('B',B)
# print('B[0,:]', B[0,:])
# print('B[0,:].shape', B[0,:].shape)
Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
print('shape of Out', Out.shape)
return Out
# def rotate_data(X, v,alpha): #(Old Version)
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
# rot_matrix = rot(v,alpha)
# # print('rot_matrix:', rot_matrix)
# # print('rot_matrix.shape:', rot_matrix.shape)
#
# # print('X', X)
# # print('shape of X[0]', X.shape[0])
# B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
#
# # print('shape of B', B.shape)
# # print('B',B)
# # print('B[0,:]', B[0,:])
# # print('B[0,:].shape', B[0,:].shape)
# Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
# print('shape of Out', Out.shape)
#
# return Out
# def translate_data(X, v): ...
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
#
# print('X', X)
# print('shape of X[0]', X.shape[0])
#
# Out = X + v
# return Out
def u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp for u',tmp)
if kappa == 0 :
tmp = np.array([0*x[0], x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1] ])
else :
tmp = np.array([-(1/kappa)*np.cos(tmp)+(1/kappa), (1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0] ])
return tmp
def grad_u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp',tmp)
grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# print('produkt', grad_u.dot(e) )
mapped_e = grad_u.dot(e)
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
# mapped_e = mapped_e.transpose()
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
return mapped_e
def compute_normal(x,kappa,e):
tmp = (x.dot(e))*kappa
partial1_u = np.array([ np.sin(tmp)*e[0] ,np.cos(tmp)*e[0], -e[1] ])
partial2_u = np.array([ np.sin(tmp)*e[1], np.cos(tmp)*e[1], e[0] ])
normal = np.cross(partial1_u,partial2_u)
# print('normal=',normal)
return normal
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
print('T:', T)
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
e_container = []
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
e_container.append(e)
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
G_container = np.array(G_container)
abar_container = np.array(abar_container)
e_container = np.array(e_container)
print('G_container', G_container)
print('G_container.shape', G_container.shape)
# idx_1 = np.where(alphas == np.pi/4)
idx_1 = np.where(np.round(alphas,2) == round(np.pi/3,2))
idx_2 = np.where(np.round(alphas,2) == 0.0)
idx_3 = np.where(np.round(alphas,2) == round(np.pi/4,2))
# idx_3 = np.where(alphas == 0)
print('Index idx_1:', idx_1)
print('Index idx_2:', idx_2)
print('Index idx_3:', idx_3)
print('Index idx_1[0][0]:', idx_1[0][0])
print('Index idx_2[0][0]:', idx_2[0][0])
print('Index idx_3[0][0]:', idx_3[0][0])
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('kappas:',kappas)
# print('alphas:',alphas)
print('min alpha:', min(alphas))
print('min kappa:', min(kappas))
print('G_container[idx_1[0][0]]', G_container[idx_1[0][0]])
print('G_container[idx_2[0][0]]', G_container[idx_2[0][0]])
print('G_container[idx_3[0][0]]', G_container[idx_3[0][0]])
print('e_container[idx_1[0][0]]', e_container[idx_1[0][0]])
print('e_container[idx_2[0][0]]', e_container[idx_2[0][0]])
print('e_container[idx_3[0][0]]', e_container[idx_3[0][0]])
idx = 2
e = e_container[idx_1[0][0]]
e = e_container[idx_2[0][0]]
# e = e_container[idx_3[0][0]]
kappa = kappas[idx_1[0][0]]
kappa = kappas[idx_2[0][0]]
# kappa = kappas[idx_3[0][0]]
angle = alphas[idx_1[0][0]]
angle = alphas[idx_2[0][0]]
# angle = alphas[idx_3[0][0]]
# kappa = kappa*2
print('kappa:',kappa)
print('angle:',angle)
#### TEST apply reflection
#
# G_tmp = G_container[idx_1[0][0]]
#
# print('G_tmp', G_tmp)
#
# # Basis:
# G_1 = np.array([[1.0,0.0], [0.0,0.0]])
# G_2 = np.array([[0.0,0.0], [0.0,1.0]])
# G_3 = (1/np.sqrt(2))*np.array([[0.0,1.0], [1.0,0.0]])
# print('G_1', G_1)
# print('G_2', G_2)
# print('G_3', G_3)
#
# G = G_tmp[0] * G_1 + G_tmp[1]*G_2 + G_tmp[2]*G_3
# print('G:', G )
#
# T = np.array([[1.0 , -1.0] , [-1.0,1.0]])
#
# TG = np.multiply(T,G)
# print('TG', TG)
#
#
#
# v = np.array([np.sqrt(TG[0][0]),np.sqrt(TG[1][1]) ])
# print('v', v)
# print('norm(v):', np.linalg.norm(v))
# norm_v = np.linalg.norm(v)
#
# kappa = norm_v**2
#
# e = (1/norm_v)*v
# print('e:', e)
# print('kappa:', kappa)
reflected_e = np.array([e[0], -1*e[1]])
e = reflected_e # Correct?! Reflect e on x-Axis ??!
print('reflected_e:', reflected_e)
############################################################################################################################################
####################################################################### KAPPA NEGATIVE ####################################################
############################################################################################################################################
# kappa = -2
num_Points = 200
num_Points = 100
# e = np.array([1,0])
# e = np.array([0,1])
# e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e = np.array([1/2,np.sqrt(3)/2])
# e = np.array([np.sqrt(3)/2,1/2])
# e = np.array([-1,0])
# e = np.array([0,-1])
###--- Creating dataset
x = np.linspace(-2,2,num_Points)
x = np.linspace(-3,3,num_Points)
# x = np.linspace(-4,4,num_Points)
# x = np.linspace(-1.5,1.5,num_Points)
# x = np.linspace(-1,1,num_Points)
y = np.linspace(-1/2,1/2,num_Points)
y = np.linspace(-1/4,1/4,num_Points)
print('type of x', type(x))
print('max of x:', max(x))
print('max of y:', max(y))
# print('x:', x)
x1, x2 = np.meshgrid(x,y)
zero = 0*x1
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# print('np.size(u1)',np.size(u1))
# print('u1.shape',u1.shape)
# colorfunction=(u1**2+u2**2)
# print('colofunction',colorfunction)
# print('u1.size:',np.size(u1))
# tmp = np.ones(np.size(u1))*kappa
# print('np.size(tmp)',np.size(tmp))
B = np.full_like(u1, 1)
# colorfunction=(u3) # TODO Color by angle
# colorfunction=(np.ones(np.size(u1))*kappa)
colorfunction=(B*kappa)
# print('colofunction',colorfunction)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# -----------------------------------------------------
# Display the mesh
fig = plt.figure()
width = 6.28 *0.5
width = 6.28 * 0.333
height = width / 1.618
height = width / 2.5
height = width
ax = plt.axes(projection ='3d', adjustable='box')
###---TEST MAP e-vectprs!
# e1 = np.array([1,0])
# e2 = np.array([0,1])
# e3 = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e1 = np.array([0,1])
# e2 = np.array([-1,0])
# e3 = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# e1_mapped = u(e1,kappa,e1)
# e2_mapped = u(e2,kappa,e2)
# e3_mapped = u(e3,kappa,e3)
# print('e1 mapped:',e1_mapped)
# print('e2 mapped:',e2_mapped)
# print('e3 mapped:',e3_mapped)
### -----------------------------------
#--e1 :
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([0,1,0])
#--e2:
Rotation_angle = np.pi/2
Rotation_vector = np.array([1,0,0])
###--e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([1,0,0])
# #2te rotation :
# Rotation_angle = np.pi/4
# Rotation_vector = np.array([0,0,1])
Rotation_angle = -np.pi/2
Rotation_angle = 0
# Rotation_angle = np.pi/2
Rotation_vector = np.array([0,1,0])
Rotation_vector = np.array([1,0,0])
# rot(np.array([0,1,0]),np.pi/2)
# ZERO ROTATION
Rotation = rot(np.array([0,1,0]),0)
# TEST :
#DETERMINE ANGLE:
angle = math.atan2(e[1], e[0])
print('angle:', angle)
## GENERAL TRANSFORMATION / ROTATION:
Rotation = rot(np.array([0,0,1]),angle).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
### if e1:
# Rotation = rot(np.array([0,0,1]),-np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Add another rotation around z-axis:
# Rotation = rot(np.array([0,0,1]),+np.pi).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/8).dot(Rotation)
#e3 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),np.pi/4)
# Rotation = rot(np.array([1,0,0]),np.pi/4)
#### if e1 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
#### if e2:
# Rotation = rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2))
# # #### if e3 :
# zufall dass np.pi/4 genau dem Winkel angle alpha entspricht?:
# (würde) bei e_2 keinen Unterschied machen um z achse zu rotieren?!
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([1,0,0]),np.pi/2)
# Rotation_vector = e3_mapped #TEST
# Rotation_vector = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_vector = np.array([0,0,1])
# v = np.array([1,0,0])
# X = np.array([u1,u2,u3])
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 2, cstride = 2, facecolors=cm.brg(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.viridis(colorfunction), alpha=.4, zorder=4)
###---- PLOT PARAMETER-PLANE:
# ax.plot_surface(x1,x2,zero,color = 'w', rstride = 1, cstride = 1 )
print('------------------ Kappa : ', kappa)
#midpoint:
midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
print('midpoint',midpoint)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
# mapped_e = Rotation.dot(mapped_e)
# normal = Rotation.dot(normal)
# Plot Mapped_midPoint
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=4) # line width
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [mapped_e[0]], [mapped_e[1]], [mapped_e[2]], color="red")
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [normal[0]], [normal[1]], [normal[2]], color="blue")
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 2,
# ec ='green',
# zorder=3)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 2,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 3)
###-- TEST Rotation :
# v = np.array([1,0,0])
# t = np.array([0,1,0])
#
# ax.arrow3D(0,0,0,
# t[0],t[1],t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
#
# # e_extend
#
# rotM = rot(v,np.pi/2)
#
# print('rotM:', rotM)
#
# rot_t = rotM.dot(t)
#
# print('rot_t:', rot_t)
#
# ax.arrow3D(0,0,0,
# rot_t[0],rot_t[1],rot_t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
### -------------------------------------------
############################################################################################################################################
####################################################################### KAPPA POSITIVE ####################################################
############################################################################################################################################
# kappa = (-1)*kappa
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.3) ##This one!
# T = rotate_data(X,Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=False)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 2, cstride = 2, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, facecolors=cm.brg(colorfunction), alpha=.8, zorder=4)
ax.plot_surface(T[0], T[1], T[2], rstride = 5, cstride = 5, color='orange', alpha=.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color='blue', alpha=.8, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=0.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=1, zorde5r=5)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
# print('midpoint',midpoint)
print('------------------ Kappa : ', kappa)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# Plot MIDPOINT:
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
# mapped_e = grad_u(midpoint,kappa,e)
# normal = compute_normal(midpoint,kappa,e)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
############################################################################################################################################
####################################################################### KAPPA ZERO #########################################################
############################################################################################################################################
kappa = 0
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, rstride = 1, cstride = 1, color = 'white', alpha=0.85)
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride =1 , cstride = 1, color = 'white', alpha=0.55, zorder=3)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.5, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color = 'white', alpha=0.55, zorder=2)
ax.plot_surface(T[0], T[1], T[2], rstride = 20, cstride = 20, color = 'gray', alpha=0.35, zorder=1, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'white', alpha=0.55, zorder=2)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
mapped_e = grad_u(midpoint,kappa,e)
normal_zeroCurv = compute_normal(midpoint,kappa,e)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
##----- PLOT MAPPED MIDPOINT :::
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# # linestyle='--', # line style will be dash line
# linewidth=1,
# zorder=5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='red',
# ec ='red')
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal_zeroCurv[0],normal_zeroCurv[1],normal_zeroCurv[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
##---------- PLOT MAPPED ORIGIN :::
# origin = np.array([0,0])
# origin_mapped = u(origin,kappa,e)
# print('origin_mapped', origin_mapped)
#
# ax.plot(origin_mapped[0],origin_mapped[1],origin_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='green', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#
# # rotate mapped origin
# # v = np.array([1,0,0])
# # alpha = Rotation_angle
#
# rotM = rot(Rotation_vector,Rotation_angle)
# # origin_mRot = rotate_data(origin_mapped,v,alpha)
# origin_mRot = rotM.dot(origin_mapped)
# print('origin_mapped Rotated', origin_mRot)
#
# # --- Compute Distance to Origin 3D
# origin_3D=np.array([0,0,0])
# distance = origin_mapped-origin_3D
# print('distance', distance)
## --------------------------------------------------------
# COMPUTE ANGLE WITH Z AXIS
z = np.array([0,0,1])
print('test', normal_zeroCurv*z)
angle_z = np.arccos(normal_zeroCurv.dot(z) /( (np.linalg.norm(z)*np.linalg.norm(normal_zeroCurv) ) ))
print('angle between normal and z-axis', angle_z)
## unfinished...
###------------------------------------- PLOT :
plt.axis('off')
# plt.axis('tight')
# ADD colorbar
# scamap = plt.cm.ScalarMappable(cmap='inferno')
# fig.colorbar(scamap)
# ax.colorbar()
# ax.axis('auto')
# ax.set_title(r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e))
# ax.set_title(r'Cylindrical minimizer' + '_$e$=' + str(e))
ax.set_xlabel(r"x-axis")
ax.set_ylabel(r"y-axis")
ax.set_zlabel(r"z-axis")
# TEST :
# ax.annotate3D('point 1', (0, 0, 0), xytext=(3, 3), textcoords='offset points')
# ax.annotate3D('point 2', (0, 1, 0),
# xytext=(-30, -30),
# textcoords='offset points',
# arrowprops=dict(ec='black', fc='white', shrink=2.5))
# ax.annotate3D('point 3', (0, 0, 1),
# xytext=(30, -30),
# textcoords='offset points',
# bbox=dict(boxstyle="round", fc="lightyellow"),
# arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))
#######################################################################################################################
u1 = T[0]
u2 = T[1]
u3 = T[2]
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /3
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /12
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /8
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /6
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /2
mid_u1 = (u1.max()+u1.min()) * 0.5
mid_u2 = (u2.max()+u2.min()) * 0.5
mid_u3 = (u3.max()+u3.min()) * 0.5
ax.set_xlim(mid_u1 - max_range, mid_u1 + max_range)
ax.set_ylim(mid_u2 - max_range, mid_u2 + max_range)
ax.set_zlim(mid_u3 - max_range, mid_u3 + max_range)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-1.5, (mid_u2 + max_range)+1.5)
# ax.autoscale(tight=True)
##----- CHANGE CAMERA POSITION:
# ax.view_init(elev=10., azim=0)
# ax.view_init(elev=38, azim=90)
# ax.view_init(elev=38, azim=120)
# ax.view_init(elev=38)
# if e1 ::
# ax.view_init(elev=44)
# ax.view_init(elev=38, azim=-90)
# ax.view_init(elev=38, azim=0)
ax.view_init(elev=25, azim=-30)
# if e3 ::
# ax.view_init(elev=25)
# ax.set_xlim3d(-2, 2)
# ax.set_ylim3d(-1.0,3.0)
# ax.set_zlim3d(-1.5,2.5)
# ax.set_ylim3d(-10,10)
# ax.set_xlim(mid_u1 - max_range-0.2, mid_u1 + max_range+0.2)
# ax.set_zlim(mid_u3 - max_range-0.2, mid_u3 + max_range+0.2)
# ax.set_ylim(mid_u2 - max_range-0.2, mid_u2 + max_range+0.2)
# width = 6.28 *0.5
# height = width / 1.618
# # height = width / 2.5
# fig.set_size_inches(width, height)
# fig.savefig('Test-Cylindrical.pdf')
# Figurename = r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e)
# Figurename = r'Cylindrical minimizer' + '_$e$=' + str(e)
Figurename = r'1-ParFamMinimizer_idx' + str(idx)
# plt.savefig("test.png", bbox_inches='tight')
# plt.figure().set_size_inches(width, height)
# plt.set_size_inches(width, height)
fig.set_size_inches(width, height)
fig.savefig(Figurename+".pdf")
plt.savefig(Figurename+".png", bbox_inches='tight')
# plt.savefig(Figurename+".png")
plt.show()
# #---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# Extra packages :
# from HelperFunctions import *
# from ClassifyMin import *
# from subprocess import Popen, PIPE
#import sys
###################### Documentation #########################
#..... add description here
###########################################################
def rot(v,alpha):
#rotate about axis v with degree deg in radians:
tmp = np.array([ [v[0]**2*(1-np.cos(alpha))+np.cos(alpha), v[0]*v[1]*(1-np.cos(alpha))-v[2]*np.sin(alpha), v[0]*v[2]*(1-np.cos(alpha))+ v[1]*np.sin(alpha) ],
[v[0]*v[1]*(1-np.cos(alpha))+v[2]*np.sin(alpha), v[1]**2*(1-np.cos(alpha))+np.cos(alpha), v[1]*v[2]*(1-np.cos(alpha))+v[0]*np.sin(alpha) ],
[v[2]*v[0]*(1-np.cos(alpha))-v[1]*np.sin(alpha), v[2]*v[1]*(1-np.cos(alpha))+v[0]*np.sin(alpha) , v[2]**2*(1-np.cos(alpha))+np.cos(alpha) ] ])
return tmp
def rotate_data(X, R):
#rotate about axis v with degree deg in radians:
# X : DataSet
# R : RotationMatrix
print('ROTATE DATA FUNCTION ---------------')
rot_matrix = R
# print('rot_matrix:', rot_matrix)
# print('rot_matrix.shape:', rot_matrix.shape)
# print('X', X)
# print('shape of X[0]', X.shape[0])
B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
# print('shape of B', B.shape)
# print('B',B)
# print('B[0,:]', B[0,:])
# print('B[0,:].shape', B[0,:].shape)
Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
print('shape of Out', Out.shape)
return Out
# def rotate_data(X, v,alpha): #(Old Version)
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
# rot_matrix = rot(v,alpha)
# # print('rot_matrix:', rot_matrix)
# # print('rot_matrix.shape:', rot_matrix.shape)
#
# # print('X', X)
# # print('shape of X[0]', X.shape[0])
# B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
#
# # print('shape of B', B.shape)
# # print('B',B)
# # print('B[0,:]', B[0,:])
# # print('B[0,:].shape', B[0,:].shape)
# Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
# print('shape of Out', Out.shape)
#
# return Out
# def translate_data(X, v): ...
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
#
# print('X', X)
# print('shape of X[0]', X.shape[0])
#
# Out = X + v
# return Out
#
# def u(x,kappa,e):
#
# tmp = (x.dot(e))*kappa
# # print('tmp for u',tmp)
# if kappa == 0 :
# tmp = np.array([0*x[0], x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1] ])
# else :
# tmp = np.array([-(1/kappa)*np.cos(tmp)+(1/kappa), (1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0] ])
# return tmp
#
#
#
#
# def grad_u(x,kappa,e):
#
# tmp = (x.dot(e))*kappa
# # print('tmp',tmp)
#
# grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# # print('produkt', grad_u.dot(e) )
# mapped_e = grad_u.dot(e)
# # print('mapped_e:', mapped_e)
# # print('siize of mapped_e', mapped_e.shape)
# # mapped_e = mapped_e.transpose()
# # print('mapped_e:', mapped_e)
# # print('siize of mapped_e', mapped_e.shape)
# return mapped_e
#
# def compute_normal(x,kappa,e):
# tmp = (x.dot(e))*kappa
# partial1_u = np.array([ np.sin(tmp)*e[0] ,np.cos(tmp)*e[0], -e[1] ])
# partial2_u = np.array([ np.sin(tmp)*e[1], np.cos(tmp)*e[1], e[0] ])
# normal = np.cross(partial1_u,partial2_u)
# # print('normal=',normal)
# return normal
def u(x,kappa,e):
tmp = (x.dot(e))*((-1)*kappa)
# print('tmp for u',tmp)
if kappa == 0 :
tmp = np.array([x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1], 0*x[0] ])
else :
tmp = np.array([ -(1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0], (1/kappa)*np.cos(tmp)-(1/kappa) ])
return tmp
# def grad_u(x,kappa,e):
#
# tmp = (x.dot(e))*kappa
# # print('tmp',tmp)
#
# grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# # print('produkt', grad_u.dot(e) )
# mapped_e = grad_u.dot(e)
# # print('mapped_e:', mapped_e)
# # print('siize of mapped_e', mapped_e.shape)
# # mapped_e = mapped_e.transpose()
# # print('mapped_e:', mapped_e)
# # print('siize of mapped_e', mapped_e.shape)
# return mapped_e
#
def grad_u(x,kappa,e):
tmp = (x.dot(e))*(-1)*kappa
# print('tmp',tmp)
grad_u = np.array([ [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]], [np.sin(tmp)*e[0], np.sin(tmp)*e[1]] ])
# print('produkt', grad_u.dot(e) )
mapped_e = grad_u.dot(e)
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
# mapped_e = mapped_e.transpose()
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
return mapped_e
def compute_normal(x,kappa,e):
tmp = (x.dot(e))*(-1)*kappa
partial1_u = np.array([ np.cos(tmp)*e[0], -e[1],np.sin(tmp)*e[0] ])
partial2_u = np.array([ np.cos(tmp)*e[1], e[0], np.sin(tmp)*e[1] ])
normal = np.cross(partial1_u,partial2_u)
# print('normal=',normal)
return normal
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
print('T:', T)
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
e_container = []
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
e_container.append(e)
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
G_container = np.array(G_container)
abar_container = np.array(abar_container)
e_container = np.array(e_container)
print('G_container', G_container)
print('G_container.shape', G_container.shape)
# idx_1 = np.where(alphas == np.pi/4)
idx_1 = np.where(np.round(alphas,2) == round(np.pi/3,2))
idx_2 = np.where(np.round(alphas,2) == 0.0)
idx_3 = np.where(np.round(alphas,2) == round(np.pi/4,2))
# idx_3 = np.where(alphas == 0)
print('Index idx_1:', idx_1)
print('Index idx_2:', idx_2)
print('Index idx_3:', idx_3)
print('Index idx_1[0][0]:', idx_1[0][0])
print('Index idx_2[0][0]:', idx_2[0][0])
print('Index idx_3[0][0]:', idx_3[0][0])
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('kappas:',kappas)
# print('alphas:',alphas)
print('min alpha:', min(alphas))
print('min kappa:', min(kappas))
print('G_container[idx_1[0][0]]', G_container[idx_1[0][0]])
print('G_container[idx_2[0][0]]', G_container[idx_2[0][0]])
print('G_container[idx_3[0][0]]', G_container[idx_3[0][0]])
print('e_container[idx_1[0][0]]', e_container[idx_1[0][0]])
print('e_container[idx_2[0][0]]', e_container[idx_2[0][0]])
print('e_container[idx_3[0][0]]', e_container[idx_3[0][0]])
###################################################
reflect = False
# reflect = True
idx = 3
if idx == 1 :
e = e_container[idx_1[0][0]]
kappa = kappas[idx_1[0][0]]
angle = alphas[idx_1[0][0]]
reflect = True
if idx == 2 :
e = e_container[idx_2[0][0]]
kappa = kappas[idx_2[0][0]]
angle = alphas[idx_2[0][0]]
if idx == 3 :
e = e_container[idx_3[0][0]]
kappa = kappas[idx_3[0][0]]
angle = alphas[idx_3[0][0]]
### SCALE ?
# kappa = kappa*2
print('kappa:',kappa)
print('angle:',angle)
###################################################
#### TEST apply reflection
#
# G_tmp = G_container[idx_1[0][0]]
#
# print('G_tmp', G_tmp)
#
# # Basis:
# G_1 = np.array([[1.0,0.0], [0.0,0.0]])
# G_2 = np.array([[0.0,0.0], [0.0,1.0]])
# G_3 = (1/np.sqrt(2))*np.array([[0.0,1.0], [1.0,0.0]])
# print('G_1', G_1)
# print('G_2', G_2)
# print('G_3', G_3)
#
# G = G_tmp[0] * G_1 + G_tmp[1]*G_2 + G_tmp[2]*G_3
# print('G:', G )
#
# T = np.array([[1.0 , -1.0] , [-1.0,1.0]])
#
# TG = np.multiply(T,G)
# print('TG', TG)
#
#
#
# v = np.array([np.sqrt(TG[0][0]),np.sqrt(TG[1][1]) ])
# print('v', v)
# print('norm(v):', np.linalg.norm(v))
# norm_v = np.linalg.norm(v)
#
# kappa = norm_v**2
#
# e = (1/norm_v)*v
# print('e:', e)
# print('kappa:', kappa)
if reflect == True:
reflected_e = np.array([e[0], -1*e[1]])
e = reflected_e # Correct?! Reflect e on x-Axis ??!
print('reflected_e:', reflected_e)
############################################################################################################################################
####################################################################### KAPPA NEGATIVE ####################################################
############################################################################################################################################
# kappa = -2
num_Points = 200
# num_Points = 100
# e = np.array([1,0])
# e = np.array([0,1])
# e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e = np.array([1/2,np.sqrt(3)/2])
# e = np.array([np.sqrt(3)/2,1/2])
# e = np.array([-1,0])
# e = np.array([0,-1])
###--- Creating dataset
x = np.linspace(-2,2,num_Points)
x = np.linspace(-2.5,2.5,num_Points)
x = np.linspace(-3,3,num_Points)
# x = np.linspace(-4,4,num_Points)
# x = np.linspace(-1.5,1.5,num_Points)
# x = np.linspace(-1,1,num_Points)
y = np.linspace(-1/2,1/2,num_Points)
y = np.linspace(-1/4,1/4,num_Points)
print('type of x', type(x))
print('max of x:', max(x))
print('max of y:', max(y))
# print('x:', x)
x1, x2 = np.meshgrid(x,y)
zero = 0*x1
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# print('np.size(u1)',np.size(u1))
# print('u1.shape',u1.shape)
# colorfunction=(u1**2+u2**2)
# print('colofunction',colorfunction)
# print('u1.size:',np.size(u1))
# tmp = np.ones(np.size(u1))*kappa
# print('np.size(tmp)',np.size(tmp))
B = np.full_like(u1, 1)
# colorfunction=(u3) # TODO Color by angle
# colorfunction=(np.ones(np.size(u1))*kappa)
colorfunction=(B*kappa)
# print('colofunction',colorfunction)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# -----------------------------------------------------
# Display the mesh
fig = plt.figure()
width = 6.28 *0.5
width = 6.28 * 0.333
height = width / 1.618
height = width / 2.5
height = width
ax = plt.axes(projection ='3d', adjustable='box')
###---TEST MAP e-vectprs!
# e1 = np.array([1,0])
# e2 = np.array([0,1])
# e3 = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e1 = np.array([0,1])
# e2 = np.array([-1,0])
# e3 = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# e1_mapped = u(e1,kappa,e1)
# e2_mapped = u(e2,kappa,e2)
# e3_mapped = u(e3,kappa,e3)
# print('e1 mapped:',e1_mapped)
# print('e2 mapped:',e2_mapped)
# print('e3 mapped:',e3_mapped)
### -----------------------------------
#--e1 :
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([0,1,0])
#--e2:
Rotation_angle = np.pi/2
Rotation_vector = np.array([1,0,0])
###--e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([1,0,0])
# #2te rotation :
# Rotation_angle = np.pi/4
# Rotation_vector = np.array([0,0,1])
Rotation_angle = -np.pi/2
Rotation_angle = 0
# Rotation_angle = np.pi/2
Rotation_vector = np.array([0,1,0])
Rotation_vector = np.array([1,0,0])
# rot(np.array([0,1,0]),np.pi/2)
# ZERO ROTATION
Rotation = rot(np.array([0,1,0]),0)
# if idx == 1:
# Rotation = rot(np.array([1,0,0]),np.pi)
# Rotation = rot(np.array([1,0,0]),np.pi).dot(rot(np.array([0,0,1]),angle))
Rotation = rot(np.array([1,0,0]),np.pi)
# TEST :
#DETERMINE ANGLE:
angle = math.atan2(e[1], e[0])
print('angle:', angle)
## GENERAL TRANSFORMATION / ROTATION:
# Rotation = rot(np.array([0,0,1]),angle).dot(Rotation)
Rotation = rot(np.array([1,0,0]),np.pi).dot(rot(np.array([0,0,1]),angle))
# Rotation = rot(np.array([0,0,1]),angle).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(Rotation)
### if e1:
# Rotation = rot(np.array([0,0,1]),-np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Add another rotation around z-axis:
# Rotation = rot(np.array([0,0,1]),+np.pi).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/8).dot(Rotation)
#e3 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),np.pi/4)
# Rotation = rot(np.array([1,0,0]),np.pi/4)
#### if e1 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
#### if e2:
# Rotation = rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2))
# # #### if e3 :
# zufall dass np.pi/4 genau dem Winkel angle alpha entspricht?:
# (würde) bei e_2 keinen Unterschied machen um z achse zu rotieren?!
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([1,0,0]),np.pi/2)
# Rotation_vector = e3_mapped #TEST
# Rotation_vector = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_vector = np.array([0,0,1])
# v = np.array([1,0,0])
# X = np.array([u1,u2,u3])
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 2, cstride = 2, facecolors=cm.brg(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.viridis(colorfunction), alpha=.4, zorder=4)
###---- PLOT PARAMETER-PLANE:
# ax.plot_surface(x1,x2,zero,color = 'w', rstride = 1, cstride = 1 )
print('------------------ Kappa : ', kappa)
#midpoint:
midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
print('midpoint',midpoint)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
# mapped_e = Rotation.dot(mapped_e)
# normal = Rotation.dot(normal)
# Plot Mapped_midPoint
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=4) # line width
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [mapped_e[0]], [mapped_e[1]], [mapped_e[2]], color="red")
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [normal[0]], [normal[1]], [normal[2]], color="blue")
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 2,
# ec ='green',
# zorder=3)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 2,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 3)
###-- TEST Rotation :
# v = np.array([1,0,0])
# t = np.array([0,1,0])
#
# ax.arrow3D(0,0,0,
# t[0],t[1],t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
#
# # e_extend
#
# rotM = rot(v,np.pi/2)
#
# print('rotM:', rotM)
#
# rot_t = rotM.dot(t)
#
# print('rot_t:', rot_t)
#
# ax.arrow3D(0,0,0,
# rot_t[0],rot_t[1],rot_t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
### -------------------------------------------
############################################################################################################################################
####################################################################### KAPPA POSITIVE ####################################################
############################################################################################################################################
# kappa = (-1)*kappa
# if kappa == 0 :
# u1 = 0*x1
# u2 = x1*e[0] + x2*e[1]
# u3 = x2*e[0] - x1*e[1]
# else :
# u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
# u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
# u3 = x2*e[0] -x1*e[1]
if kappa == 0 :
# u1 = 0*x1
# u2 = x1*e[0] + x2*e[1]
# u3 = x2*e[0] - x1*e[1]
u1 = x1*e[0] + x2*e[1]
u2 = x2*e[0] - x1*e[1]
u3 = 0*x1
else :
# u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
# u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
# u3 = x2*e[0] -x1*e[1]
u1 = -(1/kappa)*np.sin((-1)*kappa*(x1*e[0]+x2*e[1]))
u2 = x2*e[0] -x1*e[1]
u3 = (1/kappa)*np.cos((-1)*kappa*(x1*e[0]+x2*e[1]))-(1/kappa)
# ax.plot_surface(u1, u2, u3, color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.3) ##This one!
# T = rotate_data(X,Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=False)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 2, cstride = 2, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, facecolors=cm.brg(colorfunction), alpha=.8, zorder=4)
ax.plot_surface(T[0], T[1], T[2], rstride = 5, cstride = 5, color='orange', alpha=.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color='blue', alpha=.8, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=0.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=1, zorde5r=5)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
# print('midpoint',midpoint)
print('------------------ Kappa : ', kappa)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# Plot MIDPOINT:
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#midpoint:
endpoint = np.array([min(x),(max(y)+min(y))/2])
print('endpoint',endpoint)
# Map midpoint:
endpoint_mapped = u(endpoint,kappa,e)
print('mapped endpoint', endpoint_mapped)
endpoint_mapped = Rotation.dot(endpoint_mapped)
mapped_e = grad_u(endpoint,kappa,e)
normal = compute_normal(endpoint,kappa,e)
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
reverse_normal = np.array([ (-1)*normal[0], (-1)*normal[1], (-1)*normal[2]])
ax.plot(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2], # data
marker='o', # each marker will be rendered as a circle
markersize=1, # marker size
markerfacecolor='black', # marker facecolor
markeredgecolor='black', # marker edgecolor
markeredgewidth=0.5, # marker edge width
linewidth=1,
zorder=5) # line width
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
reverse_normal[0],reverse_normal[1],reverse_normal[2],
mutation_scale=10,
lw = 1.5,
arrowstyle="-|>",
linestyle='-',fc='purple', alpha=0.75,
ec ='purple',
zorder = 5)
# second Endpoint
endpoint = np.array([max(x),(max(y)+min(y))/2])
print('endpoint',endpoint)
# Map midpoint:
endpoint_mapped = u(endpoint,kappa,e)
print('mapped endpoint', endpoint_mapped)
endpoint_mapped = Rotation.dot(endpoint_mapped)
mapped_e = grad_u(endpoint,kappa,e)
normal = compute_normal(endpoint,kappa,e)
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
reverse_normal = np.array([ (-1)*normal[0], (-1)*normal[1], (-1)*normal[2]])
ax.plot(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2], # data
marker='o', # each marker will be rendered as a circle
markersize=1, # marker size
markerfacecolor='black', # marker facecolor
markeredgecolor='black', # marker edgecolor
markeredgewidth=0.5, # marker edge width
linewidth=1,
zorder=5) # line width
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
reverse_normal[0],reverse_normal[1],reverse_normal[2],
mutation_scale=10,
lw = 1.5,
arrowstyle="-|>",
linestyle='-',fc='purple', alpha=0.75,
ec ='purple',
zorder = 5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
############################################################################################################################################
####################################################################### KAPPA ZERO #########################################################
############################################################################################################################################
kappa = 0
# if kappa == 0 :
# u1 = 0*x1
# u2 = x1*e[0] + x2*e[1]
# u3 = x2*e[0] - x1*e[1]
# else :
# u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
# u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
# u3 = x2*e[0] -x1*e[1]
if kappa == 0 :
# u1 = 0*x1
# u2 = x1*e[0] + x2*e[1]
# u3 = x2*e[0] - x1*e[1]
u1 = x1*e[0] + x2*e[1]
u2 = x2*e[0] - x1*e[1]
u3 = 0*x1
else :
# u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
# u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
# u3 = x2*e[0] -x1*e[1]
u1 = -(1/kappa)*np.sin((-1)*kappa*(x1*e[0]+x2*e[1]))
u2 = x2*e[0] -x1*e[1]
u3 = (1/kappa)*np.cos((-1)*kappa*(x1*e[0]+x2*e[1]))-(1/kappa)
# ax.plot_surface(u1, u2, u3, rstride = 1, cstride = 1, color = 'white', alpha=0.85)
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride =1 , cstride = 1, color = 'white', alpha=0.55, zorder=3)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.5, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color = 'white', alpha=0.55, zorder=2)
ax.plot_surface(T[0], T[1], T[2], rstride = 20, cstride = 20, color = 'gray', alpha=0.35, zorder=1, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'white', alpha=0.55, zorder=2)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
mapped_e = grad_u(midpoint,kappa,e)
normal_zeroCurv = compute_normal(midpoint,kappa,e)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
##----- PLOT MAPPED MIDPOINT :::
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# # linestyle='--', # line style will be dash line
# linewidth=1,
# zorder=5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='red',
# ec ='red')
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal_zeroCurv[0],normal_zeroCurv[1],normal_zeroCurv[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
##---------- PLOT MAPPED ORIGIN :::
# origin = np.array([0,0])
# origin_mapped = u(origin,kappa,e)
# print('origin_mapped', origin_mapped)
#
# ax.plot(origin_mapped[0],origin_mapped[1],origin_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='green', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#
# # rotate mapped origin
# # v = np.array([1,0,0])
# # alpha = Rotation_angle
#
# rotM = rot(Rotation_vector,Rotation_angle)
# # origin_mRot = rotate_data(origin_mapped,v,alpha)
# origin_mRot = rotM.dot(origin_mapped)
# print('origin_mapped Rotated', origin_mRot)
#
# # --- Compute Distance to Origin 3D
# origin_3D=np.array([0,0,0])
# distance = origin_mapped-origin_3D
# print('distance', distance)
## --------------------------------------------------------
# COMPUTE ANGLE WITH Z AXIS
z = np.array([0,0,1])
print('test', normal_zeroCurv*z)
angle_z = np.arccos(normal_zeroCurv.dot(z) /( (np.linalg.norm(z)*np.linalg.norm(normal_zeroCurv) ) ))
print('angle between normal and z-axis', angle_z)
## unfinished...
###------------------------------------- PLOT :
plt.axis('off')
# plt.axis('tight')
# ADD colorbar
# scamap = plt.cm.ScalarMappable(cmap='inferno')
# fig.colorbar(scamap)
# ax.colorbar()
# ax.axis('auto')
# ax.set_title(r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e))
# ax.set_title(r'Cylindrical minimizer' + '_$e$=' + str(e))
ax.set_xlabel(r"x-axis")
ax.set_ylabel(r"y-axis")
ax.set_zlabel(r"z-axis")
# TEST :
# ax.annotate3D('point 1', (0, 0, 0), xytext=(3, 3), textcoords='offset points')
# ax.annotate3D('point 2', (0, 1, 0),
# xytext=(-30, -30),
# textcoords='offset points',
# arrowprops=dict(ec='black', fc='white', shrink=2.5))
# ax.annotate3D('point 3', (0, 0, 1),
# xytext=(30, -30),
# textcoords='offset points',
# bbox=dict(boxstyle="round", fc="lightyellow"),
# arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))
#######################################################################################################################
u1 = T[0]
u2 = T[1]
u3 = T[2]
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /3
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /12
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /8
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /10
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /14
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /6
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /2
mid_u1 = (u1.max()+u1.min()) * 0.5
mid_u2 = (u2.max()+u2.min()) * 0.5
mid_u3 = (u3.max()+u3.min()) * 0.5
ax.set_xlim(mid_u1 - max_range, mid_u1 + max_range)
ax.set_ylim(mid_u2 - max_range, mid_u2 + max_range)
ax.set_zlim(mid_u3 - max_range, mid_u3 + max_range)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
# ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-1.5, (mid_u2 + max_range)+1.5)
# # ax.autoscale(tight=True)
# ax.set_xlim((mid_u1 - max_range)-1, (mid_u1 + max_range)+1)
# ax.set_xlim((mid_u1 - max_range)-0.5, (mid_u1 + max_range)+0.5)
ax.set_xlim((mid_u1 - max_range)-2, (mid_u1 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+3)
# ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
##----- CHANGE CAMERA POSITION:
# ax.view_init(elev=10., azim=0)
# ax.view_init(elev=38, azim=90)
# ax.view_init(elev=38, azim=120)
# ax.view_init(elev=38)
# if e1 ::
# ax.view_init(elev=44)
# ax.view_init(elev=38, azim=-90)
# ax.view_init(elev=38, azim=0)
# ax.view_init(elev=25, azim=-30)
# ax.view_init(elev=18, azim=-30)
ax.view_init(elev=25, azim=-125)
# ax.view_init(elev=25, azim=150)
# ax.view_init(elev=25, azim=135)
# ax.view_init(elev=25, azim=125) #idx2
# ax.view_init(elev=25, azim=145)
# if e3 ::
# ax.view_init(elev=25)
# ax.set_xlim3d(-2, 2)
# ax.set_ylim3d(-1.0,3.0)
# ax.set_zlim3d(-1.5,2.5)
# ax.set_ylim3d(-10,10)
# ax.set_xlim(mid_u1 - max_range-0.2, mid_u1 + max_range+0.2)
# ax.set_zlim(mid_u3 - max_range-0.2, mid_u3 + max_range+0.2)
# ax.set_ylim(mid_u2 - max_range-0.2, mid_u2 + max_range+0.2)
# width = 6.28 *0.5
# height = width / 1.618
# # height = width / 2.5
# fig.set_size_inches(width, height)
# fig.savefig('Test-Cylindrical.pdf')
# Figurename = r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e)
# Figurename = r'Cylindrical minimizer' + '_$e$=' + str(e)
Figurename = r'1-ParFamMinimizer_idx' + str(idx)
# plt.savefig("test.png", bbox_inches='tight')
# plt.figure().set_size_inches(width, height)
# plt.set_size_inches(width, height)
# fig.set_size_inches(width, height) !!!!!
fig.savefig(Figurename+".pdf")
plt.savefig(Figurename+".png", bbox_inches='tight', dpi=300)
# plt.savefig(Figurename+".png")
plt.show()
# #---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# Extra packages :
# from HelperFunctions import *
# from ClassifyMin import *
# from subprocess import Popen, PIPE
#import sys
###################### Documentation #########################
#..... add description here
###########################################################
def rot(v,alpha):
#rotate about axis v with degree deg in radians:
tmp = np.array([ [v[0]**2*(1-np.cos(alpha))+np.cos(alpha), v[0]*v[1]*(1-np.cos(alpha))-v[2]*np.sin(alpha), v[0]*v[2]*(1-np.cos(alpha))+ v[1]*np.sin(alpha) ],
[v[0]*v[1]*(1-np.cos(alpha))+v[2]*np.sin(alpha), v[1]**2*(1-np.cos(alpha))+np.cos(alpha), v[1]*v[2]*(1-np.cos(alpha))+v[0]*np.sin(alpha) ],
[v[2]*v[0]*(1-np.cos(alpha))-v[1]*np.sin(alpha), v[2]*v[1]*(1-np.cos(alpha))+v[0]*np.sin(alpha) , v[2]**2*(1-np.cos(alpha))+np.cos(alpha) ] ])
return tmp
def rotate_data(X, R):
#rotate about axis v with degree deg in radians:
# X : DataSet
# R : RotationMatrix
print('ROTATE DATA FUNCTION ---------------')
rot_matrix = R
# print('rot_matrix:', rot_matrix)
# print('rot_matrix.shape:', rot_matrix.shape)
# print('X', X)
# print('shape of X[0]', X.shape[0])
B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
# print('shape of B', B.shape)
# print('B',B)
# print('B[0,:]', B[0,:])
# print('B[0,:].shape', B[0,:].shape)
Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
print('shape of Out', Out.shape)
return Out
# def rotate_data(X, v,alpha): #(Old Version)
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
# rot_matrix = rot(v,alpha)
# # print('rot_matrix:', rot_matrix)
# # print('rot_matrix.shape:', rot_matrix.shape)
#
# # print('X', X)
# # print('shape of X[0]', X.shape[0])
# B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
#
# # print('shape of B', B.shape)
# # print('B',B)
# # print('B[0,:]', B[0,:])
# # print('B[0,:].shape', B[0,:].shape)
# Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
# print('shape of Out', Out.shape)
#
# return Out
# def translate_data(X, v): ...
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
#
# print('X', X)
# print('shape of X[0]', X.shape[0])
#
# Out = X + v
# return Out
def u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp for u',tmp)
if kappa == 0 :
tmp = np.array([0*x[0], x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1] ])
else :
tmp = np.array([-(1/kappa)*np.cos(tmp)+(1/kappa), (1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0] ])
return tmp
def grad_u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp',tmp)
grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# print('produkt', grad_u.dot(e) )
mapped_e = grad_u.dot(e)
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
# mapped_e = mapped_e.transpose()
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
return mapped_e
def compute_normal(x,kappa,e):
tmp = (x.dot(e))*kappa
partial1_u = np.array([ np.sin(tmp)*e[0] ,np.cos(tmp)*e[0], -e[1] ])
partial2_u = np.array([ np.sin(tmp)*e[1], np.cos(tmp)*e[1], e[0] ])
normal = np.cross(partial1_u,partial2_u)
# print('normal=',normal)
return normal
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
print('T:', T)
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
e_container = []
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
e_container.append(e)
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
G_container = np.array(G_container)
abar_container = np.array(abar_container)
e_container = np.array(e_container)
print('G_container', G_container)
print('G_container.shape', G_container.shape)
# idx_1 = np.where(alphas == np.pi/4)
idx_1 = np.where(np.round(alphas,2) == round(np.pi/3,2))
idx_2 = np.where(np.round(alphas,2) == 0.0)
idx_3 = np.where(np.round(alphas,2) == round(np.pi/4,2))
# idx_3 = np.where(alphas == 0)
print('Index idx_1:', idx_1)
print('Index idx_2:', idx_2)
print('Index idx_3:', idx_3)
print('Index idx_1[0][0]:', idx_1[0][0])
print('Index idx_2[0][0]:', idx_2[0][0])
print('Index idx_3[0][0]:', idx_3[0][0])
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('kappas:',kappas)
# print('alphas:',alphas)
print('min alpha:', min(alphas))
print('min kappa:', min(kappas))
print('G_container[idx_1[0][0]]', G_container[idx_1[0][0]])
print('G_container[idx_2[0][0]]', G_container[idx_2[0][0]])
print('G_container[idx_3[0][0]]', G_container[idx_3[0][0]])
print('e_container[idx_1[0][0]]', e_container[idx_1[0][0]])
print('e_container[idx_2[0][0]]', e_container[idx_2[0][0]])
print('e_container[idx_3[0][0]]', e_container[idx_3[0][0]])
###################################################
reflect = False
# reflect = True
idx = 1
if idx == 1 :
e = e_container[idx_1[0][0]]
kappa = kappas[idx_1[0][0]]
angle = alphas[idx_1[0][0]]
reflect = True
if idx == 2 :
e = e_container[idx_2[0][0]]
kappa = kappas[idx_2[0][0]]
angle = alphas[idx_2[0][0]]
if idx == 3 :
e = e_container[idx_3[0][0]]
kappa = kappas[idx_3[0][0]]
angle = alphas[idx_3[0][0]]
### SCALE ?
# kappa = kappa*2
print('kappa:',kappa)
print('angle:',angle)
###################################################
#### TEST apply reflection
#
# G_tmp = G_container[idx_1[0][0]]
#
# print('G_tmp', G_tmp)
#
# # Basis:
# G_1 = np.array([[1.0,0.0], [0.0,0.0]])
# G_2 = np.array([[0.0,0.0], [0.0,1.0]])
# G_3 = (1/np.sqrt(2))*np.array([[0.0,1.0], [1.0,0.0]])
# print('G_1', G_1)
# print('G_2', G_2)
# print('G_3', G_3)
#
# G = G_tmp[0] * G_1 + G_tmp[1]*G_2 + G_tmp[2]*G_3
# print('G:', G )
#
# T = np.array([[1.0 , -1.0] , [-1.0,1.0]])
#
# TG = np.multiply(T,G)
# print('TG', TG)
#
#
#
# v = np.array([np.sqrt(TG[0][0]),np.sqrt(TG[1][1]) ])
# print('v', v)
# print('norm(v):', np.linalg.norm(v))
# norm_v = np.linalg.norm(v)
#
# kappa = norm_v**2
#
# e = (1/norm_v)*v
# print('e:', e)
# print('kappa:', kappa)
if reflect == True:
reflected_e = np.array([e[0], -1*e[1]])
e = reflected_e # Correct?! Reflect e on x-Axis ??!
print('reflected_e:', reflected_e)
############################################################################################################################################
####################################################################### KAPPA NEGATIVE ####################################################
############################################################################################################################################
# kappa = -2
num_Points = 200
num_Points = 100
# e = np.array([1,0])
# e = np.array([0,1])
# e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e = np.array([1/2,np.sqrt(3)/2])
# e = np.array([np.sqrt(3)/2,1/2])
# e = np.array([-1,0])
# e = np.array([0,-1])
###--- Creating dataset
x = np.linspace(-2,2,num_Points)
x = np.linspace(-3,3,num_Points)
x = np.linspace(-4,4,num_Points)
# x = np.linspace(-1.5,1.5,num_Points)
# x = np.linspace(-1,1,num_Points)
y = np.linspace(-1/2,1/2,num_Points)
y = np.linspace(-1/4,1/4,num_Points)
print('type of x', type(x))
print('max of x:', max(x))
print('max of y:', max(y))
# print('x:', x)
x1, x2 = np.meshgrid(x,y)
zero = 0*x1
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# print('np.size(u1)',np.size(u1))
# print('u1.shape',u1.shape)
# colorfunction=(u1**2+u2**2)
# print('colofunction',colorfunction)
# print('u1.size:',np.size(u1))
# tmp = np.ones(np.size(u1))*kappa
# print('np.size(tmp)',np.size(tmp))
B = np.full_like(u1, 1)
# colorfunction=(u3) # TODO Color by angle
# colorfunction=(np.ones(np.size(u1))*kappa)
colorfunction=(B*kappa)
# print('colofunction',colorfunction)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# -----------------------------------------------------
# Display the mesh
fig = plt.figure()
width = 6.28 *0.5
width = 6.28 * 0.333
height = width / 1.618
height = width / 2.5
height = width
ax = plt.axes(projection ='3d', adjustable='box')
###---TEST MAP e-vectprs!
# e1 = np.array([1,0])
# e2 = np.array([0,1])
# e3 = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e1 = np.array([0,1])
# e2 = np.array([-1,0])
# e3 = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# e1_mapped = u(e1,kappa,e1)
# e2_mapped = u(e2,kappa,e2)
# e3_mapped = u(e3,kappa,e3)
# print('e1 mapped:',e1_mapped)
# print('e2 mapped:',e2_mapped)
# print('e3 mapped:',e3_mapped)
### -----------------------------------
#--e1 :
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([0,1,0])
#--e2:
Rotation_angle = np.pi/2
Rotation_vector = np.array([1,0,0])
###--e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([1,0,0])
# #2te rotation :
# Rotation_angle = np.pi/4
# Rotation_vector = np.array([0,0,1])
Rotation_angle = -np.pi/2
Rotation_angle = 0
# Rotation_angle = np.pi/2
Rotation_vector = np.array([0,1,0])
Rotation_vector = np.array([1,0,0])
# rot(np.array([0,1,0]),np.pi/2)
# ZERO ROTATION
Rotation = rot(np.array([0,1,0]),0)
# TEST :
#DETERMINE ANGLE:
angle = math.atan2(e[1], e[0])
print('angle:', angle)
## GENERAL TRANSFORMATION / ROTATION:
Rotation = rot(np.array([0,0,1]),angle).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
### if e1:
# Rotation = rot(np.array([0,0,1]),-np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Add another rotation around z-axis:
# Rotation = rot(np.array([0,0,1]),+np.pi).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/8).dot(Rotation)
#e3 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),np.pi/4)
# Rotation = rot(np.array([1,0,0]),np.pi/4)
#### if e1 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
#### if e2:
# Rotation = rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2))
# # #### if e3 :
# zufall dass np.pi/4 genau dem Winkel angle alpha entspricht?:
# (würde) bei e_2 keinen Unterschied machen um z achse zu rotieren?!
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([1,0,0]),np.pi/2)
# Rotation_vector = e3_mapped #TEST
# Rotation_vector = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_vector = np.array([0,0,1])
# v = np.array([1,0,0])
# X = np.array([u1,u2,u3])
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 2, cstride = 2, facecolors=cm.brg(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.viridis(colorfunction), alpha=.4, zorder=4)
###---- PLOT PARAMETER-PLANE:
# ax.plot_surface(x1,x2,zero,color = 'w', rstride = 1, cstride = 1 )
print('------------------ Kappa : ', kappa)
#midpoint:
midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
print('midpoint',midpoint)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
# mapped_e = Rotation.dot(mapped_e)
# normal = Rotation.dot(normal)
# Plot Mapped_midPoint
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=4) # line width
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [mapped_e[0]], [mapped_e[1]], [mapped_e[2]], color="red")
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [normal[0]], [normal[1]], [normal[2]], color="blue")
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 2,
# ec ='green',
# zorder=3)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 2,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 3)
###-- TEST Rotation :
# v = np.array([1,0,0])
# t = np.array([0,1,0])
#
# ax.arrow3D(0,0,0,
# t[0],t[1],t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
#
# # e_extend
#
# rotM = rot(v,np.pi/2)
#
# print('rotM:', rotM)
#
# rot_t = rotM.dot(t)
#
# print('rot_t:', rot_t)
#
# ax.arrow3D(0,0,0,
# rot_t[0],rot_t[1],rot_t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
### -------------------------------------------
############################################################################################################################################
####################################################################### KAPPA POSITIVE ####################################################
############################################################################################################################################
# kappa = (-1)*kappa
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.3) ##This one!
# T = rotate_data(X,Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=False)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 2, cstride = 2, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, facecolors=cm.brg(colorfunction), alpha=.8, zorder=4)
ax.plot_surface(T[0], T[1], T[2], rstride = 5, cstride = 5, color='orange', alpha=.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color='blue', alpha=.8, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=0.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=1, zorde5r=5)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
# print('midpoint',midpoint)
print('------------------ Kappa : ', kappa)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# Plot MIDPOINT:
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#midpoint:
endpoint = np.array([min(x),(max(y)+min(y))/2])
print('endpoint',endpoint)
# Map midpoint:
endpoint_mapped = u(endpoint,kappa,e)
print('mapped endpoint', endpoint_mapped)
endpoint_mapped = Rotation.dot(endpoint_mapped)
mapped_e = grad_u(endpoint,kappa,e)
normal = compute_normal(endpoint,kappa,e)
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
############################################################################################################################################
####################################################################### KAPPA ZERO #########################################################
############################################################################################################################################
kappa = 0
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, rstride = 1, cstride = 1, color = 'white', alpha=0.85)
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride =1 , cstride = 1, color = 'white', alpha=0.55, zorder=3)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.5, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color = 'white', alpha=0.55, zorder=2)
ax.plot_surface(T[0], T[1], T[2], rstride = 20, cstride = 20, color = 'gray', alpha=0.35, zorder=1, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'white', alpha=0.55, zorder=2)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
mapped_e = grad_u(midpoint,kappa,e)
normal_zeroCurv = compute_normal(midpoint,kappa,e)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
##----- PLOT MAPPED MIDPOINT :::
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# # linestyle='--', # line style will be dash line
# linewidth=1,
# zorder=5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='red',
# ec ='red')
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal_zeroCurv[0],normal_zeroCurv[1],normal_zeroCurv[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
##---------- PLOT MAPPED ORIGIN :::
# origin = np.array([0,0])
# origin_mapped = u(origin,kappa,e)
# print('origin_mapped', origin_mapped)
#
# ax.plot(origin_mapped[0],origin_mapped[1],origin_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='green', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#
# # rotate mapped origin
# # v = np.array([1,0,0])
# # alpha = Rotation_angle
#
# rotM = rot(Rotation_vector,Rotation_angle)
# # origin_mRot = rotate_data(origin_mapped,v,alpha)
# origin_mRot = rotM.dot(origin_mapped)
# print('origin_mapped Rotated', origin_mRot)
#
# # --- Compute Distance to Origin 3D
# origin_3D=np.array([0,0,0])
# distance = origin_mapped-origin_3D
# print('distance', distance)
## --------------------------------------------------------
# COMPUTE ANGLE WITH Z AXIS
z = np.array([0,0,1])
print('test', normal_zeroCurv*z)
angle_z = np.arccos(normal_zeroCurv.dot(z) /( (np.linalg.norm(z)*np.linalg.norm(normal_zeroCurv) ) ))
print('angle between normal and z-axis', angle_z)
## unfinished...
###------------------------------------- PLOT :
plt.axis('off')
# plt.axis('tight')
# ADD colorbar
# scamap = plt.cm.ScalarMappable(cmap='inferno')
# fig.colorbar(scamap)
# ax.colorbar()
# ax.axis('auto')
# ax.set_title(r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e))
# ax.set_title(r'Cylindrical minimizer' + '_$e$=' + str(e))
ax.set_xlabel(r"x-axis")
ax.set_ylabel(r"y-axis")
ax.set_zlabel(r"z-axis")
# TEST :
# ax.annotate3D('point 1', (0, 0, 0), xytext=(3, 3), textcoords='offset points')
# ax.annotate3D('point 2', (0, 1, 0),
# xytext=(-30, -30),
# textcoords='offset points',
# arrowprops=dict(ec='black', fc='white', shrink=2.5))
# ax.annotate3D('point 3', (0, 0, 1),
# xytext=(30, -30),
# textcoords='offset points',
# bbox=dict(boxstyle="round", fc="lightyellow"),
# arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))
#######################################################################################################################
u1 = T[0]
u2 = T[1]
u3 = T[2]
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /3
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /12
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /8
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /10
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /14
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /6
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /2
mid_u1 = (u1.max()+u1.min()) * 0.5
mid_u2 = (u2.max()+u2.min()) * 0.5
mid_u3 = (u3.max()+u3.min()) * 0.5
ax.set_xlim(mid_u1 - max_range, mid_u1 + max_range)
ax.set_ylim(mid_u2 - max_range, mid_u2 + max_range)
ax.set_zlim(mid_u3 - max_range, mid_u3 + max_range)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-1.5, (mid_u2 + max_range)+1.5)
# ax.autoscale(tight=True)
ax.set_xlim((mid_u1 - max_range)-1, (mid_u1 + max_range)+1)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+3)
# ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
##----- CHANGE CAMERA POSITION:
# ax.view_init(elev=10., azim=0)
# ax.view_init(elev=38, azim=90)
# ax.view_init(elev=38, azim=120)
# ax.view_init(elev=38)
# if e1 ::
# ax.view_init(elev=44)
# ax.view_init(elev=38, azim=-90)
# ax.view_init(elev=38, azim=0)
# ax.view_init(elev=25, azim=-30)
ax.view_init(elev=18, azim=-30)
# if e3 ::
# ax.view_init(elev=25)
# ax.set_xlim3d(-2, 2)
# ax.set_ylim3d(-1.0,3.0)
# ax.set_zlim3d(-1.5,2.5)
# ax.set_ylim3d(-10,10)
# ax.set_xlim(mid_u1 - max_range-0.2, mid_u1 + max_range+0.2)
# ax.set_zlim(mid_u3 - max_range-0.2, mid_u3 + max_range+0.2)
# ax.set_ylim(mid_u2 - max_range-0.2, mid_u2 + max_range+0.2)
# width = 6.28 *0.5
# height = width / 1.618
# # height = width / 2.5
# fig.set_size_inches(width, height)
# fig.savefig('Test-Cylindrical.pdf')
# Figurename = r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e)
# Figurename = r'Cylindrical minimizer' + '_$e$=' + str(e)
Figurename = r'1-ParFamMinimizer_idx' + str(idx)
# plt.savefig("test.png", bbox_inches='tight')
# plt.figure().set_size_inches(width, height)
# plt.set_size_inches(width, height)
fig.set_size_inches(width, height)
fig.savefig(Figurename+".pdf")
plt.savefig(Figurename+".png", bbox_inches='tight')
# plt.savefig(Figurename+".png")
plt.show()
# #---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import matplotlib.ticker as tickers
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# Extra packages :
# from HelperFunctions import *
# from ClassifyMin import *
# from subprocess import Popen, PIPE
#import sys
###################### Documentation #########################
#..... add description here
###########################################################
def rot(v,alpha):
#rotate about axis v with degree deg in radians:
tmp = np.array([ [v[0]**2*(1-np.cos(alpha))+np.cos(alpha), v[0]*v[1]*(1-np.cos(alpha))-v[2]*np.sin(alpha), v[0]*v[2]*(1-np.cos(alpha))+ v[1]*np.sin(alpha) ],
[v[0]*v[1]*(1-np.cos(alpha))+v[2]*np.sin(alpha), v[1]**2*(1-np.cos(alpha))+np.cos(alpha), v[1]*v[2]*(1-np.cos(alpha))+v[0]*np.sin(alpha) ],
[v[2]*v[0]*(1-np.cos(alpha))-v[1]*np.sin(alpha), v[2]*v[1]*(1-np.cos(alpha))+v[0]*np.sin(alpha) , v[2]**2*(1-np.cos(alpha))+np.cos(alpha) ] ])
return tmp
def rotate_data(X, R):
#rotate about axis v with degree deg in radians:
# X : DataSet
# R : RotationMatrix
print('ROTATE DATA FUNCTION ---------------')
rot_matrix = R
# print('rot_matrix:', rot_matrix)
# print('rot_matrix.shape:', rot_matrix.shape)
# print('X', X)
# print('shape of X[0]', X.shape[0])
B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
# print('shape of B', B.shape)
# print('B',B)
# print('B[0,:]', B[0,:])
# print('B[0,:].shape', B[0,:].shape)
Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
print('shape of Out', Out.shape)
return Out
# def rotate_data(X, v,alpha): #(Old Version)
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
# rot_matrix = rot(v,alpha)
# # print('rot_matrix:', rot_matrix)
# # print('rot_matrix.shape:', rot_matrix.shape)
#
# # print('X', X)
# # print('shape of X[0]', X.shape[0])
# B = np.dot(rot_matrix, X.reshape(rot_matrix.shape[1],-1))
#
# # print('shape of B', B.shape)
# # print('B',B)
# # print('B[0,:]', B[0,:])
# # print('B[0,:].shape', B[0,:].shape)
# Out = np.array([B[0,:].reshape(X.shape[1],X.shape[2]), B[1,:].reshape(X.shape[1],X.shape[2]), B[2,:].reshape(X.shape[1],X.shape[2])])
# print('shape of Out', Out.shape)
#
# return Out
# def translate_data(X, v): ...
# #rotate about axis v with degree deg in radians:
# # X : DataSet
# print('ROTATE DATA FUNCTION ---------------')
# # v = np.array([1,0,0])
# # rotM = rot(v,np.pi/2)
# # print('rotM:', rotM)
#
# print('X', X)
# print('shape of X[0]', X.shape[0])
#
# Out = X + v
# return Out
def u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp for u',tmp)
if kappa == 0 :
tmp = np.array([0*x[0], x[0]*e[0] + x[1]*e[1], x[1]*e[0] - x[0]*e[1] ])
else :
tmp = np.array([-(1/kappa)*np.cos(tmp)+(1/kappa), (1/kappa)*np.sin(tmp), -x[0]*e[1]+x[1]*e[0] ])
return tmp
def grad_u(x,kappa,e):
tmp = (x.dot(e))*kappa
# print('tmp',tmp)
grad_u = np.array([ [np.sin(tmp)*e[0], np.sin(tmp)*e[1]], [np.cos(tmp)*e[0], np.cos(tmp)*e[1]], [-e[1], e[0]] ])
# print('produkt', grad_u.dot(e) )
mapped_e = grad_u.dot(e)
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
# mapped_e = mapped_e.transpose()
# print('mapped_e:', mapped_e)
# print('siize of mapped_e', mapped_e.shape)
return mapped_e
def compute_normal(x,kappa,e):
tmp = (x.dot(e))*kappa
partial1_u = np.array([ np.sin(tmp)*e[0] ,np.cos(tmp)*e[0], -e[1] ])
partial2_u = np.array([ np.sin(tmp)*e[1], np.cos(tmp)*e[1], e[0] ])
normal = np.cross(partial1_u,partial2_u)
# print('normal=',normal)
return normal
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
print('T:', T)
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
e_container = []
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
e_container.append(e)
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
G_container = np.array(G_container)
abar_container = np.array(abar_container)
e_container = np.array(e_container)
print('G_container', G_container)
print('G_container.shape', G_container.shape)
# idx_1 = np.where(alphas == np.pi/4)
idx_1 = np.where(np.round(alphas,2) == round(np.pi/3,2))
idx_2 = np.where(np.round(alphas,2) == 0.0)
idx_3 = np.where(np.round(alphas,2) == round(np.pi/4,2))
# idx_3 = np.where(alphas == 0)
print('Index idx_1:', idx_1)
print('Index idx_2:', idx_2)
print('Index idx_3:', idx_3)
print('Index idx_1[0][0]:', idx_1[0][0])
print('Index idx_2[0][0]:', idx_2[0][0])
print('Index idx_3[0][0]:', idx_3[0][0])
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('kappas:',kappas)
# print('alphas:',alphas)
print('min alpha:', min(alphas))
print('min kappa:', min(kappas))
print('G_container[idx_1[0][0]]', G_container[idx_1[0][0]])
print('G_container[idx_2[0][0]]', G_container[idx_2[0][0]])
print('G_container[idx_3[0][0]]', G_container[idx_3[0][0]])
print('e_container[idx_1[0][0]]', e_container[idx_1[0][0]])
print('e_container[idx_2[0][0]]', e_container[idx_2[0][0]])
print('e_container[idx_3[0][0]]', e_container[idx_3[0][0]])
###################################################
reflect = False
# reflect = True
idx = 1
if idx == 1 :
e = e_container[idx_1[0][0]]
kappa = kappas[idx_1[0][0]]
angle = alphas[idx_1[0][0]]
reflect = True
if idx == 2 :
e = e_container[idx_2[0][0]]
kappa = kappas[idx_2[0][0]]
angle = alphas[idx_2[0][0]]
if idx == 3 :
e = e_container[idx_3[0][0]]
kappa = kappas[idx_3[0][0]]
angle = alphas[idx_3[0][0]]
### SCALE ?
# kappa = kappa*2
print('kappa:',kappa)
print('angle:',angle)
###################################################
#### TEST apply reflection
#
# G_tmp = G_container[idx_1[0][0]]
#
# print('G_tmp', G_tmp)
#
# # Basis:
# G_1 = np.array([[1.0,0.0], [0.0,0.0]])
# G_2 = np.array([[0.0,0.0], [0.0,1.0]])
# G_3 = (1/np.sqrt(2))*np.array([[0.0,1.0], [1.0,0.0]])
# print('G_1', G_1)
# print('G_2', G_2)
# print('G_3', G_3)
#
# G = G_tmp[0] * G_1 + G_tmp[1]*G_2 + G_tmp[2]*G_3
# print('G:', G )
#
# T = np.array([[1.0 , -1.0] , [-1.0,1.0]])
#
# TG = np.multiply(T,G)
# print('TG', TG)
#
#
#
# v = np.array([np.sqrt(TG[0][0]),np.sqrt(TG[1][1]) ])
# print('v', v)
# print('norm(v):', np.linalg.norm(v))
# norm_v = np.linalg.norm(v)
#
# kappa = norm_v**2
#
# e = (1/norm_v)*v
# print('e:', e)
# print('kappa:', kappa)
if reflect == True:
reflected_e = np.array([e[0], -1*e[1]])
e = reflected_e # Correct?! Reflect e on x-Axis ??!
print('reflected_e:', reflected_e)
############################################################################################################################################
####################################################################### KAPPA NEGATIVE ####################################################
############################################################################################################################################
# kappa = -2
num_Points = 200
num_Points = 100
# e = np.array([1,0])
# e = np.array([0,1])
# e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e = np.array([1/2,np.sqrt(3)/2])
# e = np.array([np.sqrt(3)/2,1/2])
# e = np.array([-1,0])
# e = np.array([0,-1])
###--- Creating dataset
x = np.linspace(-2,2,num_Points)
x = np.linspace(-3,3,num_Points)
x = np.linspace(-4,4,num_Points)
# x = np.linspace(-1.5,1.5,num_Points)
# x = np.linspace(-1,1,num_Points)
y = np.linspace(-1/2,1/2,num_Points)
y = np.linspace(-1/4,1/4,num_Points)
print('type of x', type(x))
print('max of x:', max(x))
print('max of y:', max(y))
# print('x:', x)
x1, x2 = np.meshgrid(x,y)
zero = 0*x1
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# print('np.size(u1)',np.size(u1))
# print('u1.shape',u1.shape)
# colorfunction=(u1**2+u2**2)
# print('colofunction',colorfunction)
# print('u1.size:',np.size(u1))
# tmp = np.ones(np.size(u1))*kappa
# print('np.size(tmp)',np.size(tmp))
B = np.full_like(u1, 1)
# colorfunction=(u3) # TODO Color by angle
# colorfunction=(np.ones(np.size(u1))*kappa)
colorfunction=(B*kappa)
# print('colofunction',colorfunction)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# -----------------------------------------------------
# Display the mesh
fig = plt.figure()
width = 6.28 *0.5
width = 6.28 * 0.333
height = width / 1.618
height = width / 2.5
height = width
ax = plt.axes(projection ='3d', adjustable='box')
###---TEST MAP e-vectprs!
# e1 = np.array([1,0])
# e2 = np.array([0,1])
# e3 = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# e1 = np.array([0,1])
# e2 = np.array([-1,0])
# e3 = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# e1_mapped = u(e1,kappa,e1)
# e2_mapped = u(e2,kappa,e2)
# e3_mapped = u(e3,kappa,e3)
# print('e1 mapped:',e1_mapped)
# print('e2 mapped:',e2_mapped)
# print('e3 mapped:',e3_mapped)
### -----------------------------------
#--e1 :
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([0,1,0])
#--e2:
Rotation_angle = np.pi/2
Rotation_vector = np.array([1,0,0])
###--e = np.array([1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_angle = -np.pi/2
# Rotation_vector = np.array([1,0,0])
# #2te rotation :
# Rotation_angle = np.pi/4
# Rotation_vector = np.array([0,0,1])
Rotation_angle = -np.pi/2
Rotation_angle = 0
# Rotation_angle = np.pi/2
Rotation_vector = np.array([0,1,0])
Rotation_vector = np.array([1,0,0])
# rot(np.array([0,1,0]),np.pi/2)
# ZERO ROTATION
Rotation = rot(np.array([0,1,0]),0)
# TEST :
#DETERMINE ANGLE:
angle = math.atan2(e[1], e[0])
print('angle:', angle)
## GENERAL TRANSFORMATION / ROTATION:
Rotation = rot(np.array([0,0,1]),angle).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
### if e1:
# Rotation = rot(np.array([0,0,1]),-np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/16).dot(Rotation)
# Add another rotation around z-axis:
# Rotation = rot(np.array([0,0,1]),+np.pi).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/4).dot(Rotation)
# Rotation = rot(np.array([0,0,1]),+np.pi/8).dot(Rotation)
#e3 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2))
# Rotation = rot(np.array([0,0,1]),np.pi/4)
# Rotation = rot(np.array([1,0,0]),np.pi/4)
#### if e1 :
# Rotation = rot(np.array([0,1,0]),-np.pi/2)
#### if e2:
# Rotation = rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2))
# # #### if e3 :
# zufall dass np.pi/4 genau dem Winkel angle alpha entspricht?:
# (würde) bei e_2 keinen Unterschied machen um z achse zu rotieren?!
# Rotation = rot(np.array([0,0,1]),np.pi/4).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([0,0,1]),np.pi/2).dot(rot(np.array([0,1,0]),-np.pi/2).dot(rot(np.array([1,0,0]),-np.pi/2)))
# Rotation = rot(np.array([1,0,0]),np.pi/2)
# Rotation_vector = e3_mapped #TEST
# Rotation_vector = np.array([-1/np.sqrt(2),1/np.sqrt(2)])
# Rotation_vector = np.array([0,0,1])
# v = np.array([1,0,0])
# X = np.array([u1,u2,u3])
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 2, cstride = 2, facecolors=cm.brg(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.viridis(colorfunction), alpha=.4, zorder=4)
###---- PLOT PARAMETER-PLANE:
# ax.plot_surface(x1,x2,zero,color = 'w', rstride = 1, cstride = 1 )
print('------------------ Kappa : ', kappa)
#midpoint:
midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
print('midpoint',midpoint)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
# mapped_e = Rotation.dot(mapped_e)
# normal = Rotation.dot(normal)
# Plot Mapped_midPoint
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=4) # line width
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [mapped_e[0]], [mapped_e[1]], [mapped_e[2]], color="red")
# ax.quiver([midpoint_mapped[0]], [midpoint_mapped[1]], [midpoint_mapped[2]], [normal[0]], [normal[1]], [normal[2]], color="blue")
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 2,
# ec ='green',
# zorder=3)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 2,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 3)
###-- TEST Rotation :
# v = np.array([1,0,0])
# t = np.array([0,1,0])
#
# ax.arrow3D(0,0,0,
# t[0],t[1],t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
#
# # e_extend
#
# rotM = rot(v,np.pi/2)
#
# print('rotM:', rotM)
#
# rot_t = rotM.dot(t)
#
# print('rot_t:', rot_t)
#
# ax.arrow3D(0,0,0,
# rot_t[0],rot_t[1],rot_t[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
### -------------------------------------------
############################################################################################################################################
####################################################################### KAPPA POSITIVE ####################################################
############################################################################################################################################
# kappa = (-1)*kappa
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.3) ##This one!
# T = rotate_data(X,Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=False)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 2, cstride = 2, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, facecolors=cm.brg(colorfunction), alpha=.8, zorder=4)
ax.plot_surface(T[0], T[1], T[2], rstride = 5, cstride = 5, color='orange', alpha=.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color='blue', alpha=.8, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=.4, zorder=4, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'w', rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=0.8, zorder=4)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, facecolors=cm.autumn(colorfunction), alpha=1, zorde5r=5)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
# print('midpoint',midpoint)
print('------------------ Kappa : ', kappa)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
#map origin
origin = np.array([0,0])
origin_mapped = u(origin,kappa,e)
mapped_e = grad_u(midpoint,kappa,e)
normal = compute_normal(midpoint,kappa,e)
print('mapped_e', mapped_e)
print('normal',normal )
#
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# Plot MIDPOINT:
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#midpoint:
endpoint = np.array([min(x),(max(y)+min(y))/2])
print('endpoint',endpoint)
# Map midpoint:
endpoint_mapped = u(endpoint,kappa,e)
print('mapped endpoint', endpoint_mapped)
endpoint_mapped = Rotation.dot(endpoint_mapped)
mapped_e = grad_u(endpoint,kappa,e)
normal = compute_normal(endpoint,kappa,e)
mapped_e = Rotation.dot(mapped_e)
normal = Rotation.dot(normal)
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(endpoint_mapped[0],endpoint_mapped[1],endpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=15,
# arrowstyle="-|>",
# linestyle='dashed',fc='green',
# lw = 1.5,
# ec ='green',
# zorder=5)
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
############################################################################################################################################
####################################################################### KAPPA ZERO #########################################################
############################################################################################################################################
kappa = 0
if kappa == 0 :
u1 = 0*x1
u2 = x1*e[0] + x2*e[1]
u3 = x2*e[0] - x1*e[1]
else :
u1 = -(1/kappa)*np.cos(kappa*(x1*e[0]+x2*e[1])) + (1/kappa)
u2 = (1/kappa)*np.sin(kappa*(x1*e[0]+x2*e[1]))
u3 = x2*e[0] -x1*e[1]
# ax.plot_surface(u1, u2, u3, rstride = 1, cstride = 1, color = 'white', alpha=0.85)
# T = rotate_data(np.array([u1,u2,u3]),Rotation_vector,Rotation_angle)
T = rotate_data(np.array([u1,u2,u3]),Rotation)
# T = rotate_data(T,np.array([0,1,0]),Rotation_angle)
# T = rotate_data(T,np.array([0,0,1]),-1*Rotation_angle/2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride =1 , cstride = 1, color = 'white', alpha=0.55, zorder=3)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.55, zorder=2)
# ax.plot_surface(T[0], T[1], T[2], rstride = 1, cstride = 1, color = 'white', alpha=0.5, zorder=2, antialiased=True)
# ax.plot_surface(T[0], T[1], T[2], rstride = 10, cstride = 10, color = 'white', alpha=0.55, zorder=2)
ax.plot_surface(T[0], T[1], T[2], rstride = 20, cstride = 20, color = 'gray', alpha=0.35, zorder=1, shade=True)
# ax.plot_surface(T[0], T[1], T[2], color = 'white', alpha=0.55, zorder=2)
# midpoint = np.array([(max(x)+min(x))/2,(max(y)+min(y))/2])
mapped_e = grad_u(midpoint,kappa,e)
normal_zeroCurv = compute_normal(midpoint,kappa,e)
# Map midpoint:
midpoint_mapped = u(midpoint,kappa,e)
print('mapped midpoint', midpoint_mapped)
##----- PLOT MAPPED MIDPOINT :::
# ax.plot(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='orange', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# # linestyle='--', # line style will be dash line
# linewidth=1,
# zorder=5)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# mapped_e[0],mapped_e[1],mapped_e[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='red',
# ec ='red')
#
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal_zeroCurv[0],normal_zeroCurv[1],normal_zeroCurv[2],
# mutation_scale=10,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue')
##---------- PLOT MAPPED ORIGIN :::
# origin = np.array([0,0])
# origin_mapped = u(origin,kappa,e)
# print('origin_mapped', origin_mapped)
#
# ax.plot(origin_mapped[0],origin_mapped[1],origin_mapped[2], # data
# marker='o', # each marker will be rendered as a circle
# markersize=4, # marker size
# markerfacecolor='green', # marker facecolor
# markeredgecolor='black', # marker edgecolor
# markeredgewidth=1, # marker edge width
# linewidth=1,
# zorder=5) # line width
#
# # rotate mapped origin
# # v = np.array([1,0,0])
# # alpha = Rotation_angle
#
# rotM = rot(Rotation_vector,Rotation_angle)
# # origin_mRot = rotate_data(origin_mapped,v,alpha)
# origin_mRot = rotM.dot(origin_mapped)
# print('origin_mapped Rotated', origin_mRot)
#
# # --- Compute Distance to Origin 3D
# origin_3D=np.array([0,0,0])
# distance = origin_mapped-origin_3D
# print('distance', distance)
## --------------------------------------------------------
# COMPUTE ANGLE WITH Z AXIS
z = np.array([0,0,1])
print('test', normal_zeroCurv*z)
angle_z = np.arccos(normal_zeroCurv.dot(z) /( (np.linalg.norm(z)*np.linalg.norm(normal_zeroCurv) ) ))
print('angle between normal and z-axis', angle_z)
## unfinished...
###------------------------------------- PLOT :
plt.axis('off')
# plt.axis('tight')
# ADD colorbar
# scamap = plt.cm.ScalarMappable(cmap='inferno')
# fig.colorbar(scamap)
# ax.colorbar()
# ax.axis('auto')
# ax.set_title(r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e))
# ax.set_title(r'Cylindrical minimizer' + '_$e$=' + str(e))
ax.set_xlabel(r"x-axis")
ax.set_ylabel(r"y-axis")
ax.set_zlabel(r"z-axis")
# TEST :
# ax.annotate3D('point 1', (0, 0, 0), xytext=(3, 3), textcoords='offset points')
# ax.annotate3D('point 2', (0, 1, 0),
# xytext=(-30, -30),
# textcoords='offset points',
# arrowprops=dict(ec='black', fc='white', shrink=2.5))
# ax.annotate3D('point 3', (0, 0, 1),
# xytext=(30, -30),
# textcoords='offset points',
# bbox=dict(boxstyle="round", fc="lightyellow"),
# arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))
#######################################################################################################################
u1 = T[0]
u2 = T[1]
u3 = T[2]
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /3
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /12
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /8
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /10
max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /14
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /6
# max_range = np.array([u1.max()-u1.min(), u2.max()-u2.min(), u3.max()-u3.min()]).max() /2
mid_u1 = (u1.max()+u1.min()) * 0.5
mid_u2 = (u2.max()+u2.min()) * 0.5
mid_u3 = (u3.max()+u3.min()) * 0.5
ax.set_xlim(mid_u1 - max_range, mid_u1 + max_range)
ax.set_ylim(mid_u2 - max_range, mid_u2 + max_range)
ax.set_zlim(mid_u3 - max_range, mid_u3 + max_range)
ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
# ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-1.5, (mid_u2 + max_range)+1.5)
# # ax.autoscale(tight=True)
ax.set_xlim((mid_u1 - max_range)-1, (mid_u1 + max_range)+1)
ax.set_xlim((mid_u1 - max_range)-0.5, (mid_u1 + max_range)+0.5)
# ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+2)
ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
# ax.set_ylim((mid_u2 - max_range)-2, (mid_u2 + max_range)+3)
# ax.set_zlim((mid_u2 - max_range), (mid_u2 + max_range)+2)
##----- CHANGE CAMERA POSITION:
# ax.view_init(elev=10., azim=0)
# ax.view_init(elev=38, azim=90)
# ax.view_init(elev=38, azim=120)
# ax.view_init(elev=38)
# if e1 ::
# ax.view_init(elev=44)
# ax.view_init(elev=38, azim=-90)
# ax.view_init(elev=38, azim=0)
ax.view_init(elev=25, azim=-30)
# ax.view_init(elev=18, azim=-30)
# if e3 ::
# ax.view_init(elev=25)
# ax.set_xlim3d(-2, 2)
# ax.set_ylim3d(-1.0,3.0)
# ax.set_zlim3d(-1.5,2.5)
# ax.set_ylim3d(-10,10)
# ax.set_xlim(mid_u1 - max_range-0.2, mid_u1 + max_range+0.2)
# ax.set_zlim(mid_u3 - max_range-0.2, mid_u3 + max_range+0.2)
# ax.set_ylim(mid_u2 - max_range-0.2, mid_u2 + max_range+0.2)
# width = 6.28 *0.5
# height = width / 1.618
# # height = width / 2.5
# fig.set_size_inches(width, height)
# fig.savefig('Test-Cylindrical.pdf')
# Figurename = r'Cylindrical minimizer_$\kappa$='+ str(kappa)+ '_$e$=' + str(e)
# Figurename = r'Cylindrical minimizer' + '_$e$=' + str(e)
Figurename = r'1-ParFamMinimizer_idx' + str(idx)
# plt.savefig("test.png", bbox_inches='tight')
# plt.figure().set_size_inches(width, height)
# plt.set_size_inches(width, height)
# fig.set_size_inches(width, height) !!!!!
fig.savefig(Figurename+".pdf")
plt.savefig(Figurename+".png", bbox_inches='tight')
# plt.savefig(Figurename+".png")
plt.show()
# #---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
# from ClassifyMin import *
from ClassifyMin_New import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
def evaluate(x,y):
# (abar[0,:]*abar[1,:])**0.5
return np.sqrt(x*y)
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
scale_domain = 5
translate_startpoint = -5
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
# print('type of G', type(G))
# print('G', G)
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
num_Points = 20
num_Points = 50
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
range = 2
x_1 = np.linspace(0,range,num_Points)
y_1 = np.linspace(0,range,num_Points)
x_2 = np.linspace(-range,0,num_Points)
y_2 = np.linspace(-range,0,num_Points)
X_1,Y_1 = np.meshgrid(x_1,y_1)
X_2,Y_2 = np.meshgrid(x_2,y_2)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
# print('a1:', a1)
# print('a2:',a2 )
#
# print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
tmp1 = a1[np.where(a1*a2 >= 0)]
tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1 = a1[np.where(a1>=0 and a2 >= 0)]
# tmp2 = a2[np.where(a1>=0 and a2 >= 0)]
# tmp1 = tmp1[np.where(a1 >= 0)]
# tmp2 = tmp2[np.where(a1 >= 0)]
# tmp1_pos = a1[np.where(a1*a2 >= 0)]
# tmp2_neg = a2[np.where(a1*a2 >= 0)]
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
tmp1 = tmp1.reshape(-1,int(tmp1.shape[0]/2))
tmp2 = tmp2.reshape(-1,int(tmp2.shape[0]/2))
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
# Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
#
# Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
# Z = (tmp2**2)/tmp1
Z = np.sqrt(tmp1*tmp2)
Z1 = np.sqrt(X_1*Y_1)
Z2 = np.sqrt(X_2*Y_2)
# Z_bar = np.sqrt(abar[0,:]*abar[1,:])
Z_bar = (abar[0,:]*abar[1,:])**0.5*abar
abar = abar.T
v1 = abar[0,:]
v2 = abar[1,:]
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
evaluateVec = np.vectorize(evaluate)
Z_bar = evaluateVec(abar[0,:],abar[1,:])
# Z = np.sqrt(np.multiply(tmp1,tmp2))
# Z = np.sqrt(a1*a2)
print('v1.shape', v1.shape)
print('v1', v1)
print('Z:', Z)
print('Z_bar:', Z_bar)
# print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
# plt.style.use('seaborn')
plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
width = 6.28 *0.5
width = 6.28
height = width / 1.618
fig = plt.figure()
ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
ax.grid(True,which='major',axis='both',alpha=0.3)
# colorfunction=(B*kappa)
# print('colofunction',colorfunction)
#translate Data
# Z = Z - (Z.max()-Z.min())/2
# Z = Z - 50
# Z = Z - 500
#
# Z = Z.T
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
# print('Value of c:', c)
# print('Z.min()', Z.min())
# print('Z.max()', Z.max())
# norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
# print('norm:', norm)
# print('type of norm', type(norm))
# print('norm(0):', norm(0))
# print('norm(Z):', norm(Z))
# ax.plot(theta_rho, theta_values, 'royalblue', zorder=3, )
# ax.scatter(a1,a2, s=0.5)
# ax.scatter(tmp1_pos,tmp2_pos, s=0.5)
# ax.scatter(tmp1_neg,tmp2_neg, s=0.5)
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=100 )
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=20 )
# sns.kdeplot(np.array([a1, a2, Z]))
# sns.kdeplot(tmp1_pos,tmp2_pos,Z_pos)
# levels = [-5.0, -4, -3, 0.0, 1.5, 2.5, 3.5]
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, corner_mask=True,levels=levels)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot(norm(Z)), corner_mask=True)
# CS = ax.contour(a1, a2, Z, cm.brg(norm(Z)), levels=20)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot, levels=20)
# CS = ax.contour(a1, a2, Z, colors='k', levels=14, linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z, colors='k', levels=18, linewidths=(0.5,))
# ax.contour(negZ_a1, negZ_a2, negativeValues, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1_in, a2_in, Z_in, colors='k', linewidths=(0.5,))
# df = pd.DataFrame(data=Z_in, columns=a1_in, index=a2_in)
# df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
# columns=['a', 'b', 'c'])
# sns.kdeplot(data=df2, x="waiting", y="duration")
# sns.kdeplot(data=df2)
# CS = ax.contour(a1, a2, Z, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k', extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k')
#
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, levels=10 )
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, corner_mask=True)
#
# CS = ax.contour(a1, a2, Z,10, colors = 'k')
# ax.clabel(CS, inline=True, fontsize=4)
# cmap = cm.brg(norm(Z))
#
# C_map = cm.inferno(norm(Z))
# ax.imshow(Z, cmap=C_map, extent=[-20, 20, -20, 20], origin='lower', alpha=0.5)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20], origin='lower',
# cmap='bwr', alpha=0.8)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', vmin=Z.min(), vmax=Z.max(),
# cmap='bwr', alpha=0.6)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
cmap=mpl.cm.RdBu_r
# cmap=mpl.cm.viridis_r
cmap=mpl.cm.bwr
# # cmap=mpl.cm.coolwarm
# # cmap=mpl.cm.gnuplot
# cmap=mpl.cm.viridis
# cmap=mpl.cm.inferno
# # # cmap=mpl.cm.Blues
# cmap=mpl.cm.magma
cmap=mpl.cm.cividis
# cmap=mpl.cm.gnuplot
# cmap=mpl.cm.gnuplot
# cmap = cm.brg(Z)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=8)
# ##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
# epsilon = 0.1
# # ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# # ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# # ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color='gray', zorder=5)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color='gray', zorder=5)#yellow
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.scatter(X_1,Y_1,Z1, s=0.2)
# ax.scatter(X_2,Y_2,Z2, s=0.2)
# ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
# linewidth=0, antialiased=False,alpha=1, zorder=5)
ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=1, zorder=5)
ax.plot_surface(X_2,Y_2,Z2 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=1, zorder=5)
# ax.plot(G[0,:],G[1,:],G[2,:])
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='yellow', linestyle='--')
# ax.scatter(abar[0,:],abar[1,:],Z_bar, color='purple', zorder=5)
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='royalblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='dodgerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='cornflowerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='darkorange', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='yellow', linestyle='--')
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=1, color='coral', linestyle='--', zorder=3)
line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=2)
# CS = ax.contour(X_1,Y_1,Z1, colors='k', levels=18, linewidths=(0.5,))
start = np.array([abar[0,499],abar[1,499],Z_bar[499]])
end = np.array([abar[0,500],abar[1,500],Z_bar[500]])
# plot starting point:
# ax.scatter(abar[0,0],abar[1,0],Z_bar[0], marker='^', s=30, color='black', zorder=5)
#
#
# ax.scatter(abar[0,500],abar[1,500],Z_bar[500], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(start[0],start[1],start[2], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(end[0],end[1],end[2], marker='^', s=30, color='purple', zorder=5)
print('start:', start)
print('end:', end)
dir = end-start
# ax.arrow()
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=10,
# arrowstyle="->",
# linestyle='dashed',fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# Check proof:
# value at t = 0:
abar_zero= sstar*abar_tmp
# value_0 = [abar_zero[0], abar_zero[1] , (2*abar_zero[0]*abar_zero[1])**0.5 ]
value_0 = evaluate(abar_zero[0], abar_zero[1])
print('value_0', value_0)
# ax.scatter(value_0[0],value_0[1],value_0[2], marker='x', s=20, color='dodgerblue', zorder=5)
# ax.scatter(abar_zero[0], abar_zero[1],value_0, marker='o', s=30, color='dodgerblue', zorder=5)
## -----------------------------
# ax.scatter(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,Z, tmp2, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_trisurf(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLot x and y- Axes
# ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
# ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=1)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=1)
ax.set_xlabel(r"$a_1$", fontsize=10 ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=10 ,labelpad=0)
# ax.set_ylabel(r"energy")
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
fig.savefig('1-ParameterFamily_G+.pdf')
plt.show()
#
#
#
# # Curve parametrised by \theta_rho = alpha in parameter space
# N=100;
# theta_rho = np.linspace(1, 3, num=N)
# print('theta_rho:', theta_rho)
#
#
# theta_values = []
#
#
# for t in theta_rho:
#
# s = (1.0/10.0)*t+0.1
# theta_values.append(s)
#
#
#
#
#
# theta_rho = np.array(theta_rho)
# theta_values = np.array(theta_values)
#
# betas_ = 2.0
#
# alphas, betas, thetas = np.meshgrid(theta_rho, betas_, theta_values, indexing='ij')
#
#
# harmonicMeanVec = np.vectorize(harmonicMean)
# arithmeticMeanVec = np.vectorize(arithmeticMean)
# prestrain_b1Vec = np.vectorize(prestrain_b1)
# prestrain_b2Vec = np.vectorize(prestrain_b2)
#
# GetMuGammaVec = np.vectorize(GetMuGamma)
# muGammas = GetMuGammaVec(betas,thetas,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
#
# q1_vec = harmonicMeanVec(mu1, betas, thetas)
# q2_vec = arithmeticMeanVec(mu1, betas, thetas)
#
# b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# special case: q12 == 0!! .. braucht eigentlich nur b1 & b2 ...
# print('type b1_values:', type(b1_values))
# print('size(q1)',q1.shape)
#
#
# energy_axial1 = []
# energy_axial2 = []
#
# # for b1 in b1_values:
# for i in range(len(theta_rho)):
# print('index i:', i)
#
# print('theta_rho[i]',theta_rho[i])
# print('theta_values[i]',theta_values[i])
#
# q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta_values[i])
# q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta_values[i])
# q12 = 0.0
# q3 = GetMuGamma(beta, theta_values[i],gamma,mu1,rho1,InputFilePath ,OutputFilePath )
# b1 = prestrain_b1(rho1,beta, theta_rho[i],theta_values[i] )
# b2 = prestrain_b2(rho1,beta, theta_rho[i],theta_values[i] )
#
#
# # q2_vec = arithmeticMean(mu1, betas, thetas)
# #
# # b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# # b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# print('q1[i]',q1)
# print('q2[i]',q2)
# print('q3[i]',q3)
# print('b1[i]',b1)
# print('b2[i]',b2)
# # print('q1[i]',q1[0][i])
# # print('q2[i]',q2[i])
# # print('b1[i]',b1[i])
# # print('b2[i]',b2[i])
# #compute axial energy #1 ...
#
# a_axial1 = np.array([b1,0])
# a_axial2 = np.array([0,b2])
# b = np.array([b1,b2])
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a_axial1)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial1',a_axial1)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial1.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial1.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_1 = tmp - tmp2
# print('energy_1',energy_1)
#
#
# energy_axial1.append(energy_1)
#
#
# tmp = H.dot(a_axial2)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial2',a_axial2)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial2.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial2.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_2 = tmp - tmp2
# print('energy_2',energy_2)
#
#
# energy_axial2.append(energy_2)
#
#
#
#
#
# print('theta_values', theta_values)
#
#
#
#
#
#
#
# kappas = []
# alphas = []
# # G.append(float(s[0]))
#
#
#
#
# for t in T :
#
# abar_current = sstar*abar+t*abarperp;
# # print('abar_current', abar_current)
# abar_current[abar_current < 1e-10] = 0
# # print('abar_current', abar_current)
#
# # G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
#
# e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
# kappa = abar_current[0]+abar_current[1]
# alpha = math.atan2(e[1], e[0])
#
# print('angle current:', alpha)
#
# kappas.append(kappa)
# alphas.append(alpha)
#
#
#
# alphas = np.array(alphas)
# kappas = np.array(kappas)
#
#
# print('kappas:',kappas)
# print('alphas:',alphas)
# print('min alpha:', min(alphas))
# print('min kappa:', min(kappas))
#
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
# width = 6.28 *0.5
# height = width / 1.618
# fig = plt.figure()
# # ax = plt.axes((0.15,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.21 ,0.8,0.75))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# # ax.xaxis.set_major_locator(MultipleLocator(0.1))
# # ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# # ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# # ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
#
#
#
#
# ax.plot(alphas, kappas, 'royalblue', zorder=3, )
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
from ClassifyMin import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from chart_studio import plotly
import plotly.graph_objs as go
import plotly.express as px
import plotly.colors
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
def show(fig):
import io
import plotly.io as pio
from PIL import Image
buf = io.BytesIO()
pio.write_image(fig, buf)
img = Image.open(buf)
img.show()
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def set_size(width, fraction=1):
"""Set figure dimensions to avoid scaling in LaTeX.
Parameters
----------
width: float
Document textwidth or columnwidth in pts
fraction: float, optional
Fraction of the width which you wish the figure to occupy
Returns
-------
fig_dim: tuple
Dimensions of figure in inches
"""
# Width of figure (in pts)
fig_width_pt = width * fraction
# Convert from pt to inches
inches_per_pt = 1 / 72.27
# Golden ratio to set aesthetic figure height
# https://disq.us/p/2940ij3
golden_ratio = (5**.5 - 1) / 2
# Figure width in inches
fig_width_in = fig_width_pt * inches_per_pt
# Figure height in inches
fig_height_in = fig_width_in * golden_ratio
fig_dim = (fig_width_in, fig_height_in)
return fig_dim
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = -0.75
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
# gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
## ---- 1-ParameterFamilyCase:
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
# print('abar:',abar)
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
# b1=b[0]
# b2=b[1]
## ---------------
########################################
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
##----------------------
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
##--------------
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('sstar*abar:', sstar*abar)
# print('np.dot(sstar*abar):', np.dot(sstar*abar))
print('----------------------------')
N=1000;
# N=10;
scale_domain = 5
translate_startpoint = -1.8
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
test = sstar*abar
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# abar_current[abar_current < 1e-10] = 0 # Projection onto x-y-axis!!
print('abar_current', abar_current)
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
######################################
num_Points = 400
num_Points = 200
# num_Points = 20
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
x = np.linspace(-2,2,num_Points)
y = np.linspace(-2,2,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
print('a1:', a1)
print('a2:',a2 )
print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
# tmp1 = a1[np.where(a1*a2 >= 0)]
# tmp2 = a2[np.where(a1*a2 >= 0)]
#
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
tmp1 = a1[a1*a2 >= 0]
tmp2 = a2[a1*a2 >= 0]
tmp1 = tmp1.reshape(-1,5)
tmp2 = tmp2.reshape(-1,5)
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
#
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
#
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
print('a1:', a1)
print('a2:',a2 )
print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
print('Z:', Z)
print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
plt.style.use('seaborn')
# plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
width = 6.28 *0.5
# width = 6.28 *0.33
# width = 6.28
height = width #/ 1.618
# width = 452.9579/2
# size= set_size(width, fraction=0.5)
# print('set_size(width, fraction=0.5)', set_size(width, fraction=1))
# print('size[0]',size[0])
f_size = 10
# fig= plt.figure()
fig, ax = plt.subplots()
# fig.set_size_inches(width, height)
# fig.set_size_inches(set_size(width, fraction=0.5))
# ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.17,0.23 ,0.7,0.7))
# ax = plt.axes((0.17,0.23 ,1.0,1.0))
# ax=plt.axes()
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
ax.grid(True,which='major',axis='both',alpha=0.3)
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
#
# print('Value of c:', c)
print('Z.min()', Z.min())
print('Z.max()', Z.max())
norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
cmap=mpl.cm.RdBu_r
cmap=mpl.cm.viridis_r
# cmap=mpl.cm.bwr
cmap=mpl.cm.coolwarm
# cmap=mpl.cm.gnuplot
cmap=mpl.cm.magma_r
# cmap=mpl.cm.inferno_r
# cmap=mpl.cm.plasma
# cmap=mpl.cm.plasma_r
# cmap=mpl.cm.cividis_r
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["blue","violet","red"])
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["blue","orange"])
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", [(0,"red"), (.1,"violet"), (.5, "blue"), (1.0, "green")])
# make a colormap that has land and ocean clearly delineated and of the
# same length (256 + 256)
#
# colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256))
# colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256))
# all_colors = np.vstack((colors_undersea, colors_land))
# # cmap = mcolors.LinearSegmentedColormap.from_list(
# # 'terrain_map', all_colors)
# cmap = px.colors.sequential.agsunset
# cmap = plotly.colors.PLOTLY_SCALES["Viridis"]
# cmap = cm.brg(Z)
divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=(Z.max()+Z.min())/2, vmax=Z.max())
# divnorm=mcolors.TwoSlopeNorm(vmin=-500, vcenter=0, vmax=Z.max())
# divnorm=mcolors.TwoSlopeNorm(vmin=-10, vcenter=0. ,vmax=10)
# divnorm=mcolors.TwoSlopeNorm(vmin=-10, vcenter=0., vmax=Z.max())
# divnorm=mcolors.LogNorm(vmin=Z.min(), vmax=Z.max()) #Test LogNorm
# cmap = cm.brg(divnorm(Z))
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.9)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = mcolors.CenteredNorm(),
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=f_size)
# fig.colorbar(I)
##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
epsilon = 0.001
# ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
fillcolor = 'royalblue'
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color=fillcolor, zorder=4)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color=fillcolor, zorder=4)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=1.0, color=fillcolor, zorder=4)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=1.0, color=fillcolor, zorder=4)#yellow
## FILL
ax.fill_between([x.min(), 0-epsilon], y.min(), 0-epsilon, alpha=.25, color=fillcolor, zorder=4)#yellow
ax.fill_between([0+epsilon, x.max()], 0+epsilon, y.max(), alpha=.25, color=fillcolor, zorder=4)#yellow
ax.text(1,1, r"$\mathcal{G}^+_{\mathbf{R}^2}$", color='royalblue', size=15)
# ax.text(0.25,0.25, r"$\mathcal{S}$", color='darkorange', size=15)
# PLOT 1-PARAMETER FAMILY
print('abar:', abar)
print('abar[0,:]:', abar[0,:])
print('abar[1,:]:', abar[1,:])
line = ax.plot(abar[:,0],abar[:,1], linewidth=2, color='darkorange', linestyle='-', zorder=4)
# plt.arrow(x=1, y=0, dx=0.5, dy=0, )
# ax.arrow(1, 0, 0.5, 0, head_width=0.05, head_length=0.1, fc='k', ec='k', zorder=5)
# plt.arrow(1, 0, 0.8, 0, shape='full', lw=0, length_includes_head=True, head_width=.15, zorder=5, color='purple')
## PLOT ARROW:
# plt.arrow(1, 0, 0.5, 0, shape='full', lw=0, length_includes_head=True, head_width=.20, zorder=5, color='darkorange')
# plt.arrow(0, 1.8, 0, -0.8, shape='full', lw=0, length_includes_head=True, head_width=.20, zorder=5, color='darkorange')
# plt.arrow(0, 1.8, 0, -0.8, lw=0, head_width=.12, zorder=5, color='darkorange')
# plt.arrow(0, 2, 0, -0.5, shape='full', lw=0, length_includes_head=True, head_width=.12, zorder=5, color='darkorange')
# add_arrow(line, color='darkorange')
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# print('test:',test)
# ax.scatter(test[0],test[1])
# ax.arrow(test[0],test[1],abarperp[0],abarperp[1])
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLot x and y- Axes
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.set_xlabel(r"$a_1$", fontsize=f_size ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=f_size ,labelpad=0)
# ax.set_ylabel(r"energy")
ax.tick_params(axis='both', which='major', labelsize=f_size)
ax.tick_params(axis='both', which='minor', labelsize=f_size)
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
print('x.max()',x.max())
print('y.max()',y.max())
ax.set_xlim(x.min(),x.max())
ax.set_xlim(y.min(),y.max())
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
# fig.set_size_inches(set_size(width, fraction=0.33))
fig.savefig('Energy_ContourG+_Flat.pdf')
plt.show()
#
#
#
# # Curve parametrised by \theta_rho = alpha in parameter space
# N=100;
# theta_rho = np.linspace(1, 3, num=N)
# print('theta_rho:', theta_rho)
#
#
# theta_values = []
#
#
# for t in theta_rho:
#
# s = (1.0/10.0)*t+0.1
# theta_values.append(s)
#
#
#
#
#
# theta_rho = np.array(theta_rho)
# theta_values = np.array(theta_values)
#
# betas_ = 2.0
#
# alphas, betas, thetas = np.meshgrid(theta_rho, betas_, theta_values, indexing='ij')
#
#
# harmonicMeanVec = np.vectorize(harmonicMean)
# arithmeticMeanVec = np.vectorize(arithmeticMean)
# prestrain_b1Vec = np.vectorize(prestrain_b1)
# prestrain_b2Vec = np.vectorize(prestrain_b2)
#
# GetMuGammaVec = np.vectorize(GetMuGamma)
# muGammas = GetMuGammaVec(betas,thetas,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
#
# q1_vec = harmonicMeanVec(mu1, betas, thetas)
# q2_vec = arithmeticMeanVec(mu1, betas, thetas)
#
# b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# special case: q12 == 0!! .. braucht eigentlich nur b1 & b2 ...
# print('type b1_values:', type(b1_values))
# print('size(q1)',q1.shape)
#
#
# energy_axial1 = []
# energy_axial2 = []
#
# # for b1 in b1_values:
# for i in range(len(theta_rho)):
# print('index i:', i)
#
# print('theta_rho[i]',theta_rho[i])
# print('theta_values[i]',theta_values[i])
#
# q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta_values[i])
# q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta_values[i])
# q12 = 0.0
# q3 = GetMuGamma(beta, theta_values[i],gamma,mu1,rho1,InputFilePath ,OutputFilePath )
# b1 = prestrain_b1(rho1,beta, theta_rho[i],theta_values[i] )
# b2 = prestrain_b2(rho1,beta, theta_rho[i],theta_values[i] )
#
#
# # q2_vec = arithmeticMean(mu1, betas, thetas)
# #
# # b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# # b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# print('q1[i]',q1)
# print('q2[i]',q2)
# print('q3[i]',q3)
# print('b1[i]',b1)
# print('b2[i]',b2)
# # print('q1[i]',q1[0][i])
# # print('q2[i]',q2[i])
# # print('b1[i]',b1[i])
# # print('b2[i]',b2[i])
# #compute axial energy #1 ...
#
# a_axial1 = np.array([b1,0])
# a_axial2 = np.array([0,b2])
# b = np.array([b1,b2])
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a_axial1)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial1',a_axial1)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial1.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial1.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_1 = tmp - tmp2
# print('energy_1',energy_1)
#
#
# energy_axial1.append(energy_1)
#
#
# tmp = H.dot(a_axial2)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial2',a_axial2)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial2.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial2.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_2 = tmp - tmp2
# print('energy_2',energy_2)
#
#
# energy_axial2.append(energy_2)
#
#
#
#
#
# print('theta_values', theta_values)
#
#
#
#
#
#
#
# kappas = []
# alphas = []
# # G.append(float(s[0]))
#
#
#
#
# for t in T :
#
# abar_current = sstar*abar+t*abarperp;
# # print('abar_current', abar_current)
# abar_current[abar_current < 1e-10] = 0
# # print('abar_current', abar_current)
#
# # G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
#
# e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
# kappa = abar_current[0]+abar_current[1]
# alpha = math.atan2(e[1], e[0])
#
# print('angle current:', alpha)
#
# kappas.append(kappa)
# alphas.append(alpha)
#
#
#
# alphas = np.array(alphas)
# kappas = np.array(kappas)
#
#
# print('kappas:',kappas)
# print('alphas:',alphas)
# print('min alpha:', min(alphas))
# print('min kappa:', min(kappas))
#
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
# width = 6.28 *0.5
# height = width / 1.618
# fig = plt.figure()
# # ax = plt.axes((0.15,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.21 ,0.8,0.75))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# # ax.xaxis.set_major_locator(MultipleLocator(0.1))
# # ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# # ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# # ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
#
#
#
#
# ax.plot(alphas, kappas, 'royalblue', zorder=3, )
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
from ClassifyMin import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from chart_studio import plotly
import plotly.graph_objs as go
import plotly.express as px
import plotly.colors
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
def show(fig):
import io
import plotly.io as pio
from PIL import Image
buf = io.BytesIO()
pio.write_image(fig, buf)
img = Image.open(buf)
img.show()
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def set_size(width, fraction=1):
"""Set figure dimensions to avoid scaling in LaTeX.
Parameters
----------
width: float
Document textwidth or columnwidth in pts
fraction: float, optional
Fraction of the width which you wish the figure to occupy
Returns
-------
fig_dim: tuple
Dimensions of figure in inches
"""
# Width of figure (in pts)
fig_width_pt = width * fraction
# Convert from pt to inches
inches_per_pt = 1 / 72.27
# Golden ratio to set aesthetic figure height
# https://disq.us/p/2940ij3
golden_ratio = (5**.5 - 1) / 2
# Figure width in inches
fig_width_in = fig_width_pt * inches_per_pt
# Figure height in inches
fig_height_in = fig_width_in * golden_ratio
fig_dim = (fig_width_in, fig_height_in)
return fig_dim
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = -0.75
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
# gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
## ---- 1-ParameterFamilyCase:
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
# print('abar:',abar)
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
# b1=b[0]
# b2=b[1]
## ---------------
########################################
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
##----------------------
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
##--------------
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('sstar*abar:', sstar*abar)
# print('np.dot(sstar*abar):', np.dot(sstar*abar))
print('----------------------------')
N=1000;
N=10;
scale_domain = 5
translate_startpoint = -1.8
T_line = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
line_values = []
for t in T_line :
print('sstar*abar+t*abarperp', sstar*abar+t*abarperp)
line_values.append(sstar*abar+t*abarperp)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
test = sstar*abar
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
abar_current[abar_current < 1e-10] = 0 # Projection onto x-y-axis!!
print('abar_current', abar_current)
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
######################################
num_Points = 400
num_Points = 200
# num_Points = 20
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
x = np.linspace(-2,2,num_Points)
y = np.linspace(-2,2,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
print('a1:', a1)
print('a2:',a2 )
print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
# tmp1 = a1[np.where(a1*a2 >= 0)]
# tmp2 = a2[np.where(a1*a2 >= 0)]
#
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
tmp1 = a1[a1*a2 >= 0]
tmp2 = a2[a1*a2 >= 0]
tmp1 = tmp1.reshape(-1,5)
tmp2 = tmp2.reshape(-1,5)
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
#
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
#
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
print('a1:', a1)
print('a2:',a2 )
print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
print('Z:', Z)
print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
#
# label_size = 8
# mpl.rcParams['xtick.labelsize'] = label_size
# mpl.rcParams['ytick.labelsize'] = label_size
#
# plt.style.use('seaborn')
# # plt.style.use('seaborn-whitegrid')
# # sns.set()
# # plt.style.use('seaborn-whitegrid')
#
# label_size = 9
# mpl.rcParams['xtick.labelsize'] = label_size
# mpl.rcParams['ytick.labelsize'] = label_size
# # plt.style.use("seaborn-darkgrid")
# plt.style.use("seaborn-whitegrid")
plt.style.use("seaborn")
# plt.style.use("seaborn-paper")
# plt.style.use('ggplot')
# plt.rcParams["font.family"] = "Avenir"
# plt.rcParams["font.size"] = 16
# plt.style.use("seaborn-darkgrid")
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "10"
# mpl.rcParams['xtick.labelsize'] = 16mpl.rcParams['xtick.major.size'] = 2.5
# mpl.rcParams['xtick.bottom'] = True
# mpl.rcParams['ticks'] = True
mpl.rcParams['xtick.bottom'] = True
mpl.rcParams['xtick.major.size'] = 3
mpl.rcParams['xtick.minor.size'] = 1.5
mpl.rcParams['xtick.major.width'] = 0.75
mpl.rcParams['ytick.left'] = True
mpl.rcParams['ytick.major.size'] = 3
mpl.rcParams['ytick.minor.size'] = 1.5
mpl.rcParams['ytick.major.width'] = 0.75
mpl.rcParams.update({'font.size': 10})
mpl.rcParams['axes.labelpad'] = 3.0
width = 6.28 *0.5
# width = 6.28 *0.33
# width = 6.28
height = width #/ 1.618
# width = 452.9579/2
# size= set_size(width, fraction=0.5)
# print('set_size(width, fraction=0.5)', set_size(width, fraction=1))
# print('size[0]',size[0])
f_size = 10
# fig= plt.figure()
fig, ax = plt.subplots()
# fig.set_size_inches(width, height)
# fig.set_size_inches(set_size(width, fraction=0.5))
# ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.17,0.23 ,0.7,0.7))
# ax = plt.axes((0.17,0.23 ,1.0,1.0))
# ax=plt.axes()
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
ax.grid(True,which='major',axis='both',alpha=0.3)
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
#
# print('Value of c:', c)
print('Z.min()', Z.min())
print('Z.max()', Z.max())
norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
cmap=mpl.cm.RdBu_r
cmap=mpl.cm.viridis_r
# cmap=mpl.cm.bwr
cmap=mpl.cm.coolwarm
# cmap=mpl.cm.gnuplot
cmap=mpl.cm.magma_r
# cmap=mpl.cm.inferno_r
# cmap=mpl.cm.plasma
# cmap=mpl.cm.plasma_r
# cmap=mpl.cm.cividis_r
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["blue","violet","red"])
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["blue","orange"])
# cmap = mpl.colors.LinearSegmentedColormap.from_list("", [(0,"red"), (.1,"violet"), (.5, "blue"), (1.0, "green")])
# make a colormap that has land and ocean clearly delineated and of the
# same length (256 + 256)
#
# colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256))
# colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256))
# all_colors = np.vstack((colors_undersea, colors_land))
# # cmap = mcolors.LinearSegmentedColormap.from_list(
# # 'terrain_map', all_colors)
# cmap = px.colors.sequential.agsunset
# cmap = plotly.colors.PLOTLY_SCALES["Viridis"]
# cmap = cm.brg(Z)
divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=(Z.max()+Z.min())/2, vmax=Z.max())
# divnorm=mcolors.TwoSlopeNorm(vmin=-500, vcenter=0, vmax=Z.max())
# divnorm=mcolors.TwoSlopeNorm(vmin=-10, vcenter=0. ,vmax=10)
# divnorm=mcolors.TwoSlopeNorm(vmin=-10, vcenter=0., vmax=Z.max())
# divnorm=mcolors.LogNorm(vmin=Z.min(), vmax=Z.max()) #Test LogNorm
# cmap = cm.brg(divnorm(Z))
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.9)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# I = plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = mcolors.CenteredNorm(),
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=f_size)
# fig.colorbar(I)
##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
epsilon = 0.001
# ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
fillcolor = 'royalblue'
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color=fillcolor, zorder=4)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color=fillcolor, zorder=4)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=1.0, color=fillcolor, zorder=4)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=1.0, color=fillcolor, zorder=4)#yellow
## FILL
ax.fill_between([x.min(), 0-epsilon], y.min(), 0-epsilon, alpha=.25, color=fillcolor, zorder=4)#yellow
ax.fill_between([0+epsilon, x.max()], 0+epsilon, y.max(), alpha=.25, color=fillcolor, zorder=4)#yellow
ax.text(1,1, r"$\mathcal{G}^+_{\mathbf{R}^2}$", color='royalblue', size=15)
# ax.text(0.25,0.25, r"$\mathcal{S}$", color='darkorange', size=15)
# PLOT 1-PARAMETER FAMILY
print('abar:', abar)
print('abar[0,:]:', abar[0,:])
print('abar[1,:]:', abar[1,:])
line = ax.plot(abar[:,0],abar[:,1], linewidth=1.5, color='darkorange', linestyle='-', zorder=4)
# plt.arrow(x=1, y=0, dx=0.5, dy=0, )
# ax.arrow(1, 0, 0.5, 0, head_width=0.05, head_length=0.1, fc='k', ec='k', zorder=5)
# plt.arrow(1, 0, 0.8, 0, shape='full', lw=0, length_includes_head=True, head_width=.15, zorder=5, color='purple')
## PLOT ARROW:
# plt.arrow(1, 0, 0.5, 0, shape='full', lw=0, length_includes_head=True, head_width=.20, zorder=5, color='darkorange')
# plt.arrow(0, 1.8, 0, -0.8, shape='full', lw=0, length_includes_head=True, head_width=.20, zorder=5, color='darkorange')
# plt.arrow(0, 1.8, 0, -0.8, lw=0, head_width=.12, zorder=5, color='darkorange')
# plt.arrow(0, 2, 0, -0.5, shape='full', lw=0, length_includes_head=True, head_width=.12, zorder=5, color='darkorange')
# add_arrow(line, color='darkorange')
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# print('test:',test)
# ax.scatter(test[0],test[1])
# ax.arrow(test[0],test[1],abarperp[0],abarperp[1])
line_values= np.array(line_values)
ax.plot(line_values[:,0],line_values[:,1],'k--', linewidth=1,color='orange',alpha=0.5)
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLot x and y- Axes
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.set_xlabel(r"$a_1$", fontsize=f_size ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=f_size ,labelpad=0, rotation=0)
# ax.set_ylabel(r"energy")
ax.tick_params(axis='both', which='major', labelsize=f_size)
ax.tick_params(axis='both', which='minor', labelsize=f_size)
ax.set_ylim(-2,2)
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
print('x.max()',x.max())
print('y.max()',y.max())
ax.set_xlim(x.min(),x.max())
ax.set_xlim(y.min(),y.max())
plt.subplots_adjust(bottom=0.15)
plt.subplots_adjust(left=0.2)
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
# fig.set_size_inches(set_size(width, fraction=0.33))
fig.savefig('Energy_ContourG+_Flat.pdf')
plt.show()
#
#
#
# # Curve parametrised by \theta_rho = alpha in parameter space
# N=100;
# theta_rho = np.linspace(1, 3, num=N)
# print('theta_rho:', theta_rho)
#
#
# theta_values = []
#
#
# for t in theta_rho:
#
# s = (1.0/10.0)*t+0.1
# theta_values.append(s)
#
#
#
#
#
# theta_rho = np.array(theta_rho)
# theta_values = np.array(theta_values)
#
# betas_ = 2.0
#
# alphas, betas, thetas = np.meshgrid(theta_rho, betas_, theta_values, indexing='ij')
#
#
# harmonicMeanVec = np.vectorize(harmonicMean)
# arithmeticMeanVec = np.vectorize(arithmeticMean)
# prestrain_b1Vec = np.vectorize(prestrain_b1)
# prestrain_b2Vec = np.vectorize(prestrain_b2)
#
# GetMuGammaVec = np.vectorize(GetMuGamma)
# muGammas = GetMuGammaVec(betas,thetas,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
#
# q1_vec = harmonicMeanVec(mu1, betas, thetas)
# q2_vec = arithmeticMeanVec(mu1, betas, thetas)
#
# b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# special case: q12 == 0!! .. braucht eigentlich nur b1 & b2 ...
# print('type b1_values:', type(b1_values))
# print('size(q1)',q1.shape)
#
#
# energy_axial1 = []
# energy_axial2 = []
#
# # for b1 in b1_values:
# for i in range(len(theta_rho)):
# print('index i:', i)
#
# print('theta_rho[i]',theta_rho[i])
# print('theta_values[i]',theta_values[i])
#
# q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta_values[i])
# q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta_values[i])
# q12 = 0.0
# q3 = GetMuGamma(beta, theta_values[i],gamma,mu1,rho1,InputFilePath ,OutputFilePath )
# b1 = prestrain_b1(rho1,beta, theta_rho[i],theta_values[i] )
# b2 = prestrain_b2(rho1,beta, theta_rho[i],theta_values[i] )
#
#
# # q2_vec = arithmeticMean(mu1, betas, thetas)
# #
# # b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# # b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# print('q1[i]',q1)
# print('q2[i]',q2)
# print('q3[i]',q3)
# print('b1[i]',b1)
# print('b2[i]',b2)
# # print('q1[i]',q1[0][i])
# # print('q2[i]',q2[i])
# # print('b1[i]',b1[i])
# # print('b2[i]',b2[i])
# #compute axial energy #1 ...
#
# a_axial1 = np.array([b1,0])
# a_axial2 = np.array([0,b2])
# b = np.array([b1,b2])
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a_axial1)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial1',a_axial1)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial1.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial1.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_1 = tmp - tmp2
# print('energy_1',energy_1)
#
#
# energy_axial1.append(energy_1)
#
#
# tmp = H.dot(a_axial2)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial2',a_axial2)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial2.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial2.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_2 = tmp - tmp2
# print('energy_2',energy_2)
#
#
# energy_axial2.append(energy_2)
#
#
#
#
#
# print('theta_values', theta_values)
#
#
#
#
#
#
#
# kappas = []
# alphas = []
# # G.append(float(s[0]))
#
#
#
#
# for t in T :
#
# abar_current = sstar*abar+t*abarperp;
# # print('abar_current', abar_current)
# abar_current[abar_current < 1e-10] = 0
# # print('abar_current', abar_current)
#
# # G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
#
# e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
# kappa = abar_current[0]+abar_current[1]
# alpha = math.atan2(e[1], e[0])
#
# print('angle current:', alpha)
#
# kappas.append(kappa)
# alphas.append(alpha)
#
#
#
# alphas = np.array(alphas)
# kappas = np.array(kappas)
#
#
# print('kappas:',kappas)
# print('alphas:',alphas)
# print('min alpha:', min(alphas))
# print('min kappa:', min(kappas))
#
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
# width = 6.28 *0.5
# height = width / 1.618
# fig = plt.figure()
# # ax = plt.axes((0.15,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.21 ,0.8,0.75))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# # ax.xaxis.set_major_locator(MultipleLocator(0.1))
# # ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# # ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# # ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
#
#
#
#
# ax.plot(alphas, kappas, 'royalblue', zorder=3, )
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
from ClassifyMin import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.proj3d import proj_transform
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
def evaluate(x,y):
# (abar[0,:]*abar[1,:])**0.5
return np.sqrt(x*y)
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, x, y, z, dx, dy, dz, *args, **kwargs):
super().__init__((0, 0), (0, 0), *args, **kwargs)
self._xyz = (x, y, z)
self._dxdydz = (dx, dy, dz)
def draw(self, renderer):
x1, y1, z1 = self._xyz
dx, dy, dz = self._dxdydz
x2, y2, z2 = (x1 + dx, y1 + dy, z1 + dz)
xs, ys, zs = proj_transform((x1, x2), (y1, y2), (z1, z2), self.axes.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
super().draw(renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
scale_domain = 5
translate_startpoint = -5
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
# print('type of G', type(G))
# print('G', G)
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
num_Points = 20
num_Points = 50
num_Points = 200
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
range = 2
x_1 = np.linspace(0,range,num_Points)
y_1 = np.linspace(0,range,num_Points)
x_2 = np.linspace(-range,0,num_Points)
y_2 = np.linspace(-range,0,num_Points)
X_1,Y_1 = np.meshgrid(x_1,y_1)
X_2,Y_2 = np.meshgrid(x_2,y_2)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
# print('a1:', a1)
# print('a2:',a2 )
#
# print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
tmp1 = a1[np.where(a1*a2 >= 0)]
tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1 = a1[np.where(a1>=0 and a2 >= 0)]
# tmp2 = a2[np.where(a1>=0 and a2 >= 0)]
# tmp1 = tmp1[np.where(a1 >= 0)]
# tmp2 = tmp2[np.where(a1 >= 0)]
# tmp1_pos = a1[np.where(a1*a2 >= 0)]
# tmp2_neg = a2[np.where(a1*a2 >= 0)]
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
tmp1 = tmp1.reshape(-1,int(tmp1.shape[0]/2))
tmp2 = tmp2.reshape(-1,int(tmp2.shape[0]/2))
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
# Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
#
# Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
# Z = (tmp2**2)/tmp1
Z = np.sqrt(tmp1*tmp2)
Z1 = np.sqrt(X_1*Y_1)
Z2 = np.sqrt(X_2*Y_2)
# Z_bar = np.sqrt(abar[0,:]*abar[1,:])
Z_bar = (abar[0,:]*abar[1,:])**0.5*abar
abar = abar.T
v1 = abar[0,:]
v2 = abar[1,:]
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
evaluateVec = np.vectorize(evaluate)
Z_bar = evaluateVec(abar[0,:],abar[1,:])
# Z = np.sqrt(np.multiply(tmp1,tmp2))
# Z = np.sqrt(a1*a2)
print('v1.shape', v1.shape)
print('v1', v1)
print('Z:', Z)
print('Z_bar:', Z_bar)
# print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
# plt.style.use('seaborn')
plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
width = 6.28 *0.5
width = 6.28
height = width / 1.618
fig = plt.figure()
ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
ax.grid(True,which='major',axis='both',alpha=0.3)
# colorfunction=(B*kappa)
# print('colofunction',colorfunction)
#translate Data
# Z = Z - (Z.max()-Z.min())/2
# Z = Z - 50
# Z = Z - 500
#
# Z = Z.T
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
# print('Value of c:', c)
# print('Z.min()', Z.min())
# print('Z.max()', Z.max())
# norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
# print('norm:', norm)
# print('type of norm', type(norm))
# print('norm(0):', norm(0))
# print('norm(Z):', norm(Z))
# ax.plot(theta_rho, theta_values, 'royalblue', zorder=3, )
# ax.scatter(a1,a2, s=0.5)
# ax.scatter(tmp1_pos,tmp2_pos, s=0.5)
# ax.scatter(tmp1_neg,tmp2_neg, s=0.5)
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=100 )
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=20 )
# sns.kdeplot(np.array([a1, a2, Z]))
# sns.kdeplot(tmp1_pos,tmp2_pos,Z_pos)
# levels = [-5.0, -4, -3, 0.0, 1.5, 2.5, 3.5]
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, corner_mask=True,levels=levels)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot(norm(Z)), corner_mask=True)
# CS = ax.contour(a1, a2, Z, cm.brg(norm(Z)), levels=20)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot, levels=20)
# CS = ax.contour(a1, a2, Z, colors='k', levels=14, linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z, colors='k', levels=18, linewidths=(0.5,))
# ax.contour(negZ_a1, negZ_a2, negativeValues, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1_in, a2_in, Z_in, colors='k', linewidths=(0.5,))
# df = pd.DataFrame(data=Z_in, columns=a1_in, index=a2_in)
# df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
# columns=['a', 'b', 'c'])
# sns.kdeplot(data=df2, x="waiting", y="duration")
# sns.kdeplot(data=df2)
# CS = ax.contour(a1, a2, Z, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k', extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k')
#
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, levels=10 )
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, corner_mask=True)
#
# CS = ax.contour(a1, a2, Z,10, colors = 'k')
# ax.clabel(CS, inline=True, fontsize=4)
# cmap = cm.brg(norm(Z))
#
# C_map = cm.inferno(norm(Z))
# ax.imshow(Z, cmap=C_map, extent=[-20, 20, -20, 20], origin='lower', alpha=0.5)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20], origin='lower',
# cmap='bwr', alpha=0.8)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', vmin=Z.min(), vmax=Z.max(),
# cmap='bwr', alpha=0.6)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
cmap=mpl.cm.RdBu_r
# cmap=mpl.cm.viridis_r
cmap=mpl.cm.bwr
# # cmap=mpl.cm.coolwarm
# # cmap=mpl.cm.gnuplot
# cmap=mpl.cm.viridis
# cmap=mpl.cm.inferno
cmap=mpl.cm.Blues
# cmap=mpl.cm.magma
# cmap=mpl.cm.cividis
# cmap=mpl.cm.gnuplot
# cmap=mpl.cm.gnuplot
cmap = mpl.colors.ListedColormap(["royalblue"], name='from_list', N=None)
# m = cm.ScalarMappable(norm=norm, cmap=cmap)
# m = cm.ScalarMappable(cmap=cmap)
# cmap = cm.brg(Z)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=8)
# ##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
# epsilon = 0.1
# # ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# # ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# # ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color='gray', zorder=5)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color='gray', zorder=5)#yellow
line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=2)
# CS = ax.contour(X_1,Y_1,Z1, colors='k', levels=18, linewidths=(0.5,))
start = np.array([abar[0,499],abar[1,499],Z_bar[499]])
end = np.array([abar[0,500],abar[1,500],Z_bar[500]])
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.scatter(X_1,Y_1,Z1, s=0.2)
# ax.scatter(X_2,Y_2,Z2, s=0.2)
# X = np.concatenate((X_1, X_2), axis=0)
# Y = np.concatenate((Y_1, Y_2), axis=0)
# Z = np.concatenate((Z1, Z2), axis=0)
# ax.plot_surface(X,Y,Z)
ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.75, zorder=5)
ax.plot_surface(X_2,Y_2,Z2 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.75, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , facecolor = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , facecolor = 'lightblue', edgecolor='none', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , #color='C0',
# rstride=1, cstride=1,linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , #color='C0',
# rstride=1, cstride=1,linewidth=0, alpha=0.8, zorder=5, shade=True)
# ax.plot_surface(X_2,Y_2,Z2)
# X_2 = X_2.reshape(-1,1).flatten()
# Y_2 = Y_2.reshape(-1,1).flatten()
# Z2 = Z2.reshape(-1,1).flatten()
# #
# ax.plot_trisurf(X_2,Y_2,Z2, color='blue' )
#
#
# X_1 = X_1.reshape(-1,1).flatten()
# Y_1 = Y_1.reshape(-1,1).flatten()
# Z1 = Z1.reshape(-1,1).flatten()
# ax.plot_trisurf(X_1,Y_1,Z1 , color='blue')
# ax.plot_surface(X_1,Y_1,Z1 , cmap=cmap,
# linewidth=0, antialiased=False,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , cmap=cmap,
# linewidth=0, antialiased=True,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , color = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot(G[0,:],G[1,:],G[2,:])
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='yellow', linestyle='--')
# ax.scatter(abar[0,:],abar[1,:],Z_bar, color='purple', zorder=5)
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='royalblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='dodgerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='cornflowerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='darkorange', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='yellow', linestyle='--')
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=1, color='coral', linestyle='--', zorder=3)
# plot starting point:
# ax.scatter(abar[0,0],abar[1,0],Z_bar[0], marker='^', s=30, color='black', zorder=5)
#
#
# ax.scatter(abar[0,500],abar[1,500],Z_bar[500], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(start[0],start[1],start[2], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(end[0],end[1],end[2], marker='^', s=30, color='purple', zorder=5)
print('start:', start)
print('end:', end)
dir = end-start
# ax.arrow()
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=10,
# arrowstyle="->",
# linestyle='dashed',fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# Check proof:
# value at t = 0:
abar_zero= sstar*abar_tmp
# value_0 = [abar_zero[0], abar_zero[1] , (2*abar_zero[0]*abar_zero[1])**0.5 ]
value_0 = evaluate(abar_zero[0], abar_zero[1])
print('value_0', value_0)
# ax.scatter(value_0[0],value_0[1],value_0[2], marker='x', s=20, color='dodgerblue', zorder=5)
# ax.scatter(abar_zero[0], abar_zero[1],value_0, marker='o', s=30, color='dodgerblue', zorder=5)
## -----------------------------
# ax.scatter(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,Z, tmp2, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_trisurf(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLot x and y- Axes
# ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
# ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=1)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=1)
ax.set_xlabel(r"$a_1$", fontsize=10 ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=10 ,labelpad=0)
# ax.set_ylabel(r"energy")
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
fig.savefig('1-ParameterFamily_G+.pdf')
plt.show()
#
#
#
# # Curve parametrised by \theta_rho = alpha in parameter space
# N=100;
# theta_rho = np.linspace(1, 3, num=N)
# print('theta_rho:', theta_rho)
#
#
# theta_values = []
#
#
# for t in theta_rho:
#
# s = (1.0/10.0)*t+0.1
# theta_values.append(s)
#
#
#
#
#
# theta_rho = np.array(theta_rho)
# theta_values = np.array(theta_values)
#
# betas_ = 2.0
#
# alphas, betas, thetas = np.meshgrid(theta_rho, betas_, theta_values, indexing='ij')
#
#
# harmonicMeanVec = np.vectorize(harmonicMean)
# arithmeticMeanVec = np.vectorize(arithmeticMean)
# prestrain_b1Vec = np.vectorize(prestrain_b1)
# prestrain_b2Vec = np.vectorize(prestrain_b2)
#
# GetMuGammaVec = np.vectorize(GetMuGamma)
# muGammas = GetMuGammaVec(betas,thetas,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
#
# q1_vec = harmonicMeanVec(mu1, betas, thetas)
# q2_vec = arithmeticMeanVec(mu1, betas, thetas)
#
# b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# special case: q12 == 0!! .. braucht eigentlich nur b1 & b2 ...
# print('type b1_values:', type(b1_values))
# print('size(q1)',q1.shape)
#
#
# energy_axial1 = []
# energy_axial2 = []
#
# # for b1 in b1_values:
# for i in range(len(theta_rho)):
# print('index i:', i)
#
# print('theta_rho[i]',theta_rho[i])
# print('theta_values[i]',theta_values[i])
#
# q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta_values[i])
# q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta_values[i])
# q12 = 0.0
# q3 = GetMuGamma(beta, theta_values[i],gamma,mu1,rho1,InputFilePath ,OutputFilePath )
# b1 = prestrain_b1(rho1,beta, theta_rho[i],theta_values[i] )
# b2 = prestrain_b2(rho1,beta, theta_rho[i],theta_values[i] )
#
#
# # q2_vec = arithmeticMean(mu1, betas, thetas)
# #
# # b1_vec = prestrain_b1Vec(rho1, betas, alphas, thetas)
# # b2_vec = prestrain_b2Vec(rho1, betas, alphas, thetas)
# print('q1[i]',q1)
# print('q2[i]',q2)
# print('q3[i]',q3)
# print('b1[i]',b1)
# print('b2[i]',b2)
# # print('q1[i]',q1[0][i])
# # print('q2[i]',q2[i])
# # print('b1[i]',b1[i])
# # print('b2[i]',b2[i])
# #compute axial energy #1 ...
#
# a_axial1 = np.array([b1,0])
# a_axial2 = np.array([0,b2])
# b = np.array([b1,b2])
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a_axial1)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial1',a_axial1)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial1.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial1.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_1 = tmp - tmp2
# print('energy_1',energy_1)
#
#
# energy_axial1.append(energy_1)
#
#
# tmp = H.dot(a_axial2)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a_axial2',a_axial2)
# print('tmp',tmp)
#
# tmp = (1/2)*a_axial2.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a_axial2.dot(tmp2)
#
# print('tmp2',tmp2)
# energy_2 = tmp - tmp2
# print('energy_2',energy_2)
#
#
# energy_axial2.append(energy_2)
#
#
#
#
#
# print('theta_values', theta_values)
#
#
#
#
#
#
#
# kappas = []
# alphas = []
# # G.append(float(s[0]))
#
#
#
#
# for t in T :
#
# abar_current = sstar*abar+t*abarperp;
# # print('abar_current', abar_current)
# abar_current[abar_current < 1e-10] = 0
# # print('abar_current', abar_current)
#
# # G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
#
# e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
# kappa = abar_current[0]+abar_current[1]
# alpha = math.atan2(e[1], e[0])
#
# print('angle current:', alpha)
#
# kappas.append(kappa)
# alphas.append(alpha)
#
#
#
# alphas = np.array(alphas)
# kappas = np.array(kappas)
#
#
# print('kappas:',kappas)
# print('alphas:',alphas)
# print('min alpha:', min(alphas))
# print('min kappa:', min(kappas))
#
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams["font.family"] = "serif"
# mpl.rcParams["font.size"] = "9"
# width = 6.28 *0.5
# height = width / 1.618
# fig = plt.figure()
# # ax = plt.axes((0.15,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.21 ,0.8,0.75))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# # ax.xaxis.set_major_locator(MultipleLocator(0.1))
# # ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# # ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# # ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
#
#
#
#
# ax.plot(alphas, kappas, 'royalblue', zorder=3, )
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
from ClassifyMin import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.proj3d import proj_transform
from mpl_toolkits.mplot3d import proj3d
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
import mayavi.mlab as mlab
from mayavi.api import OffScreenEngine
mlab.options.offscreen = True
from chart_studio import plotly
import plotly.graph_objs as go
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
def evaluate(x,y):
# (abar[0,:]*abar[1,:])**0.5
return np.sqrt(x*y)
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
# scale_domain = 5
# translate_startpoint = -5
scale_domain = 5
translate_startpoint = -1.8
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
# print('type of G', type(G))
# print('G', G)
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
num_Points = 20
num_Points = 50
num_Points = 200
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
range = 2
x_1 = np.linspace(0,range,num_Points)
y_1 = np.linspace(0,range,num_Points)
x_2 = np.linspace(-range,0,num_Points)
y_2 = np.linspace(-range,0,num_Points)
X_1,Y_1 = np.meshgrid(x_1,y_1)
X_2,Y_2 = np.meshgrid(x_2,y_2)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
# print('a1:', a1)
# print('a2:',a2 )
#
# print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
tmp1 = a1[np.where(a1*a2 >= 0)]
tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1 = a1[np.where(a1>=0 and a2 >= 0)]
# tmp2 = a2[np.where(a1>=0 and a2 >= 0)]
# tmp1 = tmp1[np.where(a1 >= 0)]
# tmp2 = tmp2[np.where(a1 >= 0)]
# tmp1_pos = a1[np.where(a1*a2 >= 0)]
# tmp2_neg = a2[np.where(a1*a2 >= 0)]
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
tmp1 = tmp1.reshape(-1,int(tmp1.shape[0]/2))
tmp2 = tmp2.reshape(-1,int(tmp2.shape[0]/2))
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
# Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
#
# Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
# Z = (tmp2**2)/tmp1
Z = np.sqrt(tmp1*tmp2)
Z1 = np.sqrt(X_1*Y_1)
Z2 = np.sqrt(X_2*Y_2)
# Z_bar = np.sqrt(abar[0,:]*abar[1,:])
Z_bar = (abar[0,:]*abar[1,:])**0.5*abar
abar = abar.T
v1 = abar[0,:]
v2 = abar[1,:]
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
evaluateVec = np.vectorize(evaluate)
Z_bar = evaluateVec(abar[0,:],abar[1,:])
# Z = np.sqrt(np.multiply(tmp1,tmp2))
# Z = np.sqrt(a1*a2)
print('v1.shape', v1.shape)
print('v1', v1)
print('Z:', Z)
print('Z_bar:', Z_bar)
# print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
# plt.style.use('seaborn')
plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
width = 6.28 *0.5
# width = 6.28
height = width / 1.618
height = width
fig = plt.figure()
ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
ax.grid(True,which='major',axis='xy',alpha=0.3)
# ax.grid(False,which='major',alpha=0.3)
# Hide grid lines
# ax.grid(False)
# colorfunction=(B*kappa)
# print('colofunction',colorfunction)
#translate Data
# Z = Z - (Z.max()-Z.min())/2
# Z = Z - 50
# Z = Z - 500
#
# Z = Z.T
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
# print('Value of c:', c)
# print('Z.min()', Z.min())
# print('Z.max()', Z.max())
# norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
# print('norm:', norm)
# print('type of norm', type(norm))
# print('norm(0):', norm(0))
# print('norm(Z):', norm(Z))
# ax.plot(theta_rho, theta_values, 'royalblue', zorder=3, )
# ax.scatter(a1,a2, s=0.5)
# ax.scatter(tmp1_pos,tmp2_pos, s=0.5)
# ax.scatter(tmp1_neg,tmp2_neg, s=0.5)
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=100 )
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=20 )
# sns.kdeplot(np.array([a1, a2, Z]))
# sns.kdeplot(tmp1_pos,tmp2_pos,Z_pos)
# levels = [-5.0, -4, -3, 0.0, 1.5, 2.5, 3.5]
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, corner_mask=True,levels=levels)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot(norm(Z)), corner_mask=True)
# CS = ax.contour(a1, a2, Z, cm.brg(norm(Z)), levels=20)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot, levels=20)
# CS = ax.contour(a1, a2, Z, colors='k', levels=14, linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z, colors='k', levels=18, linewidths=(0.5,))
# ax.contour(negZ_a1, negZ_a2, negativeValues, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1_in, a2_in, Z_in, colors='k', linewidths=(0.5,))
# df = pd.DataFrame(data=Z_in, columns=a1_in, index=a2_in)
# df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
# columns=['a', 'b', 'c'])
# sns.kdeplot(data=df2, x="waiting", y="duration")
# sns.kdeplot(data=df2)
# CS = ax.contour(a1, a2, Z, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k', extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k')
#
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, levels=10 )
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, corner_mask=True)
#
# CS = ax.contour(a1, a2, Z,10, colors = 'k')
# ax.clabel(CS, inline=True, fontsize=4)
# cmap = cm.brg(norm(Z))
#
# C_map = cm.inferno(norm(Z))
# ax.imshow(Z, cmap=C_map, extent=[-20, 20, -20, 20], origin='lower', alpha=0.5)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20], origin='lower',
# cmap='bwr', alpha=0.8)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', vmin=Z.min(), vmax=Z.max(),
# cmap='bwr', alpha=0.6)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
cmap=mpl.cm.RdBu_r
# cmap=mpl.cm.viridis_r
cmap=mpl.cm.bwr
# # cmap=mpl.cm.coolwarm
# # cmap=mpl.cm.gnuplot
# cmap=mpl.cm.viridis
# cmap=mpl.cm.inferno
cmap=mpl.cm.Blues
# cmap=mpl.cm.magma
# cmap=mpl.cm.cividis
# cmap=mpl.cm.gnuplot
# cmap=mpl.cm.gnuplot
cmap = mpl.colors.ListedColormap(["royalblue"], name='from_list', N=None)
# m = cm.ScalarMappable(norm=norm, cmap=cmap)
# m = cm.ScalarMappable(cmap=cmap)
# cmap = cm.brg(Z)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=8)
# ##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
# epsilon = 0.1
# # ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# # ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# # ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color='gray', zorder=5)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color='gray', zorder=5)#yellow
print('abar', abar)
print('abar.shape',abar.shape)
line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=1)
# CS = ax.contour(X_1,Y_1,Z1, colors='k', levels=18, linewidths=(0.5,))
start = np.array([abar[0,499],abar[1,499],Z_bar[499]])
end = np.array([abar[0,500],abar[1,500],Z_bar[500]])
# idx = np.where(np.round(Z_bar,3) == np.round( 0.03581463,3) )
idx = np.where(np.round(Z_bar,3) == np.round( 0.02823972,3) )
print('idx[0][0]', idx[0][0])
# abar_1 = abar[0,0:idx[0][0]]
# abar_2 = abar[1,0:idx[0][0]]
line = ax.plot(abar[0,idx[0][0]:-1],abar[1,idx[0][0]:-1],Z_bar[idx[0][0]:-1], linewidth=2, color='coral', zorder=5)
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.scatter(X_1,Y_1,Z1, s=0.2)
# ax.scatter(X_2,Y_2,Z2, s=0.2)
# X = np.concatenate((X_1, X_2), axis=0)
# Y = np.concatenate((Y_1, Y_2), axis=0)
# Z = np.concatenate((Z1, Z2), axis=0)
# ax.plot_surface(X,Y,Z)
ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
ax.plot_surface(X_2,Y_2,Z2 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , facecolor = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , facecolor = 'lightblue', edgecolor='none', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , #color='C0',
# rstride=1, cstride=1,linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , #color='C0',
# rstride=1, cstride=1,linewidth=0, alpha=0.8, zorder=5, shade=True)
# ax.plot_surface(X_2,Y_2,Z2)
# X_2 = X_2.reshape(-1,1).flatten()
# Y_2 = Y_2.reshape(-1,1).flatten()
# Z2 = Z2.reshape(-1,1).flatten()
#
# ax.plot_trisurf(X_2,Y_2,Z2, color='blue' )
# X_1 = X_1.reshape(-1,1).flatten()
# Y_1 = Y_1.reshape(-1,1).flatten()
# Z1 = Z1.reshape(-1,1).flatten()
# ax.plot_trisurf(X_1,Y_1,Z1 , color='blue')
### MAYAVI TEST
# mlab.figure(bgcolor=(1.0, 1.0, 1.0), size=(1000,1000))
# mlab.view(azimuth=90, elevation=125)
# mlab.view(azimuth=100, elevation=115)
# axes = mlab.axes(color=(0, 0, 0), nb_labels=5)
# mlab.orientation_axes()
# mlab.mesh(X_1, Y_1,Z1, color=(0,0,1) , transparent=True )
# mlab.plot3d(abar[0,:],abar[1,:],Z_bar, line_width=1)
# mlab.mesh(X_2, Y_2,Z2)
# mlab.savefig("./example.png")
### --------------------------------------------
# ax.plot_surface(X_1,Y_1,Z1 , cmap=cmap,
# linewidth=0, antialiased=False,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , cmap=cmap,
# linewidth=0, antialiased=True,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , color = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot(G[0,:],G[1,:],G[2,:])
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='yellow', linestyle='--')
# ax.scatter(abar[0,:],abar[1,:],Z_bar, color='purple', zorder=5)
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='royalblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='dodgerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='cornflowerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='darkorange', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='yellow', linestyle='--')
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=1, color='coral', linestyle='--', zorder=3)
# plot starting point:
# ax.scatter(abar[0,0],abar[1,0],Z_bar[0], marker='^', s=30, color='black', zorder=5)
#
#
# ax.scatter(abar[0,500],abar[1,500],Z_bar[500], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(start[0],start[1],start[2], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(end[0],end[1],end[2], marker='^', s=30, color='purple', zorder=5)
# define origin
o = np.array([0,0,0])
start = np.array([1,0,0])
end = np.array([2.5,0,0])
print('start:', start)
print('end:', end)
dir = end-start
print('dir:', dir)
# ax.arrow()
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=10,
# arrowstyle="->",
# linestyle='dashed',fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0)
# style = ArrowStyle('Fancy', head_length=1, head_width=1.5, tail_width=0.5)
# ADD ARROW:
# a = Arrow3D([start[0], end[0]], [start[1], end[1]], [start[2], end[2]], mutation_scale=15, arrowstyle='-|>', color='darkorange')
# ax.add_artist(a)
## ADD Annotation
ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=12)
# ax.text(0.5, 0.5, "Test")
# ax.text(9, 0, 0, "red", color='red')
### ---- Check proof:
# value at t = 0:
abar_zero= sstar*abar_tmp
# value_0 = [abar_zero[0], abar_zero[1] , (2*abar_zero[0]*abar_zero[1])**0.5 ]
value_0 = evaluate(abar_zero[0], abar_zero[1])
print('value_0', value_0)
# ax.scatter(value_0[0],value_0[1],value_0[2], marker='x', s=20, color='dodgerblue', zorder=5)
# ax.scatter(abar_zero[0], abar_zero[1],value_0, marker='o', s=30, color='dodgerblue', zorder=5)
## -----------------------------
# ax.scatter(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,Z, tmp2, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_trisurf(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLOT X AND Y AXIS:
# ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
# ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=1 ,zorder=5)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=1)
ax.set_xlabel(r"$a_1$", fontsize=10 ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=10 ,labelpad=0)
# ax.get_xaxis().set_visible(False)
# ax = plt.gca(projection="3d")
# ax._axis3don = False
ZL = ax.get_zgridlines()
# ax.set_ylabel(r"energy")
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
fig.savefig('1-ParameterFamily_G+.pdf')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
from ClassifyMin import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.proj3d import proj_transform
from mpl_toolkits.mplot3d import proj3d
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
import mayavi.mlab as mlab
from mayavi.api import OffScreenEngine
mlab.options.offscreen = True
from chart_studio import plotly
import plotly.graph_objs as go
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
def evaluate(x,y):
# (abar[0,:]*abar[1,:])**0.5
return np.sqrt(x*y)
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
# scale_domain = 5
# translate_startpoint = -5
# scale_domain = 5
# translate_startpoint = -1.8
scale_domain = 5
translate_startpoint = -1.8
T_line = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
line_values = []
for t in T_line :
print('sstar*abar+t*abarperp', sstar*abar+t*abarperp)
line_values.append(sstar*abar+t*abarperp)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
# print('type of G', type(G))
# print('G', G)
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
num_Points = 20
num_Points = 50
num_Points = 200
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
range = 2
x_1 = np.linspace(0,range,num_Points)
y_1 = np.linspace(0,range,num_Points)
x_2 = np.linspace(-range,0,num_Points)
y_2 = np.linspace(-range,0,num_Points)
X_1,Y_1 = np.meshgrid(x_1,y_1)
X_2,Y_2 = np.meshgrid(x_2,y_2)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
# print('a1:', a1)
# print('a2:',a2 )
#
# print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
tmp1 = a1[np.where(a1*a2 >= 0)]
tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1 = a1[np.where(a1>=0 and a2 >= 0)]
# tmp2 = a2[np.where(a1>=0 and a2 >= 0)]
# tmp1 = tmp1[np.where(a1 >= 0)]
# tmp2 = tmp2[np.where(a1 >= 0)]
# tmp1_pos = a1[np.where(a1*a2 >= 0)]
# tmp2_neg = a2[np.where(a1*a2 >= 0)]
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
tmp1 = tmp1.reshape(-1,int(tmp1.shape[0]/2))
tmp2 = tmp2.reshape(-1,int(tmp2.shape[0]/2))
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
# Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
#
# Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
# Z = (tmp2**2)/tmp1
Z = np.sqrt(tmp1*tmp2)
Z1 = np.sqrt(X_1*Y_1)
Z2 = np.sqrt(X_2*Y_2)
# Z_bar = np.sqrt(abar[0,:]*abar[1,:])
Z_bar = (abar[0,:]*abar[1,:])**0.5*abar
abar = abar.T
v1 = abar[0,:]
v2 = abar[1,:]
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
evaluateVec = np.vectorize(evaluate)
Z_bar = evaluateVec(abar[0,:],abar[1,:])
# Z = np.sqrt(np.multiply(tmp1,tmp2))
# Z = np.sqrt(a1*a2)
print('v1.shape', v1.shape)
print('v1', v1)
print('Z:', Z)
print('Z_bar:', Z_bar)
# print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
# plt.style.use('seaborn')
plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
width = 6.28 *0.5
# width = 6.28
height = width / 1.618
height = width
fig = plt.figure()
ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
ax.grid(True,which='major',axis='xy',alpha=0.3)
# ax.grid(False,which='major',alpha=0.3)
# Hide grid lines
# ax.grid(False)
# colorfunction=(B*kappa)
# print('colofunction',colorfunction)
#translate Data
# Z = Z - (Z.max()-Z.min())/2
# Z = Z - 50
# Z = Z - 500
#
# Z = Z.T
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
# print('Value of c:', c)
# print('Z.min()', Z.min())
# print('Z.max()', Z.max())
# norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
# print('norm:', norm)
# print('type of norm', type(norm))
# print('norm(0):', norm(0))
# print('norm(Z):', norm(Z))
# ax.plot(theta_rho, theta_values, 'royalblue', zorder=3, )
# ax.scatter(a1,a2, s=0.5)
# ax.scatter(tmp1_pos,tmp2_pos, s=0.5)
# ax.scatter(tmp1_neg,tmp2_neg, s=0.5)
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=100 )
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=20 )
# sns.kdeplot(np.array([a1, a2, Z]))
# sns.kdeplot(tmp1_pos,tmp2_pos,Z_pos)
# levels = [-5.0, -4, -3, 0.0, 1.5, 2.5, 3.5]
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, corner_mask=True,levels=levels)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot(norm(Z)), corner_mask=True)
# CS = ax.contour(a1, a2, Z, cm.brg(norm(Z)), levels=20)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot, levels=20)
# CS = ax.contour(a1, a2, Z, colors='k', levels=14, linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z, colors='k', levels=18, linewidths=(0.5,))
# ax.contour(negZ_a1, negZ_a2, negativeValues, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1_in, a2_in, Z_in, colors='k', linewidths=(0.5,))
# df = pd.DataFrame(data=Z_in, columns=a1_in, index=a2_in)
# df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
# columns=['a', 'b', 'c'])
# sns.kdeplot(data=df2, x="waiting", y="duration")
# sns.kdeplot(data=df2)
# CS = ax.contour(a1, a2, Z, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k', extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k')
#
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, levels=10 )
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, corner_mask=True)
#
# CS = ax.contour(a1, a2, Z,10, colors = 'k')
# ax.clabel(CS, inline=True, fontsize=4)
# cmap = cm.brg(norm(Z))
#
# C_map = cm.inferno(norm(Z))
# ax.imshow(Z, cmap=C_map, extent=[-20, 20, -20, 20], origin='lower', alpha=0.5)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20], origin='lower',
# cmap='bwr', alpha=0.8)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', vmin=Z.min(), vmax=Z.max(),
# cmap='bwr', alpha=0.6)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
cmap=mpl.cm.RdBu_r
# cmap=mpl.cm.viridis_r
cmap=mpl.cm.bwr
# # cmap=mpl.cm.coolwarm
# # cmap=mpl.cm.gnuplot
# cmap=mpl.cm.viridis
# cmap=mpl.cm.inferno
cmap=mpl.cm.Blues
# cmap=mpl.cm.magma
# cmap=mpl.cm.cividis
# cmap=mpl.cm.gnuplot
# cmap=mpl.cm.gnuplot
cmap = mpl.colors.ListedColormap(["royalblue"], name='from_list', N=None)
# m = cm.ScalarMappable(norm=norm, cmap=cmap)
# m = cm.ScalarMappable(cmap=cmap)
# cmap = cm.brg(Z)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=8)
# ##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
# epsilon = 0.1
# # ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# # ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# # ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color='gray', zorder=5)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color='gray', zorder=5)#yellow
#### LINE SEGMENTS :
line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=5)
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=1)
# print('abar', abar)
# print('abar.shape',abar.shape)
# start = np.array([abar[0,499],abar[1,499],Z_bar[499]])
# end = np.array([abar[0,500],abar[1,500],Z_bar[500]])
# idx = np.where(np.round(Z_bar,3) == np.round( 0.02823972,3) )
# print('idx[0][0]', idx[0][0])
# line = ax.plot(abar[0,idx[0][0]:-1],abar[1,idx[0][0]:-1],Z_bar[idx[0][0]:-1], linewidth=2, color='coral', zorder=5)
### -----------------------------------
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.scatter(X_1,Y_1,Z1, s=0.2)
# ax.scatter(X_2,Y_2,Z2, s=0.2)
# X = np.concatenate((X_1, X_2), axis=0)
# Y = np.concatenate((Y_1, Y_2), axis=0)
# Z = np.concatenate((Z1, Z2), axis=0)
# ax.plot_surface(X,Y,Z)
ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
ax.plot_surface(X_2,Y_2,Z2 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , facecolor = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , facecolor = 'lightblue', edgecolor='none', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , #color='C0',
# rstride=1, cstride=1,linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , #color='C0',
# rstride=1, cstride=1,linewidth=0, alpha=0.8, zorder=5, shade=True)
# ax.plot_surface(X_2,Y_2,Z2)
# X_2 = X_2.reshape(-1,1).flatten()
# Y_2 = Y_2.reshape(-1,1).flatten()
# Z2 = Z2.reshape(-1,1).flatten()
#
# ax.plot_trisurf(X_2,Y_2,Z2, color='blue' )
# X_1 = X_1.reshape(-1,1).flatten()
# Y_1 = Y_1.reshape(-1,1).flatten()
# Z1 = Z1.reshape(-1,1).flatten()
# ax.plot_trisurf(X_1,Y_1,Z1 , color='blue')
### MAYAVI TEST
# mlab.figure(bgcolor=(1.0, 1.0, 1.0), size=(1000,1000))
# mlab.view(azimuth=90, elevation=125)
# mlab.view(azimuth=100, elevation=115)
# axes = mlab.axes(color=(0, 0, 0), nb_labels=5)
# mlab.orientation_axes()
# mlab.mesh(X_1, Y_1,Z1, color=(0,0,1) , transparent=True )
# mlab.plot3d(abar[0,:],abar[1,:],Z_bar, line_width=1)
# mlab.mesh(X_2, Y_2,Z2)
# mlab.savefig("./example.png")
### --------------------------------------------
# ax.plot_surface(X_1,Y_1,Z1 , cmap=cmap,
# linewidth=0, antialiased=False,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , cmap=cmap,
# linewidth=0, antialiased=True,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , color = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot(G[0,:],G[1,:],G[2,:])
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='yellow', linestyle='--')
# ax.scatter(abar[0,:],abar[1,:],Z_bar, color='purple', zorder=5)
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='royalblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='dodgerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='cornflowerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='darkorange', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='yellow', linestyle='--')
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=1, color='coral', linestyle='--', zorder=3)
# plot starting point:
# ax.scatter(abar[0,0],abar[1,0],Z_bar[0], marker='^', s=30, color='black', zorder=5)
#
#
# ax.scatter(abar[0,500],abar[1,500],Z_bar[500], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(start[0],start[1],start[2], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(end[0],end[1],end[2], marker='^', s=30, color='purple', zorder=5)
# define origin
o = np.array([0,0,0])
start = np.array([1,0,0])
end = np.array([2.5,0,0])
print('start:', start)
print('end:', end)
dir = end-start
print('dir:', dir)
# ax.arrow()
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=10,
# arrowstyle="->",
# linestyle='dashed',fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0)
# style = ArrowStyle('Fancy', head_length=1, head_width=1.5, tail_width=0.5)
# ADD ARROW:
# a = Arrow3D([start[0], end[0]], [start[1], end[1]], [start[2], end[2]], mutation_scale=15, arrowstyle='-|>', color='darkorange')
# ax.add_artist(a)
## ADD Annotation
# ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=12)
ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=15)
# ax.text(0.5, 0.5, "Test")
# ax.text(9, 0, 0, "red", color='red')
### ---- Check proof:
# value at t = 0:
abar_zero= sstar*abar_tmp
# value_0 = [abar_zero[0], abar_zero[1] , (2*abar_zero[0]*abar_zero[1])**0.5 ]
value_0 = evaluate(abar_zero[0], abar_zero[1])
print('value_0', value_0)
# ax.scatter(value_0[0],value_0[1],value_0[2], marker='x', s=20, color='dodgerblue', zorder=5)
# ax.scatter(abar_zero[0], abar_zero[1],value_0, marker='o', s=30, color='dodgerblue', zorder=5)
## -----------------------------
# ax.scatter(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,Z, tmp2, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_trisurf(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLOT X AND Y AXIS:
# ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
# ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=1 ,zorder=5)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=1)
# Plot 1-Parameter Line
line_values= np.array(line_values)
ax.plot(line_values[:,0],line_values[:,1],'k--', linewidth=1,color='orange',alpha=0.8)
ax.set_xlabel(r"$a_1$", fontsize=10 ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=10 ,labelpad=0)
plt.subplots_adjust(left=0.0)
plt.subplots_adjust(bottom=0.25)
# ax.get_xaxis().set_visible(False)
# ax = plt.gca(projection="3d")
# ax._axis3don = False
ZL = ax.get_zgridlines()
# ax.set_ylabel(r"energy")
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
# ax.legend(loc='upper right')
fig.set_size_inches(width, height)
fig.savefig('1-ParameterFamily_G+.pdf')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
import math
import os
import subprocess
import fileinput
import re
import matlab.engine
import sys
# from ClassifyMin import *
from ClassifyMin_New import *
from HelperFunctions import *
# from CellScript import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from vtk.util import numpy_support
from pyevtk.hl import gridToVTK
import time
import matplotlib.ticker as ticker
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator
import pandas as pd
import seaborn as sns
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.proj3d import proj_transform
from mpl_toolkits.mplot3d import proj3d
# from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.text import Annotation
from matplotlib.patches import FancyArrowPatch
import mayavi.mlab as mlab
from mayavi.api import OffScreenEngine
mlab.options.offscreen = True
from chart_studio import plotly
import plotly.graph_objs as go
# from matplotlib import rc
# rc('text', usetex=True) # Use LaTeX font
#
# import seaborn as sns
# sns.set(color_codes=True)
# set the colormap and centre the colorbar
class MidpointNormalize(mcolors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mcolors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
def format_func(value, tick_number):
# find number of multiples of pi/2
# N = int(np.round(2 * value / np.pi))
# if N == 0:
# return "0"
# elif N == 1:
# return r"$\pi/2$"
# elif N == -1:
# return r"$-\pi/2$"
# elif N == 2:
# return r"$\pi$"
# elif N % 2 > 0:
# return r"${0}\pi/2$".format(N)
# else:
# return r"${0}\pi$".format(N // 2)
##find number of multiples of pi/2
N = int(np.round(4 * value / np.pi))
if N == 0:
return "0"
elif N == 1:
return r"$\pi/4$"
elif N == -1:
return r"$-\pi/4$"
elif N == 2:
return r"$\pi/2$"
elif N == -2:
return r"$-\pi/2$"
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
else:
return r"${0}\pi$".format(N // 2)
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def find_nearestIdx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def energy(a1,a2,q1,q2,q12,q3,b1,b2):
a = np.array([a1,a2])
b = np.array([b1,b2])
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
tmp = H.dot(a)
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
tmp2 = A.dot(b)
# print('tmp2',tmp2)
tmp2 = 2*a.dot(tmp2)
# print('tmp2',tmp2)
energy = tmp - tmp2
# print('energy',energy)
# energy_axial1.append(energy_1)
return energy
def evaluate(x,y):
# (abar[0,:]*abar[1,:])**0.5
return np.sqrt(x*y)
# def energy(a1,a2,q1,q2,q12,q3,b1,b2):
#
#
# b = np.array([b1,b2])
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
#
#
# tmp = H.dot(a)
#
# print('H',H)
# print('A',A)
# print('b',b)
# print('a',a)
# print('tmp',tmp)
#
# tmp = (1/2)*a.dot(tmp)
# print('tmp',tmp)
#
# tmp2 = A.dot(b)
# print('tmp2',tmp2)
# tmp2 = 2*a.dot(tmp2)
#
# print('tmp2',tmp2)
# energy = tmp - tmp2
# print('energy',energy)
#
#
# # energy_axial1.append(energy_1)
#
# return energy
#
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
class Annotation3D(Annotation):
def __init__(self, text, xyz, *args, **kwargs):
super().__init__(text, xy=(0, 0), *args, **kwargs)
self._xyz = xyz
def draw(self, renderer):
x2, y2, z2 = proj_transform(*self._xyz, self.axes.M)
self.xy = (x2, y2)
super().draw(renderer)
def _annotate3D(ax, text, xyz, *args, **kwargs):
'''Add anotation `text` to an `Axes3d` instance.'''
annotation = Annotation3D(text, xyz, *args, **kwargs)
ax.add_artist(annotation)
setattr(Axes3D, 'annotate3D', _annotate3D)
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
def _arrow3D(ax, x, y, z, dx, dy, dz, *args, **kwargs):
'''Add an 3d arrow to an `Axes3D` instance.'''
arrow = Arrow3D(x, y, z, dx, dy, dz, *args, **kwargs)
ax.add_artist(arrow)
setattr(Axes3D, 'arrow3D', _arrow3D)
################################################################################################################
################################################################################################################
################################################################################################################
InputFile = "/inputs/computeMuGamma.parset"
OutputFile = "/outputs/outputMuGamma.txt"
# --------- Run from src folder:
path_parent = os.path.dirname(os.getcwd())
os.chdir(path_parent)
path = os.getcwd()
print(path)
InputFilePath = os.getcwd()+InputFile
OutputFilePath = os.getcwd()+OutputFile
print("InputFilepath: ", InputFilePath)
print("OutputFilepath: ", OutputFilePath)
print("Path: ", path)
print('---- Input parameters: -----')
# q1=1;
# q2=2;
# q12=1/2;
# q3=((4*q1*q2)**0.5-q12)/2;
# # H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
#
# H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
# A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
# abar = np.array([q12+2*q3, 2*q2])
# abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
#
# print('abar:',abar)
#
# b = np.linalg.lstsq(A, abar)[0]
# print('b',b)
#
#
# # print('abar:',np.shape(abar))
# # print('np.transpose(abar):',np.shape(np.transpose(abar)))
# sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# # sstar = (1/(q1+q2))*abar.dot(tmp)
# print('sstar', sstar)
# abarperp= np.array([abar[1],-abar[0]])
# print('abarperp:',abarperp)
# -------------------------- Input Parameters --------------------
mu1 = 1.0
rho1 = 1.0
alpha = 5.0
theta = 1.0/2
# theta= 0.1
beta = 5.0
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/2
# # theta= 0.1
# beta = 5.0
#Figure3:
# mu1 = 1.0
# rho1 = 1.0
# alpha = 2.0
# theta = 1.0/8
# # theta= 0.1
# beta = 2.0
# alpha= -5
#set gamma either to 1. '0' 2. 'infinity' or 3. a numerical positive value
gamma = '0'
gamma = 'infinity'
lambda1 = 0.0
print('---- Input parameters: -----')
print('mu1: ', mu1)
print('rho1: ', rho1)
# print('alpha: ', alpha)
print('beta: ', beta)
# print('theta: ', theta)
print('gamma:', gamma)
print('lambda1: ', lambda1)
print('----------------------------')
# ----------------------------------------------------------------
print('----------------------------')
# ----------------------------------------------------------------
q1 = (1.0/6.0)*harmonicMean(mu1, beta, theta)
q2 = (1.0/6.0)*arithmeticMean(mu1, beta, theta)
q12 = 0.0
q3 = GetMuGamma(beta, theta,gamma,mu1,rho1,InputFilePath ,OutputFilePath )
b1 = prestrain_b1(rho1,beta, alpha, theta )
b2 = prestrain_b2(rho1,beta, alpha, theta )
# 1-ParameterFamilyCase:
q1=1;
q2=2;
q12=1/2;
q3=((4*q1*q2)**0.5-q12)/2;
# H=[2*q1,q12+2*q3;q12+2*q3,2*q2];
H = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
A = np.array([[q1,1/2*q12], [1/2*q12,q2] ])
abar = np.array([q12+2*q3, 2*q2])
abar = (1.0/math.sqrt((q12+2*q3)**2+(2*q2)**2))*abar
print('abar:',abar)
b = np.linalg.lstsq(A, abar)[0]
print('b',b)
b1=b[0]
b2=b[1]
# print('abar:',np.shape(abar))
# print('np.transpose(abar):',np.shape(np.transpose(abar)))
sstar = (1/(q1+q2))*abar.dot(A.dot(b))
# sstar = (1/(q1+q2))*abar.dot(tmp)
print('sstar', sstar)
abarperp= np.array([abar[1],-abar[0]])
print('abarperp:',abarperp)
print('----------------------------')
# ----------------------------------------------------------------
N=1000;
# scale_domain = 5
# translate_startpoint = -5
# scale_domain = 5
# translate_startpoint = -1.8
scale_domain = 5
translate_startpoint = -1.8
T_line = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
line_values = []
for t in T_line :
print('sstar*abar+t*abarperp', sstar*abar+t*abarperp)
line_values.append(sstar*abar+t*abarperp)
T = np.linspace(-sstar*(q12+2*q3)/(2*q2), sstar*(2*q2)/(q12+2*q3), num=N)
# T = np.linspace(-sstar*(q12+2*q3)/(2*q2)*scale_domain + translate_startpoint, sstar*(2*q2)/(q12+2*q3)*scale_domain , num=N)
# T = np.linspace(-2,2, num=N)
# print('T:', T)
print('T.min():', T.min())
print('T.max():', T.max())
kappas = []
alphas = []
# G.append(float(s[0]))
G_container = []
abar_container = []
abar_tmp = abar
for t in T :
abar_current = sstar*abar+t*abarperp;
# print('abar_current', abar_current)
abar_current[abar_current < 1e-10] = 0
# print('abar_current', abar_current)
# G = np.array([[2*q1, q12+2*q3], [q12+2*q3,2*q2] ])
G = [abar_current[0], abar_current[1] , (2*abar_current[0]*abar_current[1])**0.5 ]
# print('type of G', type(G))
# print('G', G)
G_container.append(G)
abar_container.append(abar_current)
e = [(abar_current[0]/(abar_current[0]+abar_current[1]))**0.5, (abar_current[1]/(abar_current[0]+abar_current[1]))**0.5]
kappa = abar_current[0]+abar_current[1]
alpha = math.atan2(e[1], e[0])
# print('angle current:', alpha)
kappas.append(kappa)
alphas.append(alpha)
alphas = np.array(alphas)
kappas = np.array(kappas)
# print('G_container', G_container)
G = np.array(G_container)
abar = np.array(abar_container)
print('G', G)
print('abar', abar)
print('abar.shape',abar.shape)
print('q1 = ', q1)
print('q2 = ', q2)
print('q3 = ', q3)
print('q12 = ', q12)
print('b1 = ', b1)
print('b2 = ', b2)
num_Points = 20
num_Points = 50
num_Points = 200
# Creating dataset
x = np.linspace(-5,5,num_Points)
y = np.linspace(-5,5,num_Points)
x = np.linspace(-20,20,num_Points)
y = np.linspace(-20,20,num_Points)
# x = np.linspace(-10,10,num_Points)
# y = np.linspace(-10,10,num_Points)
# x = np.linspace(-60,60,num_Points)
# y = np.linspace(-60,60,num_Points)
#
#
# x = np.linspace(-40,40,num_Points)
# y = np.linspace(-40,40,num_Points)
range = 2
x_1 = np.linspace(0,range,num_Points)
y_1 = np.linspace(0,range,num_Points)
x_2 = np.linspace(-range,0,num_Points)
y_2 = np.linspace(-range,0,num_Points)
X_1,Y_1 = np.meshgrid(x_1,y_1)
X_2,Y_2 = np.meshgrid(x_2,y_2)
a1, a2 = np.meshgrid(x,y)
# geyser = sns.load_dataset("geyser")
# print('type of geyser:', type(geyser))
# print('geyser:',geyser)
ContourRange=20
x_in = np.linspace(-ContourRange,ContourRange,num_Points)
y_in = np.linspace(-ContourRange,ContourRange,num_Points)
a1_in, a2_in = np.meshgrid(x_in,y_in)
# print('a1:', a1)
# print('a2:',a2 )
#
# print('a1.shape', a1.shape)
#-- FILTER OUT VALUES for G+ :
tmp1 = a1[np.where(a1*a2 >= 0)]
tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1 = a1[np.where(a1>=0 and a2 >= 0)]
# tmp2 = a2[np.where(a1>=0 and a2 >= 0)]
# tmp1 = tmp1[np.where(a1 >= 0)]
# tmp2 = tmp2[np.where(a1 >= 0)]
# tmp1_pos = a1[np.where(a1*a2 >= 0)]
# tmp2_neg = a2[np.where(a1*a2 >= 0)]
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
tmp1 = tmp1.reshape(-1,int(tmp1.shape[0]/2))
tmp2 = tmp2.reshape(-1,int(tmp2.shape[0]/2))
print('tmp1.shape',tmp1.shape)
print('tmp1.shape[0]',tmp1.shape[0])
print('tmp2.shape',tmp2.shape)
print('tmp2.shape[0]',tmp2.shape[0])
# np.take(a, np.where(a>100)[0], axis=0)
# tmp1 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = np.take(a1, np.where(a1*a2 >= 0)[0], axis=0)
# tmp2 = a2[np.where(a1*a2 >= 0)]
# tmp1 = a1[a1*a2 >= 0]
# tmp2 = a2[a1*a2 >= 0]
# tmp1_pos = a1[np.where(a1*a2 >= 0) ]
# tmp2_pos = a2[np.where(a1*a2 >= 0) ]
# tmp1_pos = tmp1_pos[np.where(tmp1_pos >= 0)]
# tmp2_pos = tmp2_pos[np.where(tmp2_pos >= 0)]
# tmp1_neg = a1[a1*a2 >= 0 ]
# tmp2_neg = a2[a1*a2 >= 0 ]
# tmp1_neg = tmp1_neg[tmp1_neg < 0]
# tmp2_neg = tmp2_neg[tmp2_neg < 0]
# a1 = tmp1
# a2 = tmp2
#
# a1 = a1.reshape(-1,5)
# a2 = a2.reshape(-1,5)
# tmp1_pos = tmp1_pos.reshape(-1,5)
# tmp2_pos = tmp2_pos.reshape(-1,5)
# tmp1_neg = tmp1_neg.reshape(-1,5)
# tmp2_neg = tmp2_neg.reshape(-1,5)
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
energyVec = np.vectorize(energy)
# Z = energyVec(np.array([a1,a2]),q1,q2,q12,q3,b1,b2)
# Z = energyVec(a1,a2,q1,q2,q12,q3,b1,b2)
#
# Z_in = energyVec(a1_in,a2_in,q1,q2,q12,q3,b1,b2)
# Z = (tmp2**2)/tmp1
Z = np.sqrt(tmp1*tmp2)
Z1 = np.sqrt(X_1*Y_1)
Z2 = np.sqrt(X_2*Y_2)
# Z_bar = np.sqrt(abar[0,:]*abar[1,:])
Z_bar = (abar[0,:]*abar[1,:])**0.5*abar
abar = abar.T
v1 = abar[0,:]
v2 = abar[1,:]
# print('a1:', a1)
# print('a2:',a2 )
# print('a1.shape', a1.shape)
evaluateVec = np.vectorize(evaluate)
Z_bar = evaluateVec(abar[0,:],abar[1,:])
# Z = np.sqrt(np.multiply(tmp1,tmp2))
# Z = np.sqrt(a1*a2)
print('v1.shape', v1.shape)
print('v1', v1)
print('Z:', Z)
print('Z_bar:', Z_bar)
# print('any', np.any(Z<0))
#
# negZ_a1 = a1[np.where(Z<0)]
# negZ_a2 = a2[np.where(Z<0)]
# negativeValues = Z[np.where(Z<0)]
# print('negativeValues:',negativeValues)
#
# print('negZ_a1',negZ_a1)
# print('negZ_a2',negZ_a2)
#
#
# negZ_a1 = negZ_a1.reshape(-1,5)
# negZ_a2 = negZ_a2.reshape(-1,5)
# negativeValues = negativeValues.reshape(-1,5)
#
# Z_pos = energyVec(tmp1_pos,tmp2_pos,q1,q2,q12,q3,b1,b2)
# Z_neg = energyVec(tmp1_neg,tmp2_neg,q1,q2,q12,q3,b1,b2)
# print('Test energy:' , energy(np.array([1,1]),q1,q2,q12,q3,b1,b2))
# print('Z_pos.shape', Z_pos.shape)
## -- PLOT :
mpl.rcParams['text.usetex'] = True
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = "9"
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
# plt.style.use('seaborn')
plt.style.use('seaborn-whitegrid')
# sns.set()
# plt.style.use('seaborn-whitegrid')
label_size = 9
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
mpl.rcParams["font.size"] =10
width = 6.28 *0.5
# width = 6.28
height = width / 1.618
height = width
fig = plt.figure()
ax = plt.axes(projection ='3d', adjustable='box')
# ax = plt.axes((0.17,0.21 ,0.75,0.75))
# ax = plt.axes((0.15,0.18,0.8,0.8))
# ax.tick_params(axis='x',which='major', direction='out',pad=5)
# ax.tick_params(axis='y',which='major', length=3, width=1, direction='out',pad=3)
# ax.xaxis.set_major_locator(MultipleLocator(0.1))
# ax.xaxis.set_minor_locator(MultipleLocator(0.05))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 8))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 16))
# ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
# ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
# ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
# ax.grid(True,which='major',axis='both',alpha=0.3)
ax.grid(True,which='major',axis='xy',alpha=0.3)
# ax.grid(False,which='major',alpha=0.3)
# Hide grid lines
# ax.grid(False)
# colorfunction=(B*kappa)
# print('colofunction',colorfunction)
#translate Data
# Z = Z - (Z.max()-Z.min())/2
# Z = Z - 50
# Z = Z - 500
#
# Z = Z.T
# Substract constant:
# c = (b1**2)*q1+b1*b2*q12+(b2**2)*q2
# Z = Z-c
# print('Value of c:', c)
# print('Z.min()', Z.min())
# print('Z.max()', Z.max())
# norm=mcolors.Normalize(Z.min(),Z.max())
# facecolors=cm.brg(norm)
# print('norm:', norm)
# print('type of norm', type(norm))
# print('norm(0):', norm(0))
# print('norm(Z):', norm(Z))
# ax.plot(theta_rho, theta_values, 'royalblue', zorder=3, )
# ax.scatter(a1,a2, s=0.5)
# ax.scatter(tmp1_pos,tmp2_pos, s=0.5)
# ax.scatter(tmp1_neg,tmp2_neg, s=0.5)
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=100 )
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, levels=20 )
# sns.kdeplot(np.array([a1, a2, Z]))
# sns.kdeplot(tmp1_pos,tmp2_pos,Z_pos)
# levels = [-5.0, -4, -3, 0.0, 1.5, 2.5, 3.5]
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, corner_mask=True,levels=levels)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot(norm(Z)), corner_mask=True)
# CS = ax.contour(a1, a2, Z, cm.brg(norm(Z)), levels=20)
# CS = ax.contour(a1, a2, Z, cmap=plt.cm.gnuplot, levels=20)
# CS = ax.contour(a1, a2, Z, colors='k', levels=14, linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z, colors='k', levels=18, linewidths=(0.5,))
# ax.contour(negZ_a1, negZ_a2, negativeValues, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1_in, a2_in, Z_in, colors='k', linewidths=(0.5,))
# df = pd.DataFrame(data=Z_in, columns=a1_in, index=a2_in)
# df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
# columns=['a', 'b', 'c'])
# sns.kdeplot(data=df2, x="waiting", y="duration")
# sns.kdeplot(data=df2)
# CS = ax.contour(a1, a2, Z, colors='k', linewidths=(0.5,))
# CS = ax.contour(a1, a2, Z,10, cmap=plt.cm.gnuplot, extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k', extend='both', levels=50)
# CS = ax.contourf(a1, a2, Z,10, colors='k')
#
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, levels=10 )
# # CS = ax.contour(tmp1_pos,tmp2_pos, Z_pos,10, cmap=plt.cm.gnuplot, corner_mask=True)
#
# CS = ax.contour(a1, a2, Z,10, colors = 'k')
# ax.clabel(CS, inline=True, fontsize=4)
# cmap = cm.brg(norm(Z))
#
# C_map = cm.inferno(norm(Z))
# ax.imshow(Z, cmap=C_map, extent=[-20, 20, -20, 20], origin='lower', alpha=0.5)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20], origin='lower',
# cmap='bwr', alpha=0.8)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', vmin=Z.min(), vmax=Z.max(),
# cmap='bwr', alpha=0.6)
# ax.imshow(norm(Z), extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
cmap=mpl.cm.RdBu_r
# cmap=mpl.cm.viridis_r
cmap=mpl.cm.bwr
# # cmap=mpl.cm.coolwarm
# # cmap=mpl.cm.gnuplot
# cmap=mpl.cm.viridis
# cmap=mpl.cm.inferno
cmap=mpl.cm.Blues
# cmap=mpl.cm.magma
# cmap=mpl.cm.cividis
# cmap=mpl.cm.gnuplot
# cmap=mpl.cm.gnuplot
cmap = mpl.colors.ListedColormap(["royalblue"], name='from_list', N=None)
# m = cm.ScalarMappable(norm=norm, cmap=cmap)
# m = cm.ScalarMappable(cmap=cmap)
# cmap = cm.brg(Z)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower', norm = norm,
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap='coolwarm', alpha=0.6)
# ax.imshow(Z, extent=[-20, 20, -20, 20],origin='lower',
# cmap=cmap, alpha=0.6)
# divnorm=mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=Z.max())
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower',
# cmap=cmap, alpha=0.6)
# plt.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max()],origin='lower', norm = divnorm,
# cmap=cmap, alpha=0.6)
# COLORBAR :
# cbar = plt.colorbar()
# cbar.ax.tick_params(labelsize=8)
# ##----- ADD RECTANGLE TO COVER QUADRANT :
# epsilon = 0.4
# epsilon = 0.1
# # ax.axvspan(0, x.max(), y.min(), 0, alpha=1, color='yellow', zorder=5)#yellow
# # ax.fill_between([0, x.max()], y.min(), 0, alpha=0.3, color='yellow', zorder=5)#yellow
# # ax.fill_between([x.min(), 0], 0, y.max(), alpha=0.3, color='yellow', zorder=5)#yellow
# ax.fill_between([0+epsilon, x.max()], y.min(), 0-epsilon, alpha=0.7, color='gray', zorder=5)#yellow
# ax.fill_between([x.min(), 0-epsilon], 0+epsilon, y.max(), alpha=0.7, color='gray', zorder=5)#yellow
#### LINE SEGMENTS :
line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=5)
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='coral', zorder=1)
# print('abar', abar)
# print('abar.shape',abar.shape)
# start = np.array([abar[0,499],abar[1,499],Z_bar[499]])
# end = np.array([abar[0,500],abar[1,500],Z_bar[500]])
# idx = np.where(np.round(Z_bar,3) == np.round( 0.02823972,3) )
# print('idx[0][0]', idx[0][0])
# line = ax.plot(abar[0,idx[0][0]:-1],abar[1,idx[0][0]:-1],Z_bar[idx[0][0]:-1], linewidth=2, color='coral', zorder=5)
### -----------------------------------
# ax.plot_surface(a1,a2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.scatter(X_1,Y_1,Z1, s=0.2)
# ax.scatter(X_2,Y_2,Z2, s=0.2)
# X = np.concatenate((X_1, X_2), axis=0)
# Y = np.concatenate((Y_1, Y_2), axis=0)
# Z = np.concatenate((Z1, Z2), axis=0)
# ax.plot_surface(X,Y,Z)
ax.plot_surface(X_1,Y_1,Z1 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
ax.plot_surface(X_2,Y_2,Z2 ,cmap=cmap,
linewidth=0, antialiased=True,alpha=.35, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , facecolor = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , facecolor = 'lightblue', edgecolor='none', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_1,Y_1,Z1 , #color='C0',
# rstride=1, cstride=1,linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , #color='C0',
# rstride=1, cstride=1,linewidth=0, alpha=0.8, zorder=5, shade=True)
# ax.plot_surface(X_2,Y_2,Z2)
# X_2 = X_2.reshape(-1,1).flatten()
# Y_2 = Y_2.reshape(-1,1).flatten()
# Z2 = Z2.reshape(-1,1).flatten()
#
# ax.plot_trisurf(X_2,Y_2,Z2, color='blue' )
# X_1 = X_1.reshape(-1,1).flatten()
# Y_1 = Y_1.reshape(-1,1).flatten()
# Z1 = Z1.reshape(-1,1).flatten()
# ax.plot_trisurf(X_1,Y_1,Z1 , color='blue')
### MAYAVI TEST
# mlab.figure(bgcolor=(1.0, 1.0, 1.0), size=(1000,1000))
# mlab.view(azimuth=90, elevation=125)
# mlab.view(azimuth=100, elevation=115)
# axes = mlab.axes(color=(0, 0, 0), nb_labels=5)
# mlab.orientation_axes()
# mlab.mesh(X_1, Y_1,Z1, color=(0,0,1) , transparent=True )
# mlab.plot3d(abar[0,:],abar[1,:],Z_bar, line_width=1)
# mlab.mesh(X_2, Y_2,Z2)
# mlab.savefig("./example.png")
### --------------------------------------------
# ax.plot_surface(X_1,Y_1,Z1 , cmap=cmap,
# linewidth=0, antialiased=False,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , cmap=cmap,
# linewidth=0, antialiased=True,alpha=1, zorder=5)
# ax.plot_surface(X_2,Y_2,Z2 , color = 'lightblue', #cmap=cmap,
# linewidth=0, antialiased=True, alpha=1, zorder=5)
# ax.plot(G[0,:],G[1,:],G[2,:])
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='yellow', linestyle='--')
# ax.scatter(abar[0,:],abar[1,:],Z_bar, color='purple', zorder=5)
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=2, color='royalblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='dodgerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='cornflowerblue', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='darkorange', linestyle='--')
# ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=3, color='yellow', linestyle='--')
# line = ax.plot(abar[0,:],abar[1,:],Z_bar, linewidth=1, color='coral', linestyle='--', zorder=3)
# plot starting point:
# ax.scatter(abar[0,0],abar[1,0],Z_bar[0], marker='^', s=30, color='black', zorder=5)
#
#
# ax.scatter(abar[0,500],abar[1,500],Z_bar[500], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(start[0],start[1],start[2], marker='^', s=30, color='purple', zorder=5)
# ax.scatter(end[0],end[1],end[2], marker='^', s=30, color='purple', zorder=5)
# define origin
o = np.array([0,0,0])
start = np.array([1,0,0])
end = np.array([2.5,0,0])
print('start:', start)
print('end:', end)
dir = end-start
print('dir:', dir)
# ax.arrow()
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=10,
# arrowstyle="->",
# linestyle='dashed',fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(midpoint_mapped[0],midpoint_mapped[1],midpoint_mapped[2],
# normal[0],normal[1],normal[2],
# mutation_scale=15,
# lw = 1.5,
# arrowstyle="-|>",
# linestyle='dashed',fc='blue',
# ec ='blue',
# zorder = 5)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
# ax.arrow3D(start[0],start[1],start[2],
# dir[0],dir[1],dir[2],
# mutation_scale=20,
# arrowstyle="->",
# fc='coral',
# lw = 1,
# ec ='coral',
# zorder=3)
arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0)
# style = ArrowStyle('Fancy', head_length=1, head_width=1.5, tail_width=0.5)
# ADD ARROW:
# a = Arrow3D([start[0], end[0]], [start[1], end[1]], [start[2], end[2]], mutation_scale=15, arrowstyle='-|>', color='darkorange')
# ax.add_artist(a)
## ADD Annotation
# ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=12)
# ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=15)
ax.text(0, 0, 1.5, r"$\mathcal G^+$", color='royalblue', size=13)
# ax.text(0.5, 0.5, "Test")
# ax.text(9, 0, 0, "red", color='red')
### ---- Check proof:
# value at t = 0:
abar_zero= sstar*abar_tmp
# value_0 = [abar_zero[0], abar_zero[1] , (2*abar_zero[0]*abar_zero[1])**0.5 ]
value_0 = evaluate(abar_zero[0], abar_zero[1])
print('value_0', value_0)
# ax.scatter(value_0[0],value_0[1],value_0[2], marker='x', s=20, color='dodgerblue', zorder=5)
# ax.scatter(abar_zero[0], abar_zero[1],value_0, marker='o', s=30, color='dodgerblue', zorder=5)
## -----------------------------
# ax.scatter(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_surface(tmp1,Z, tmp2, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot_trisurf(tmp1,tmp2, Z, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
# ax.plot(theta_rho, energy_axial1, 'royalblue', zorder=3, label=r"axialMin1")
# ax.plot(theta_rho, energy_axial2, 'forestgreen', zorder=3, label=r"axialMin2")
# ax.plot(-1.0*alphas, kappas, 'red', zorder=3, )
# lg = ax.legend(bbox_to_anchor=(0.0, 0.75), loc='upper left')
### PLOT X AND Y AXIS:
# ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=0.5)
# ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=0.5)
ax.plot(ax.get_xlim(),[0,0],'k--', linewidth=1 ,zorder=5)
ax.plot([0,0],ax.get_ylim(), 'k--', linewidth=1)
# Plot 1-Parameter Line
line_values= np.array(line_values)
ax.plot(line_values[:,0],line_values[:,1],'k--', linewidth=1,color='orange',alpha=0.8)
ax.set_xlabel(r"$a_1$", fontsize=10 ,labelpad=0)
ax.set_ylabel(r"$a_2$", fontsize=10 ,labelpad=0)
# ax.margins(x=0.5, y=-0.25) # Values in (-0.5, 0.0) zooms in to center
# ax.margins(x=0.5, y=0) # Values in (-0.5, 0.0) zooms in to center
plt.subplots_adjust(left=0.0)
plt.subplots_adjust(bottom=0.1)
plt.rcParams["figure.autolayout"] = True
# ax.get_xaxis().set_visible(False)
# ax = plt.gca(projection="3d")
# ax._axis3don = False
ZL = ax.get_zgridlines()
# ax.set_ylabel(r"energy")
# ax.set_xticks([-np.pi/2, -np.pi/4 ,0, np.pi/4, np.pi/2 ])
# labels = ['$0$',r'$\pi/8$', r'$\pi/4$' ,r'$3\pi/8$' , r'$\pi/2$']
# ax.set_yticklabels(labels)
# ax.view_init(elev=30, azim=-65)
# ax.legend(loc='upper right')
# plt.tight_layout()
# fig.tight_layout()
fig.set_size_inches(width, height)
fig.savefig('1-ParameterFamily_G+.pdf')
plt.show()