Demo entry 6353129

test

   

Submitted by anonymous on Mar 29, 2017 at 23:06
Language: Python. Code size: 8.4 kB.

from math import *

def read_file(filename):
    f = open(filename)
    a = f.read().splitlines() #reads whole file object, splits into list
    f.close() # close the file object
    return a

def decimal_degrees(c):
    ''' Converts lat or long string into decimal. Negates if W or S.
    Input format 123 12 12.1234 N'''
    deci = c.split(' ') # split string into a list
    for i in range(0, 3):
        deci[i] = float(deci[i]) # convert entries 0,1,2 into floats
    deci[0] = deci[0] + (deci[1]/60) + (deci[2]/3600) #add min, sec
    if deci[3] == "W" or deci[3] == "S":
        deci[0]= -deci[0] # negate if West or South
    return deci[0] #only need to return the first element

def format_airports(d):
    '''Input format = NAME\t11 11 11.11 N\t111 11 11.11 W
    Returns [nx5] list of airports, where n = number of airports.'''
    b = [] # create an empty list
    for i in range (0, len(d)):
        b.append(d[i].split('\t'))
    del b[0] # delete headers column
    for i in range(0, len(b)):
        b[i].append(decimal_degrees(b[i][1]))#create lat_decimal b[i][3]
        b[i].append(decimal_degrees(b[i][2])) #create long_decimal b[i][4]
    return b

def format_GE(d):
    '''String input: Name\t12 12 12.1234 N\t123 12 12.123 E\telev
    Outputs [n x 5] list: [Name, Lat, Long, Degrees Lat, Degrees Long]
    Name, Lat, Long are strings. Degrees Lat, Degrees Long are floats.
    '''
    b = [] # create empty list
    for i in range (0, len(d)):
        b.append(d[i].split('\t')) # split each line into columns, assign to b
    del b[0] # delete top row (column titles)
    for i in range(0, len(b)):
        b[i][0] = b[i][0] + " (" + b[i][3] + " MSL)" # concatenate name+elev
        del b[i][3] # delete elevation column
        b[i].append(decimal_degrees(b[i][1])) # add lat degrees column
        b[i].append(decimal_degrees(b[i][2])) # add long degrees column
    return b

def format_DDOF(d):
    '''String input: list of rows from DDOF. Outputs same [nx5] list
    as format_data_GE function.'''
    count = 0
    while count <= 5: # delete first 6 rows (headers)
        del d[0]
        count += 1
    p = []; q = []; r = []; t = []; u = []; v =[] #create new lists
    for i in range (0, len(d)):
        p.append(d[i][9:19]+" ( "+d[i][93:98]+" FT MSL) "+d[i][72:82])#NAME COL
        q.append(d[i][45:56]+" "+d[i][56]) #LAT COLUMN (string)
        r.append(d[i][58:70]+" "+d[i][70]) #LONG COLUMN (string)
        t.append(decimal_degrees(q[i])) #LAT_decimals COLUMN (float)
        u.append(decimal_degrees(r[i])) #LONG_decimals COLUMN (float)
        v.append([ p[i], q[i], r[i], t[i], u[i] ]) # [n x 5] matrix
    return v

def haversine_dist(x1, y1, x2, y2):
    '''Calculates the great circle distance between two sets
    of (x,y) coordinates using the Haversine formula.'''

    # OK if radians are negative?
    # add conditions precluding > 180 deg etc.
    R = 6378.137 #kilometers
    lat1 = radians(x1)
    long1 = radians(y1)
    lat2 = radians(x2)
    long2 = radians(y2)

    delta_lat = lat2 - lat1
    delta_long = long2 - long1
    a = (sin(delta_lat/2.0))**2 + cos(lat1) *cos(lat2) *(sin(delta_long/2.0))**2
    c = 2 * atan2(sqrt(a),sqrt(1-a))
    d = R * c # kilometers
    #hav_dist = d / 1852 # convert to to Nautical Mile
    return d

def airport_dist(arp, obsts): # input single airport + full list of obstacles
    """returns the distance of each obstacle for a given airport"""
    result = []
    for i in range(0, len(obsts)):
        result.append(haversine_dist(arp[3], arp[4], obsts[i][3], obsts[i][4]))
    return result # result is an [ n x 1 ] list of distances

def all_dists(a): # send airports list here
    """Returns the distance of each obstacle to an airport, for given list of
    airports. Returns [nxm] table of distances, where n = number of airports
    and m = number of obstacles."""
    b = [] # create empty list
    for j in range(0, len(a)):
        b.append(airport_dist(a[j],obstacles))
    return b

