Beispiel #1
0
def calc_occurs(target, result, field_name, field_type, field_length):
    """
    Calculates frequencies on a field in target (table, feature, shp) and returns
    a table of results.
    """
    # création du dictionnaire (temporaire) des occurences/fréquences
    dico_freq = {}
    # création de la table résultat (= en sortie)
    new_table(path.split(result)[0], path.split(result)[1])
    # curseurs pour parcourir (r = read) et écrire (w = write) les données ligne par ligne
    curs_r = SearchCursor(target, "", "", field_name)
    curs_w = InsertCursor(result)
    # ajout des 2 champs dans la table résultat
    add_field(result, "OCCUR", field_type, "", "", field_length)
    add_field(result, "FREQ", "SHORT")
    # calcul et ajout au dictionnaire intermédiaire
    for obj in curs_r:
        value = obj.getValue(field_name)
        if dico_freq.has_key(value):
            dico_freq[value] = dico_freq.get(value)+1
        else:
            dico_freq[value] = 1
    del curs_r
    # mise à jour de la table résultats
    for occur in dico_freq.keys():
        row = curs_w.newRow()
        row.OCCUR = occur
        row.FREQ = dico_freq.get(occur)
        curs_w.insertRow(row)
    # nettoyage des curseurs (pour éviter le verrouillage des données = .lock)
    del row, curs_w
    # fin de fonction
    return dico_freq
Beispiel #2
0
    def updateFC(self):
        '''
        Updates the feature class based on the distances found in the other
        two functions

        input:
        lstNames - 'b' from the LevDist function
        '''
        try:
            d0 = time.clock()
            z = self.LevDist(self.namePairs)
            
            dupeCount = 0
            modCount = 0
            ctr = 0
            self.insGNDB = []
            while z:
                # n =  varFlag,gUFI,gName,xUFI,xName,gUNI
                n = z.next()
                       
                # cursor must apply to external names feature class; else will throw exception
                # as fields such as "MF" do not exist
                uc = UpdateCursor(self.path+'/'+self.name)
                
                gUFI = n[1]
                gN = n[2]
                xUFI = n[3]
                xN = n[4]
                gUNI = n[5]

                # initialize an empty list to put GNDB row objects for records to be demoted
                # from N to V NT
                
                for row in uc:
                    try:
                        uni = 1
                        # print row.getValue('FULL_NAME'), xN
                        uc_name = row.getValue('FULL_NAME')
                        uc_ufi = row.getValue('UFI')
                        if uc_name == xN and uc_ufi == xUFI:
                            if n[0] == 'DUPLICATE':
                                dupeCount += 1
                                row.setValue('GEONAME_NOTE',n[0])
                                # set MF column to M to capture coordinates
                                # or other feature mods
                                row.setValue('MF','M')

                                ##################
                                #
                                # need to change this with new sources
                                row.setValue('USID1','TU-GAZETTEER-09')
                                #
                                ##################
                                row.setValue('SOURCE_MOD_TYPE1','F')
                                row.setValue('UFI', gUFI)
                                row.setValue('UNI', gUNI)
                                uc.updateRow(row)
                                ctr += 1
                                # if exName is duplicate of GNDB Variant, find and
                                # demote GNDB N name
                                if n[6] == 'V':
                                    rr = self.demote_gndb_rec(n[1],gUNI)

                            elif n[0] == 'VARIANT':
                                # Turkey Gazetteer is considered authoritative
                                # so discrepancies favor the gazetteer
                                # handles the external record
                                vRow = self.handle_variants(n,row)
                                uc.updateRow(vRow)
                                # demote the GNDB NT to 'V'
                                rr = self.demote_gndb_rec(n[1], gUNI) # = gndb row
                                self.insGNDB.append(rr)
                                modCount +=1
                                ctr +=1

                            print n[1]

                    except StopIteration:
                        print 'uc done'
                
                        
        except StopIteration:
            print "ctr = %d" % ctr
            print "Feature class modified:\n\t%d duplicate features found \
                    \n\t%d variant names added" % (dupeCount,modCount)
            d1 = time.clock()
            delta = d1-d0
            print "%s took %f to complete." % (sys._getframe().f_code.co_name,\
                                               delta)

            ins_cur = InsertCursor(self.path+'/'+self.name)
            ins_num = 0
            for rec in self.insGNDB:
                if rec == None:
                    continue
                pt = Point()
                row = ins_cur.newRow()
                for k,d in rec.iteritems():
                    
                    row.setValue(k,d)
                    row.setValue('MF','M')
                    row.setValue('NT','V')
                    if k == 'LON':
                        pt.X = d
                    elif k == 'LAT':
                        pt.Y = d
                row.setNull('NAME_RANK')
                row.setValue('SOURCE_MOD_TYPE1','N')
                pt_geo = PointGeometry(pt)
                row.setValue('Shape',pt_geo)
                ins_cur.insertRow(row)
                ins_num += 1

            print "%d GNDB name records demoted and added to feature class." % \
                  ins_num
            
            del ins_cur

        except Exception, e:
            e = sys.exc_info()
            log_file = open("H:/Programming/PyErrorLog.txt", 'a')
            log_file.write(str(datetime.datetime.now().time()) + "\n")
            log_file.write(str(e[0]) + "\n")
            log_file.write(str(e[1]) + "\n")
            traceback.print_tb(e[2],None,log_file)
            log_file.write('\n')
            log_file.close()
		type, destination, destination_year, d_scale, d_scale_year = parseInputTablename(lu_input)
		
		if t_scale != d_scale or d_scale_year != t_scale_year:
			AM("Geographic scales of land use and travel time do not match.")
		
		# Create a table to hold the results
		out_table = createOutputFilename(mode, mode_year, destination, destination_year, t_scale, t_scale_year)
		env.workspace = output_workspace
		CreateTable(output_workspace, out_table)
		AddField(out_table, t_scale, "TEXT", field_length=15)
		for threshold in thresholds:
			field_name = "t"+str(threshold)
			AddField(out_table, field_name, "LONG")
		
		# Populate the output table
		cursor = InsertCursor(out_table)
		for oid in lu_table.listIDs():
			row = cursor.newRow()
			row.setValue(t_scale, oid)

			for threshold in thresholds:
				field_name = "t"+str(threshold)
				opportunities = 0
				for did in lu_table.listIDs():
					if tt_table.timeFromTo(oid, did) <= threshold:
						opportunities = opportunities + lu_table.opportunitiesAtFeature(did)
				row.setValue(field_name, opportunities)
				
			cursor.insertRow(row)
	
# Restore original environment