· 8 years ago · Jan 11, 2018, 10:54 PM
1# Original huff_model layer
2ori_huff_model = QgsVectorLayer("path", "polygon", "ogr")
3
4# Make a copy of the huff model layer in memory to work with so that all
5# changes made to copy only keeping original data intact
6huff_model = QgsVectorLayer("Polygon?crs=epsg:4326", "Huff_Model", "memory")
7huff_model_data = huff_model.dataProvider()
8
9# Change the census layer name to blank before joining to newly created layer so that only a '_' remains after the join before each column name in the format '_<column name>'
10rename = QgsMapLayerRegistry.instance().mapLayersByName("TorontoCMA_2006census_region")[0]
11if rename.name() == "TorontoCMA_2006census_region":
12 rename.setLayerName('')
13
14huff_model.startEditing()
15
16attr = ori_huff_model.dataProvider().fields().toList()
17huff_model_data.addAttributes(attr)
18huff_model.updateFields()
19
20feat = QgsFeature()
21for elem in ori_huff_model.getFeatures():
22 feat.setGeometry(elem.geometry())
23 feat.setAttributes(elem.attributes())
24 huff_model.addFeatures([feat])
25
26# Find the index of the mall(field) that will be used to find the correct
27# probabilities within that field
28for field in huff_model.fields():
29 field_id = huff_model.fieldNameIndex(field.name())
30 print ">>> Field name: {} Field ID: {}".format(field.name(), field_id)
31 if "HiSC1009" == field.name():
32 mall = huff_model.fieldNameIndex(field.name())
33 print "<<< mall ID: {}".format(mall)
34 break
35
36# This is where you choose the mall that you want the market areas for.
37# Currently accepts an index number, which that corresponds to the column
38# in the attribute table. I.e 1 for the first column aka first mall, 2 for
39# the second column aka second mall and so forth.
40qid = QInputDialog()
41
42title = "Which mall would you like to find the market area for?"
43label = "Name: "
44mode = QLineEdit.Normal
45default = "<mall name here>"
46
47text, ok = QInputDialog.getText(qid, title, label, mode, default)
48col_num = int(text)
49print col_num
50
51# Create two new fields that will only show the primary and secondary market
52# areas based on what is chosen as primary and secondary marketer
53# probabilities
54primary = QgsField('Primary', QVariant.Double, 'double', 2, 2)
55huff_model.addAttribute(primary)
56index_pri = huff_model.fieldNameIndex('Primary')
57
58secondary = QgsField('Secondary', QVariant.Double, 'double', 2, 2)
59huff_model.addAttribute(secondary)
60index_sec = huff_model.fieldNameIndex('Secondary')
61
62for feature in huff_model.getFeatures():
63 probability = feature.attributes()
64 ctuid = feature["CTUID"]
65 if not probability[col_num]:
66 print ("This mall does not exist")
67 else:
68 # Primary market values will go into this column
69 if probability[col_num] >= .6:
70 huff_model.changeAttributeValue(feature.id(), index_pri, probability[col_num])
71 # Secondary market values will go into this column
72 if .4 <= probability[col_num] < .6:
73 huff_model.changeAttributeValue(feature.id(), index_sec, probability[col_num])
74
75# Delete all other columns except for the CTUID, Primary, Secondary columns
76fields = []
77fieldnames = {'CTUID', 'Primary', 'Secondary'}
78for field in huff_model.fields():
79 if field.name() not in fieldnames:
80 fields.append(huff_model.fieldNameIndex(field.name()))
81
82huff_model.deleteAttributes(fields)
83
84# Delete all other features (rows) that do not have a probability in the
85# primary and the secondary fields
86expr = QgsExpression(""Primary" is NULL and "Secondary" is NULL")
87for f in huff_model.getFeatures(QgsFeatureRequest(expr)):
88 huff_model.deleteFeature(f.id())
89
90huff_model.updateExtents()
91huff_model.commitChanges()
92
93# Making sure that only one copy layer exists at a time, if running the
94 script multiple times with different malls
95layers = QgsMapLayerRegistry.instance().mapLayers()
96for name, layer in layers.iteritems():
97 if layer.name() == "Huff_Model":
98 print "It exists"
99 if "Huff_Model" in name:
100 QgsMapLayerRegistry.instance().removeMapLayer(layer)
101 else:
102 print "Does not exist"
103
104# Add newly formatted layer to map
105reg = QgsMapLayerRegistry.instance()
106reg.addMapLayer(huff_model)
107
108# Join the census layer to the newly created layer to show specific demographic data.
109targetLyr = QgsMapLayerRegistry.instance().mapLayersByName("Huff_Model")[0]
110censusLyr = QgsMapLayerRegistry.instance().mapLayersByName('')[0]
111root = QgsProject.instance().layerTreeRoot()
112
113mytargetLyr = root.findLayer(targetLyr.id())
114targetClone = mytargetLyr.clone()
115parent = mytargetLyr.parent()
116parent.insertChildNode(0, targetClone)
117parent.removeChildNode(mytargetLyr)
118
119mycensusLyr = root.findLayer(censusLyr.id())
120censusClone = mycensusLyr.clone()
121parent = mycensusLyr.parent()
122parent.insertChildNode(1, censusClone)
123parent.removeChildNode(mycensusLyr)
124
125# Set properties for the join
126targetField = 'CTUID'
127inField = 'CTUID'
128joinObject = QgsVectorJoinInfo()
129joinObject.joinLayerId = censusLyr.id()
130joinObject.joinFieldName = inField
131joinObject.targetFieldName = targetField
132print(targetLyr.addJoin(joinObject)) # You should get True as response.
133targetLyr.addJoin(joinObject)
134
135# Make the created layer that now has a joined attribute table active.
136huff_model = iface.activeLayer()
137# Set up variables to be able to perform a loop to change all layer names
138field_names = [] # This will hold all the field names in a string
139idx = 0
140startCol = 0
141endCol = len(huff_model.pendingFields())
142countCol = (range(startCol, endCol, 1))
143
144for field in huff_model.fields():
145 name = str(field.name()).replace('_', '') # Turn all field names from unicode to a string
146 field_names.append(name) # Add to the list above
147
148print ">>> {}".format(field_names)
149
150# Change all the field names in a loop. This currently does not work. Print statements are for debugging and testing. I want to remove the hyphen (see image) but it doesn't change despite the rest of the code running.
151for colNumber in countCol:
152 with edit(huff_model):
153 print "<<< {}".format(type(field_names[idx]))
154 newName = field_names[idx]
155 print "~~~ {}".format(newName)
156 huff_model.renameAttribute(colNumber, newName)
157 idx = idx + 1
158
159# Turn the census layer back into it's original name on the layer panel
160rename = QgsMapLayerRegistry.instance().mapLayersByName("")[0]
161if rename.name() == "":
162 rename.setLayerName('TorontoCMA_2006census_region')