def print_report(a):
    '''For a given airport, checks if any obstacles are within the check radius.
    Input for <a> is distance_matrix (ie. the airport / obstacle distance matrix)).
    Prints results to output.txt '''
    #b = radius
    count = 0
    out_data = open("output.txt",'w')
    for i in range(0, len(a)): # for every airport
        for j in range(0, len(a[i])): # check if each obstacle is in range
            if distance_matrix[i][j] <= RADIUS:
                message = ("Obstacle %s is %.1f km from %s aerodrome." % (
                obstacles[j][0], distance_matrix[i][j], airports[i][0] ))
                print message
                out_data.write(message)
                out_data.write("\r\n")
                count = count + 1
    summary = ("\r\nChecked %d obstacles against %d aerodromes. "
                "%d results within radius %.1f km.\r\n" % (
                len(obstacles), len(airports), count, RADIUS ) )
    print summary
    out_data.write(summary)
    out_data.close()
    return None

def create_kml(): # input airports list first, see if we can plot it
    output = open("output.kml",'w')# "\" used for spacing
    output.write("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:\
gx="http://www.google.com/kml/ext/2.2" xmlns:\
kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>\r\n
	<name>Line Measure -mod.kml</name>
	<Style id="inline0">
		<IconStyle>
			<color>ff00ff55</color>
			<scale>1.2</scale>
			<Icon>
				<href>\
                http://maps.google.com/mapfiles/kml/shapes/open-diamond.png\
                </href>
			</Icon>
		</IconStyle>
		<LabelStyle>
			<color>ff00ff55</color>
		</LabelStyle>
		<ListStyle>
		</ListStyle>
		<LineStyle>
			<color>6600ff00</color>
			<width>08</width>
		</LineStyle>
	</Style>
	<Style id="inline1">
		<IconStyle>
			<color>ff00ff55</color>
			<scale>1.4</scale>
			<Icon>
				<href>\
                http://maps.google.com/mapfiles/kml/shapes/open-diamond.png\
                </href>
			</Icon>
		</IconStyle>
		<LabelStyle>
			<color>ff00ff55</color>
		</LabelStyle>
		<ListStyle>
		</ListStyle>
		<LineStyle>
			<color>6600ff00</color>
			<width>10</width>
		</LineStyle>
	</Style>
	<StyleMap id="inline">
		<Pair>
			<key>normal</key>
			<styleUrl>#inline0</styleUrl>
		</Pair>
		<Pair>
			<key>highlight</key>
			<styleUrl>#inline1</styleUrl>
		</Pair>
	</StyleMap>""")
    #output.write(create_line(42,-76,42.5,-75.8))
    for i in range(0, len(distance_matrix)): # for every airport
        for j in range(0, len(distance_matrix[i])): # check if each obstacle is in range
            if distance_matrix[i][j] <= RADIUS:
                output.write(create_line(
                        airports[i][3],airports[i][4],airports[i][0],
                        obstacles[j][3],obstacles[j][4],obstacles[j][0]))
    output.write("""
                </Document>
            </kml>""")
    output.close()
    return None

def create_line(x1,y1,name1,x2,y2,name2):
    lines = """<Placemark>
	<name>Line Measure</name>
    <styleUrl>#inline</styleUrl>
    <LineString>
        <tessellate>1</tessellate>
        <coordinates>
            %f,%f,600
            %f,%f,600
			</coordinates>
		</LineString>
	</Placemark>
    <Placemark>
        <name>%s</name>
    	   <styleUrl>#inline</styleUrl>
           <Point>
                <coordinates>%f,%f,0</coordinates>
    	   </Point>
    </Placemark>
    <Placemark>
        <name>%s</name>
            <styleUrl>#inline</styleUrl>
            <Point>
                <coordinates>%f,%f,0</coordinates>
        	</Point>
    </Placemark>
        """ % (y1, x1, y2, x2, name1, y1, x1, name2, y2, x2)

    return lines


print 100 * "-"
RADIUS = float(raw_input("\r\nEnter check radius (km): ")) # km
OBS_FILENAME = "DOF DAILY CHANGE UPDATE.txt"
#OBS_FILENAME = "obstacles.txt"
ARP_FILENAME = "airports.txt"

in_data = read_file(OBS_FILENAME)
obstacles = format_DDOF(in_data)
in_data = read_file(ARP_FILENAME)
airports = format_airports(in_data)

distance_matrix = all_dists(airports)
print_report(distance_matrix)
create_kml()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).