-
Notifications
You must be signed in to change notification settings - Fork 0
/
meshfitter2D.py
executable file
·1663 lines (1352 loc) · 55.9 KB
/
meshfitter2D.py
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 copy import copy, deepcopy
import numpy as np
from scipy.interpolate import splrep,splint,interp1d
from scipy.optimize import bisect
from random import randint, random
import multiprocessing
import os
pjoin = os.path.join
import fit2D_card as fit2D
import madgraph.various.banner as banner_mod
import madgraph.various.lhe_parser as lhe_parser
def plot (infile,outfile=None):
""" Plot the canvas with the 2D mesh."""
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
x,y,width,height = np.loadtxt(infile, unpack = True)
fig, ax = plt.subplots()
a = 0.
b = 0.
min_x = min(x)
min_y = min(y)
rectangles = []
for i in range(len(x)):
rectangles.append(Rectangle((x[i], y[i]),
width[i],height[i],fill=False))
# if y[i]==min_y:
# a += width[i]
# if x[i]==min_x:
# b += height[i]
tmp_x=x[i]+width[i]
if tmp_x > a:
a = tmp_x
tmp_y=y[i]+height[i]
if tmp_y > b:
b = tmp_y
pc = PatchCollection(rectangles, facecolor='w', edgecolor='b' )
ax.add_collection(pc)
plt.xlim((min_x,a))
plt.ylim((min_y,b))
if not outfile:
plt.show()
else:
plt.savefig(outfile)
plt.close('all')
#===============================================================================
# Basic Geometrical Point in 2-dimensions
#===============================================================================
class Point (object):
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def __str__ (self):
return "({0}, {1})".format(self.x, self.y)
def __add__(self,other):
""" Overwrite the sum operator by applying the
sum component-by-component. The result is a new point."""
return Point(self.x+other.x, self.y+other.y)
def exchange_xy (self):
""" Exchange components: x<->y."""
self.x, self.y = self.y, self.x
def midpoint(self,other):
""" Calculate the middle point of the point with another one.
The result is a new point."""
sum = self+other
return Point(0.5*sum.x,0.5*sum.y)
# overwrite the inequality relations
# ordering priority: first in x variable and in the y one
def cmp (self,other):
if self.x > other.x: return 1
if self.x < other.x: return -1
if self.y > other.y: return 1
if self.y < other.y: return -1
def __eq__(self, other):
return self.cmp(other) == 0
def __le__(self, other):
return self.cmp(other) <= 0
def __ge__(self, other):
return self.cmp(other) >= 0
def __gt__(self, other):
return self.cmp(other) > 0
def __lt__(self, other):
return self.cmp(other) < 0
def __ne__(self, other):
return self.cmp(other) != 0
#===============================================================================
# Point with weight
#===============================================================================
class WeightedPoint (Point):
def __init__(self,x=0,y=0,weight=1):
self.weight = weight
super(WeightedPoint,self).__init__(x,y)
def isincell(self,cell):
""" Return true if the coordinates are within the given cell."""
if self.x < cell.corner.x or \
self.x > cell.corner.x + cell.width : return False
if self.y < cell.corner.y or \
self.y > cell.corner.y + cell.height : return False
return True
#===============================================================================
# Cell class
#===============================================================================
class Cell (object):
"""Class to define the basic element of the 2Dmesh."""
def __init__(self,pos,width,height,x=0):
self.corner = pos
self.width = width
self.height = height
self.weight = 0
if x == 0:
self.pts = []
self.npts = 0
else:
self.pts = []
for pt in x:
if pt.isincell(self):
self.pts.append(pt)
self.weight += pt.weight
self.npts = len(self.pts)
self.weight
def addpts(self,x):
""" Fill the cell with points given as list of WeightedPoints.
Only points whose coordinates are within the cell are added."""
for pt in x:
if pt.isincell(self):
self.pts.append(pt)
self.weight += pt.weight
self.npts += len(self.pts)
def error(self):
""" Compute the total error from the weight of each point."""
tmp = 0
for pt in self.pts:
tmp += pt.weight**2
return np.sqrt(tmp)
def split_vertically(self,xsplit,x1=0,x2=0):
""" Divide a cell into two new cells with a vertical line
starting at a given x coordinate. If the mother cell contains
some points, they will be assigned to the daughter cells."""
if x1 == 0 and x2 == 0:
lcell = Cell(self.corner,xsplit-self.corner.x,self.height)
rcell = Cell(Point(xsplit,self.corner.y),
self.width-xsplit+self.corner.x,self.height)
x1=[]
x2=[]
for pt in self.pts:
if pt.isincell(lcell):
x1.append(pt)
else:
x2.append(pt)
lcell.addpts(x1)
rcell.addpts(x2)
else:
lcell = Cell(self.corner,xsplit-self.corner.x,self.height,x1)
rcell = Cell(Point(xsplit,self.corner.y),
self.width-xsplit+self.corner.x,self.height,x2)
return lcell, rcell
def split_horizontally(self,ysplit,x1=0,x2=0):
""" Divide a cell into two new cells with a horizontal line
starting at a given y coordinate. If the mother cell contains
some points, they will be assigned to the daughter cells."""
if x1 == 0 and x2 == 0:
dcell = Cell(self.corner,self.width,ysplit-self.corner.y)
ucell = Cell(Point(self.corner.x,ysplit),self.width,
self.height-ysplit+self.corner.y)
x1=[]
x2=[]
for pt in self.pts:
if pt.isincell(dcell):
x1.append(pt)
else:
x2.append(pt)
dcell.addpts(x1)
ucell.addpts(x2)
else:
dcell = Cell(self.corner,self.width,ysplit-self.corner.y,x1)
ucell = Cell(Point(self.corner.x,ysplit),self.width,
self.height-ysplit+self.corner.y,x2)
return dcell, ucell
def multi_split_vertically(self,isplit,xsplit):
""" Divide a cell into new cells with a vertical line
starting at a given x coordinate. If the mother cell contains
some points, they will be assigned to the daughter cells."""
self.pts.sort()
subcell = []
corner = self.corner
x=self.pts[:isplit[1]-1]
for i in range(len(isplit)):
subcell.append(Cell(corner,xsplit[i]-corner.x,self.height,x))
corner = Point(xsplit[i],corner.y)
if i != len(isplit)-1:
x=self.pts[isplit[i]-1:isplit[i+1]-1]
x=self.pts[isplit[-1]-1:]
subcell.append(Cell(corner,self.corner.x+self.width-xsplit[-1],self.height,x))
return subcell
def multi_split_horizontally(self,isplit,ysplit):
""" Divide a cell into new cells with a vertically line
starting at a given x coordinate. If the mother cell contains
some points, they will be assigned to the daughter cells."""
for pt in self.pts:
pt.exchange_xy()
self.pts.sort()
for pt in self.pts:
pt.exchange_xy()
subcell = []
corner = self.corner
x=self.pts[:isplit[1]-1]
for i in range(len(isplit)):
subcell.append(Cell(corner,self.width,ysplit[i]-corner.y,x))
# subcell.append(Cell(corner,xsplit[i]-corner.x,self.height,x))
corner = Point(corner.x,ysplit[i])
# corner = Point(xsplit[i],corner.y)
if i != len(isplit)-1:
x=self.pts[isplit[i]-1:isplit[i+1]-1]
x=self.pts[isplit[-1]-1:]
subcell.append(Cell(corner,self.width,self.corner.y+self.height-ysplit[-1],x))
# subcell.append(Cell(corner,self.corner.x+self.width-xsplit[-1],self.height,x))
return subcell
def __str__(self):
s = "Cell : corner={0}, width={1}, height={2}".format(self.corner,
self.width, self.height)
if self.npts==0:
s = s +"\n It is empty"
else:
s = s + "\n It contains {0} points: ".format(self.npts)
for pt in self.pts:
s = s + "\n {0}".format(pt)
return s
#===============================================================================
# 2D Histogram as collection of Cells
#===============================================================================
class CellHistogram(object):
"""Class to define the 2Dmesh as a collection of cells fitted starting
from the data sample."""
def __init__(self, pos, width, height, npts_exit=25 ,suffix=None):
self.cells = []
self.intervals_x = []
self.intervals_y = []
self.canvas = Cell(pos,width,height)
self.npts = 0
self.weight = 0
self.width=width
self.height=height
self.npts_exit=npts_exit
if not suffix:
self.suffix=''
else:
self.suffix='-'+str(suffix)
def add_pts(self,x):
""" Fill the canvas with points given as list of WeightedPoints.
Only points whose coordinates are within the canvas region
are added."""
if self.npts > 0:
print("Error: Histogram is not empty!")
elif False in [isinstance(x[i],WeightedPoint) for i in range(len(x))]:
print("Input Error: Points must be WeightedPoint objects!")
else:
self.canvas.addpts(x)
self.npts = self.canvas.npts
self.weight = self.canvas.weight
def write_cell(self,cell,file):
# check if the cell is almost empty
corner_x = cell.corner.x
corner_y = cell.corner.y
width = cell.width
height = cell.height
peripheral = False
# check whether the cell is on the boundary or not
fac=0.98
epstol = 0.001
wgt = cell.weight
cell.pts.sort()
if self.canvas.corner.x != 0.:
if( abs(corner_x /self.canvas.corner.x -1.) < epstol ):
peripheral = True
weight=0
for pt in cell.pts[::-1]:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
width = width -(cell.pts[isplit+1].x-corner_x)
corner_x = cell.pts[isplit+1].x
if(abs( (corner_x+width)/(self.canvas.corner.x+self.canvas.width) -1.) < epstol):
peripheral = True
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
width = cell.pts[isplit-1].x-corner_x
for pt in cell.pts:
pt.exchange_xy()
cell.pts.sort()
for pt in cell.pts:
pt.exchange_xy()
if self.canvas.corner.y != 0.:
if( abs( corner_y/self.canvas.corner.y -1. ) < epstol ):
peripheral = True
weight=0
for pt in cell.pts[::-1]:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
height = height -(cell.pts[isplit+1].y-corner_y)
corner_y = cell.pts[isplit+1].y
if( abs( (corner_y+height)/(self.canvas.corner.y+self.canvas.height) -1. ) < epstol) :
peripheral = True
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
height = cell.pts[isplit-1].y-corner_y
if not peripheral:
fac=0.98
cell.pts.sort()
wgt = cell.weight
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
while (True):
if( cell.pts[0].x-corner_x < width/2. ):
if ( cell.pts[isplit-1].x-corner_x < width/2. ):
width=width/2.
continue
if( cell.pts[1].x-corner_x > width/2. ):
corner_x = corner_x + width/2.
width=width/2.
continue
break
for pt in cell.pts:
pt.exchange_xy()
cell.pts.sort()
for pt in cell.pts:
pt.exchange_xy()
#wgt = cell.weight
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > fac*wgt):
isplit = cell.pts.index(pt)
break
while (True):
if( cell.pts[0].y-corner_y < height/2. ):
if ( cell.pts[isplit-1].y-corner_y < height/2. ):
height = height/2.
continue
if( cell.pts[1].y-corner_y > height/2. ):
corner_y = corner_y + height/2.
height = height/2.
continue
break
s = str(corner_x) + "\t" + str(corner_y) + "\t" + \
str(width) + "\t" + str(height) + "\n"
file.write(s)
def fit(self,fit_type='cell',start_direction='horizontally',ncores=1):
""" Fit 2Dcell/1Dinterval mesh according to data points distribution. """
method_name = 'fit_' + str(fit_type)
fit_method = getattr(self, method_name)
local_canvas = deepcopy(self.canvas)
canvas=[]
tmp_canvas = []
nstart=1
self.flag_inv_order=False
if (fit_type=='cell'):
if start_direction == 'horizontally':
split = [self.equalweight_split_horizontally,self.equalweight_split_vertically]
elif start_direction == 'vertically':
split = [self.equalweight_split_vertically,self.equalweight_split_horizontally]
if ncores in [2**j for j in range(1,10)]:
canvas.append(local_canvas)
n = int(np.log(ncores)/np.log(2))
if (n%2==0):
for i in range(n/2):
for cell in canvas:
cell1,cell2 = split[0](cell)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = deepcopy(tmp_canvas)
tmp_canvas= []
for cell in canvas:
cell1,cell2 = split[1](cell)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = deepcopy(tmp_canvas)
tmp_canvas= []
else:
cell1,cell2 = split[0](local_canvas)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = deepcopy(tmp_canvas)
tmp_canvas= []
for i in range((n-1)/2):
for cell in canvas:
cell1,cell2 = split[1](cell)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = deepcopy(tmp_canvas)
tmp_canvas= []
for cell in canvas:
cell1,cell2 = split[0](cell)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = deepcopy(tmp_canvas)
tmp_canvas= []
self.flag_inv_order = True
elif (ncores%2==0):
print('Warning: multicores has been tested only for number of cores = 2^j, j integer')
tmp_canvas = self.multi_equalweight_split_vertically(local_canvas,ncores/2)
canvas = tmp_canvas
tmp_canvas= []
for cell in canvas:
cell1,cell2 = self.equalweight_split_horizontally(cell)
tmp_canvas.append(cell1)
tmp_canvas.append(cell2)
canvas = tmp_canvas
tmp_canvas= []
flag_inv_order = True
else:
print('Warning: multicores has been tested only for number of cores = 2^j, j integer')
canvas = self.multi_equalweight_split_horizontally(local_canvas,ncores)
else:
canvas = self.multi_equalweight_split_vertically(local_canvas,ncores)
if (not canvas): exit(-1)
jobs = []
k=0
for i in range(ncores):
p = multiprocessing.Process(target=fit_method, args=(canvas[i],k,nstart,start_direction))
jobs.append(p)
p.start()
k +=1
for p in jobs:
p.join()
method_name = 'combine_result_' + str(fit_type)
combine_method = getattr(self, method_name)
return combine_method(ncores)
def combine_result_cell(self,ncores):
filenames = ['cell_fortran_'+str(i)+'.dat' for i in range(ncores)]
with open('cell_fortran'+str(self.suffix)+'.dat', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
os.remove(fname)
def combine_result_1D_x(self,ncores):
filenames = ['ehist_'+str(i)+'.dat' for i in range(ncores)]
filetmp = 'ehist_tmp.dat'
with open(filetmp, 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
os.remove(fname)
out = open('ehist'+str(self.suffix)+'.dat', 'w')
tmp = np.loadtxt(filetmp, unpack = True)
tmp_T = np.transpose(tmp)
sort = tmp_T[tmp_T[:,0].argsort()]
# x,y,width,height = np.loadtxt('cell_fortran'+str(self.suffix)+'.dat', unpack = True)
# xmin=min(x)
# if xmin > sort[0,0]:
# sort[0,0] = xmin
# c = [x[i]+width[i] for i in range(len(x))]
# xmax = max(c)
# if xmax < sort[-1,1]:
# sort[-1,1]= xmax
for line in sort:
out.write(str(line)[1:-1]+"\n")
os.remove(filetmp)
# def combine_result_1D_y(self,ncores):
# filenames = ['thetahist_'+str(i)+'.dat' for i in range(ncores)]
# filetmp = 'thetahist_tmp.dat'
# with open(filetmp, 'w') as outfile:
# for fname in filenames:
# with open(fname) as infile:
# for line in infile:
# outfile.write(line)
# os.remove(fname)
# out = open('thetahist.dat', 'w')
# tmp = np.loadtxt(filetmp, unpack = True)
# tmp_T = np.transpose(tmp)
# sort = tmp_T[tmp_T[:,0].argsort()]
# for line in sort:
# out.write(str(line)[1:-1]+"\n")
# os.remove(filetmp)
def fit_cell(self,canvas,i,ncores,start_direction):
npts=self.npts
weight_exit = self.npts_exit*self.weight/npts
file = 'cell_fortran_'+str(i)+'.dat'
out = open(file,'w')
# if ncores!=1 :
# cells = self.multi_equalweight_split_vertically(canvas,ncores)
# else:
cells = [canvas]
if start_direction == 'horizontally':
split = [self.equalweight_split_horizontally,self.equalweight_split_vertically]
elif start_direction == 'vertically':
split = [self.equalweight_split_vertically,self.equalweight_split_horizontally]
if self.flag_inv_order==False:
while ( (not cells) == False):
for cell in cells:
if(cell.weight > weight_exit):
cell1, cell2= split[0](cell)
if (cell1.weight > weight_exit):
subcell1, subcell2 = split[1](cell1)
cells.append(subcell1)
cells.append(subcell2)
else:
self.write_cell(cell1,out)
if (cell2.weight > weight_exit):
subcell3, subcell4 = split[1](cell2)
cells.append(subcell3)
cells.append(subcell4)
else:
self.write_cell(cell2,out)
else:
self.write_cell(cell,out)
cells.remove(cell)
else:
while ( (not cells) == False):
for cell in cells:
if(cell.weight > weight_exit):
cell1, cell2= split[1](cell)
if (cell1.weight > weight_exit):
subcell1, subcell2 = split[0](cell1)
cells.append(subcell1)
cells.append(subcell2)
else:
self.write_cell(cell1,out)
if (cell2.weight > weight_exit):
subcell3, subcell4 = split[0](cell2)
cells.append(subcell3)
cells.append(subcell4)
else:
self.write_cell(cell2,out)
else:
self.write_cell(cell,out)
cells.remove(cell)
print('end fit')
out.close()
def fit_1D_x(self,canvas,i,nstart,start_direction):
file = 'ehist_'+str(i)+'.dat'
out = open(file,'w')
cells = [canvas]
npts=self.npts
# weight_exit = self.weight/50.
weight_exit = self.weight/50.
split = [self.equalweight_split_vertically]
while ( (not cells) == False):
for cell in cells:
if(cell.weight > weight_exit):
cell1, cell2= split[0](cell)
cells.append(cell1)
cells.append(cell2)
else:
s = str(cell.corner.x) + "\t" + str(cell.corner.x + cell.width) + "\t" + \
str(cell.weight/cell.width) + "\t" + str(cell.error()/cell.width) + "\n"
out.write(s)
cells.remove(cell)
print('end fit')
out.close()
# def fit_1D_y(self):
# file = 'thetahist_'+str(i)+'.dat'
# out = open(file,'w')
# cells = [canvas]
# npts=self.npts
# weight_exit = self.weight/50
# while ( (not cells) == False):
# for cell in cells:
# if(cell.weight > weight_exit):
# cell1, cell2= self.equalweight_split_horizontally(cell)
# cells.append(cell1)
# cells.append(cell2)
# else:
# s = str(cell.corner.y) + "\t" + str(cell.corner.y + cell.height) + "\t" + \
# str(cell.weight/cell.height) + "\t" + str(cell.error()/cell.height) + "\n"
# cells.remove(cell)
# print('end fit')
def equalweight_split_vertically(self,cell):
""" Split a cell vertically with the criterion of equal weight."""
cell.pts.sort()
isplit = len(cell.pts)/2
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > cell.weight/2):
isplit = cell.pts.index(pt)
break
xsplit = (cell.pts[isplit-1].midpoint(cell.pts[isplit])).x
lcell, rcell = cell.split_vertically(xsplit,
cell.pts[:isplit-1],cell.pts[isplit-1:])
return lcell, rcell
def equalweight_split_horizontally(self,cell):
""" Split a cell horizontally with the criterion of equal weight."""
for pt in cell.pts:
pt.exchange_xy()
cell.pts.sort()
for pt in cell.pts:
pt.exchange_xy()
isplit = len(cell.pts)/2
weight=0
for pt in cell.pts:
weight += pt.weight
if (weight > cell.weight/2):
isplit = cell.pts.index(pt)
break
ysplit = (cell.pts[isplit-1].midpoint(cell.pts[isplit])).y
dcell, ucell = cell.split_horizontally(ysplit,
cell.pts[:isplit-1],cell.pts[isplit-1:])
return dcell,ucell
def multi_equalweight_split_vertically(self,cell,npart):
""" Multi-Split (npart) a cell vertically with the criterion
of equal weight."""
if(npart==1):
return [cell]
cell.pts.sort()
weight=0
isplit=[]
i=1
for pt in cell.pts:
weight += pt.weight
if (weight > i*cell.weight/npart):
isplit.append(cell.pts.index(pt))
i+=1
if (i==npart):
break
xsplit=[]
for i in isplit:
xsplit.append( (cell.pts[i-1].midpoint(cell.pts[i])).x )
return cell.multi_split_vertically(isplit,xsplit)
def multi_equalweight_split_horizontally(self,cell,npart):
""" Multi-Split (npart) a cell horizontally with the criterion
of equal weight."""
if(npart==1):
return [cell]
for pt in cell.pts:
pt.exchange_xy()
cell.pts.sort()
for pt in cell.pts:
pt.exchange_xy()
weight=0
isplit=[]
i=1
for pt in cell.pts:
weight += pt.weight
if (weight > i*cell.weight/npart):
isplit.append(cell.pts.index(pt))
i+=1
if (i==npart):
break
ysplit=[]
for i in isplit:
ysplit.append( (cell.pts[i-1].midpoint(cell.pts[i])).y )
return cell.multi_split_horizontally(isplit,ysplit)
def equalpts_split_vertically(self,i):
""" Split a cell vertically with the criterion of equal number of points."""
y = copy.deepcopy(self.cells[i].pts)
y.sort()
if len(y)%2 == 0:
isplit = len(y)/2
else:
isplit = (len(y)-1)/2+randint(0,1)
xsplit = (y[isplit-1].midpoint(y[isplit])).x
lcell, rcell = self.cells[i].split_vertically(xsplit,
y[:isplit],y[isplit:])
self.cells[i:i+1] = lcell, rcell
def equalpts_split_horizontally(self,i):
""" Split a cell horizontally with the criterion of equal number of points."""
y = copy.deepcopy(self.cells[i].pts)
for pt in y:
pt.exchange_xy()
y.sort()
for pt in y:
pt.exchange_xy()
if len(y)%2 == 0:
isplit = len(y)/2
else:
isplit = (len(y)-1)/2+randint(0,1)
ysplit = (y[isplit-1].midpoint(y[isplit])).y
dcell, ucell = self.cells[i].split_horizontally(ysplit,
y[:isplit],y[isplit:])
self.cells[i:i+1] = dcell, ucell
def plot (self,outfile=None):
""" Plot the canvas with the 2D mesh."""
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
rectangles = []
if not self.cells:
rectangles.append(Rectangle((self.canvas.corner.x, self.canvas.corner.y),
self.canvas.width,self.canvas.height,fill=False))
ax.add_patch(rectangles[0])
else:
for cell in self.cells:
rectangles.append(Rectangle((cell.corner.x, cell.corner.y),
cell.width,cell.height,fill=False))
pc = PatchCollection(rectangles, facecolor='w', edgecolor='b' )
ax.add_collection(pc)
plt.xlim((self.canvas.corner.x,self.width))
plt.ylim((self.canvas.corner.y,self.height))
if not outfile:
plt.show()
else:
plt.savefig(outfile)
class fit2D_energy_theta(CellHistogram):
lpp2 = {'electron' : 0, 'DIS' : 1}
ebeam2 = {'electron' : 0.000511, 'DIS' : 0.938}
def __init__(self,proc_characteristics,input_lhe_evts,interaction_channel):
# load proc info and fit params
self.proc_characteristics = proc_characteristics
self.fit2D_card = fit2D.Fit2DCard(pjoin('fit2D_card.dat'))
self.interaction_channel = interaction_channel
#check for corrupted events
#self.fixLHE(input_lhe_evts)
#store and reweight evts
self.npass,self.E_min,self.E_max,self.theta_min,self.theta_max,self.data = \
self.store_reweight(input_lhe_evts)
super(fit2D_energy_theta,self).__init__(Point(self.E_min,self.theta_min), \
self.E_max-self.E_min,self.theta_max-self.theta_min,self.fit2D_card['npoints_cell'])
self.add_pts(self.data)
self.resol_fac = 3.
def fixLHE(self,inputLHE):
evtsLHEin = lhe_parser.EventFile(inputLHE)
evtsLHEout = lhe_parser.EventFile(path=inputLHE+'-tmp.gz',mode='w')
banner = evtsLHEin.get_banner()
banner.write(evtsLHEout, close_tag=False)
for event in evtsLHEin:
corrupted = False
for particle in event:
p = lhe_parser.FourMomentum(particle)
if(np.isnan(p.E)):
corrupted = True
if not corrupted:
evtsLHEout.write_events(event)
os.system('mv '+inputLHE+'-tmp.gz '+inputLHE)
def heaviside(self,x):
if x>0:
return 1
else:
return 0
def max_travel_distance(self,ctheta,stheta,cphi,sphi):
depth = self.fit2D_card['depth']
z1 = self.fit2D_card['d_target_detector']
z2 = z1 + depth
if (ctheta<0.):
return 0.
else:
theta = np.arccos(ctheta)
# off-axis
# if (self.fit2D_card['off_axis']):
# thetac = self.fit2D_card['thetac']
# delta_theta = self.fit2D_card['theta_aperture']
# yc = z1*np.sin(thetac)
# rcone_proj = z1*(np.sin(thetac+delta_theta)-np.sin(thetac))
# if abs(theta -thetac) > delta_theta:
# return 0.
# r = z1*stheta
# sphi_star = (r**2-rcone_proj**2+yc**2)/(2.*r*yc)
# if sphi < sphi_star:
# return 0.
# else:
# return self.fit2D_card['off_axis_depth']
if (self.fit2D_card['off_axis']):
yc = self.fit2D_card['yc']
r_proj = self.fit2D_card['radius']
thetac = np.arctan(yc/z1)
thetah = np.arctan((yc+r_proj)/z1)
thetal = np.arctan((yc-r_proj)/z1)
if theta>thetah or theta<thetal:
return 0.
r = z1*np.tan(theta)
cphi_star = (r**2-r_proj**2+yc**2)/(2.*r*yc)
#print sphi,cphi_star
if sphi > 0 and sphi > cphi_star:
return depth/ctheta
else:
return 0.
# cylinder detector
if (self.fit2D_card['cylinder']):
# theta_min = self.fit2D_card['theta_min']
# if theta_min!=0.:
# print('Error: theta_min != 0. do not supported!')
# exit(-1)
theta_max = self.fit2D_card['theta_max']
if theta > theta_max: