-
Notifications
You must be signed in to change notification settings - Fork 2
/
ULAP1.0.pyt
837 lines (785 loc) · 39 KB
/
ULAP1.0.pyt
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
# -*- coding: utf-8 -*-
import arcpy, os
import laparcgis7 as d
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
self.label = "Unified Facility Location-Allocation Problems"
self.alias = "Unified Facility Location-Allocation Problems"
# List of tool classes associated with this toolbox
self.tools = [Tool1,Tool2,Tool3]
class Tool1(object):
def __init__(self):
self.label = "Facility Location-Allocation Problems"
self.description = "Facility Location-Allocation Problems"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
feas=arcpy.Parameter(name='feas', displayName='Map layer', datatype='GPFeatureLayer', direction='Input',parameterType='Required')
fld_id=arcpy.Parameter(name='id_fld', displayName='ID field', datatype='Field', direction='Input', parameterType='Required')
fld_id.parameterDependencies = [feas.name]
fld_demand=arcpy.Parameter(name='demand_fld', displayName='Demand field', datatype='Field', direction='Input', parameterType='Required')
fld_demand.parameterDependencies = [feas.name]
fld_supply=arcpy.Parameter(name='supply_fld', displayName='Supply field', datatype='Field', direction='Input', parameterType='Required')
fld_supply.parameterDependencies = [feas.name]
fld_fcost=arcpy.Parameter(name='fcost_fld', displayName='Facility cost', datatype='Field', direction='Input', parameterType='Optional')
fld_fcost.parameterDependencies = [feas.name]
connectivity=arcpy.Parameter(name='connectivity', displayName='connectivity?', datatype='GPBoolean',direction='Input',parameterType='Optional')
connectivity.value=True
#solver,popsize,timelimit,spp
solver=arcpy.Parameter(displayName="Solver", name="Solver", datatype="GPString",parameterType="Required", direction="Input")
solver.filter.type = 'ValueList'
solver.filter.list = ['ils','lr_ils','mip','mip1','mip2']
popsize=arcpy.Parameter(displayName="Pop size/Multistarts", name="popsize", datatype="GPLong",parameterType="Required", direction="Input")
popsize.value=10
timelimit=arcpy.Parameter(displayName="Time limit in seconds", name="timelimit", datatype="GPLong",parameterType="Required", direction="Input")
timelimit.value=300
spp=arcpy.Parameter(displayName="SPP modeling (0,1,2)", name="spp", datatype="GPLong",parameterType="Required", direction="Input")
spp.value=0
locsize=arcpy.Parameter(displayName="Num. of facilities to select", name="locsize", datatype="GPLong",parameterType="Required", direction="Input")
mip_solver=arcpy.Parameter(displayName="MIP Solver", name="mipSolver", datatype="GPString",parameterType="Required", direction="Input")
mip_solver.filter.type = 'ValueList'
slist=d.mip_solvers[:]
slist.append("_")
mip_solver.filter.list = slist
mip_solver.value=slist[0]
outfile=arcpy.Parameter(name='outfile', displayName='Output layer', datatype='DEFeatureClass', direction='Output',parameterType='Required')
operator=arcpy.Parameter(displayName="Search operator", name="operators", datatype="GPString",parameterType="Required", direction="Input")
operator.filter.type = 'ValueList'
operator.filter.list = ['one-unit-move','two-unit-move','three-unit-move']
operator.value='two-unit-move'
distype=arcpy.Parameter(displayName="Distance type", name="distancetype", datatype="GPString",parameterType="Required", direction="Input")
distype.filter.type = 'ValueList'
distype.filter.list = ['Euclidean','Manhattan','User Defined']
distype.value='Euclidean'
networkfile=arcpy.Parameter(displayName="Distance file", name="disfile", datatype="DEFile",parameterType="Optional", direction="Input")
networkfile.enabled=False
return [feas,fld_id,fld_demand, fld_supply, fld_fcost, distype, networkfile, locsize, outfile,connectivity,solver,popsize,timelimit,spp,mip_solver,operator]
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if parameters[5].altered:
if parameters[5].value=='User Defined':
parameters[6]. enabled = True
else:
parameters[6]. enabled = False
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
if arcpy.env.workspace==None:
arcpy.AddMessage("please click the button 'Envronments...', and set the workspace!!!")
return
arcpy.AddMessage("available MIP solvers "+str(d.mip_solvers) )
dataTable=[]
fn=parameters[0].value
if fn.name.find("\\") < 0:
fn=fn.dataSource
#mxd = arcpy.mapping.MapDocument("CURRENT")
#for lyr in arcpy.mapping.ListLayers(mxd):
# if lyr.name == fn:
# fn=lyr.dataSource
# break
desc = arcpy.Describe(fn)
idf=parameters[1].valueAsText
df=parameters[2].valueAsText
sf=parameters[3].valueAsText
fcost_field=parameters[4].valueAsText
if fcost_field=="":
d.fixed_cost_obj=0
else:
d.fixed_cost_obj=1
numf=parameters[7].value
arcpy.AddMessage("reading spatial units ...")
cursor = arcpy.SearchCursor(fn)
row = cursor.next()
idx=0
fcenters=[]
capacities=[]
facilityCost=[]
id2idx={}
x=0.0
y=0.0
while row:
#unit=[idx, x, y, demand, id,cap,cand,cost]
r=[idx,x,y,row.getValue(df),row.getValue(idf),row.getValue(sf),0,0.0]
id2idx[r[4]]=r[0]
if fcost_field != None:
r[7]=row.getValue(fcost_field)
if r[5]>0:
fcenters.append(idx)
capacities.append(r[5])
facilityCost.append(r[7])
dataTable.append(r)
row = cursor.next()
idx+=1
del cursor, row
d.nodes=dataTable
num_units=len(dataTable)
arcpy.env.overwriteOutput = True
geometries = arcpy.CopyFeatures_management(fn, arcpy.Geometry())
for i in range(num_units):
cid=geometries[i].centroid
dataTable[i][1]=cid.X
dataTable[i][2]=cid.Y
#arcpy.AddMessage("units: "+str(dataTable[i]))
arcpy.AddMessage("total demand units: "+str(num_units))
arcpy.AddMessage("total spply units: "+str(len(fcenters)) )
if numf>len(fcenters):
arcpy.AddMessage("too large number of facilities to select, total facilities: "+str(len(fcenters)))
return
#connectivity
ws=arcpy.env.workspace
if ws.find(".gdb"):
ws=os.path.dirname(arcpy.env.workspace)
arcpy.env.workspace=ws
arcpy.AddMessage("searching for neighbor units ... " )
swm="swm.swm"
swmdb="swm.dbf"
if arcpy.Exists(swm): arcpy.Delete_management(swm)
if arcpy.Exists(swmdb): arcpy.Delete_management(swmdb)
if desc.shapeType=='Point':
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm,"DELAUNAY_TRIANGULATION" )
else:
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm, "CONTIGUITY_EDGES_ONLY")
arcpy.ConvertSpatialWeightsMatrixtoTable_stats(swm, swmdb)
unit_neighbors=[[] for x in range(num_units) ]
rows = arcpy.SearchCursor(swmdb)
for row in rows:
id1=row.getValue(idf)
id2=row.getValue("NID")
unit_neighbors[id2idx[id1]].append(id2idx[id2])
del row, rows
#for x in unit_neighbors: arcpy.AddMessage(str(x))
arcpy.AddMessage("calcaulating distance ... " )
dist_ij=[[999999.999 for x in range(num_units) ] for y in range(num_units)]
#['Euclidean','Manhattan','User Defined']
if parameters[5].valueAsText=='User Defined':
dfile=parameters[6].valueAsText
sta=d.readdistance(dfile)
if sta<=0: return
dist_ij=d.nodedij
else:
for i in range(num_units):
for j in range(i,num_units):
if j==i:
dist_ij[i][j]=0.0
continue
d3=0.0
if parameters[5].valueAsText=='Manhattan':
d3= (abs(dataTable[i][1]-dataTable[j][1])+ abs(dataTable[i][2]-dataTable[j][2]))/1000
if parameters[5].valueAsText=='Euclidean':
d2=pow(dataTable[i][1]-dataTable[j][1],2)
d2+=pow(dataTable[i][2]-dataTable[j][2],2)
d3=pow(d2,0.5)/1000
dist_ij[i][j]=d3
dist_ij[j][i]=d3
d.nodes=dataTable
d.node_neighbors=unit_neighbors
d.nodedij=dist_ij
#problem defination
d.location_problem=1
d.pop_dis_coeff=100000.0
d.spatial_contiguity=0
d.allowing_less_facilities=0
d.max_num_facility=len(fcenters)
#numf=d.max_num_facility
if numf>0: d.allowing_less_facilities=0
d.solver_message=0
d.facilityCandidate=fcenters[:]
d.facilityCapacity=capacities[:]
d.facilityCost=facilityCost[:]
#sol=[0 for x in range(num_units)]
#if d.check_continuality_feasibility(sol,0)==0:
# arcpy.AddMessage("the spatial units are not connected!")
# return
arcpy.AddMessage("facilities: "+str(d.facilityCandidate) )
arcpy.AddMessage("capacities: "+str(d.facilityCapacity) )
#arcpy.AddMessage("costs: "+str(d.facilityCost) )
#arcpy.AddMessage("distance: "+str(dist_ij) )
d.spatial_contiguity=1
if parameters[9].value==False: d.spatial_contiguity=0
#initialize instance data
d.initialize_instance()
arcpy.AddMessage("total demand: "+str(d.total_pop) )
arcpy.AddMessage("total supply: "+str(d.total_supply) )
#arcpy.AddMessage(str(d.nodes[0:50]))
#arcpy.AddMessage(str(d.capacities))
#arcpy.AddMessage(str(d.facilityCost))
solver=parameters[10].valueAsText
psize=parameters[11].value
timelimit=parameters[12].value
spp=parameters[13].value
d.mip_solver=parameters[14].valueAsText
if d.mip_solver not in d.mip_solvers:
spp=0
operator=parameters[15].value
if operator=='one-unit-move': d.operators_selected=[0]
if operator=='two-unit-move':d.operators_selected=[0,1]
if operator=='three-unit-move': d.operators_selected=[0,1,2]
arcpy.AddMessage("solving the problem......")
arcpy.SetProgressorLabel("solving the problem......")
results=[]
if solver=='ils':
arcpy.SetProgressorLabel("searching ...")
d.initial_solution_method=0
results=d.ils(numf, psize, timelimit, spp,-1)
if solver=='lr_ils':
arcpy.SetProgressorLabel("searching ...")
d.initial_solution_method=9
results=d.ils(numf, psize, timelimit, spp,-1)
if solver=='mip':
arcpy.SetProgressorLabel("modeling ...")
results=d.mip(numf,d.location_problem,d.spatial_contiguity,timelimit)
if solver=='mip1': #FLP-LR and SAP
arcpy.SetProgressorLabel("modeling ...")
if d.spatial_contiguity==1: results=d.mip(numf,2,1,timelimit)
else:
arcpy.AddMessage("only used for district contiguity")
return
if solver=='mip2':#FLP-MIP and SAP
arcpy.SetProgressorLabel("modeling ...")
if d.spatial_contiguity==1: results=d.mip(numf,3,1,timelimit)
else:
arcpy.AddMessage("only used for district contiguity")
return
if len(results)<=1:
arcpy.AddMessage("Fatal solver error!!!")
if len(results)==1: arcpy.AddMessage(str(results[0]))
biobj=results[0]
obj=results[1]
overload=results[2]
centers=results[3]
sol=results[4]
arcpy.SetProgressorLabel("outputting the service area layer ...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
#arcpy.AddMessage("solution: " +str(sol))
arcpy.env.overwriteOutput = True
newlayer=arcpy.CopyFeatures_management(fn,parameters[8].value)
arcpy.AddField_management(newlayer, "Selected", "Long")
arcpy.AddField_management(newlayer, "SA_ID", "Long")
cursor = arcpy.UpdateCursor(newlayer)
row = cursor.next()
idx=0
while row:
r=sol[idx]
fu=d.centersID[r]
row.setValue("SA_ID", fu)
if idx in centers:
row.setValue("Selected", 1)
else:
row.setValue("Selected", 0)
cursor.updateRow(row)
row = cursor.next()
idx+=1
del cursor, row
arcpy.AddMessage("solution summary...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
arcpy.AddMessage("ServiceAreaId, FacilityID, No.units, total demand, supply, total distance")
for i in range(d.num_districts):
if d.district_info[i][0]<1: continue
arcpy.AddMessage("{0},{1},{2},{3},{4},{5}".format(i,dataTable[d.centersID[i]][4],d.district_info[i][0],d.district_info[i][1],d.district_info[i][3], int(d.district_info[i][2]*1000)/1000.0))
return
class Tool2(object):
def __init__(self):
self.label = "Facility Service Area Problem"
self.description = "Facility Service Area Problem"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
feas=arcpy.Parameter(name='feas', displayName='Map layer', datatype='GPFeatureLayer', direction='Input',parameterType='Required')
fld_id=arcpy.Parameter(name='id_fld', displayName='ID field', datatype='Field', direction='Input', parameterType='Required')
fld_id.parameterDependencies = [feas.name]
fld_demand=arcpy.Parameter(name='demand_fld', displayName='Demand field', datatype='Field', direction='Input', parameterType='Required')
fld_demand.parameterDependencies = [feas.name]
fld_supply=arcpy.Parameter(name='supply_fld', displayName='Supply field', datatype='Field', direction='Input', parameterType='Required')
fld_supply.parameterDependencies = [feas.name]
connectivity=arcpy.Parameter(name='connectivity', displayName='connectivity?', datatype='GPBoolean',direction='Input',parameterType='Optional')
connectivity.value=True
#solver,popsize,timelimit,spp
solver=arcpy.Parameter(displayName="Solver", name="Solver", datatype="GPString",parameterType="Required", direction="Input")
solver.filter.type = 'ValueList'
solver.filter.list = ['ils','lr_ils','mip']
popsize=arcpy.Parameter(displayName="Pop size/Multistarts", name="popsize", datatype="GPLong",parameterType="Required", direction="Input")
popsize.value=10
timelimit=arcpy.Parameter(displayName="Time limit in seconds", name="timelimit", datatype="GPLong",parameterType="Required", direction="Input")
timelimit.value=300
spp=arcpy.Parameter(displayName="SPP modeling (0,1,2)", name="spp", datatype="GPLong",parameterType="Required", direction="Input")
spp.value=0
mip_solver=arcpy.Parameter(displayName="MIP Solver", name="mipSolver", datatype="GPString",parameterType="Required", direction="Input")
mip_solver.filter.type = 'ValueList'
slist=d.mip_solvers[:]
slist.append("_")
mip_solver.filter.list = slist
mip_solver.value=slist[0]
outfile=arcpy.Parameter(name='outfile', displayName='Output layer', datatype='DEFeatureClass', direction='Output',parameterType='Required')
operator=arcpy.Parameter(displayName="Search operator", name="operators", datatype="GPString",parameterType="Required", direction="Input")
operator.filter.type = 'ValueList'
operator.filter.list = ['one-unit-move','two-unit-move','three-unit-move']
operator.value='two-unit-move'
distype=arcpy.Parameter(displayName="Distance type", name="distancetype", datatype="GPString",parameterType="Required", direction="Input")
distype.filter.type = 'ValueList'
distype.filter.list = ['Euclidean','Manhattan','User Defined']
distype.value='Euclidean'
networkfile=arcpy.Parameter(displayName="Distance file", name="disfile", datatype="DEFile",parameterType="Optional", direction="Input")
networkfile.enabled=False
return [feas,fld_id,fld_demand, fld_supply, distype, networkfile, outfile,connectivity,solver,popsize,timelimit,spp,mip_solver,operator]
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if parameters[4].altered:
if parameters[4].value=='User Defined':
parameters[5]. enabled = True
else:
parameters[5]. enabled = False
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
if arcpy.env.workspace==None:
arcpy.AddMessage("please click the button 'Envronments...', and set the workspace!!!")
return
arcpy.AddMessage("available MIP solvers "+str(d.mip_solvers) )
dataTable=[]
fn=parameters[0].value
if fn.name.find("\\") < 0:
fn=fn.dataSource
#mxd = arcpy.mapping.MapDocument("CURRENT")
#for lyr in arcpy.mapping.ListLayers(mxd):
# if lyr.name == fn:
# fn=lyr.dataSource
# break
desc = arcpy.Describe(fn)
idf=parameters[1].valueAsText
df=parameters[2].valueAsText
sf=parameters[3].valueAsText
d.fixed_cost_obj=0
#numf=parameters[7].value
arcpy.AddMessage("reading spatial units ...")
cursor = arcpy.SearchCursor(fn)
row = cursor.next()
idx=0
fcenters=[]
capacities=[]
facilityCost=[]
id2idx={}
x=0.0
y=0.0
while row:
#unit=[idx, x, y, demand, id,cap,cand,cost]
r=[idx,x,y,row.getValue(df),row.getValue(idf),row.getValue(sf),0,0.0]
id2idx[r[4]]=r[0]
if r[5]>0:
fcenters.append(idx)
capacities.append(r[5])
facilityCost.append(0)
dataTable.append(r)
row = cursor.next()
idx+=1
del cursor, row
d.nodes=dataTable
num_units=len(dataTable)
arcpy.env.overwriteOutput = True
geometries = arcpy.CopyFeatures_management(fn, arcpy.Geometry())
for i in range(num_units):
cid=geometries[i].centroid
dataTable[i][1]=cid.X
dataTable[i][2]=cid.Y
#arcpy.AddMessage("units: "+str(dataTable[i]))
arcpy.AddMessage("total demand units: "+str(num_units))
arcpy.AddMessage("total spply units: "+str(len(fcenters)) )
if len(fcenters)==0:
arcpy.AddMessage("no any facility!" )
return
#connectivity
ws=arcpy.env.workspace
if ws.find(".gdb"):
ws=os.path.dirname(arcpy.env.workspace)
arcpy.env.workspace=ws
arcpy.AddMessage("searching for neighbor units ... " )
swm="swm.swm"
swmdb="swm.dbf"
if arcpy.Exists(swm): arcpy.Delete_management(swm)
if arcpy.Exists(swmdb): arcpy.Delete_management(swmdb)
if desc.shapeType=='Point':
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm,"DELAUNAY_TRIANGULATION" )
else:
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm, "CONTIGUITY_EDGES_ONLY")
arcpy.ConvertSpatialWeightsMatrixtoTable_stats(swm, swmdb)
unit_neighbors=[[] for x in range(num_units) ]
rows = arcpy.SearchCursor(swmdb)
for row in rows:
id1=row.getValue(idf)
id2=row.getValue("NID")
unit_neighbors[id2idx[id1]].append(id2idx[id2])
del row, rows
#for x in unit_neighbors: arcpy.AddMessage(str(x))
arcpy.AddMessage("calcaulating distance ... " )
dist_ij=[[999999.999 for x in range(num_units) ] for y in range(num_units)]
#['Euclidean','Manhattan','User Defined']
if parameters[4].valueAsText=='User Defined':
dfile=parameters[5].valueAsText
sta=d.readdistance(dfile)
if sta<=0: return
dist_ij=d.nodedij
else:
for i in range(num_units):
for j in range(i,num_units):
if j==i:
dist_ij[i][j]=0.0
continue
d3=0.0
if parameters[4].valueAsText=='Manhattan':
d3= (abs(dataTable[i][1]-dataTable[j][1])+ abs(dataTable[i][2]-dataTable[j][2]))/1000
if parameters[4].valueAsText=='Euclidean':
d2=pow(dataTable[i][1]-dataTable[j][1],2)
d2+=pow(dataTable[i][2]-dataTable[j][2],2)
d3=pow(d2,0.5)/1000
dist_ij[i][j]=d3
dist_ij[j][i]=d3
d.nodes=dataTable
d.node_neighbors=unit_neighbors
d.nodedij=dist_ij
#problem defination
d.location_problem=1
d.pop_dis_coeff=1000.0
d.pop_deviation=0.00
d.spatial_contiguity=0
d.allowing_less_facilities=0
d.max_num_facility=len(fcenters)
d.solver_message=0
d.facilityCandidate=fcenters[:]
d.facilityCapacity=capacities[:]
d.facilityCost=facilityCost[:]
numf=d.max_num_facility
#sol=[0 for x in range(num_units)]
#if d.check_continuality_feasibility(sol,0)==0:
# arcpy.AddMessage("the spatial units are not connected!")
# return
arcpy.AddMessage("facilities: "+str(d.facilityCandidate) )
arcpy.AddMessage("capacities: "+str(d.facilityCapacity) )
arcpy.AddMessage("costs: "+str(d.facilityCost) )
#arcpy.AddMessage("distance: "+str(dist_ij) )
d.spatial_contiguity=1
if parameters[7].value==False: d.spatial_contiguity=0
arcpy.AddMessage("fixed_cost_obj: "+str(d.fixed_cost_obj) )
#initialize instance data
d.initialize_instance()
arcpy.AddMessage("total demand: "+str(d.total_pop) )
arcpy.AddMessage("total supply: "+str(d.total_supply) )
#arcpy.AddMessage(str(d.nodes[0:50]))
#arcpy.AddMessage(str(d.capacities))
#arcpy.AddMessage(str(d.facilityCost))
solver=parameters[8].valueAsText
psize=parameters[9].value
timelimit=parameters[10].value
spp=parameters[11].value
d.mip_solver=parameters[12].valueAsText
if d.mip_solver not in d.mip_solvers:
spp=0
operator=parameters[13].value
if operator=='one-unit-move': d.operators_selected=[0]
if operator=='two-unit-move':d.operators_selected=[0,1]
if operator=='three-unit-move': d.operators_selected=[0,1,2]
arcpy.AddMessage("solving the problem......")
arcpy.SetProgressorLabel("solving the problem......")
if solver=='ils':
arcpy.SetProgressorLabel("searching ...")
d.initial_solution_method=0
results=d.ils(numf, psize, timelimit, spp,-1)
if solver=='lr_ils':
arcpy.SetProgressorLabel("searching ...")
d.initial_solution_method=9
results=d.ils(numf, psize, timelimit, spp,-1)
if solver=='mip':
arcpy.SetProgressorLabel("modeling ...")
results=d.mip(numf,0,d.spatial_contiguity,timelimit)
if len(results)<=1:
arcpy.AddMessage("Fatal solver error!!!")
if len(results)==1: arcpy.AddMessage(str(results[0]))
return
biobj=results[0]
obj=results[1]
overload=results[2]
centers=results[3]
sol=results[4]
arcpy.SetProgressorLabel("outputting the service area layer ...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
#arcpy.AddMessage("solution: " +str(sol))
arcpy.env.overwriteOutput = True
newlayer=arcpy.CopyFeatures_management(fn,parameters[6].value)
arcpy.AddField_management(newlayer, "SA_ID", "Long")
cursor = arcpy.UpdateCursor(newlayer)
row = cursor.next()
idx=0
while row:
r=sol[idx]
fu=d.centersID[r]
row.setValue("SA_ID", fu)
cursor.updateRow(row)
row = cursor.next()
idx+=1
del cursor, row
arcpy.AddMessage("solution summary...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
arcpy.AddMessage("ServiceAreaId, FacilityID, No.units, total demand, supply, total distance")
for i in range(d.num_districts):
arcpy.AddMessage("{0},{1},{2},{3},{4},{5}".format(i,dataTable[d.centersID[i]][4],d.district_info[i][0],d.district_info[i][1],d.district_info[i][3], int(d.district_info[i][2]*1000)/1000.0))
return
class Tool3(object):
def __init__(self):
self.label = "Political Districting Problem"
self.description = "Political Districting Problem"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
feas=arcpy.Parameter(name='feas', displayName='Map layer', datatype='GPFeatureLayer', direction='Input',parameterType='Required')
fld_id=arcpy.Parameter(name='id_fld', displayName='ID field', datatype='Field', direction='Input', parameterType='Required')
fld_id.parameterDependencies = [feas.name]
fld_demand=arcpy.Parameter(name='demand_fld', displayName='Population field', datatype='Field', direction='Input', parameterType='Required')
fld_demand.parameterDependencies = [feas.name]
locsize=arcpy.Parameter(displayName="Num. of districts", name="locsize", datatype="GPLong",parameterType="Required", direction="Input")
deviation=arcpy.Parameter(displayName="Maximum deviation", name="deviation", datatype="GPDouble",parameterType="Required", direction="Input")
deviation.value=0.0
overloadpenalty=arcpy.Parameter(displayName="Penalty cost on district balance", name="Penalty", datatype="GPDouble",parameterType="Required", direction="Input")
overloadpenalty.value=1.0
#solver,popsize,timelimit,spp
solver=arcpy.Parameter(displayName="Solver", name="Solver", datatype="GPString",parameterType="Required", direction="Input")
solver.filter.type = 'ValueList'
solver.filter.list = ['ils','mip']
solver.value='ils'
popsize=arcpy.Parameter(displayName="Multistarts", name="popsize", datatype="GPLong",parameterType="Required", direction="Input")
popsize.value=6
timelimit=arcpy.Parameter(displayName="Time limit in seconds", name="timelimit", datatype="GPLong",parameterType="Required", direction="Input")
timelimit.value=200
spp=arcpy.Parameter(displayName="SPP modeling (0,1)", name="spp", datatype="GPLong",parameterType="Required", direction="Input")
spp.value=0
mip_solver=arcpy.Parameter(displayName="MIP Solver", name="mipSolver", datatype="GPString",parameterType="Required", direction="Input")
mip_solver.filter.type = 'ValueList'
slist=d.mip_solvers[:]
slist.append("_")
mip_solver.filter.list = slist
mip_solver.value=slist[0]
outfile=arcpy.Parameter(name='outfile', displayName='Output layer', datatype='DEFeatureClass', direction='Output',parameterType='Required')
operator=arcpy.Parameter(displayName="Search operator", name="operators", datatype="GPString",parameterType="Required", direction="Input")
operator.filter.type = 'ValueList'
operator.filter.list = ['one-unit-move','two-unit-move','three-unit-move']
operator.value='two-unit-move'
distype=arcpy.Parameter(displayName="Distance type", name="distancetype", datatype="GPString",parameterType="Required", direction="Input")
distype.filter.type = 'ValueList'
distype.filter.list = ['Euclidean','Manhattan','User Defined']
distype.value='Euclidean'
networkfile=arcpy.Parameter(displayName="Distance file", name="disfile", datatype="DEFile",parameterType="Optional", direction="Input")
networkfile.enabled=False
return [feas,fld_id,fld_demand, distype, networkfile, locsize, deviation, overloadpenalty,outfile,solver,popsize,timelimit,spp,mip_solver,operator]
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if parameters[4].altered:
if parameters[4].value=='User Defined':
parameters[5]. enabled = True
else:
parameters[5]. enabled = False
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
if arcpy.env.workspace==None:
arcpy.AddMessage("please click the button 'Envronments...', and set the workspace!!!")
return
arcpy.AddMessage("available MIP solvers "+str(d.mip_solvers) )
dataTable=[]
fn=parameters[0].value
if fn.name.find("\\") < 0:
fn=fn.dataSource
#mxd = arcpy.mapping.MapDocument("CURRENT")
#for lyr in arcpy.mapping.ListLayers(mxd):
# if lyr.name == fn:
# fn=lyr.dataSource
# break
desc = arcpy.Describe(fn)
idf=parameters[1].valueAsText
df=parameters[2].valueAsText
numf=parameters[5].value
if numf<2:
arcpy.AddMessage("Please Input the number of districts (>=2)!")
return
d.fixed_cost_obj=0
arcpy.AddMessage("reading spatial units ...")
cursor = arcpy.SearchCursor(fn)
row = cursor.next()
idx=0
fcenters=[]
capacities=[]
facilityCost=[]
id2idx={}
x=0.0
y=0.0
while row:
#unit=[idx, x, y, demand, id,cap,cand,cost]
r=[idx,x,y,row.getValue(df),row.getValue(idf),0.0,0.0,0.0]
id2idx[r[4]]=r[0]
dataTable.append(r)
row = cursor.next()
idx+=1
del cursor, row
d.nodes=dataTable
num_units=len(dataTable)
arcpy.env.overwriteOutput = True
geometries = arcpy.CopyFeatures_management(fn, arcpy.Geometry())
for i in range(num_units):
cid=geometries[i].centroid
dataTable[i][1]=cid.X
dataTable[i][2]=cid.Y
#arcpy.AddMessage("units: "+str(dataTable[i]))
arcpy.AddMessage("total spatial units: "+str(num_units))
#connectivity
ws=arcpy.env.workspace
if ws.find(".gdb"):
ws=os.path.dirname(arcpy.env.workspace)
arcpy.env.workspace=ws
arcpy.AddMessage("searching for neighbor units ... " )
swm="swm.swm"
swmdb="swm.dbf"
if arcpy.Exists(swm): arcpy.Delete_management(swm)
if arcpy.Exists(swmdb): arcpy.Delete_management(swmdb)
if desc.shapeType=='Point':
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm,"DELAUNAY_TRIANGULATION" )
else:
arcpy.GenerateSpatialWeightsMatrix_stats (fn, idf, swm, "CONTIGUITY_EDGES_ONLY")
arcpy.ConvertSpatialWeightsMatrixtoTable_stats(swm, swmdb)
unit_neighbors=[[] for x in range(num_units) ]
rows = arcpy.SearchCursor(swmdb)
for row in rows:
id1=row.getValue(idf)
id2=row.getValue("NID")
unit_neighbors[id2idx[id1]].append(id2idx[id2])
del row, rows
#for x in unit_neighbors: arcpy.AddMessage(str(x))
arcpy.AddMessage("calcaulating distance ... " )
dist_ij=[[999999.999 for x in range(num_units) ] for y in range(num_units)]
numf=parameters[5].value
#['Euclidean','Manhattan','User Defined']
if parameters[3].valueAsText=='User Defined':
dfile=parameters[4].valueAsText
sta=d.readdistance(dfile)
if sta<=0: return
dist_ij=d.nodedij
else:
for i in range(num_units):
for j in range(i,num_units):
if j==i:
dist_ij[i][j]=0.0
continue
d3=0.0
if parameters[3].valueAsText=='Manhattan':
d3= (abs(dataTable[i][1]-dataTable[j][1])+ abs(dataTable[i][2]-dataTable[j][2]))/1000
if parameters[3].valueAsText=='Euclidean':
d2=pow(dataTable[i][1]-dataTable[j][1],2)
d2+=pow(dataTable[i][2]-dataTable[j][2],2)
d3=pow(d2,0.5)/1000
dist_ij[i][j]=d3
dist_ij[j][i]=d3
d.nodes=dataTable
d.node_neighbors=unit_neighbors
d.nodedij=dist_ij
#problem defination
d.location_problem=2
d.pop_deviation=parameters[6].value
d.pop_dis_coeff=parameters[7].value
d.spatial_contiguity=1
d.fixed_cost_obj=0
d.max_num_facility=numf
d.allowing_less_facilities=0
d.solver_message=0
#initialize instance data
d.initialize_instance()
arcpy.AddMessage("total demand: "+str(d.total_pop) )
arcpy.AddMessage("number of districts: "+str(d.max_num_facility) )
solver=parameters[9].valueAsText
psize=parameters[10].value
timelimit=parameters[11].value
spp=parameters[12].value
d.mip_solver=parameters[13].valueAsText
if d.mip_solver not in d.mip_solvers:
spp=0
operator=parameters[14].value
if operator=='one-unit-move': d.operators_selected=[0]
if operator=='two-unit-move':d.operators_selected=[0,1]
if operator=='three-unit-move': d.operators_selected=[0,1,2]
arcpy.AddMessage("solving the problem......")
arcpy.SetProgressorLabel("solving the problem......")
if solver=='ils':
arcpy.SetProgressorLabel("searching ...")
results=d.ils(numf, psize, timelimit, spp,-1)
if solver=='mip':
arcpy.SetProgressorLabel("searching centers ...")
arcpy.AddMessage("searching centers ...")
d.initial_solution(0)
arcpy.SetProgressorLabel("modeling ...")
arcpy.AddMessage("modeling, please wait ...")
d.mipmodel_pulp()
if d.biobjective<0:
arcpy.AddMessage("Fatal solver error!!!")
if len(results)==1: arcpy.AddMessage(str(results[0]))
return
results=[d.biobjective, d.objective, d.objective_overload, d.centersID, d.node_groups]
if len(results)<=1:
arcpy.AddMessage("Fatal solver error!!!")
if len(results)==1: arcpy.AddMessage(str(results[0]))
return
biobj=results[0]
obj=results[1]
overload=results[2]
centers=results[3]
sol=results[4]
arcpy.SetProgressorLabel("outputting the service area layer ...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
#arcpy.AddMessage("solution: " +str(sol))
arcpy.env.overwriteOutput = True
newlayer=arcpy.CopyFeatures_management(fn,parameters[8].value)
arcpy.AddField_management(newlayer, "Selected", "Long")
arcpy.AddField_management(newlayer, "SA_ID", "Long")
cursor = arcpy.UpdateCursor(newlayer)
row = cursor.next()
idx=0
while row:
r=sol[idx]
fu=d.centersID[r]
row.setValue("SA_ID", fu)
if idx in centers:
row.setValue("Selected", 1)
else:
row.setValue("Selected", 0)
cursor.updateRow(row)
row = cursor.next()
idx+=1
del cursor, row
arcpy.AddMessage("solution summary...")
arcpy.AddMessage("obj, total distance and overload: " + str(biobj)+" "+str(obj) + " "+str(overload))
arcpy.AddMessage("ServiceAreaId, FacilityID, No.units, total demand, supply, total distance")
for i in range(d.num_districts):
if d.district_info[i][0]<1: continue
arcpy.AddMessage("{0},{1},{2},{3},{4},{5}".format(i,dataTable[d.centersID[i]][4],d.district_info[i][0],d.district_info[i][1],d.district_info[i][3], int(d.district_info[i][2]*1000)/1000.0))
return