-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgParameterisationStreamline.py
More file actions
3430 lines (2607 loc) · 113 KB
/
Copy pathAgParameterisationStreamline.py
File metadata and controls
3430 lines (2607 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pylab import *
import struct
import time
#import wavetools as wv
from scipy import interpolate,signal,ndimage
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.stats import norm
import pylab
from IPython.display import display, Math, Latex
from scipy.ndimage import gaussian_filter1d, gaussian_filter, median_filter
import random
import scipy.ndimage
from mpl_toolkits import mplot3d
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import ticker
import math
import plotly.graph_objects as go
import pandas as pd
import plotly.io as pio
#from lmfit import Parameters,minimize, fit_report
from scipy.spatial.transform import Rotation as R
import math as m
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.path import Path
import matplotlib.patches as patches
from skimage import measure
from sklearn.neighbors import KernelDensity
from scipy.interpolate import RegularGridInterpolator
#from mayavi import mlab
import plotly.graph_objects as go
from scipy.spatial import Voronoi
#import pyvista as pv
import matplotlib.colors as mcolors
import copy
import glfw
from glfw.GLFW import *
import OpenGL
import open3d as o3d
import pdb
import seaborn as sns
from PIL import Image
import cv2
import skimage
import skimage.exposure as exposure
import torch
import torch.nn as nn
from skimage.io import imread
from skimage.filters import threshold_otsu
from skimage import color
from skimage.restoration import denoise_bilateral
from skimage.segmentation import slic
from skimage.color import label2rgb
import re
from scipy.spatial.transform import Rotation as R
from scipy.spatial import KDTree
from scipy.interpolate import griddata
import scipy.fftpack as fft
from sklearn.neighbors import KDTree
from scipy.spatial import distance
from scipy.spatial import ConvexHull
from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy
import vtk
#%%
def FS(k_x,k_y,k_z,a,C_0,C_200,C_211,C_220,C_310,C_222,C_321):
Calc=(3
-(np.cos(0.5*a*k_y)*np.cos(0.5*a*k_z)+np.cos(0.5*a*k_z)*np.cos(0.5*a*k_x)+np.cos(0.5*a*k_x)*np.cos(0.5*a*k_y))
+C_200*(3-(np.cos(a*k_y)+np.cos(a*k_z)+np.cos(a*k_x)))
+C_211*(3-((np.cos(a*k_x)*np.cos(0.5*a*k_y)*np.cos(0.5*a*k_z))+(np.cos(a*k_y)*np.cos(0.5*a*k_z)*np.cos(0.5*a*k_x))+(np.cos(a*k_z)*np.cos(0.5*a*k_x)*np.cos(0.5*a*k_y))))
+C_220*(3-((np.cos(a*k_y)*np.cos(a*k_z))+(np.cos(a*k_z)*np.cos(a*k_x))+(np.cos(a*k_x)*np.cos(a*k_y))))
+C_310*(6-((np.cos(1.5*a*k_x)*np.cos(0.5*a*k_y))+(np.cos(1.5*a*k_y)*np.cos(0.5*a*k_z))+(np.cos(1.5*a*k_z)*np.cos(0.5*a*k_x)))
-((np.cos(1.5*a*k_y)*np.cos(0.5*a*k_x))+(np.cos(1.5*a*k_z)*np.cos(0.5*a*k_y))+(np.cos(1.5*a*k_x)*np.cos(0.5*a*k_z))))
+C_222*(1-(np.cos(a*k_x)*np.cos(a*k_y)*np.cos(a*k_z)))
+C_321*(6-((np.cos(1.5*a*k_x)*np.cos(a*k_y)*np.cos(0.5*a*k_z))+(np.cos(1.5*a*k_y)*np.cos(a*k_z)*np.cos(0.5*a*k_x))+(np.cos(1.5*a*k_z)*np.cos(a*k_x)*np.cos(0.5*a*k_y)))
-((np.cos(1.5*a*k_z)*np.cos(a*k_y)*np.cos(0.5*a*k_x))+(np.cos(1.5*a*k_x)*np.cos(a*k_z)*np.cos(0.5*a*k_y))+(np.cos(1.5*a*k_y)*np.cos(a*k_x)*np.cos(0.5*a*k_z))))
)-C_0
return Calc
def cart2lat(k_x,k_y,k_z,revec):
npoints=size(k_x)
cartk=np.zeros([npoints,3])
cartk[:,0]=k_x
cartk[:,1]=k_y
cartk[:,2]=k_z
latk=np.zeros([npoints,3])
if np.linalg.det(revec)==0:
print('inverse revec not exist')
else:
#ndim=len(cartk[0])
inv_revec=np.linalg.inv(revec)
latk[:,0:3]=(np.matmul(revec,cartk[:,0:3].T)).T
latk[:,0:3]=np.round(latk[:,0:3],8)
#latk[:,4:ndim]=cartk[:,4:ndim]
return latk
def lat2cart(latkp,revec): #%latkpt should be n *3 matrix
eps=10**-10
v11=len(latkp)
v22=size(latkp[0])
latk=np.zeros([v22,v11])
latk[:,0]=latkp[0]
latk[:,1]=latkp[1]
latk[:,2]=latkp[2]
cartkp=np.zeros([v22,v11])
cartkp[:,0:3]=np.matmul(revec,latk[:,0:3].T).T
if v22>=4:
cartkp[:,4:v22]=latkp[:,4:v22]
cartkp=np.round(cartkp,12)
return cartkp
# def Plane(plane,npoints,dim):
# k_x=
# k_y=
# k_z=
def PlaneR(a,npoints,plane,order):
RefPlane=[1,1,0]
Rm=np.zeros([3,3])
phi=[]
theta=[]
psi=[]
k_x = k_y = k_z =np.linspace(0,2*np.pi*a,npoints)
#Calculate Rotation Matrix going from RefPlane (n) -> plane (b)
#Normalize Miller Indices to get unit vector
n=RefPlane/np.sqrt(sum(np.square(RefPlane)))
b=plane/np.sqrt(sum(np.square(plane)))
t=np.cross(n,b)/np.sqrt(sum(np.square(np.cross(n,b))))
#Create Rotation Matrix
Rm[:,0]=b
Rm[:,1]=t
Rm[:,2]=n
#Calculate Euler Angles
if order == 'zxz':
# phi = (np.arctan(-Rm[0,2] / Rm[1,2])) #*180/np.pi
# theta = (np.arctan(-Rm[1,2] / (Rm[2,2] *np.cos(phi)))) #*180/np.pi
# psi = (np.arctan(Rm[2,0] / Rm[2,1])) #*180/np.pi
phi = (np.arccos(Rm[2,2]))*180/np.pi
theta = (np.arctan(Rm[0,2] /-Rm[1,2]))*180/np.pi
psi = (np.arctan(Rm[2,0]/Rm[2,1]))*180/np.pi
return Rm
def Rx(theta):
return np.matrix([[ 1, 0 , 0 ],
[ 0, m.cos(theta),-m.sin(theta)],
[ 0, m.sin(theta), m.cos(theta)]])
def Ry(theta):
return np.matrix([[ m.cos(theta), 0, m.sin(theta)],
[ 0 , 1, 0 ],
[-m.sin(theta), 0, m.cos(theta)]])
def Rz(theta):
return np.matrix([[ m.cos(theta), -m.sin(theta), 0 ],
[ m.sin(theta), m.cos(theta) , 0 ],
[ 0 , 0 , 1 ]])
def lod_mesh_export(mesh, lods, extension):
mesh_lods={}
for i in lods:
mesh_lod = mesh.simplify_quadric_decimation(i)
o3d.io.write_triangle_mesh("lod_"+str(i)+extension, mesh_lod)
mesh_lods[i]=mesh_lod
print("generation of "+str(i)+" LoD successful")
return mesh_lods
def ChangeSampleDensity(array,whichtype,new_length): #1 is defined length, 2 is defined density change
if shape(array)[1] > 3:
array=transpose(np.array(array))
nx=np.arange(0, array.shape[0])
fit = interpolate.interp1d(nx, array, axis=0)
new=[]
#array[:,0]=np.linspace(np.min(array[:,0]),np.max(array[:,0]), len(array))
if whichtype == 1:
new = fit(np.linspace(0, array.shape[0]-1, new_length))
if whichtype == 2:
new = fit(np.linspace(0, array.shape[0]-1, new_length*len(array)))
return new
def zdata(xydata,Rmatrix):
zcol=[]
xyzdata=[]
for i in range(len(xydata)):
zcol.append(np.matmul(Rmatrix[2,0:2],transpose(np.linalg.inv(Rmatrix[0:2,0:2]).dot(xydata[i,0:2])))[0,0])
xyzdata=np.insert(xydata, 2, np.array([zcol]), axis=1)
return xyzdata
# def symnorm(contour):
# contour=np.round(countour,4)
# for i in range(len(contour)):
# indexnumber=np.where((np.round(p[:,0],4)==-np.round(p[0,0],4)) & (np.round(p[:,1],4)==-np.round(p[0,1],4)))[0][0]
def BZCalc(cell,lc):
"""
Generate the Brillouin Zone of a given cell. The BZ is the Wigner-Seitz cell
of the reciprocal lattice, which can be constructed by Voronoi decomposition
to the reciprocal lattice. A Voronoi diagram is a subdivision of the space
into the nearest neighborhoods of a given set of points.
"""
cell= np.linalg.inv(cell).T
cell=cell*lc #0.81293684
cell = np.asarray(cell, dtype=float)
assert cell.shape == (3, 3)
px, py, pz = np.tensordot(cell, np.mgrid[-1:2, -1:2, -1:2], axes=[0, 0])
points = np.c_[px.ravel(), py.ravel(), pz.ravel()]
vor = Voronoi(points)
bz_facets = []
bz_ridges = []
bz_vertices = []
# for rid in vor.ridge_vertices:
# if( np.all(np.array(rid) >= 0) ):
# bz_ridges.append(vor.vertices[np.r_[rid, [rid[0]]]])
# bz_facets.append(vor.vertices[rid])
for pid, rid in zip(vor.ridge_points, vor.ridge_vertices):
# WHY 13 ????
# The Voronoi ridges/facets are perpendicular to the lines drawn between the
# input points. The 14th input point is [0, 0, 0].
if(pid[0] == 13 or pid[1] == 13):
bz_ridges.append(vor.vertices[np.r_[rid, [rid[0]]]])
bz_facets.append(vor.vertices[rid])
bz_vertices += rid
bz_vertices = list(set(bz_vertices))
return vor.vertices[bz_vertices], bz_ridges, bz_facets
def BZPlanes(rlv, version): #version=0 you didnt give the reciprocal lattice vector
if version == 0:
rlv=reclatvec(rlv)
print('You gave the unit cell, reciprocal lattice vector calculated')
else: print('You gave the reciprocal lattice vector')
#G=np.array([np.sum(rlv,axis=1)])
G=np.zeros([1,3])
b1=rlv[0,:]
b2=rlv[1,:]
b3=rlv[2,:]
check=np.zeros([((3**3)-1),3])
counter=0
planes=[]
for i in range(-1,2):
for j in range(-1,2):
for k in range(-1,2):
if i == j == k == 0:
continue
G[0,0]=b1[0]*i+b1[1]*j+b1[2]*k
G[0,1]=b2[0]*i+b2[1]*j+b2[2]*k
G[0,2]=b3[0]*i+b3[1]*j+b3[2]*k
G2=np.array((G[0,0],G[0,1],G[0,2]))
#print(G2)
if (m.dist([0,0,0],G2)/2) <= abs(b1[2]+b2[2]+b3[2]):
planes.append(G2/2)
check[counter,:]=G2
counter=counter+1
planes=np.array(planes)
return planes
def BZCheck(rlv,x,y,z,version): #version=0 you didnt give the reciprocal lattice vector
if version == 0:
rlv=reclatvec(rlv)
print('You gave the unit cell, reciprocal lattice vector calculated')
else: print('You gave the reciprocal lattice vector')
#G=np.array([np.sum(rlv,axis=1)])
G=np.zeros([1,3])
b1=rlv[0,:]
b2=rlv[1,:]
b3=rlv[2,:]
check=np.zeros([((3**3)-1),3])
counter=0
for i in range(-1,2):
for j in range(-1,2):
for k in range(-1,2):
if i == j == k == 0:
continue
G[0,0]=b1[0]*i+b1[1]*j+b1[2]*k
G[0,1]=b2[0]*i+b2[1]*j+b2[2]*k
G[0,2]=b3[0]*i+b3[1]*j+b3[2]*k
G2=np.array([(G[0,0],G[0,1],G[0,2])])
check[counter,:]=G2
counter=counter+1
rtc=[]
for i in range(len(x)):
test=np.array([x[i],y[i],z[i]])
for j in range(len(check)):
rangetest=np.matmul(test,(check[j,:]))
rtc=np.dot(-check[j,:],check[j,:])/2
if abs(rangetest) > abs(rtc):
x[i]=np.nan
y[i]=np.nan
z[i]=np.nan
#FSurf[i]=np.nan
break
return x,y,z
def reclatvec(cell):
assert cell.shape == (3, 3)
rlv=np.zeros([3,3])
a1=np.array([cell[0,:]])
a2=np.array([cell[1,:]])
a3=np.array([cell[2,:]])
nm=(np.dot(a1,(np.cross(a2,a3)).T))
rlv[0,:]=2*np.pi*((np.cross(a2,a3))/nm)
rlv[1,:]=2*np.pi*((np.cross(a3,a1))/nm)
rlv[2,:]=2*np.pi*((np.cross(a1,a2))/nm)
return rlv
def SF(FerSur,Ef,o,IMS):
#IMS=0.001
SF=np.zeros(FerSur.shape)
FerSur=FerSur+Ef
SF=(-1/np.pi)*(IMS)/((o-FerSur)**2+IMS**2)
#noise2 = np.random.poisson(SF,[SF.shape[0],SF.shape[1]])
# noise = np.random.normal(0,np.nanstd(SF),[SF.shape[0],SF.shape[1]])
# pois=SF
# for i in range(len(pois[:,0])):
# for j in range(len(pois[0,:])):
# if SF[i,j]>0:
# pois[i,j]=np.random.poisson(SF[i,j])
# if noise[i,j]>0:
# noise[i,j]=np.random.poisson(noise[i,j])
# SF=(SF*pois)+noise
return SF #pois+noise
def SFFSCont(x,y,SpecFunc,skipcon):
cs=plt.contour(x,y,SpecFunc,50,cmap='viridis')
plt.close()
store=[]
print(len(cs.allsegs))
for i in range(len(cs.allsegs)):
if len(cs.allsegs[i]) == 0: #First few contours are interfering with BZ
continue
if i <= skipcon:
continue
o=np.concatenate(cs.allsegs[i])
store.append(o)
# plt.plot(o[:, 0], o[:, 1],'.', linewidth=2)
# plt.show()
store=np.concatenate(store)
df = pd.DataFrame(store, columns = ["xval", "yval"])
df2 = pd.DataFrame(df[(df['xval']>0) & (df['yval']>0)].groupby("yval").mean())
df2 = df2.reset_index()
df2 = pd.DataFrame(df2.groupby("xval").mean())
df2 = df2.reset_index()
df3 = pd.DataFrame(df[(df['xval']>0) & (df['yval']<0)].groupby("yval").mean())
df3 = df3.reset_index()
df3 = pd.DataFrame(df3.groupby("xval").mean())
df3 = df3.reset_index()
df3 = df3.iloc[::-1]
df4 = pd.DataFrame(df[(df['xval']<0) & (df['yval']>0)].groupby("yval").mean())
df4 = df4.reset_index()
df4 = pd.DataFrame(df4.groupby("xval").mean())
df4 = df4.reset_index()
df5 = pd.DataFrame(df[(df['xval']<0) & (df['yval']<0)].groupby("yval").mean())
df5 = df5.reset_index()
df5 = pd.DataFrame(df5.groupby("xval").mean())
df5 = df5.reset_index()
df5 = df5.iloc[::-1]
df2=df2.append(df3, ignore_index = True)
df2=df2.append(df5, ignore_index = True)
df2=df2.append(df4, ignore_index = True)
avg=df2.to_numpy()
#avg=avg[avg[:,0].argsort()]
store=np.array(store)
return store #avg
def outliers(cont,pointskips,tol): #At the moment the data needs to be ordered so it follows the contour in one direction
distances=[]
cir=[]
shiftedx=[]
orx=[]
ory=[]
orx2=[]
ory2=[]
ol=[]
neck=[]
for i in range(len(cont)):
if i == (len(cont)-1):
distances.append(m.dist(cont[i,:], cont[0,:]))
w=cont[i,0]+((cont[i,0]-cont[0,0])/2)
w1=w
u=cont[i,1]+((cont[i,1]-cont[0,1])/2)
u1=u
d=m.dist(cont[i,:], cont[0,:])
d=abs(d)
else:
distances.append(m.dist(cont[i,:], cont[i+1,:]))
w=cont[i,0]+((cont[i+1,0]-cont[i,0])/2)
w1=w
u=cont[i,1]+((cont[i+1,1]-cont[i,1])/2)
u1=u
d=m.dist(cont[i,:], cont[i+1,:])
d=abs(d)
ory2.append(u1)
orx2.append(w1)
if i == 0:
dold=d
if d > 50*dold:
#print(i,d)
if i == (len(cont)-2):
d1=m.dist(cont[(len(cont)-1),:], cont[0,:])
d1=abs(d1)
d2=m.dist(cont[i,:], cont[i-1,:])
d2=abs(d2)
if i == (len(cont)-1):
d1=m.dist(cont[0,:], cont[1,:])
d1=abs(d1)
d2=m.dist(cont[i,:], cont[i-1,:])
d2=abs(d2)
else:
d1=m.dist(cont[i+1,:], cont[i+2,:])
d1=abs(d1)
d2=m.dist(cont[i,:], cont[i-1,:])
d2=abs(d2)
#print((d/d2)**2, (d/d1)**2, (((((((d/d2)**2+(d/d1)**2)**2)*d2**2)**2)*d1**2)**2),i,'\n',d,d1,d2)
if (((d/d2)**2)*((d/d1)**2)) > 1000**2 and (((((((d/d2)**2+(d/d1)**2)**2)*d2**2)**2)*d1**2)**2) > 0.9 :
neck.append(i)
continue
else:
ol.append(i)
#print(d,d1,d2,i)
#print((d/d2)**2, (d/d1)**2, (((((((d/d2)**2+(d/d1)**2)**2)*d2**2)**2)*d1**2)**2),i)
s=w**2+u**2
w=np.sqrt(w**2/s)*d*(w1/abs(w1))
u=np.sqrt(u**2/s)*d*(u1/abs(u1))
cir.append(u)
shiftedx.append(w)
ory.append(u1)
orx.append(w1)
dold=d
distances=np.array(distances)
ory=np.array(ory)
orx=np.array(orx)
ory2=np.array(ory2)
orx2=np.array(orx2)
shiftedx=np.array(shiftedx)
cir=np.array(cir)
neck=np.array(neck)
mx=np.where(np.sqrt(cir**2+shiftedx**2) == np.amax(np.sqrt(cir**2+shiftedx**2)))[0][0]
scale=((cont[mx,0]**2+cont[mx,1]**2)*1.2)/max((np.sqrt(cir**2+shiftedx**2)))
s=orx**2+ory**2
cirx=np.sqrt(orx**2/4)*(orx/abs(orx))
ciry=np.sqrt(ory**2/4)*(ory/abs(ory))
shiftedx=(np.array(shiftedx)*scale)+cirx
cir=(np.array(cir)*scale)+ciry
s=orx2**2+ory2**2
cirx2=np.sqrt(orx2**2/4)*(orx2/abs(orx2))
ciry2=np.sqrt(ory2**2/4)*(ory2/abs(ory2))
average=sum(distances)/len(distances)
s=cont[:,0]**2+cont[:,1]**2
w=(np.sqrt(cont[:,0]**2/s)*average*(cont[:,0]/abs(cont[:,0]))*scale)+cirx2
u=(np.sqrt(cont[:,1]**2/s)*average*(cont[:,1]/abs(cont[:,1]))*scale)+ciry2
for j in range(pointskips):
pointsskipped=j
for i in range(len(cont)):
if i >= (len(cont)-pointsskipped-1):
p=abs(m.dist(cont[i-(1+pointsskipped),:], cont[i,:]))+abs(m.dist(cont[i,:], cont[0+(pointsskipped+(1-len(cont))),:]))
else:
p=abs(m.dist(cont[i-(1+pointsskipped),:], cont[i,:]))+abs(m.dist(cont[i,:], cont[i+(1+pointsskipped),:]))
if p > (average*2*(1+pointsskipped)):
ol.append(i)
ol.append(i-(1+pointsskipped))
ol.append(i+(1+pointsskipped))
ol=np.array(ol)
ol = [i for i in ol if i not in neck]
for i in range(len(ol)):
if ol[i] > (len(cont)-1):
ol[i]=ol[i]-len(cont)
df = pd.DataFrame(ol, columns = ["position"])
df=df.groupby(["position"])["position"].count().reset_index(name="count")
ol=df.to_numpy()
olp=cont[ol[:,0],:]
cmap = mcolors.LinearSegmentedColormap.from_list("mymap", ["yellow","orange","red"])
plt.figure(figsize=(5, 3), dpi=200)
plt.xlim(np.min(cont[:,0])*1.5,np.max(cont[:,0])*1.5)
plt.ylim(np.min(cont[:,1])*1.5,np.max(cont[:,1])*1.5)
plt.title('Extracted Contour with distance between points')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(cont[:,0],cont[:,1],'.', linewidth=2,label='SF Contour')
plt.plot([cirx[0], shiftedx[0]], [ciry[0], cir[0]],color='purple',label='Distance between points')
plt.plot([cirx, shiftedx], [ciry, cir],color='purple')
#plt.plot([np.zeros(len(shiftedx)), shiftedx], [np.zeros(len(cir)), cir])
plt.plot(w,u,'.', linewidth=2, color='orange', label='Average')
plt.scatter(olp[:,0],olp[:,1],c=ol[:,1],linewidth=2,vmin=np.min(ol[:,1]), vmax=np.max(ol[:,1]),cmap=cmap, label='SF Contour Outlier Chance')
plt.legend(loc='lower right',prop={'size': 5})
plt.show()
threshold=np.round(tol*np.max(ol[:,1]))
ol=ol[ol[:,1] >= threshold]
cont=np.delete(cont, ol[:,0], axis=0)
return cont,neck
def orthogonal_points(coords, s):
"""Given a tuple coords containing two 2-dimensional points and also
given a positive number s, return two other distinct points such
that the line segment between each output point and coords[0] is
orthogonal (perpendicular) to the line segment between coords[0] and
coords[1] and the distance from each output point to coords[0] is s.
"""
(point1x, point1y), (point2x, point2y) = coords
points_vectorx, points_vectory = point2x - point1x, point2y - point1y
points_vector_length = math.hypot(points_vectorx, points_vectory)
normalized_x, normalized_y = (points_vectorx * s / points_vector_length,
points_vectory * s / points_vector_length)
newpoint1x, newpoint1y = point1x + normalized_y, point1y - normalized_x
newpoint2x, newpoint2y = point1x - normalized_y, point1y + normalized_x
return ([newpoint1x, newpoint1y], [newpoint2x, newpoint2y])
def display_inlier_outlier(cloud, ind):
inlier_cloud = cloud.select_by_index(ind)
outlier_cloud = cloud.select_by_index(ind, invert=True)
print("Showing outliers (red) and inliers (gray): ")
outlier_cloud.paint_uniform_color([1, 0, 0])
inlier_cloud.paint_uniform_color([0.8, 0.8, 0.8])
o3d.visualization.draw([inlier_cloud, outlier_cloud],show_skybox=False, bg_color=(0.0, 0.0, 0.0, 1.0))
def mirrorfold(sf,x,y):
#x and y are the lines at which the folding happens
dd=[]
# Get all valid indices
idx1 = np.flatnonzero(sf[:,0]>=x)
idx2 = np.flatnonzero(sf[:,0]<=x)
idx3 = np.flatnonzero(sf[:,1]>=y)
idx4 = np.flatnonzero(sf[:,1]<=y)
q1=sf[np.intersect1d(idx1,idx3)]
q2=sf[np.intersect1d(idx2,idx4)]
q3=sf[np.intersect1d(idx3,idx2)]
q4=sf[np.intersect1d(idx4,idx1)]
q=q1
q=np.append(q,(q2*-1),axis=0)
q=np.append(q,(q3*[-1,1]),axis=0)
q=np.append(q,(q4*[1,-1]),axis=0)
dd=q
dd=np.append(dd,(q*-1),axis=0)
dd=np.append(dd,(q*[-1,1]),axis=0)
dd=np.append(dd,(q*[1,-1]),axis=0)
return dd
def kdefilter(d,bndwdth):
kde=KernelDensity(kernel='gaussian', bandwidth=bndwdth).fit(d) #
score=kde.score_samples(d)
plt.axes().set_aspect('equal')
sns.kdeplot(d,x=d[:, 0], y=d[:, 1], cmap="Blues", fill=True, thresh=0.05)
plt.scatter(d[:, 0], d[:, 1],c=score)
plt.colorbar()
plt.show()
lim=input('Select bottom cut off value:') # Get the input
while lim != "": # Loop until it is a blank line
idx = np.flatnonzero(score>=float(lim))
plt.axes().set_aspect('equal')
plt.scatter(d[idx, 0], d[idx, 1],c=score[idx])
plt.colorbar()
plt.show()
lim = input('OPTIONS: \nSelect NEW cut off value,\ntype "redo" to recalculate the KDE for the current cut off or\nhit enter to collect data!:') # Get the input again
if lim == "redo":
d=d[idx,:]
kde2=KernelDensity(kernel='gaussian', bandwidth=bndwdth).fit(d) #
score=kde2.score_samples(d)
plt.axes().set_aspect('equal')
sns.kdeplot(d,x=d[:, 0], y=d[:, 1], cmap="Blues", fill=True, thresh=0.05)
plt.scatter(d[:, 0], d[:, 1],c=score)
plt.colorbar()
plt.show()
idx = np.flatnonzero(score>=np.min(score))
lim=input('Select bottom cut off value or\nhit enter to collect data!:') # Get the input
d=d[idx,:]
lim=input('Do you want your data downsampled? \n"y" or "n":') # Get the input
if lim == "y": # Loop until it is a blank line
lim=input('How do you want to downsample? \n1: Groups points by corresponding mathcing x then y coordinates. \n2: Uses a radius about a point to average the data within that radius about a point. \n"1" or "2"?:') # Get the input
if lim == "1":
db4=d
df = pd.DataFrame(d, columns = ["xval", "yval"])
df2 = pd.DataFrame(df[(df['xval']>0) & (df['yval']>0)].groupby("yval").mean())
df2 = df2.reset_index()
df2 = pd.DataFrame(df2.groupby("xval").mean())
df2 = df2.reset_index()
df3 = pd.DataFrame(df[(df['xval']>0) & (df['yval']<0)].groupby("yval").mean())
df3 = df3.reset_index()
df3 = pd.DataFrame(df3.groupby("xval").mean())
df3 = df3.reset_index()
df3 = df3.iloc[::-1]
df4 = pd.DataFrame(df[(df['xval']<0) & (df['yval']>0)].groupby("yval").mean())
df4 = df4.reset_index()
df4 = pd.DataFrame(df4.groupby("xval").mean())
df4 = df4.reset_index()
df5 = pd.DataFrame(df[(df['xval']<0) & (df['yval']<0)].groupby("yval").mean())
df5 = df5.reset_index()
df5 = pd.DataFrame(df5.groupby("xval").mean())
df5 = df5.reset_index()
df5 = df5.iloc[::-1]
df2=df2.append(df3, ignore_index = True)
df2=df2.append(df5, ignore_index = True)
df2=df2.append(df4, ignore_index = True)
d=df2.to_numpy()
plt.rcParams['figure.figsize'] = [10,8]
plt.plot(db4[:, 0], db4[:, 1],'.', linewidth=1,label='Before.',)
plt.plot(d[:, 0], d[:, 1],'.', linewidth=2,label='After',)
plt.legend()
plt.show()
if lim == "2":
cpoint=np.flatnonzero(score>=(max(score)*0.80))[0]
radest=m.dist(d[cpoint,:], d[cpoint+1,:])*1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
plt.scatter(d[:, 0], d[:, 1],c='black')
plt.scatter(d[cpoint, 0], d[cpoint, 1],c='red')
ax1.add_patch(patches.Circle((d[cpoint, 0], d[cpoint, 1]), radest, color='g', linewidth=1, fill=False))
plt.show()
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
plt.xlim(d[cpoint, 0]-(radest*2),d[cpoint, 0]+(radest*2))
plt.ylim(d[cpoint, 1]-(radest*2),d[cpoint, 1]+(radest*2))
plt.scatter(d[:, 0], d[:, 1],c='black')
plt.scatter(d[cpoint, 0], d[cpoint, 1],c='red')
ax1.add_patch(patches.Circle((d[cpoint, 0], d[cpoint, 1]), radest, color='g', linewidth=1, fill=False))
plt.show()
print(radest)
lim=input('Input Radius? \n"y" or "n":') # Get the input
if lim=="y":
radestnew=input('Radius:')
#radestnew=radest
while radestnew !=" ":
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
plt.xlim(d[cpoint, 0]-(radestnew*2),d[cpoint, 0]+(radestnew*2))
plt.ylim(d[cpoint, 1]-(radestnew*2),d[cpoint, 1]+(radestnew*2))
plt.scatter(d[:, 0], d[:, 1],c='black')
plt.scatter(d[cpoint, 0], d[cpoint, 1],c='red')
ax1.add_patch(patches.Circle((d[cpoint, 0], d[cpoint, 1]), radestnew, color='g', linewidth=1, fill=False))
ax1.add_patch(patches.Circle((d[cpoint, 0], d[cpoint, 1]), radest, color='r', linewidth=1, fill=False))
plt.show()
radest=radestnew
radestnew=input('Radius (enter to take last value):')
meanx=[]
meany=[]
dhold=np.array(d)
deletemask=np.array(d)
y=0
for y in range(len(dhold)):
if np.isnan(dhold[y,0]) == True:
continue
x=np.where(d==dhold[y,:])[0][0]
maskmap = d-d[x,:]
mask = maskmap[:,0]**2 + maskmap[:,1]**2 <= 0.05**2
deletemask[mask,:]=np.nan
dhold=deletemask #np.delete(dhold,mask,axis=0)
#un-mask center and values below 0
#mask[centerMask]=False
#mask[inputMat<0]=False
#get the mean
meanx.append(np.mean(d[mask,0]))
meany.append(np.mean(d[mask,1]))
deletemask[x,0],deletemask[x,1]=np.mean(d[mask,0]),np.mean(d[mask,1])
#y=y+1
meanx=np.array(meanx)
meany=np.array(meany)
meanAll=np.zeros([len(meanx),2])
meanAll[:,0]=meanx
meanAll[:,1]=meany
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
plt.scatter(d[:, 0], d[:, 1],c='black',label='Old')
plt.scatter(deletemask[:, 0], deletemask[:, 1],c='red',label='Removed')
plt.scatter(meanAll[:, 0], meanAll[:, 1],c='blue',label='New')
plt.legend()
plt.show()
#lim=input('Hit enter to keep! Anything else to retry!:') # Get the input
d=meanAll
lim=input('More KDE? \n"y" or "n":') # Get the input
if lim == "y": # Loop until it is a blank line
kde2=KernelDensity(kernel='gaussian', bandwidth=bndwdth).fit(d) #
score=kde2.score_samples(d)
plt.axes().set_aspect('equal')
sns.kdeplot(d,x=d[:, 0], y=d[:, 1], cmap="Blues", fill=True, thresh=0.05)
plt.scatter(d[:, 0], d[:, 1],c=score)
plt.colorbar()
plt.show()
lim=input('Select bottom cut off value:') # Get the input
while lim != "": # Loop until it is a blank line
idx = np.flatnonzero(score>=float(lim))
plt.axes().set_aspect('equal')
plt.scatter(d[idx, 0], d[idx, 1],c=score[idx])
plt.colorbar()
plt.show()
lim = input('OPTIONS: \nSelect NEW cut off value,\ntype "redo" to recalculate the KDE for the current cut off or\nhit enter to collect data!:') # Get the input again
if lim == "redo":
d=d[idx,:]
kde2=KernelDensity(kernel='gaussian', bandwidth=bndwdth).fit(d) #
score=kde2.score_samples(d)
plt.axes().set_aspect('equal')
sns.kdeplot(d,x=d[:, 0], y=d[:, 1], cmap="Blues", fill=True, thresh=0.05)
plt.scatter(d[:, 0], d[:, 1],c=score)
plt.colorbar()
plt.show()
idx = np.flatnonzero(score>=np.min(score))
lim=input('Select bottom cut off value or\nhit enter to collect data!:') # Get the input
d=d[idx,:]
#Neck checklist:
#Distance between previous 3 nearest neighbours are further than the next neighbour.
#Distance between the point and the edge of the BZ is smaller than the next point.
#The gradient of the 3 previous neighbours
#It can only be a neck if the sandwhiching distance and distance ratios are small and not in the same magnitude
#Use
#1st check to see if a neck may be present if so then we go into more details
distances=[]
for i in range(len(d)):
if i == (len(d)-1):
distances.append(m.dist(d[i,:], d[0,:]))
else:
distances.append(m.dist(d[i,:], d[i+1,:]))
distances=np.array(distances)
distances=abs(distances)
sm=0
neckdetector=False
necklist=[]
ratio=[]
# for i in range(len(distances)):
# sm=sm+distances[i]
# if i == (len(distances)-1):
# if distances[0] > 20*(sm/(i+1)):
# neckdetector=True
# necklist.append(i+1)
# continue
# else:
# ratio.append(distances[i+1]/(sm/(i+1)))
# if distances[i+1] > 20*(sm/(i+1)):
# neckdetector=True
# necklist.append(i+1)
# sm=sm-distances[i+1]
# continue
#ratio=np.array(ratio)
distanceindex=distances.argsort()
for i in range(10):
if distanceindex[-i]==(len(distances)-1):
if (distances[distanceindex[-(i+1)]]/distances[distanceindex[-i]])>=0.80 or (distances[distanceindex[-i]]/distances[distanceindex[-(i-1)]])>=0.80:
if distances[distanceindex[-i]]/(distances[distanceindex[-i]-1]+distances[0])>1.5:
if np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[0]))) or np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[distanceindex[-i]-1]))):
necklist.append(distanceindex[-i])
neckdetector=True
elif i==len(distanceindex):
if (distances[distanceindex[-1]]/distances[distanceindex[-i]])>=0.80 or (distances[distanceindex[-i]]/distances[distanceindex[-(i-1)]])>=0.80:
if distances[distanceindex[-i]]/(distances[distanceindex[-i]-1]+distances[distanceindex[-i]+1])>1:
if np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[distanceindex[-i]+1]))) or np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[distanceindex[-i]-1]))):
necklist.append(distanceindex[-i])
neckdetector=True
else:
if (distances[distanceindex[-(i+1)]]/distances[distanceindex[-i]])>=0.80 or (distances[distanceindex[-i]]/distances[distanceindex[-(i-1)]])>=0.80:
if distances[distanceindex[-i]]/(distances[distanceindex[-i]-1]+distances[distanceindex[-i]+1])>0.9:
if np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[distanceindex[-i]+1]))) or np.floor(np.log10(np.abs(distances[distanceindex[-i]])))>np.floor(np.log10(np.abs(distances[distanceindex[-i]-1]))):
necklist.append(distanceindex[-i])
neckdetector=True
#print(necklist)
necklist=np.array(necklist)
necklist=necklist[necklist.argsort()]
notnecks=[]
if neckdetector==True:
plt.axes().set_aspect('equal')
plt.scatter(d[:, 0], d[:, 1],c='black')
plt.scatter(d[necklist, 0], d[necklist, 1],c='green')
plt.show()
print(len(necklist),'Potential necks found')
lim=input('Are necks present? "y" or "n":') # Get the input
if lim=="y":
#bzp=BZPlanes(rcell*0.92, 1)
# kde2=KernelDensity(kernel='gaussian', bandwidth=bndwdth).fit(d) #
# score=kde2.score_samples(d2[necklist])
# print(score)
for i in range(len(necklist)):
if necklist[i] == 0: #NEED TO ADJUST THIS SO IT CHECKS THE DISTANCE OF THE PREVIOUS POINT AND THE NEXT AND SELECTS THE LARGER DISTANCE
p=1
elif necklist[i] % 2 == 0:
p=1 # Even
else:
p=-1
plt.axes().set_aspect('equal')
#sns.kdeplot(d2,x=d2[:, 0], y=d2[:, 1], cmap="Blues", fill=True, thresh=0.05)
plt.scatter(d[:, 0], d[:, 1],c='black')
plt.scatter(d[necklist[i]:(necklist[i]+p), 0], d[necklist[i]:(necklist[i]+p), 1],c='green')
plt.plot(d[necklist[i]:(necklist[i]+p), 0], d[necklist[i]:(necklist[i]+p), 1],c='red')
plt.colorbar()
plt.show()
lim=input('Is this a neck? "y" or "n"')
if lim == "y":
print('saved')
if lim == "n":
notnecks.append(i)
necklist=np.delete(necklist,notnecks,axis=0)
print(necklist)
return d #,distances,distanceindex
def radMask(index,radius,array):
a,b = index
nx,ny = array.shape
y,x = np.ogrid[-a:nx-a,-b:ny-b]
mask = x*x + y*y <= radius*radius
return mask
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in degrees.
"""
angle=angle*(m.pi/180)
ox, oy = origin
dta=point.copy()
for i in range(len(point)):
px, py = point[i,:]
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
dta[i,0]=qx
dta[i,1]=qy
return dta
def Downsample(d,datatype):
if datatype=='2D':
#meanAll is going to store ~18000 points
meanAll=np.zeros((600,600))
for x in range(600):
for y in range(600):
centerMask=(x,y)
mask=radMask(centerMask,50,d)
#un-mask center and values below 0
mask[centerMask]=False
#mask[d<0]=False
#get the mean
meanAll[x,y]=np.mean(d[mask])
else:
ymin=np.min(d[:,1])
xmin=np.min(d[:,0])
d[:,0]=d[:,0]+abs(xmin)
d[:,1]=d[:,1]+abs(ymin)
cpoint=int(np.round(len(d)/2))
radest=m.dist(d[cpoint,:], d[cpoint+1,:])*1