def __toKML(self):
        """
        Public subscribers' geography information,
        if it's available in his foaf files,
        into KML file
        """

        from kml import KML
        kml = KML()
        
        count = 0
        
        for mail, subscriber in self.subscribers.items():
            lat, lon = subscriber.getGeo()
            pic = subscriber.getPic()
            if ((lat != None) and (lon != None)): 
                count += 1
                kml.addPlace(lat, lon, name=subscriber.getName(), description=pic)
                
            
        #and dump to disk
        try:
            kml_file = open(self.config.get('dir') + 'subscribers.kml', 'w+')
            kml.write(kml_file)
            kml_file.flush()
            kml_file.close()
            print count, 'subcribers\' coordinates exported in KML'
        except IOError, detail:
            print 'Error exporting coordinates to KML: ' + str(detail)
Example #2
0
def make_KML_average_columns(averages_dict):
    kml = KML()
    aves = {}
    for point, bucket in averages_dict.items():
        aves[point] = {"vel": [], "azm": []}
        vel = Mean() + point.velocity
        azm = Mean() + point.azimuth
        for en in ens:
            vel += en.velocity
            azm += en.azimuth
        aves[point]["vel"] = vel
        aves[point]["azm"] = azm
    
    f = open("../data/column_averages.xml",'w')
    f.write("latitude, longitude, velocity_mean, v_std, v_n, azimuth_mean, a_std, a_n\n")
    mkstr = lambda x: ("%s" % x).replace(", ","<br/>").replace("=",": ")
    for point, ave in aves.items():
        vel = ave["vel"]
        azm = ave["azm"]
        text = "<h2>Velocity:</h2><p>%s</p>" % mkstr(vel)
        text += "<h2>Azimuth:</h2><p>%s</p>" % mkstr(azm)
        desc = description_from_text(text)
        pt = Placemark(int(azm), point.point, desc)
        kml.addPlacemark(pt)
        line = list(point.point)
        line.append(vel())
        line.append(azm())
        f.write(",".join(line) + "\n")
    f.close()

    kml.output("../data/column_averages.kml")
Example #3
0
 def write_kml_output(self, ships, out_name):
     """
     saves a summary of all selected ships in KML format
     (or KMZ if gzip option selected)
     out_name is used to compute the output filename
     returns filename
     """
     # create an instance of the KML class
     kml = KML()
     # send it the `contents` method to retrieve the text
     # to be written in the kml file
     contents = kml.contents(
         ships,
         kml_name=out_name,
         description=f"Positions for ship(s) {out_name}")
     # compute suffix based on self.args.gzip
     #  - whether the --gzip option was passed or not
     suffix = "kmz" if self.args.gzip else "kml"
     # compute full filename
     kml_filename = f"{out_name}.{suffix}"
     # message
     print(f"Opening {kml_filename} for ship {out_name}")
     # open a plain file or compressed file as requested
     with gzip.open(kml_filename, 'w', newline="\n") if self.args.gzip \
             else open(kml_filename, 'w', newline="\n") as out:
         out.write(contents)
     # return filename
     return kml_filename
Example #4
0
def outputData(name, collection, atDepth=None):
    kml = KML(name)
    file = open("../data/%s.csv" % name.replace(" ", "_"), "w")
    file.write(
        "number, latitude, longitude, v_mean, v_dev, v_n, v_err, v_min, v_max, a_mean, a_dev, a_n, a_err, a_min, a_max, d_mean, d_dev, d_n, d_err, d_min, d_max\n"
    )
    for lst in collection.values():
        for col in lst:
            col.calcAverages()
            point = col.point
            if atDepth:
                velocity, azimuth = col.averageAtDepth(atDepth)
            else:
                velocity, azimuth = col.velocity, col.azimuth
            name = int(degrees(azimuth))  # Cast to a Python int b/c MeanAzimuth has a long string representation
            depth = col.depth
            style = int(velocity)
            if style == 0:
                style = "O"
            elif (name < 0) or (style < 0):
                style = "red-diamond"
                name = ""
            PL = Placemark(name, point, velocity, azimuth, depth, style)
            kml.addPlacemark(PL)
            file.write("%i, %f, %f," % (PL.id, point[0], point[1]))
            for val in [velocity, azimuth, depth]:
                for v in val():
                    file.write(" %0.3f," % v)
            file.write("\n")
    # Kludge to zero out the ID number, so that we have a new zero point for each depth.
    PL.zero()
    kml.output()
    file.close()
Example #5
0
 def write_kml_output(self, ships, out_name):
     """
     saves a summary of all selected ships in KML format
     (or KMZ if gzip option selected)
     out_name is used to compute the output filename
     returns filename
     """
     # create an instance of the KML class
     kml = KML()
     # send it the `contents` method to retrieve the text
     # to be written in the kml file
     contents = kml.contents(ships, kml_name=out_name,
                             description = "Positions for ship(s) {}".\
                                           format(out_name)
                            )
     # compute suffix based on self.args.gzip
     #  - whether the --gzip option was passed or not
     suffix = "kmz" if self.args.gzip else "kml"
     # compute full filename
     kml_filename = "{}.{}".format(out_name, suffix)
     # message
     print ("Opening {kml_filename} for ship {out_name}".\
            format(**locals()))
     # open a plain file or compressed file as requested
     with gzip.open(kml_filename, 'w') if self.args.gzip \
          else open(kml_filename, 'w') as out:
         out.write(contents)
     # return filename
     return kml_filename
Example #6
0
    def geocode_cust_addresses(self, caddresses):
        """Geocode all addresses from a customer dict."""
        kml = KML()
        xmlroot = kml.xmlroot
        # geocode addresses
        for key, value in caddresses.items():
            logging.info('Geocoding address..')
            gcaddr = geocode(value)
            logging.info('Appending row to kml..')
            xmlroot[0].append(kml.placemark(key, value, gcaddr))
            self.wait(10)

        self.notifysubswrite(
            kml.serialize(xmlroot), '*.kml', 'Google Earth KML')
Example #7
0
    def geocode_cust_addresses(self, caddresses):
        """Geocode all addresses from a customer dict."""
        kml = KML()
        xmlroot = kml.xmlroot
        # geocode addresses
        for key, value in caddresses.items():
            logging.info('Geocoding address..')
            gcaddr = geocode(value)
            logging.info('Appending row to kml..')
            xmlroot[0].append(kml.placemark(key, value, gcaddr))
            self.wait(10)

        self.notifysubswrite(kml.serialize(xmlroot), '*.kml',
                             'Google Earth KML')
Example #8
0
def make_KML_average_columns(averages_dict):
    kml = KML()
    aves = {}
    for point, bucket in averages_dict.items():
        aves[point] = {"vel": [], "azm": []}
        vel = Mean() + point.velocity
        azm = Mean() + point.azimuth
        for en in ens:
            vel += en.velocity
            azm += en.azimuth
        aves[point]["vel"] = vel
        aves[point]["azm"] = azm

    f = open("../data/column_averages.xml", 'w')
    f.write(
        "latitude, longitude, velocity_mean, v_std, v_n, azimuth_mean, a_std, a_n\n"
    )
    mkstr = lambda x: ("%s" % x).replace(", ", "<br/>").replace("=", ": ")
    for point, ave in aves.items():
        vel = ave["vel"]
        azm = ave["azm"]
        text = "<h2>Velocity:</h2><p>%s</p>" % mkstr(vel)
        text += "<h2>Azimuth:</h2><p>%s</p>" % mkstr(azm)
        desc = description_from_text(text)
        pt = Placemark(int(azm), point.point, desc)
        kml.addPlacemark(pt)
        line = list(point.point)
        line.append(vel())
        line.append(azm())
        f.write(",".join(line) + "\n")
    f.close()

    kml.output("../data/column_averages.kml")
Example #9
0
    def __toKML(self):
        """
        Public subscribers' geography information,
        if it's available in his foaf files,
        into KML file
        """

        from kml import KML
        kml = KML()

        for mail, subscriber in self.subscribers.items():
            lat, lon = subscriber.getGeo()
            pic = subscriber.getPic()
            if ((lat != None) and (lon != None)):
                kml.addPlace(lat,
                             lon,
                             name=subscriber.getName(),
                             description=pic)

        #and dump to disk
        try:
            kml_file = open(self.config.get('dir') + 'subscribers.kml', 'w+')
            kml.write(kml_file)
            kml_file.flush()
            kml_file.close()
        except IOError, detail:
            print 'Error exporting coordinates to KML: ' + str(detail)
Example #10
0
def outputData(name, collection, atDepth=None):
    kml = KML(name)
    file = open("../data/%s.csv" % name.replace(" ", "_"), "w")
    file.write(
        "number, latitude, longitude, v_mean, v_dev, v_n, v_err, v_min, v_max, a_mean, a_dev, a_n, a_err, a_min, a_max, d_mean, d_dev, d_n, d_err, d_min, d_max\n"
    )
    for lst in collection.values():
        for col in lst:
            col.calcAverages()
            point = col.point
            if atDepth:
                velocity, azimuth = col.averageAtDepth(atDepth)
            else:
                velocity, azimuth = col.velocity, col.azimuth
            name = int(
                degrees(azimuth)
            )  # Cast to a Python int b/c MeanAzimuth has a long string representation
            depth = col.depth
            style = int(velocity)
            if style == 0: style = "O"
            elif ((name < 0) or (style < 0)):
                style = "red-diamond"
                name = ""
            PL = Placemark(name, point, velocity, azimuth, depth, style)
            kml.addPlacemark(PL)
            file.write("%i, %f, %f," % (PL.id, point[0], point[1]))
            for val in [velocity, azimuth, depth]:
                for v in val():
                    file.write(" %0.3f," % v)
            file.write("\n")
    # Kludge to zero out the ID number, so that we have a new zero point for each depth.
    PL.zero()
    kml.output()
    file.close()
Example #11
0
def make_KML_at_depths(averages_dict, depths=(3, 6, 9)):
    kmls = {}
    for depth in depths:
        kmls[depth] = KML()
        for point, aves in averages_dict.items():
            vel = aves[depth]["vel"]
            azimuth = aves[depth]["azm"]
            desc = description_from_text("Velocity: %0.3f<br/>Azimuth: %0.3f" %
                                         (velocity, azimuth))
            pt = Placemark(int(azimuth), point.point, desc)
            kmls[depth].addPlacemark(pt)
    for key in kmls.keys():
        kmls[key].output("../data/depth%i.kml" % key)
Example #12
0
def map(orbit_data, output_file, colour, width, indices):
    """Maps GMAT data from the file orbit_data as a KMZ file"""
    print "Creating map for orbit file", orbit_data
    coords = []
    if not os.path.exists(orbit_data):
        raise IOError('File "%s" does not exist' % orbit_data)
    with open(orbit_data, 'r') as orbit:
        for i, row in enumerate(orbit):
            if indices[0] <= i <= indices[1] and i % 2 == 0:
                try:
                    lat, lon = [float(x) for x in row.split()[:2]]
                except:
                    print row
                    print i
                    raise
                coords.append((lon, lat))
            else:
                pass

    line_style = KML.LineStyle(colour=colour, width=width, id='GroundTrack')

    print "Making KML"
    coord = KML.Coord(coords)
    track = KML.LineString(
        coord,
        style=line_style,
        name='GMAT Orbit Track',
        description='Ground track for GMAT orbit from file %s' %
        os.path.split(orbit_data)[-1])

    map = KML.KML(name='GMAT Orbit')
    map.add_object(track)

    if output_file is None:
        output_file = os.path.join(os.path.splitext(orbit_data)[0], '.kmz')
    map.write(output_file)
    print "File saved as", os.path.realpath(output_file)
Example #13
0
    def run_format(self,formatcls):
        if formatcls in self.results:
            return
        prereq = RunManager.prereqs[formatcls]
        if prereq and prereq not in self.results:
            self.run_format(prereq)

        if formatcls == OSM_XML:
            task = OSM_XML(self.aoi_geom, self.dir + 'export.osm',url=self.overpass_api_url)
        if formatcls == OSM_PBF:
            task = OSM_PBF(self.dir + 'export.osm',self.dir+'export.pbf')
        if formatcls == Geopackage:
            task = Geopackage(
                self.dir+'export.pbf',
                self.dir+'export.gpkg',
                self.dir,
                self.feature_selection,
                self.aoi_geom,
                per_theme=self.per_theme
            )
        if formatcls == GarminIMG:
            assert self.garmin_splitter and self.garmin_mkgmap
            task = GarminIMG(
                    self.dir+'export.pbf',
                    self.dir,
                    self.garmin_splitter,
                    self.garmin_mkgmap,
                    self.aoi_geom)
        if formatcls == OsmAndOBF:
            assert self.map_creator_dir
            task = OsmAndOBF(self.dir+'export.pbf',self.dir,self.map_creator_dir)
        if formatcls == KML:
            task = KML(self.dir + 'export.gpkg',self.dir,self.feature_selection)
        if formatcls == Shapefile:
            task = Shapefile(self.dir + 'export.gpkg',self.dir,self.feature_selection)

        self.on_task_start(formatcls)
        task.run()
        self.on_task_success(formatcls,task.results)
        self.results[formatcls] = task
Example #14
0
#!/usr/bin/env python

import argparse

from parse import parse_listing_file
from kml import KML

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--test', action='store_true', help='If flag is '
                    'present, does not run geocode lookup.')
parser.add_argument('file')

params = parser.parse_args()
file = open(params.file)

listings = parse_listing_file(file)

kml_generator = KML(test=params.test)
kml_generator.generate_from_listings(listings)
Example #15
0
def make_KML_from_ensemble_list(ensemble_list, designator=None):
    kml = KML()
    for en in ensemble_list:
        kml.addPlacemark(make_Placemark(ensemble))
    des = str(designator) if designator else ""
    kml.output("../data/transects%s.kml" % des)
Example #16
0
def make_KML_from_ensemble_list(ensemble_list, designator=None):
    kml = KML()
    for en in ensemble_list:
        kml.addPlacemark(make_Placemark(ensemble))
    des = str(designator) if designator else ""
    kml.output("../data/transects%s.kml" % des)