Example #1
0
    def __init__(self,
                 parent,
                 lat=32.10932741542229,
                 lon=34.89818882620658,
                 zoom=15):
        super().__init__(parent)
        Projection.__init__(self)
        Tiles.__init__(self, self.tileRetrieved)
        self.recentre(lat, lon, zoom)
        self.drag = False
        self.dragStartCoords = (0, 0)
        self.layers = []
        self.Bind(wx.EVT_SIZE, self.sizeChanged)
        self.Bind(wx.EVT_PAINT, self.updatePanel)
        self.Bind(wx.EVT_MOUSEWHEEL, self.scroll_event)

        self.Bind(wx.EVT_LEFT_DOWN, self.click)
        self.Bind(wx.EVT_LEFT_UP, self.release)
        self.Bind(wx.EVT_MOTION, self.mousemove)

        self.Bind(wx.EVT_MOUSEWHEEL, self.scroll_event)
        size = self.GetSize()
        self.mousePosition = wx.Point(size.GetWidth() / 2,
                                      size.GetHeight() / 2)

        self.SetBackgroundStyle(wx.BG_STYLE_PAINT)
Example #2
0
def get_world_size(minlat, minlon, maxlat, maxlon):
    """Return the world size in X-Z coordinates."""
    x1, z1 = Projection.project(minlon, minlat)
    x2, z2 = Projection.project(maxlon, maxlat)
    xSize = math.fabs(x2 - x1)
    zSize = math.fabs(z2 - z1)
    return (xSize, zSize)
Example #3
0
def select_clusters(img, clusters, origin):
    """Return 4 borderlines that bound the table"""
    if len(clusters) < 4:
        return clusters, None
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    in_frame = lambda x, y: 0 <= x < img_hsv.shape[
        1] and 0 <= y < img_hsv.shape[0]
    attempt = 1
    for quadruple in combinations(clusters, 4):
        quadruple.sort()
        borders = [lines[0] for lines in quadruple]
        corners = get_corners(borders, origin)
        slope = horizon_slope(borders)
        if corners and slope < 0.3:
            # average color in the central area
            mean_color, stddev = mean_deviation(img_hsv, corners,
                                                green_mask(img))
            for i in range(4):
                for line in reversed(quadruple[i]):
                    borders[i] = line
                    corners = get_corners(borders, origin)
                    if not all(in_frame(*c) for c in corners):
                        continue
                    pr = Projection(corners, origin)
                    inner_strip, outer_strip = pr.border_neighbourhoods(i - 1)
                    inner_color, inner_dev = mean_deviation(
                        img_hsv, inner_strip)
                    outer_color, outer_dev = mean_deviation(
                        img_hsv, outer_strip)
                    inner_diff = np.abs(inner_color - mean_color)
                    outer_diff = np.abs(outer_color - mean_color)

                    if TEST:
                        imgt = img.copy()
                        for line in borders:
                            draw_line(imgt, line, origin)
                        draw_polygon(imgt, inner_strip)
                        draw_polygon(imgt, outer_strip)
                        cv2.imwrite(
                            'data/lines/steps/%s_%02d.jpg' %
                            (filename.replace('.', ''), attempt), imgt)
                        attempt += 1
                        print('in %s out %s ind %s outd %s' %
                              (inner_diff, outer_diff, inner_dev, outer_dev))

                    if (inner_diff[0] < 10 and inner_dev[0] < 20
                            and max(inner_diff) < 100
                            and (outer_diff[0] > 10 or outer_dev[0] > 20)):
                        if TEST:
                            print('v')
                        break
                else:  # loop finished without break, no i'th borderline found
                    break  # stop search
            else:  # search was not stopped, all borderlines found
                clusters = [[line for line in lines if line[1] < border[1]]
                            for lines, border in zip(quadruple, borders)]
                return clusters, borders
    return clusters, None
Example #4
0
 def center_coordinates(minlat, minlon, maxlat, maxlon):
     """Center the coordinate around (0,0) and returns the offsets between earth and local world coordinate."""
     x1, z1 = Projection.project(minlon, minlat)
     x2, z2 = Projection.project(maxlon, maxlat)
     xOffset = (x1 + x2) / 2
     zOffset = (z1 + z2) / 2
     for osmid in OSMCoord.coordDictionnary:
         # inverse X, because OSM and Webots X are inversed
         OSMCoord.coordDictionnary[osmid].x = -OSMCoord.coordDictionnary[osmid].x + xOffset
         OSMCoord.coordDictionnary[osmid].z = OSMCoord.coordDictionnary[osmid].z - zOffset
     return xOffset, zOffset
Example #5
0
 def __init__(self, scale=1.0, fov=97.62815):
     # 106.2602 comes from 2*atan(4/3), to give the 90 deg inner image a dim of 3/4 of the full dim.
     # 97.62815 comes from 2*atan(8/7), for 7/8 image as inner 90 deg
     self.scale = scale
     self.proj = {
         'forward': Projection(xrot=0.0, yrot=0.0, fov=fov, aspect=1.0),
         'left': Projection(xrot=0.0, yrot=-90.0, fov=fov, aspect=1.0),
         'right': Projection(xrot=0.0, yrot=90.0, fov=fov, aspect=1.0),
         'up': Projection(xrot=-90.0, yrot=0.0, fov=fov, aspect=1.0),
         'down': Projection(xrot=90.0, yrot=0.0, fov=fov, aspect=1.0)
     }
Example #6
0
def create_projection():
    database_url = os.environ[DATABASE_URL]
    database_replica_set = os.environ[DATABASE_REPLICA_SET]
    database_name = os.environ[DATABASE_NAME]
    parent_filename = request.json[PARENT_FILENAME_NAME]
    projection_filename = request.json[PROJECTION_FILENAME_NAME]
    projection_fields = request.json[FIELDS_NAME]

    database = Database(
        database_url,
        database_replica_set,
        os.environ[DATABASE_PORT],
        database_name,
    )

    request_validator = UserRequest(database)

    request_errors = analyse_request_errors(request_validator, parent_filename,
                                            projection_filename,
                                            projection_fields)

    if request_errors is not None:
        return request_errors

    database_url_input = Database.collection_database_url(
        database_url,
        database_name,
        parent_filename,
        database_replica_set,
    )

    database_url_output = Database.collection_database_url(
        database_url,
        database_name,
        projection_filename,
        database_replica_set,
    )

    metadata_creator = Metadata(database)
    projection = Projection(metadata_creator, database_url_input,
                            database_url_output)

    projection.create(parent_filename, projection_filename, projection_fields)

    return (
        jsonify({
            MESSAGE_RESULT:
            MICROSERVICE_URI_GET + projection_filename +
            MICROSERVICE_URI_GET_PARAMS
        }),
        HTTP_STATUS_CODE_SUCCESS_CREATED,
    )
Example #7
0
 def find_projection(self, proj_id, movie_id):
     chosen_proj = Projection()
     chosen_movie = self.find_movie(movie_id)
     for projection in chosen_movie.projections:
         if projection.id == proj_id:
             chosen_proj = projection
     return chosen_proj
Example #8
0
 def add_projection(self, movie_id, type, date, time):
     projection = Projection(movie_id=movie_id,
                             type=type,
                             date=date,
                             time=time)
     self.session.add(projection)
     self.session.commit()
 def add_projections(self, data_for_projections):
     projections = []
     for projection in data_for_projections:
         projections.append(
             Projection(type=projection[0],
                        dateTime=projection[1],
                        movie_id=projection[2]))
Example #10
0
 def add_projection(self):
     type_ = input('type>')
     date_ = input('date>')
     time_ = input('time>')
     movie_id = int(input('movie_id'))
     new_projection = Projection(type_=type_, date_=date_, time_=time_, movie_id=movie_id)
     self.__session.add(new_projection)
     self.__session.commit()
Example #11
0
 def add(osmid, long, lat):
     """Add a new coordinate to the list from longitude latitude."""
     coord = OSMCoord()
     coord.OSMID = osmid
     coord.long = long
     coord.lat = lat
     coord.x, coord.z = Projection.project(coord.long, coord.lat)
     OSMCoord.coordDictionnary[osmid] = coord
Example #12
0
 def add(osmid, long, lat, tags):
     """Add a new node to the list from longitude latitude."""
     node = OSMNode()
     node.OSMID = osmid
     node.long = long
     node.lat = lat
     node.x, node.z = Projection.project(node.long, node.lat)
     node.tags = tags
     OSMNode.nodeDictionnary[osmid] = node
Example #13
0
    def read_from_file(self, filename):

        # Open data file for reading
        # File must be kept open, otherwise GDAL methods segfault.
        fid = self.fid = gdal.Open(filename, gdal.GA_ReadOnly)
        if fid is None:
            msg = 'Could not open file %s' % filename
            raise Exception(msg)

        # Record raster metadata from file
        basename, ext = os.path.splitext(filename)

        # If file is ASCII, check that projection is around.
        # GDAL does not check this nicely, so it is worth an
        # error message
        if ext == '.asc':
            try:
                open(basename + '.prj')
            except IOError:
                msg = ('Projection file not found for %s. You must supply '
                       'a projection file with extension .prj' % filename)
                raise RuntimeError(msg)

        # Look for any keywords
        self.keywords = read_keywords(basename + '.keywords')

        # Determine name
        if 'title' in self.keywords:
            rastername = self.keywords['title']
        else:
            # Use basename without leading directories as name
            rastername = os.path.split(basename)[-1]

        self.name = rastername
        self.filename = filename

        self.projection = Projection(self.fid.GetProjection())
        self.geotransform = self.fid.GetGeoTransform()
        self.columns = fid.RasterXSize
        self.rows = fid.RasterYSize
        self.number_of_bands = fid.RasterCount

        # Assume that file contains all data in one band
        msg = 'Only one raster band currently allowed'
        if self.number_of_bands > 1:
            msg = ('WARNING: Number of bands in %s are %i. '
                   'Only the first band will currently be '
                   'used.' % (filename, self.number_of_bands))
            # FIXME(Ole): Let us use python warnings here
            raise Exception(msg)

        # Get first band.
        band = self.band = fid.GetRasterBand(1)
        if band is None:
            msg = 'Could not read raster band from %s' % filename
            raise Exception(msg)
Example #14
0
 def calc_brightness(self):
     """
     Project the electron number density or gas mass density profile
     to calculate the 2D surface brightness profile.
     """
     if self.cf_radius is None or self.cf_value is None:
         raise ValueError("cooling function profile missing")
     if self.cf_spline is None:
         self.fit_spline(spline="cooling_function", log10=[])
     #
     ne = self.calc_density_electron()
     # flux per unit volume
     cf_new = self.eval_spline(spline="cooling_function", x=self.r)
     flux = cf_new * ne**2 / AstroParams.ratio_ne_np
     # project the 3D flux into 2D brightness
     rout = (self.r + self.r_err) * au.kpc.to(au.cm)
     projector = Projection(rout)
     brightness = projector.project(flux)
     return brightness
Example #15
0
 def __init__(self, id, name, rating):
     proj = Movie.cursor.execute("SELECT * FROM projections")
     self.id = id
     self.name = name
     self.rating = rating
     self.projections = []
     for row in proj:
         if row[1] == self.id:
             self.projections.append(
                 Projection(row[0], row[1], row[2], row[3], row[4]))
Example #16
0
 def check0(self, ch, w, debug=False):
     env = Env(w, [])
     visitor = Projection()
     visitor.execute(ch, env, debug)
     chor = visitor.choreography
     vectorize(chor, w)
     checker = CompatibilityCheck(chor, w)
     checker.localChoiceChecks()
     checker.generateTotalGuardsChecks()
     checker.computePreds(debug)
     checker.generateCompatibilityChecks(debug)
     for i in range(0, len(checker.vcs)):
         vc = checker.vcs[i]
         if not vc.discharge(debug=debug):
             print(i, "inFP", vc.title)
             if vc.hasModel():
                 print(vc.modelStr())
             return False
     return True
Example #17
0
def print_header(file, minlat, minlon, maxlat, maxlon, elevation=None):
    """Print the 'WorldInfo', 'Viewpoint', 'TexturedBackground', 'TexturedBackgroundLight' and 'Floor' nodes."""
    xSize, zSize = get_world_size(minlat=minlat,
                                  minlon=minlon,
                                  maxlat=maxlat,
                                  maxlon=maxlon)
    file.write("#VRML_SIM R2021a utf8\n")
    file.write("WorldInfo {\n")
    file.write("  info [\n")
    file.write(
        "    \"World generated using the Open Street Map to Webots importer\"\n"
    )
    file.write("    \"Author: David Mansolino <*****@*****.**>\"\n")
    file.write("  ]\n")
    file.write("  coordinateSystem \"NUE\"\n")
    longitude = (float(maxlon) + float(minlon)) / 2
    latitude = (float(maxlat) + float(minlat)) / 2
    x, z = Projection.project(longitude, latitude)
    height = 0
    if elevation is not None:
        height = elevation.interpolate_height(x, z)
    file.write("  gpsCoordinateSystem \"WGS84\"\n")
    file.write("  gpsReference " + str(latitude) + " " + str(longitude) + " " +
               str(height) + "\n")
    file.write("  lineScale " + str(round(max(xSize, zSize) / 200.0)) + "\n")
    file.write("}\n")
    file.write("Viewpoint {\n")
    file.write("  orientation 0.305 0.902 0.305 4.609\n")
    position = round(xSize * math.cos(0.785) * 1.5 +
                     zSize * math.cos(0.785) * 1.5)
    file.write("  position " + str(-position * 1.25) + " " + str(position) +
               " 0\n")
    file.write("  near 3\n")
    file.write("}\n")
    file.write("TexturedBackground {\n")
    file.write("}\n")
    file.write("TexturedBackgroundLight {\n")
    file.write("}\n")
    if elevation is None:
        file.write("Floor {\n")
        file.write("  translation 0 -0.02 0\n")
        file.write("  size " + str(round(1.5 * xSize)) + " " +
                   str(round(1.5 * zSize)) + "\n")
        file.write("  appearance PBRAppearance {\n")
        file.write("    baseColorMap ImageTexture {\n")
        file.write("      url [\n")
        file.write("        \"textures/grass.jpg\"\n")
        file.write("      ]\n")
        file.write("    }\n")
        file.write("    roughness 1\n")
        file.write("    metalness 0\n")
        file.write("  }\n")
        file.write("}\n")
    else:
        file.write(elevation.floorString)
Example #18
0
File: layer.py Project: vck/inasafe
    def __init__(self,
                 name=None,
                 projection=None,
                 keywords=None,
                 style_info=None,
                 sublayer=None):
        """Common constructor for all types of layers

        See docstrings for class Raster and class Vector for details.
        """

        # Name
        msg = ('Specified name  must be a string or None. '
               'I got %s with type %s' % (name, str(type(name))[1:-1]))
        verify(isinstance(name, basestring) or name is None, msg)
        self.name = name

        # Projection
        self.projection = Projection(projection)

        # Keywords
        if keywords is None:
            self.keywords = {}
        else:
            msg = ('Specified keywords must be either None or a '
                   'dictionary. I got %s' % keywords)
            verify(isinstance(keywords, dict), msg)
            self.keywords = keywords

        # Style info
        if style_info is None:
            self.style_info = {}
        else:
            msg = ('Specified style_info must be either None or a '
                   'dictionary. I got %s' % style_info)
            verify(isinstance(style_info, dict), msg)
            self.style_info = style_info

        # Defaults
        self.sublayer = sublayer
        self.filename = None
        self.data = None
Example #19
0
 def make_reservation(self):
     while True:
         name = input("Step 1 (User) Choose name> ")
         if name == "give_up":
             break
         num_tickets = input("Step 1 (User) Choose the number of tickets> ")
         if num_tickets == "give_up":
             break
         num_tickets = int(num_tickets)
         print("Current movies:")
         self.show_movies()
         chosen_movie = None
         chosen_proj = Projection()
         movie_id = input("Step 2 (Movie) Choose a movie> ")
         if movie_id == "give_up":
             break
         movie_id = int(movie_id)
         chosen_movie = self.find_movie(movie_id)
         for projection in chosen_movie.projections:
             projection.load_reservations(projection.id)
         print("Projections for movie {}".format(chosen_movie.name))
         self.show_projection(movie_id)
         proj_id = input("Step 3 (Projection) Choose projection> ")
         if proj_id == "give_up":
             break
         proj_id = int(proj_id)
         print("Available seats (marked with a dot):")
         chosen_proj = self.find_projection(proj_id, movie_id)
         print(chosen_proj.id)
         chosen_proj.show_seats()
         seats = []
         seats = self.choose_seats(num_tickets, chosen_proj)
         if seats is False:
             break
         chosen_proj.show_seats()
         self.print_reservation_details(chosen_movie, chosen_proj, seats)
         command = input("To finalize type <finalize>: ")
         if command == "finalize":
             for seat in seats:
                 manage_tables.add_reservations(name, chosen_proj.id, seat[0], seat[1])
Example #20
0
def create_projection():
    parent_filename = request.json[PARENT_FILENAME_NAME]
    projection_filename = request.json[PROJECTION_FILENAME_NAME]
    projection_fields = request.json[FIELDS_NAME]

    request_errors = analyse_request_errors(request_validator, parent_filename,
                                            projection_filename,
                                            projection_fields)

    if request_errors is not None:
        return request_errors

    database_url_input = Database.collection_database_url(
        database_url,
        database_name,
        parent_filename,
        database_replica_set,
    )

    database_url_output = Database.collection_database_url(
        database_url,
        database_name,
        projection_filename,
        database_replica_set,
    )

    metadata_creator = Metadata(database)
    projection = Projection(metadata_creator, database_url_input,
                            database_url_output)

    projection.create(parent_filename, projection_filename, projection_fields)

    return (
        jsonify({
            MESSAGE_RESULT:
            f'{MICROSERVICE_URI_GET}{projection_filename}'
            f'{MICROSERVICE_URI_GET_PARAMS}'
        }),
        HTTP_STATUS_CODE_SUCCESS_CREATED,
    )
Example #21
0
def main():
    engine = create_engine("sqlite:///cinema_database.db")
    Base.metadata.create_all(engine)
    session = Session(bind=engine)

    session.add_all([
        Movie(name="The Hunger Games: Catching Fire", rating=7.9),
        Movie(name="Wreck-It Ralph", rating=7.8),
        Movie(name="Her", rating=8.3)
    ])

    session.add_all([
        Projection(movie_id=1, type="3D", date="2014-04-01", time="19:10"),
        Projection(movie_id=1, type="2D", date="2014-04-01", time="19:00"),
        Projection(movie_id=1, type="4DX", date="2014-04-02", time="21:00"),
        Projection(movie_id=3, type="2D", date="2014-04-05", time="20:20"),
        Projection(movie_id=2, type="3D", date="2014-04-02", time="22:00"),
        Projection(movie_id=2, type="2D", date="2014-04-02", time="19:30")
    ])

    session.add_all([
        Reservation(username="******", projection_id=1, row=2, col=1),
        Reservation(username="******", projection_id=1, row=3, col=5),
        Reservation(username="******", projection_id=1, row=7, col=8),
        Reservation(username="******", projection_id=3, row=1, col=1),
        Reservation(username="******", projection_id=3, row=1, col=2),
        Reservation(username="******", projection_id=5, row=2, col=3),
        Reservation(username="******", projection_id=5, row=2, col=4)
    ])

    session.commit()
Example #22
0
def print_header(file, minlat, minlon, maxlat, maxlon, elevation=None):
    """Print the 'WorldInfo', 'Viewpoint', 'TexturedBackground', 'TexturedBackgroundLight' and 'Floor' nodes."""
    xSize, zSize = get_world_size(minlat=minlat,
                                  minlon=minlon,
                                  maxlat=maxlat,
                                  maxlon=maxlon)
    file.write("#VRML_SIM R2018a utf8\n")
    file.write("WorldInfo {\n")
    file.write("  info [\n")
    file.write(
        "    \"World generated using the Open Street Map to Webots importer\"\n"
    )
    file.write("    \"Author: David Mansolino <*****@*****.**>\"\n")
    file.write("  ]\n")
    file.write("  northDirection 0 0 1\n")
    longitude = (float(maxlon) + float(minlon)) / 2
    latitude = (float(maxlat) + float(minlat)) / 2
    x, z = Projection.project(longitude, latitude)
    height = 0
    if elevation is not None:
        height = elevation.interpolate_height(x, z)
    file.write("  gpsCoordinateSystem \"WGS84\"\n")
    file.write("  gpsReference " + str(latitude) + " " + str(longitude) + " " +
               str(height) + "\n")
    file.write("  lineScale " + str(round(max(xSize, zSize) / 200.0)) + "\n")
    file.write("}\n")
    file.write("Viewpoint {\n")
    file.write("  orientation 0 0.92 0.38 3.1416\n")
    position = round(xSize * math.cos(0.785) * 1.5 +
                     zSize * math.cos(0.785) * 1.5)
    file.write("  position 0 " + str(position) + " " + str(-position) + "\n")
    file.write("  near 3\n")
    file.write("}\n")
    file.write("TexturedBackground {\n")
    file.write("}\n")
    file.write("TexturedBackgroundLight {\n")
    file.write("}\n")
    file.write("Fog {\n")
    file.write("  color 0.93 0.96 1.0\n")
    file.write("  visibilityRange %s\n" % (max(3000, xSize, zSize)))
    file.write("}\n")
    if elevation is None:
        file.write("Floor {\n")
        file.write("  translation 0 -0.02 0\n")
        file.write("  size " + str(round(1.5 * xSize)) + " " +
                   str(round(1.5 * zSize)) + "\n")
        file.write("  texture [\n")
        file.write("    \"textures/grass.jpg\"\n")
        file.write("  ]\n")
        file.write("}\n")
    else:
        file.write(elevation.floorString)
Example #23
0
 def add_projection(self):
     movie_id = input("Type the movie_id: ")
     movie_name = self.get_movie_title_by_id(movie_id)
     print("Adding projection for " + movie_name)
     type = input("Enter the type of the projection: ")
     date = self.obtain_date()
     time = self.obtain_time()
     projection = Projection(type=type,
                             date=date,
                             time=time,
                             movie_id=movie_id)
     self.__session.add(projection)
     self.__session.commit()
Example #24
0
def main():
    """The main function in which everything you run should start."""
    # Make sure that the output/ directory exists, or create it otherwise.
    output_dir = pathlib.Path.cwd() / "output"
    if not output_dir.is_dir():
        output_dir.mkdir()


#DAY 1
    print("DAY 1 \nSquare Trial")
    rectangle_1 = Rectangle(-1, 0, -1, 0, 1)
    rectangle_2 = Rectangle(0, 1, 0, 1, .5)
    circle_1 = Circle(.8, .1, .05, 1)
    #attenuation for a rectangle
    print('The attenuation at your point for the is:',
          rectangle_1.attenuation(7, 0))
    collection = ObjectCollection()
    #collection.append(rectangle_1)
    #collection.append(rectangle_2)
    collection.append(circle_1)

    #print(Projection.theta(theta_idx))

    #DAY 2
    #attenutation of a circle because this would be useful for changing the
    #coordinates of eta and xi
    print('\nDAY 2 \nCircle Trial')

    print('The attenuation at (1.2 , 1.2):', circle_1.attenuation(1.2, 1.2))
    print('Integrated attenuation for a given eta:',
          circle_1.project_attenuation(np.pi, 0, (-2, 2)))
    myproj = Projection([0, np.pi], 100, [-2, 2], 100)
    myproj.add_object(collection, (-2, 2))

    array_to_img(
        collection.to_array(np.linspace(-2, 2, 100), np.linspace(
            -2, 2, 100))).save(output_dir / "myproj1(.8, .1, .05, 1).png")

    array_to_img(myproj.data).save(output_dir / "sin(.8, .1, .05, 1).png")
Example #25
0
    def __init__(self, w, h):
        self.res = self.w, self.h = w, h

        self.screen = pg.display.set_mode((w, h))
        self.clock = pg.time.Clock()

        self.fps = 60

        self.objects = []

        self.camera = Camera(self, (0, 0, 0))
        self.camera.camera_yaw(radians(190))
        self.projection = Projection(self)
Example #26
0
    def calc_electron_density(self):
        """
        Deproject the surface brightness profile to derive the 3D
        electron number density (and then gas mass density) profile
        by incorporating the cooling function profile.

        unit: [ cm^-3 ] if the units converted for input data
        """
        if self.s_spline is None:
            self.fit_spline(spline="brightness", log10=["x", "y"])
        if self.cf_spline is None:
            self.fit_spline(spline="cooling_function", log10=[])
        #
        s_new = self.eval_spline(spline="brightness", x=self.r)
        cf_new = self.eval_spline(spline="cooling_function", x=self.r)
        #
        projector = Projection(rout=self.r + self.r_err)
        s_deproj = projector.deproject(s_new)
        # emission measure per unit volume
        em_v = s_deproj / cf_new
        ne = np.sqrt(em_v * AstroParams.ratio_ne_np)
        self.ne = ne
        return ne
Example #27
0
 def check(self, P1, P2):
     w = World()
     p1 = P1(w, 0)
     p2 = P2(w, 1)
     env = Env(w, [])
     ch = choreo()
     visitor = Projection()
     visitor.execute(ch, env)
     chor = visitor.choreography
     vectorize(chor, w)
     checker = CompatibilityCheck(chor, w)
     checker.localChoiceChecks()
     checker.generateTotalGuardsChecks()
     checker.computePreds()
     checker.generateCompatibilityChecks()
     for i in range(0, len(checker.vcs)):
         vc = checker.vcs[i]
         if not vc.discharge():
             print(i, "inFP", vc.title)
             if vc.hasModel():
                 print(vc.modelStr())
             return False
     return True
Example #28
0
class GenerateReprojectedImages(object):
    def __init__(self, name, scale, xrot=0.0, yrot=0.0, fov=90.0, aspect=1.0):
        self.name = "reproj_" + name
        self.scale = scale
        self.proj = Projection(xrot=xrot, yrot=yrot, fov=fov, aspect=aspect)

    def __call__(self, sample):
        input_dim = (sample['generated'].shape[1], sample['generated'].shape[0])
        output_dim = (input_dim[0] * self.scale, input_dim[1] * self.scale)
        phi, theta = self.proj.generate_map(output_dim=output_dim, input_dim=input_dim)
        interpolation = cv2.INTER_AREA
        remap = cv2.remap(sample['generated'], phi, theta, interpolation=interpolation, borderValue=0,
                          borderMode=cv2.BORDER_CONSTANT)
        sample[self.name] = remap

        return sample
def create_table_projcetions():
    projectionscount = 6
    projections = [Projection() for i in range(projectionscount)]

    movie_id = [1, 1, 1, 3, 2, 2]
    types = ["3D", "2D", "4DX", "2D", "3D", "2D"]
    datetimes = [[2014, 4, 1, 19, 10], [2014, 4, 1, 19, 00],
                 [2014, 4, 2, 21, 00], [2014, 4, 5, 20, 20],
                 [2014, 4, 2, 22, 00], [2014, 4, 2, 19, 30]]

    for i in range(projectionscount):
        projections[i].movie_id = movie_id[i]
        projections[i].type = types[i]
        projections[i].datetime = datetime(*datetimes[i])

    session.add_all(projections)
Example #30
0
 def loadModules(self):
   self.modules['poi']['rss'] = geoRss(self.modules,
                                       os.path.join(os.path.dirname(__file__),
                                                    'Setup', 'feeds.txt'))
   #self.modules['poi']['geonames'] = geonames(self.modules)
   #self.modules['poi']['waypoints'] = waypointsModule(self.modules, "data/waypoints.gpx")
   self.modules['poi']['osm'] = osmPoiModule(self.modules)
   self.modules['overlay'] = guiOverlay(self.modules)
   self.modules['position'] = geoPosition()
   self.modules['tiles'] = tileHandler(self.modules)
   self.modules['data'] = DataStore(self.modules)
   self.modules['events'] = pyrouteEvents(self.modules)
   self.modules['sketch'] = sketching(self.modules)
   self.modules['osmdata'] = osmData(self.modules)
   self.modules['projection'] = Projection()
   self.modules['tracklog'] = tracklog(self.modules)
   self.modules['meta'] = moduleInfo(self.modules)
   self.modules['route'] = RouteOrDirect(self.modules['osmdata'].data)
Example #31
0
    def forward(self, volume, image_features, projection_indices_3d,
                projection_indices_2d, volume_dims):
        assert len(volume.shape) == 5 and len(image_features.shape) == 4
        batch_size = volume.shape[0]
        num_images = projection_indices_3d.shape[0] // batch_size

        # project 2d to 3d
        image_features = [
            Projection.apply(ft, ind3d, ind2d, volume_dims)
            for ft, ind3d, ind2d in zip(image_features, projection_indices_3d,
                                        projection_indices_2d)
        ]
        image_features = torch.stack(image_features, dim=4)

        # reshape to max pool over features
        sz = image_features.shape
        image_features = image_features.view(sz[0], -1,
                                             batch_size * num_images)
        if num_images == self.num_images:
            image_features = self.pooling(image_features)
        else:
            image_features = nn.MaxPool1d(
                kernel_size=num_images)(image_features)
        image_features = image_features.view(sz[0], sz[1], sz[2], sz[3],
                                             batch_size)
        image_features = image_features.permute(4, 0, 1, 2, 3)

        volume = self.features3d(volume)
        image_features = self.features2d(image_features)
        x = torch.cat([volume, image_features], 1)
        x = self.features(x)
        x = x.view(batch_size, self.nf2 * 54)
        semantic_output = self.semanticClassifier(x)
        semantic_output = semantic_output.view(batch_size, self.grid_dims[2],
                                               self.num_classes)
        scan_output = None
        if self.train_scan_completion:
            scan_output = self.scanClassifier(x)
            # scan_output - [batch_size, 62, 2]
            scan_output = scan_output.view(
                batch_size, self.grid_dims[2],
                3)  # 3 represents voxel grid occupancy values
        return semantic_output, scan_output
Example #32
0
    def __init__(self, name=None, projection=None,
                 keywords=None, style_info=None,
                 sublayer=None):
        """Common constructor for all types of layers

        See docstrings for class Raster and class Vector for details.
        """

        # Name
        msg = ('Specified name  must be a string or None. '
               'I got %s with type %s' % (name, str(type(name))[1:-1]))
        verify(isinstance(name, basestring) or name is None, msg)
        self.name = name

        # Projection
        self.projection = Projection(projection)

        # Keywords
        if keywords is None:
            self.keywords = {}
        else:
            msg = ('Specified keywords must be either None or a '
                   'dictionary. I got %s' % keywords)
            verify(isinstance(keywords, dict), msg)
            self.keywords = keywords

        # Style info
        if style_info is None:
            self.style_info = {}
        else:
            msg = ('Specified style_info must be either None or a '
                   'dictionary. I got %s' % style_info)
            verify(isinstance(style_info, dict), msg)
            self.style_info = style_info

        # Defaults
        self.sublayer = sublayer
        self.filename = None
        self.data = None
Example #33
0
class Vector:
    """Class for abstraction of vector data
    """

    def __init__(self, data=None, projection=None, geometry=None,
                 name='', keywords=None, style_info=None):
        """Initialise object with either geometry or filename

        Input
            data: Can be either
                * a filename of a vector file format known to GDAL
                * List of dictionaries of fields associated with
                  point coordinates
                * None
            projection: Geospatial reference in WKT format.
                        Only used if geometry is provide as a numeric array,
            geometry: A list of either point coordinates or polygons
            name: Optional name for layer.
                  Only used if geometry is provide as a numeric array
            keywords: Optional dictionary with keywords that describe the
                      layer. When the layer is stored, these keywords will
                      be written into an associated file with extension
                      .keywords.

                      Keywords can for example be used to display text
                      about the layer in a web application.

        Note that if data is a filename, all other arguments are ignored
        as they will be inferred from the file.

        The geometry type will be inferred from the dimensions of geometry.
        If each entry is one set of coordinates the type will be ogr.wkbPoint,
        if it is an array of coordinates the type will be ogr.wkbPolygon.
        """

        if data is None and projection is None and geometry is None:
            # Instantiate empty object
            self.name = name
            self.projection = None
            self.geometry = None
            self.geometry_type = None
            self.filename = None
            self.data = None
            self.extent = None
            self.keywords = {}
            self.style_info = {}
            return

        if isinstance(data, basestring):
            self.read_from_file(data)
        else:
            # Assume that data is provided as sequences provided as
            # arguments to the Vector constructor
            # with extra keyword arguments supplying metadata

            self.name = name
            self.filename = None

            if keywords is None:
                self.keywords = {}
            else:
                msg = ('Specified keywords must be either None or a '
                       'dictionary. I got %s' % keywords)
                assert isinstance(keywords, dict), msg
                self.keywords = keywords

            if style_info is None:
                self.style_info = {}
            else:
                msg = ('Specified style_info must be either None or a '
                       'dictionary. I got %s' % style_info)
                assert isinstance(style_info, dict), msg
                self.style_info = style_info

            msg = 'Geometry must be specified'
            assert geometry is not None, msg

            msg = 'Geometry must be a sequence'
            assert is_sequence(geometry), msg
            self.geometry = geometry

            self.geometry_type = get_geometry_type(geometry)

            #msg = 'Projection must be specified'
            #assert projection is not None, msg
            self.projection = Projection(projection)

            self.data = data
            if data is not None:
                msg = 'Data must be a sequence'
                assert is_sequence(data), msg

                msg = ('The number of entries in geometry and data '
                       'must be the same')
                assert len(geometry) == len(data), msg

            # FIXME: Need to establish extent here

    def __str__(self):
        """Render as name, number of features, geometry type
        """

        g_type_str = geometrytype2string(self.geometry_type)
        return ('Vector data set: %s, %i features, geometry type '
                '%s (%s)' % (self.name,
                             len(self),
                             str(self.geometry_type),
                             g_type_str))

    def __len__(self):
        """Size of vector layer defined as number of features
        """

        return len(self.geometry)

    def __eq__(self, other, rtol=1.0e-5, atol=1.0e-8):
        """Override '==' to allow comparison with other vector objecs

        Input
           other: Vector instance to compare to
           rtol, atol: Relative and absolute tolerance.
                       See numpy.allclose for details
        """

        # Check type
        if not isinstance(other, Vector):
            msg = ('Vector instance cannot be compared to %s'
                   ' as its type is %s ' % (str(other), type(other)))
            raise TypeError(msg)

        # Check projection
        if self.projection != other.projection:
            return False

        # Check geometry
        if not numpy.allclose(self.get_geometry(),
                              other.get_geometry(),
                              rtol=rtol, atol=atol):
            return False

        # Check keys
        x = self.get_data()
        y = other.get_data()

        for key in x[0]:
            for i in range(len(y)):
                if key not in y[i]:
                    return False

        for key in y[0]:
            for i in range(len(x)):
                if key not in x[i]:
                    return False

        # Check data
        for i, a in enumerate(x):
            for key in a:
                X = a[key]
                Y = y[i][key]
                if X != Y:
                    # Not obviously equal, try some special cases

                    res = None
                    try:
                        # try numerical comparison with tolerances
                        res = numpy.allclose(X, Y,
                                             rtol=rtol, atol=atol)
                    except:
                        pass
                    else:
                        if not res:
                            return False

                    try:
                        # Try to cast as booleans. This will take care of
                        # None, '', True, False, ...
                        res = (bool(X) is bool(Y))
                    except:
                        pass
                    else:
                        if not res:
                            return False

                    if res is None:
                        # None of the comparisons could be done
                        return False

        # Check keywords
        if self.keywords != other.keywords:
            return False

        # Vector layers are identical up to the specified tolerance
        return True

    def __ne__(self, other):
        """Override '!=' to allow comparison with other projection objecs
        """
        return not self == other

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_filename(self):
        return self.filename

    def get_keywords(self, key=None):
        """Return keywords dictionary
        """
        if key is None:
            return self.keywords
        else:
            if key in self.keywords:
                return self.keywords[key]
            else:
                msg = ('Keyword %s does not exist in %s: Options are '
                       '%s' % (key, self.get_name(), self.keywords.keys()))
                raise Exception(msg)

    def get_style_info(self):
        """Return style_info dictionary
        """
        return self.style_info

    def get_caption(self):
        """Return 'caption' keyword if present. Otherwise ''.
        """
        if 'caption' in self.keywords:
            return self.keywords['caption']
        else:
            return ''

    def read_from_file(self, filename):
        """ Read and unpack vector data.

        It is assumed that the file contains only one layer with the
        pertinent features. Further it is assumed for the moment that
        all geometries are points.

        * A feature is a geometry and a set of attributes.
        * A geometry refers to location and can be point, line, polygon or
          combinations thereof.
        * The attributes or obtained through GetField()

        The full OGR architecture is documented at
        * http://www.gdal.org/ogr/ogr_arch.html
        * http://www.gdal.org/ogr/ogr_apitut.html

        Examples are at
        * danieljlewis.org/files/2010/09/basicpythonmap.pdf
        * http://invisibleroads.com/tutorials/gdal-shapefile-points-save.html
        * http://www.packtpub.com/article/geospatial-data-python-geometry
        """

        basename, _ = os.path.splitext(filename)

        # Look for any keywords
        self.keywords = read_keywords(basename + '.keywords')

        # FIXME (Ole): Should also look for style file to populate style_info

        # Determine name
        if 'title' in self.keywords:
            vectorname = self.keywords['title']
        else:
            # Use basename without leading directories as name
            vectorname = os.path.split(basename)[-1]

        self.name = vectorname
        self.filename = filename
        self.geometry_type = None  # In case there are no features

        fid = ogr.Open(filename)
        if fid is None:
            msg = 'Could not open %s' % filename
            raise IOError(msg)

        # Assume that file contains all data in one layer
        msg = 'Only one vector layer currently allowed'
        if fid.GetLayerCount() > 1:
            msg = ('WARNING: Number of layers in %s are %i. '
                   'Only the first layer will currently be '
                   'used.' % (filename, fid.GetLayerCount()))
            raise Exception(msg)

        layer = fid.GetLayerByIndex(0)

        # Get spatial extent
        self.extent = layer.GetExtent()

        # Get projection
        p = layer.GetSpatialRef()
        self.projection = Projection(p)

        # Get number of features
        N = layer.GetFeatureCount()

        # Extract coordinates and attributes for all features
        geometry = []
        data = []
        for i in range(N):
            feature = layer.GetFeature(i)
            if feature is None:
                msg = 'Could not get feature %i from %s' % (i, filename)
                raise Exception(msg)

            # Record coordinates ordered as Longitude, Latitude
            G = feature.GetGeometryRef()
            if G is None:
                msg = ('Geometry was None in filename %s ' % filename)
                raise Exception(msg)
            else:
                self.geometry_type = G.GetGeometryType()
                if self.geometry_type == ogr.wkbPoint:
                    geometry.append((G.GetX(), G.GetY()))
                elif self.geometry_type == ogr.wkbLineString:
                    M = G.GetPointCount()
                    coordinates = []
                    for j in range(M):
                        coordinates.append((G.GetX(j), G.GetY(j)))

                    # Record entire line as an Mx2 numpy array
                    geometry.append(numpy.array(coordinates,
                                                dtype='d',
                                                copy=False))
                elif self.geometry_type == ogr.wkbPolygon:
                    ring = G.GetGeometryRef(0)
                    M = ring.GetPointCount()
                    coordinates = []
                    for j in range(M):
                        coordinates.append((ring.GetX(j), ring.GetY(j)))

                    # Record entire polygon ring as an Mx2 numpy array
                    geometry.append(numpy.array(coordinates,
                                                dtype='d',
                                                copy=False))
                #elif self.geometry_type == ogr.wkbMultiPolygon:
                #    # FIXME: Unpact multiple polygons to simple polygons
                #    # For hints on how to unpack see
#http://osgeo-org.1803224.n2.nabble.com/
#gdal-dev-Shapefile-Multipolygon-with-interior-rings-td5391090.html

                #    ring = G.GetGeometryRef(0)
                #    M = ring.GetPointCount()
                #    coordinates = []
                #    for j in range(M):
                #        coordinates.append((ring.GetX(j), ring.GetY(j)))

                #    # Record entire polygon ring as an Mx2 numpy array
                #    geometry.append(numpy.array(coordinates,
                #                                dtype='d',
                #                                copy=False))

                else:
                    msg = ('Only point, line and polygon geometries are '
                           'supported. '
                           'Geometry type in filename %s '
                           'was %s.' % (filename,
                                        self.geometry_type))
                    raise Exception(msg)

            # Record attributes by name
            number_of_fields = feature.GetFieldCount()
            fields = {}
            for j in range(number_of_fields):
                name = feature.GetFieldDefnRef(j).GetName()

                # FIXME (Ole): Ascertain the type of each field?
                #              We need to cast each appropriately?
                #              This is issue #66
                #              (https://github.com/AIFDR/riab/issues/66)
                #feature_type = feature.GetFieldDefnRef(j).GetType()
                fields[name] = feature.GetField(j)
                #print 'Field', name, feature_type, j, fields[name]

            data.append(fields)

        # Store geometry coordinates as a compact numeric array
        self.geometry = geometry
        self.data = data

    def write_to_file(self, filename):
        """Save vector data to file

        Input
            filename: filename with extension .shp or .gml

        Note, if attribute names are longer than 10 characters they will be
        truncated. This is due to limitations in the shp file driver and has
        to be done here since gdal v1.7 onwards has changed its handling of
        this issue: http://www.gdal.org/ogr/drv_shapefile.html
        """

        # Check file format
        basename, extension = os.path.splitext(filename)

        msg = ('Invalid file type for file %s. Only extensions '
               'shp or gml allowed.' % filename)
        assert extension == '.shp' or extension == '.gml', msg
        driver = DRIVER_MAP[extension]

        # FIXME (Ole): Tempory flagging of GML issue (ticket #18)
        if extension == '.gml':
            msg = ('OGR GML driver does not store geospatial reference.'
                   'This format is disabled for the time being. See '
                   'https://github.com/AIFDR/riab/issues/18')
            raise Exception(msg)

        # Derive layername from filename (excluding preceding dirs)
        layername = os.path.split(basename)[-1]

        # Get vector data
        geometry = self.get_geometry()
        data = self.get_data()

        N = len(geometry)

        # Clear any previous file of this name (ogr does not overwrite)
        try:
            os.remove(filename)
        except:
            pass

        # Create new file with one layer
        drv = ogr.GetDriverByName(driver)
        if drv is None:
            msg = 'OGR driver %s not available' % driver
            raise Exception(msg)

        ds = drv.CreateDataSource(filename)
        if ds is None:
            msg = 'Creation of output file %s failed' % filename
            raise Exception(msg)

        lyr = ds.CreateLayer(layername,
                             self.projection.spatial_reference,
                             self.geometry_type)
        if lyr is None:
            msg = 'Could not create layer %s' % layername
            raise Exception(msg)

        # Define attributes if any
        store_attributes = False
        if data is not None:
            if len(data) > 0:
                try:
                    fields = data[0].keys()
                except:
                    msg = ('Input parameter "attributes" was specified '
                           'but it does not contain dictionaries with '
                           'field information as expected. The first'
                           'element is %s' % data[0])
                    raise Exception(msg)
                else:
                    # Establish OGR types for each element
                    ogrtypes = {}
                    for name in fields:
                        att = data[0][name]
                        py_type = type(att)
                        msg = ('Unknown type for storing vector '
                               'data: %s, %s' % (name, str(py_type)[1:-1]))
                        assert py_type in TYPE_MAP, msg
                        ogrtypes[name] = TYPE_MAP[py_type]

            else:
                msg = ('Input parameter "data" was specified '
                       'but appears to be empty')
                raise Exception(msg)

            # Create attribute fields in layer
            store_attributes = True
            for name in fields:
                fd = ogr.FieldDefn(name, ogrtypes[name])
                # FIXME (Ole): Trying to address issue #16
                #              But it doesn't work and
                #              somehow changes the values of MMI in test
                #width = max(128, len(name))
                #print name, width
                #fd.SetWidth(width)

                # Silent handling of warnings like
                # Warning 6: Normalized/laundered field name:
                #'CONTENTS_LOSS_AUD' to 'CONTENTS_L'
                gdal.PushErrorHandler('CPLQuietErrorHandler')
                if lyr.CreateField(fd) != 0:
                    msg = 'Could not create field %s' % name
                    raise Exception(msg)

                # Restore error handler
                gdal.PopErrorHandler()

        # Store geometry
        geom = ogr.Geometry(self.geometry_type)
        layer_def = lyr.GetLayerDefn()
        for i in range(N):
            # Create new feature instance
            feature = ogr.Feature(layer_def)

            # Store geometry and check
            if self.geometry_type == ogr.wkbPoint:
                x = float(geometry[i][0])
                y = float(geometry[i][1])
                geom.SetPoint_2D(0, x, y)
            elif self.geometry_type == ogr.wkbPolygon:
                wkt = array2wkt(geometry[i], geom_type='POLYGON')
                geom = ogr.CreateGeometryFromWkt(wkt)
            else:
                msg = 'Geometry type %s not implemented' % self.geometry_type
                raise Exception(msg)

            feature.SetGeometry(geom)

            G = feature.GetGeometryRef()
            if G is None:
                msg = 'Could not create GeometryRef for file %s' % filename
                raise Exception(msg)

            # Store attributes
            if store_attributes:
                for j, name in enumerate(fields):
                    actual_field_name = layer_def.GetFieldDefn(j).GetNameRef()

                    val = data[i][name]

                    if type(val) == numpy.ndarray:
                        # A singleton of type <type 'numpy.ndarray'> works
                        # for gdal version 1.6 but fails for version 1.8
                        # in SetField with error: NotImplementedError:
                        # Wrong number of arguments for overloaded function
                        val = float(val)
                    elif val is None:
                        val = ''

                    feature.SetField(actual_field_name, val)

            # Save this feature
            if lyr.CreateFeature(feature) != 0:
                msg = 'Failed to create feature %i in file %s' % (i, filename)
                raise Exception(msg)

            feature.Destroy()

        # Write keywords if any
        write_keywords(self.keywords, basename + '.keywords')

        # FIXME (Ole): Maybe store style_info

    def get_attribute_names(self):
        """ Get available attribute names

        These are the ones that can be used with get_data
        """

        return self.data[0].keys()

    def get_data(self, attribute=None, index=None):
        """Get vector attributes

        Data is returned as a list where each entry is a dictionary of
        attributes for one feature. Entries in get_geometry() and
        get_data() are related as 1-to-1

        If optional argument attribute is specified and a valid name,
        then the list of values for that attribute is returned.

        If optional argument index is specified on the that value will
        be returned. Any value of index is ignored if attribute is None.
        """

        if hasattr(self, 'data'):
            if attribute is None:
                return self.data
            else:
                msg = ('Specified attribute %s does not exist in '
                       'vector layer %s. Valid names are %s'
                       '' % (attribute, self, self.data[0].keys()))
                assert attribute in self.data[0], msg

                if index is None:
                    # Return all values for specified attribute
                    return [x[attribute] for x in self.data]
                else:
                    # Return value for specified attribute and index
                    msg = ('Specified index must be either None or '
                           'an integer. I got %s' % index)
                    assert type(index) == type(0)

                    msg = ('Specified index must lie within the bounds '
                           'of vector layer %s which is [%i, %i]'
                           '' % (self, 0, len(self) - 1))
                    assert 0 <= index < len(self)

                    return self.data[index][attribute]
        else:
            msg = 'Vector data instance does not have any attributes'
            raise Exception(msg)

    def get_geometry(self):
        """Return geometry for vector layer.

        Depending on the feature type, geometry is

        geometry type     output type
        -----------------------------
        point             coordinates (Nx2 array of longitudes and latitudes)
        line              TODO
        polygon           list of arrays of coordinates

        """
        return self.geometry

    def get_projection(self, proj4=False):
        """Return projection of this layer as a string
        """
        return self.projection.get_projection(proj4)

    def get_bounding_box(self):
        """Get bounding box coordinates for vector layer.

        Format is [West, South, East, North]
        """
        e = self.extent
        return [e[0],  # West
                e[2],  # South
                e[1],  # East
                e[3]]  # North

    def get_extrema(self, attribute=None):
        """Get min and max values from specified attribute

        Return min, max
        """
        if attribute is None:
            msg = ('Valid attribute name must be specified in get_extrema '
                   'for vector layers. I got None.')
            raise RuntimeError(msg)

        x = self.get_data(attribute)
        return min(x), max(x)

    def get_topN(self, attribute, N=10):
        """Get top N features

        Input
            attribute: The name of attribute where values are sought
            N: How many

        Output
            layer: New vector layer with selected features
        """

        # FIXME (Ole): Maybe generalise this to arbitrary expressions

        # Input checks
        msg = ('Specfied attribute must be a string. '
               'I got %s' % (type(attribute)))
        assert isinstance(attribute, basestring), msg

        msg = 'Specified attribute was empty'
        assert attribute != '', msg

        msg = 'N must be a positive number. I got %i' % N
        assert N > 0, msg

        # Create list of values for specified attribute
        values = self.get_data(attribute)

        # Sort and select using Schwarzian transform
        A = zip(values, self.data, self.geometry)
        A.sort()

        # Pick top N and unpack
        _, data, geometry = zip(*A[-N:])

        # Create new Vector instance and return
        return Vector(data=data,
                      projection=self.get_projection(),
                      geometry=geometry)

    def interpolate(self, X, name=None, attribute=None):
        """Interpolate values of this vector layer to other layer

        Input
            X: Layer object defining target
            name: Optional name of interpolated layer
            attribute: Optional attribute name to use.
                       If None, all attributes are used.

        Output
            Y: Layer object with values of this vector layer interpolated to
               geometry of input layer X
        """

        msg = 'Input to Vector.interpolate must be a vector layer instance'
        assert X.is_vector, msg

        X_projection = X.get_projection()
        S_projection = self.get_projection()

        msg = ('Projections must be the same: I got %s and %s'
               % (S_projection, X_projection))
        assert S_projection == X_projection, msg

        msg = ('Vector layer to interpolate from must be polygon geometry. '
               'I got OGR geometry type %s'
               % geometrytype2string(self.geometry_type))
        assert self.is_polygon_data, msg

        # FIXME (Ole): Maybe organise this the same way it is done with rasters
        if X.is_polygon_data:
            # Use centroids, in case of polygons
            X = convert_polygons_to_centroids(X)

        msg = ('Vector layer to interpolate to must be point geometry. '
               'I got OGR geometry type %s'
               % geometrytype2string(X.geometry_type))
        assert X.is_point_data, msg

        msg = ('Name must be either a string or None. I got %s'
               % (str(type(X)))[1:-1])
        assert name is None or isinstance(name, basestring), msg

        msg = ('Attribute must be either a string or None. I got %s'
               % (str(type(X)))[1:-1])
        assert attribute is None or isinstance(attribute, basestring), msg

        attribute_names = self.get_attribute_names()
        if attribute is not None:
            msg = ('Requested attribute "%s" did not exist in %s'
                   % (attribute, attribute_names))
            assert attribute in attribute_names, msg

        #----------------
        # Start algorithm
        #----------------

        # Extract point features
        points = ensure_numeric(X.get_geometry())
        attributes = X.get_data()
        N = len(X)

        # Extract polygon features
        geom = self.get_geometry()
        data = self.get_data()
        assert len(geom) == len(data)

        # Augment point features with empty attributes from polygon
        for a in attributes:
            if attribute is None:
                # Use all attributes
                for key in attribute_names:
                    a[key] = None
            else:
                # Use only requested attribute
                a[attribute] = None

            # Always create attribute to indicate if point was
            # inside any of the polygons
            a[DEFAULT_ATTRIBUTE] = None

        # Traverse polygons and assign attributes to points that fall inside
        for i, polygon in enumerate(geom):
            if attribute is None:
                # Use all attributes
                poly_attr = data[i]
            else:
                # Use only requested attribute
                poly_attr = {attribute: data[i][attribute]}

            # Assign default attribute to indicate points inside
            poly_attr[DEFAULT_ATTRIBUTE] = True

            # Clip data points by polygons and add polygon attributes
            indices = inside_polygon(points, polygon)
            for k in indices:
                for key in poly_attr:
                    # Assign attributes from polygon to points
                    attributes[k][key] = poly_attr[key]

        # Create new Vector instance and return
        V = Vector(data=attributes,
                   projection=X.get_projection(),
                   geometry=X.get_geometry())
        return V

    @property
    def is_raster(self):
        return False

    @property
    def is_vector(self):
        return True

    @property
    def is_point_data(self):
        return self.is_vector and self.geometry_type == ogr.wkbPoint

    @property
    def is_line_data(self):
        return self.is_vector and self.geometry_type == ogr.wkbLineString

    @property
    def is_polygon_data(self):
        return self.is_vector and self.geometry_type == ogr.wkbPolygon

    @property
    def is_riab_spatial_object(self):
        return True
Example #34
0
    def __init__(self, data=None, projection=None, geometry=None,
                 geometry_type=None,
                 name='', keywords=None, style_info=None):
        """Initialise object with either geometry or filename

        Input
            data: Can be either
                * a filename of a vector file format known to GDAL
                * List of dictionaries of fields associated with
                  point coordinates
                * None
            projection: Geospatial reference in WKT format.
                        Only used if geometry is provide as a numeric array,
            geometry: A list of either point coordinates or polygons/lines
                      (see note below)
            geometry_type: Desired interpretation of geometry.
                           Valid options are 'point', 'line', 'polygon' or
                           the ogr types: 1, 2, 3
                           If None, a geometry_type will be inferred
            name: Optional name for layer.
                  Only used if geometry is provide as a numeric array
            keywords: Optional dictionary with keywords that describe the
                      layer. When the layer is stored, these keywords will
                      be written into an associated file with extension
                      .keywords.

                      Keywords can for example be used to display text
                      about the layer in a web application.

        Notes

        If data is a filename, all other arguments are ignored
        as they will be inferred from the file.

        The geometry type will be inferred from the dimensions of geometry.
        If each entry is one set of coordinates the type will be ogr.wkbPoint,
        if it is an array of coordinates the type will be ogr.wkbPolygon.

        Each polygon or line feature take the form of an Nx2 array representing
        vertices where line segments are joined
        """

        if data is None and projection is None and geometry is None:
            # Instantiate empty object
            self.name = name
            self.projection = None
            self.geometry = None
            self.geometry_type = None
            self.filename = None
            self.data = None
            self.extent = None
            self.keywords = {}
            self.style_info = {}
            return

        if isinstance(data, basestring):
            self.read_from_file(data)
        else:
            # Assume that data is provided as sequences provided as
            # arguments to the Vector constructor
            # with extra keyword arguments supplying metadata

            self.name = name
            self.filename = None

            if keywords is None:
                self.keywords = {}
            else:
                msg = ('Specified keywords must be either None or a '
                       'dictionary. I got %s' % keywords)
                verify(isinstance(keywords, dict), msg)
                self.keywords = keywords

            if style_info is None:
                self.style_info = {}
            else:
                msg = ('Specified style_info must be either None or a '
                       'dictionary. I got %s' % style_info)
                verify(isinstance(style_info, dict), msg)
                self.style_info = style_info

            msg = 'Geometry must be specified'
            verify(geometry is not None, msg)

            msg = 'Geometry must be a sequence'
            verify(is_sequence(geometry), msg)
            self.geometry = geometry

            self.geometry_type = get_geometry_type(geometry, geometry_type)

            #msg = 'Projection must be specified'
            #verify(projection is not None, msg)
            self.projection = Projection(projection)

            if data is None:
                # Generate default attribute as OGR will do that anyway
                # when writing
                data = []
                for i in range(len(geometry)):
                    data.append({'ID': i})

            # Check data
            self.data = data
            if data is not None:
                msg = 'Data must be a sequence'
                verify(is_sequence(data), msg)

                msg = ('The number of entries in geometry and data '
                       'must be the same')
                verify(len(geometry) == len(data), msg)
Example #35
0
class Render(object):
    """
    This class handles the OpenGL rendering process

    This is separate from the pyglet rendering, as it runs using OpenGL
    directly
    """

# ------------------------------------------------------------------
# HANDLE INITIALIZATION
# ------------------------------------------------------------------

    def __init__(self, *args, **kwargs):
        """
        General initialization function for OpenGL, readying all the
        non-stimuli images and setting the parameters for rendering
        parameters
        """
        # Initialize the OpenGL parameters
        self.__init_GL()
        opengl_info()
        stereo = False

        if not STIMULI_ONLY:
            # Initiate the message textures we will use in the experiment
            self.__init_messages()
            # Initiate the fixation point texture we will use
            self.__init_fix()

        # Initialize the geometry
        self.__init_geometry()
        # Initialize the lighting
        self.__init_lighting()

        if args:
            # self.__init_VBO(args)
            self.__init_projection(args)
            stereo = args[-1]
        self.__init_modelview()

        self.__init_stereo(stereo)
        self.__init_grid()

        # Enable the basic GL_STATES that will be in use throughout
        # the experiment
        self.enable_GL_STATE()

    def __init_GL(self):
        """
        General initialization module for OpenGL, setting all of the
        parameters to be use throughout the experiment
        """
        # Set the background color to black
        glClearColor(0.0, 0.0, 0.0, 1.0)
        # Set the clearing depth buffer
        glClearDepth(1.0)

        # Select type of depth test to perform
        glDepthFunc(GL_LEQUAL)
        # Really good for perspective calculations
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

    def __init_messages(self):
        """
        Prepare all the message images for rendering as textures
        """
        # Store all the message images here
        self.messages = {}
        # Iterating through all the message images
        for filename in IMG_MSG:
            # Get the name of the message state
            state = findall(r'\\(\w+)\.jpg', filename)
            # If the regex finds something, use the first element
            # of the resultant list
            if state:
                state = state[0]
            # Load the image
            self.messages[state] = load(filename)

    def __init_fix(self):
        # Load the fixation point image from directory
        self.fix_image = load(IMG_FIX)

    def __init_stereo(self, stereo):
        if stereo:
            self.buffers = [GL_BACK_LEFT, GL_BACK_RIGHT]
        else:
            self.buffers = [GL_BACK]

    def __init_grid(self):
        self.translate_stimuli = [
                                  (-2.0, 4.0), (0.0, 4.0), (2.0, 4.0),
                                  (-2.0, 2.0), (0.0, 2.0), (2.0, 2.0),
                                  (-2.0, 0.0), (0.0, 0.0), (2.0, 0.0),
                                  (-2.0, -2.0), (0.0, -2.0), (2.0, -2.0)
        ]
        self.translate_stimuli = [(0.0, 0.0)]
        self.translate_message = [(0.0, 0.0)]

    # def __init_VBO(self, args):
        # Calculate the width displacement from the midpoint of the screen
        # wd = round(self.fix_image.width / float(args[0]), 2)
        # Calculate the height displacement from the midpoint of the screen
        # hd = round(self.fix_image.height / float(args[1]), 2)

        # self.vbo = VBO(wd, hd)

# ------------------------------------------------------------------
# HANDLE GEOMETRY
# ------------------------------------------------------------------

    def __init_geometry(self):
        """
        This module sets the geometry to be used in the rendering of
        the display messages and stimuli
        """
        # Set values for geometry that will be used later
        self.rotation = {'X': 0.0, 'Y': 0.0, 'Z': 0.0}
        self.translation = {'X': 0.0, 'Y': 0.0, 'Z': STIMULI_DEPTH}
        self.scale = {'X': 1.0, 'Y': 1.0, 'Z': 1.0}

    def __set_geometry(self):
        """
        Setup the geometry for the model
        Takes care of the translation, rotation and scaling needs of the model
        """
        # Switch to modelview
        glMatrixMode(GL_MODELVIEW)
        # Reset The View
        glLoadIdentity()

        # Move into the screen
        glTranslatef(self.translation['X'],
                     self.translation['Y'],
                     self.translation['Z'])

        # Rotate the texture on its X-axis
        glRotatef(self.rotation['X'] * -1, 1.0, 0.0, 0.0)
        # Rotate the texture on its Y-axis
        glRotatef(self.rotation['Y'] * -1, 0.0, 1.0, 0.0)
        # Rotate the texture on its Z-axis
        glRotatef(self.rotation['Z'] * -1, 0.0, 0.0, 1.0)

        # Scale the texture
        # For Z-axis, multiply it by the HEIGHT_RATIO set
        glScalef(self.scale['X'], self.scale['Y'],
                 self.scale['Z'])

# ------------------------------------------------------------------
# HANDLE MATRICES
# ------------------------------------------------------------------

    def __init_projection(self, args):
        self.projection = Projection(args[0], args[1], args[2])

    def __init_modelview(self):
        self.modelview = ModelView()

    def __set_modelview(self):
        self.modelview.set_matrix(self.rotation, self.scale, self.translation)

# ------------------------------------------------------------------
# HANDLE LIGHTING
# ------------------------------------------------------------------

    def __init_lighting(self):
        """
        This module sets the lighting parameters to be used by the shaders
        in the rendering of the stimuli

        NOTE: This is used only with the rendering of stimuli, it is
              not used with the display of messages or the fixation point
        """
        # Set the light position
        # If there is only light source being used, set it to the first
        # element of LIGHT_POSITION
        if len(LIGHT_POSITION) == 1:
            self.light_position = LIGHT_POSITION[0]
        # If there are multiple light sources, we keep it as a list
        else:
            self.light_position = LIGHT_POSITION

        # Set the light color
        # If there is only light source being used, set it to the first
        # element of LIGHT_COLOR
        if len(LIGHT_COLOR) == 1:
            self.light_color = LIGHT_COLOR[0]
        # If there are multiple light sources, we keep it as a list
        else:
            self.light_color = LIGHT_COLOR

# ------------------------------------------------------------------
# HANDLE OPENGL STATES
# ------------------------------------------------------------------

    def enable_GL_STATE(self):
        """
        Enables all required OpenGL states

        This module will enable:
            - Depth Test
            - Texture
            - Array Buffers
        """
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_TEXTURE_2D)

        if not ENABLE_SHADER or GLSL_VERSION == 130:
            # Enable all the corresponding buffer arrays
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            glEnableClientState(GL_VERTEX_ARRAY)
            glEnableClientState(GL_NORMAL_ARRAY)

    def disable_GL_STATE(self):
        """
        Disables all enabled OpenGL states

        This module will disable:
            - Depth Test
            - Array Buffers
        for complete shutdown of all GL_STATES
        """
        glDisable(GL_DEPTH_TEST)
        glDisable(GL_TEXTURE_2D)

        if not ENABLE_SHADER or GLSL_VERSION == 130:
            # Disable all the corresponding buffer arrays
            glDisableClientState(GL_VERTEX_ARRAY)
            glDisableClientState(GL_TEXTURE_COORD_ARRAY)
            glDisableClientState(GL_NORMAL_ARRAY)

# ------------------------------------------------------------------
# HANDLE VERTEX BUFFER OBJECTS
#
# THIS CODE HAS NOW BEEN MOVE TO vbo.py
# AND IMPLEMENTED WITH MULTI-THREADING
# ------------------------------------------------------------------

    def create_VBO(self, window_width, window_height):
        """
        Create OpenGL Vertex Buffer Objects as need for:
            - Non-stimuli images
            - Stimuli images
        """
        scaleX = SCALE_X
        scaleY = SCALE_Y
        if not ENABLE_SHADER or GLSL_VERSION == 130:
            scaleX = 1.0
            scaleY = 1.0

        if not STIMULI_ONLY:
            self.message_VBO = {}
            # Create the Vertex Buffer Object to house the texture
            # coordinates and vertices for message display
            self.__message_VBO(window_width, window_height, scaleX, scaleY)

        self.stimuli_VBO = {}
        # Create the Vertex Buffer Object to house the texture
        # coordinates, vertices and normals for the stimuli
        self.__stimuli_VBO(scaleX, scaleY)

    def __message_VBO(self, width, height, scaleX, scaleY):
        """
        Create the Vertex Buffer Objects for message display
        """
        # Calculate the width displacement from the midpoint of the screen
        wd = round(self.fix_image.width / float(width), 2)
        # Calculate the height displacement from the midpoint of the screen
        hd = round(self.fix_image.height / float(height), 2)

        # Create the buffer array for Vertex
        l = [
             [(0.0 - wd) * scaleX, (0.0 - hd) * scaleY],
             [(0.0 + wd) * scaleX, (0.0 - hd) * scaleY],
             [(0.0 + wd) * scaleX, (0.0 + hd) * scaleY],
             [(0.0 - wd) * scaleX, (0.0 + hd) * scaleY]
        ]
        self.message_VBO['vertex'] = VertexBuffer(array(l, dtype=float32))

        # Create the buffer array for TexCoord
        l = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]
        self.message_VBO['texcoord'] = VertexBuffer(array(l, dtype=float32))

        # Create the buffer array for Normal
        l = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0],
             [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]
        self.message_VBO['normal'] = VertexBuffer(array(l, dtype=float32))

#     def __message_VBO2(self, width, height):
#         """
#         Create the Vertex Buffer Objects for message display
#         """
#         # Calculate the width displacement from the midpoint of the screen
#         wd = round(self.fix_image.width / float(width), 2)
#         # Calculate the height displacement from the midpoint of the screen
#         hd = round(self.fix_image.height / float(height), 2)
#
#         vertices = [
#         #           VERTEX              TEXCOORD  NORMAL
#                     [0.0 - wd, 0.0 - hd, 0.0, 0.0, 0.0, 0.0, 1.0],
#                     [0.0 + wd, 0.0 - hd, 1.0, 0.0, 0.0, 0.0, 1.0],
#                     [0.0 + wd, 0.0 + hd, 1.0, 1.0, 0.0, 0.0, 1.0],
#                     [0.0 - wd, 0.0 + hd, 0.0, 1.0, 0.0, 0.0, 1.0]
#         ]
#
#         self.message_VBO = VertexBuffer(array(vertices, dtype=float32))

    def __stimuli_VBO(self, scaleX, scaleY):
        """
        Create the Vertex Buffer Objects for stimuli display
        """
        # Initiate the VBOs pertaining to the stimuli texture
        self.stimuli_VBO['vertex'] = []
        self.stimuli_VBO['texcoord'] = []
        self.stimuli_VBO['normal'] = []

        t0 = time()
        # Iterate through the points, moving up by the preset value:
        # STEP_SIZE
        for X in xrange(0, WIDTH - STEP_SIZE + 1, STEP_SIZE):
            for Y in xrange(0, HEIGHT - STEP_SIZE + 1, STEP_SIZE):

                # BOTTOM LEFT CORNER
                x, y, vertX, vertY = get_coords(X, Y, scaleX, scaleY)
                self.stimuli_VBO['vertex'].append([vertX, vertY])
                self.stimuli_VBO['texcoord'].append([x, y])

                # BOTTOM RIGHT CORNER
                x, y, vertX, vertY = get_coords(X + STEP_SIZE, Y,
                                                scaleX, scaleY)
                self.stimuli_VBO['vertex'].append([vertX, vertY])
                self.stimuli_VBO['texcoord'].append([x, y])

                # TOP RIGHT CORNER
                x, y, vertX, vertY = get_coords(X + STEP_SIZE,
                                                Y + STEP_SIZE,
                                                scaleX, scaleY)
                self.stimuli_VBO['vertex'].append([vertX, vertY])
                self.stimuli_VBO['texcoord'].append([x, y])

                # TOP LEFT CORNER
                x, y, vertX, vertY = get_coords(X, Y + STEP_SIZE,
                                                scaleX, scaleY)
                self.stimuli_VBO['vertex'].append([vertX, vertY])
                self.stimuli_VBO['texcoord'].append([x, y])

                for i in range(0, 4):
                    self.stimuli_VBO['normal'].append([0.0, 0.0, 1.0])

        # Instatiate the Vertex Buffer Objects using VertexBuffer
        self.stimuli_VBO['vertex'] = \
        VertexBuffer(array(self.stimuli_VBO['vertex'], dtype=float32))
        self.stimuli_VBO['texcoord'] = \
        VertexBuffer(array(self.stimuli_VBO['texcoord'], dtype=float32))
        self.stimuli_VBO['normal'] = \
        VertexBuffer(array(self.stimuli_VBO['normal'], dtype=float32))

        print 'Preparing the VBOs took %s seconds' % get_time(t0, time())

#     def __stimuli_VBO2(self):
#         """
#         Create the Vertex Buffer Objects for stimuli display
#         """
#         vertices = []
#         indices = []
#         next_column = HEIGHT / STEP_SIZE + 1
#
#         # Iterate through the points, moving up by the preset value:
#         # STEP_SIZE
#         for X in xrange(0, WIDTH + 1, STEP_SIZE):
#             for Y in xrange(0, HEIGHT + 1, STEP_SIZE):
#                 # Handle the VERTEX BUFFER OBJECT
#                 x, y, vertX, vertY = self.__get_coords(X, Y)
#                 vertices.append(
#                 #         VERTEX        TEXCOORD
#                          [vertX, vertY, x, y,
#                 #         NORMAL
#                           0.0, 0.0, 1.0]
#                 )
#
#                 # Handle the ELEMENT BUFFER OBJECT
#                 index_x = X / STEP_SIZE
#                 index_y = Y / STEP_SIZE
#                 origin = index_x + index_y
#
#                 indices.append(
#                 #               BOTTOM LEFT CORNER
#                                [origin,
#                 #               BOTTOM RIGHT CORNER
#                                 origin + next_column,
#                 #               TOP RIGHT CORNER
#                                 origin + next_column + 1,
#                 #               TOP LEFT CORNER
#                                 origin + 1
#                                ]
#                 )
#
#         self.stimuli_VBO = VertexBuffer(array(vertices, dtype=float32))
#         self.indices_VBO = VertexBuffer(array(indices, dtype=int32))

    def bind_message(self):
        """
        Bind all the Vertex Buffer Objects necessary for displaying
        messages and the fixation point
        """
        # Bind all the Vertex Buffer Objects
        if ENABLE_SHADER and GLSL_VERSION == 330:
            self.message_VBO['vertex'].bind_attribute(0, 2, GL_FLOAT)
            self.message_VBO['texcoord'].bind_attribute(1, 2, GL_FLOAT)
            self.message_VBO['normal'].bind_attribute(2, 3, GL_FLOAT)
        else:
            self.message_VBO['vertex'].bind_vertices(2, GL_FLOAT)
            self.message_VBO['texcoord'].bind_texcoords(2, GL_FLOAT)
            self.message_VBO['normal'].bind_normals(GL_FLOAT)

    def bind_stimuli(self):
        """
        Bind all the Vertex Buffer Objects necessary for displaying the
        stimuli
        """
        # Bind all the Vertex Buffer Objects
        if ENABLE_SHADER and GLSL_VERSION == 330:
            self.stimuli_VBO['vertex'].bind_attribute(0, 2, GL_FLOAT)
            self.stimuli_VBO['texcoord'].bind_attribute(1, 2, GL_FLOAT)
            self.stimuli_VBO['normal'].bind_attribute(2, 3, GL_FLOAT)
        else:
            self.stimuli_VBO['vertex'].bind_vertices(2, GL_FLOAT)
            self.stimuli_VBO['texcoord'].bind_texcoords(2, GL_FLOAT)
            self.stimuli_VBO['normal'].bind_normals(GL_FLOAT)

    def unbind_all(self):
        if hasattr(self, 'message_VBO'):
            self.message_VBO['vertex'].unbind()
            self.message_VBO['texcoord'].unbind()
            self.message_VBO['normal'].unbind()

        if hasattr(self, 'stimuli_VBO'):
            self.stimuli_VBO['vertex'].unbind()
            self.stimuli_VBO['texcoord'].unbind()
            self.stimuli_VBO['normal'].unbind()

# ------------------------------------------------------------------
# HANDLE SHADERS
# ------------------------------------------------------------------

    def create_shaders(self):
        """
        Create the OpenGL program on the GPU and attach the shaders
        """
        # If set to use shaders, enable them accordingly
        if ENABLE_SHADER:
            # Get the vertex shader
            vs = VertexShader(VERTEX_SHADER_FILE)
            # Get the fragment shader
            fs = FragmentShader(FRAGMENT_SHADER_FILE)
            # Assign the shader for the program
            self.shader = ShaderProgram(vs, fs)
            # Use the shader with the program
            self.shader.use()

    def pass_to_shaders(self, program, process_stimuli, colormap, heightmap,
                        normalmap):
        """
        Pass variables to shaders
        """
        # ----------------------------------------------------------
        # HANDLE DISPLACEMENT MAPPING VARIABLES
        # ----------------------------------------------------------

        # Get the texture for colormap
        colormap = colormap.get_texture()
        # Work on GL_TEXTURE0
        glActiveTexture(GL_TEXTURE0)
        # Bind the colormap
        glBindTexture(colormap.target, colormap.id)
        # Get the location of the colormap and pass it to the shader
        loc = glGetUniformLocation(program.id, 'colormap')
        glUniform1i(loc, 0)

        # Work on GL_TEXTURE_1
        glActiveTexture(GL_TEXTURE1)
        # Get the location of the heightmap
        loc = glGetUniformLocation(program.id, 'heightmap')
        # If the use of heightmaps is enabled, this must mean we are
        # rendering the stimuli
        if process_stimuli:
            # Get the texture for heightmap
            heightmap = heightmap.get_texture()
            # Bind the displacement map
            glBindTexture(heightmap.target, heightmap.id)
        # Pass the variable colormap to the loc for heightmap in
        # the vertex shader
        glUniform1i(loc, 1)

        glActiveTexture(GL_TEXTURE2)
        loc = glGetUniformLocation(program.id, 'normalmap')
        normalmap = normalmap.get_texture()
        glBindTexture(normalmap.target, normalmap.id)
        glUniform1i(loc, 2)

        # ----------------------------------------------------------
        # HANDLE LIGHTING VARIABLES
        # ----------------------------------------------------------

        # Get the location of the light position and pass it to the
        # shader
        # loc = glGetUniformLocation(program.id, 'light_position')
        # glUniform3fv(loc, NUM_LIGHTS, self.light_position)

        # Get the location of the light color and pass it to the shader
        # loc = glGetUniformLocation(program.id, 'light_color')
        # glUniform3fv(loc, NUM_LIGHTS, self.light_color)

        loc = glGetUniformLocation(program.id, 'light_direction')
        glUniform3fv(loc, 1, LIGHT_DIRECTION)

        # ----------------------------------------------------------
        # HANDLE ENABLERS
        # ----------------------------------------------------------

        # Get the location of the enable_vertex variable and pass enabled
        # to it
        loc = glGetUniformLocation(program.id, 'process_stimuli')
        glUniform1iv(loc, 1, process_stimuli)

        loc = glGetUniformLocation(program.id, 'per_pixel')
        glUniform1iv(loc, 1, PER_PIXEL)

        # ----------------------------------------------------------
        # HANDLE VERTEX BUFFER OBJECTS
        # ----------------------------------------------------------

        # loc = glGetAttribLocation(program.id, 'vertVertex')
        # glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, 0, None)
        # glEnableVertexAttribArray(loc)

        # loc = glGetAttribLocation(program.id, 'vertTexCoord')
        # if process_stimuli:
            # glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, 0,
            #                       self.stimuli_stride)
        # else:
            # glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, 0,
            #                       self.message_stride)
        # glEnableVertexAttribArray(loc)

        # loc = glGetAttribLocation(program.id, 'vertNormal')
        # if process_stimuli:
            # glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0,
            #                       self.stimuli_stride * 2)
        # else:
            # glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0,
            #                       self.message_stride * 2)
        # glEnableVertexAttribArray(loc)

# ------------------------------------------------------------------
# HANDLE TEXTURE
# ------------------------------------------------------------------

    def assign_texture(self, texture, width=WIDTH, height=HEIGHT):
        """
        Assign the texture for viewing in OpenGL
        """
        # Bind the texture
        print texture.get_texture().id
        glBindTexture(GL_TEXTURE_2D, texture.get_texture().id)
        # Assign 2D texture
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, pixel_access(texture))

        # Settings for use of the texture
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

# ------------------------------------------------------------------
# HANDLE OPENGL DRAWING
# ------------------------------------------------------------------

    def draw(self, render_stimuli=False, rot=0.0):
        """
        General draw module that must decide between the draw module
        to use. It can either render a stimuli image or non-stimuli
        message or fixation point
        """
        for count, color_buffer in enumerate(self.buffers):
            glDrawBuffer(color_buffer)
            # Clear the screen and the depth buffer
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            if ENABLE_SHADER and GLSL_VERSION == 330:
                self.projection.set_projection_matrix(self.projection\
                                                      .eyeshiftset[count])
            else:
                self.projection.set_perspective(50.0)

            # If not drawing the stimuli, we can reset the geometry
            if not rot:
                # Initialize the geometry each time, to reset it
                self.__init_geometry()

            if render_stimuli:
                translate = self.translate_stimuli
            else:
                translate = self.translate_message

            if not count:
                rot = deg_to_rad(-rot)
            for x, y in translate:
                self.translation['Z'] = STIMULI_DEPTH
                self.translation['X'] = x * SCALE_X
                self.translation['Y'] = y * cos(rot) * SCALE_Y
                if y:
                    self.translation['Z'] += (y * sin(rot) * SCALE_Y)

                # Now set the values
                if ENABLE_SHADER and GLSL_VERSION == 330:
                    self.modelview.set_matrix(self.rotation, self.scale,
                                              self.translation)
                    self.__pass_matrix()
                else:
                    self.__set_geometry()

                # For testing purposes only
                # self.__print_matrices()

                # If we must render_stimuli, we call self.__draw_model
                if rot:
                    self.__draw_model()
                # If we must render a non-stimuli image,
                # we call self.__draw_message
                else:
                    self.__draw_message()

    def __pass_matrix(self):
        loc = glGetUniformLocation(self.shader.id, 'ProjectionMatrix')
        glUniformMatrix4fv(loc, 1, GL_FALSE, self.projection.matrix)

        loc = glGetUniformLocation(self.shader.id, 'ModelViewMatrix')
        glUniformMatrix4fv(loc, 1, GL_FALSE, self.modelview.matrix)

        loc = glGetUniformLocation(self.shader.id, 'NormalMatrix')
        glUniformMatrix3fv(loc, 1, GL_FALSE, self.modelview.normal)

    def __print_matrices(self):
        print 'GL_PROJECTION_MATRIX:'
        if ENABLE_SHADER:
            print self.projection.matrix
        else:
            print glGetFloatv(GL_PROJECTION_MATRIX)

        print 'GL_MODELVIEW_MATRIX:'
        if ENABLE_SHADER:
            print self.modelview.matrix
        else:
            print glGetFloatv(GL_MODELVIEW_MATRIX)

    def __draw_axis(self):
        """
        Draw the three axes to indicate their positioning

        DEPRECATED
        """
        glBegin(GL_LINES)

        # Draw line for X axis
        glColor3f(1.0, 0.0, 0.0)
        glVertex3f(0.0, 0.0, 0.0)
        glVertex3f(1.0, 0.0, 0.0)

        # Draw line for Y axis
        glColor3f(0.0, 1.0, 0.0)
        glVertex3f(0.0, 0.0, 0.0)
        glVertex3f(0.0, 1.0, 0.0)

        # Draw line for Z axis
        glColor3f(0.0, 0.0, 1.0)
        glVertex3f(0.0, 0.0, 0.0)
        glVertex3f(0.0, 0.0, 1.0)
        glEnd()

    def __draw_message(self):
        """
        Draw the message or fixation point
        """
        # Draw the quadrilateral mapping it to the texture
        glDrawArrays(GL_QUADS, 0, 4)

    def __draw_model(self):
        """
        Draw the stimulus
        """
        points = (WIDTH / STEP_SIZE) * (HEIGHT / STEP_SIZE) * 4
        # If set to render solid, render the solid version
        if RENDER_SOLID:
            # Start drawing the quadrilateral
            glDrawArrays(GL_QUADS, 0, points)
        # Else produce wireframe
        else:
            # Draw lines to indicate the wireframe
            glDrawArrays(GL_LINES, 0, points)
Example #36
0
 def __init_projection(self, args):
     self.projection = Projection(args[0], args[1], args[2])
Example #37
0
    def __init__(self, data=None, projection=None, geometry=None,
                 name='', keywords=None, style_info=None):
        """Initialise object with either geometry or filename

        Input
            data: Can be either
                * a filename of a vector file format known to GDAL
                * List of dictionaries of fields associated with
                  point coordinates
                * None
            projection: Geospatial reference in WKT format.
                        Only used if geometry is provide as a numeric array,
            geometry: A list of either point coordinates or polygons
            name: Optional name for layer.
                  Only used if geometry is provide as a numeric array
            keywords: Optional dictionary with keywords that describe the
                      layer. When the layer is stored, these keywords will
                      be written into an associated file with extension
                      .keywords.

                      Keywords can for example be used to display text
                      about the layer in a web application.

        Note that if data is a filename, all other arguments are ignored
        as they will be inferred from the file.

        The geometry type will be inferred from the dimensions of geometry.
        If each entry is one set of coordinates the type will be ogr.wkbPoint,
        if it is an array of coordinates the type will be ogr.wkbPolygon.
        """

        if data is None and projection is None and geometry is None:
            # Instantiate empty object
            self.name = name
            self.projection = None
            self.geometry = None
            self.geometry_type = None
            self.filename = None
            self.data = None
            self.extent = None
            self.keywords = {}
            self.style_info = {}
            return

        if isinstance(data, basestring):
            self.read_from_file(data)
        else:
            # Assume that data is provided as sequences provided as
            # arguments to the Vector constructor
            # with extra keyword arguments supplying metadata

            self.name = name
            self.filename = None

            if keywords is None:
                self.keywords = {}
            else:
                msg = ('Specified keywords must be either None or a '
                       'dictionary. I got %s' % keywords)
                assert isinstance(keywords, dict), msg
                self.keywords = keywords

            if style_info is None:
                self.style_info = {}
            else:
                msg = ('Specified style_info must be either None or a '
                       'dictionary. I got %s' % style_info)
                assert isinstance(style_info, dict), msg
                self.style_info = style_info

            msg = 'Geometry must be specified'
            assert geometry is not None, msg

            msg = 'Geometry must be a sequence'
            assert is_sequence(geometry), msg
            self.geometry = geometry

            self.geometry_type = get_geometry_type(geometry)

            #msg = 'Projection must be specified'
            #assert projection is not None, msg
            self.projection = Projection(projection)

            self.data = data
            if data is not None:
                msg = 'Data must be a sequence'
                assert is_sequence(data), msg

                msg = ('The number of entries in geometry and data '
                       'must be the same')
                assert len(geometry) == len(data), msg
Example #38
0
    def read_from_file(self, filename):
        """ Read and unpack vector data.

        It is assumed that the file contains only one layer with the
        pertinent features. Further it is assumed for the moment that
        all geometries are points.

        * A feature is a geometry and a set of attributes.
        * A geometry refers to location and can be point, line, polygon or
          combinations thereof.
        * The attributes or obtained through GetField()

        The full OGR architecture is documented at
        * http://www.gdal.org/ogr/ogr_arch.html
        * http://www.gdal.org/ogr/ogr_apitut.html

        Examples are at
        * danieljlewis.org/files/2010/09/basicpythonmap.pdf
        * http://invisibleroads.com/tutorials/gdal-shapefile-points-save.html
        * http://www.packtpub.com/article/geospatial-data-python-geometry
        """

        basename, _ = os.path.splitext(filename)

        # Look for any keywords
        self.keywords = read_keywords(basename + '.keywords')

        # FIXME (Ole): Should also look for style file to populate style_info

        # Determine name
        if 'title' in self.keywords:
            vectorname = self.keywords['title']
        else:
            # Use basename without leading directories as name
            vectorname = os.path.split(basename)[-1]

        self.name = vectorname
        self.filename = filename
        self.geometry_type = None  # In case there are no features

        fid = ogr.Open(filename)
        if fid is None:
            msg = 'Could not open %s' % filename
            raise IOError(msg)

        # Assume that file contains all data in one layer
        msg = 'Only one vector layer currently allowed'
        if fid.GetLayerCount() > 1:
            msg = ('WARNING: Number of layers in %s are %i. '
                   'Only the first layer will currently be '
                   'used.' % (filename, fid.GetLayerCount()))
            raise Exception(msg)

        layer = fid.GetLayerByIndex(0)

        # Get spatial extent
        self.extent = layer.GetExtent()

        # Get projection
        p = layer.GetSpatialRef()
        self.projection = Projection(p)

        # Get number of features
        N = layer.GetFeatureCount()

        # Extract coordinates and attributes for all features
        geometry = []
        data = []
        for i in range(N):
            feature = layer.GetFeature(i)
            if feature is None:
                msg = 'Could not get feature %i from %s' % (i, filename)
                raise Exception(msg)

            # Record coordinates ordered as Longitude, Latitude
            G = feature.GetGeometryRef()
            if G is None:
                msg = ('Geometry was None in filename %s ' % filename)
                raise Exception(msg)
            else:
                self.geometry_type = G.GetGeometryType()
                if self.geometry_type == ogr.wkbPoint:
                    geometry.append((G.GetX(), G.GetY()))
                elif self.geometry_type == ogr.wkbLineString:
                    M = G.GetPointCount()
                    coordinates = []
                    for j in range(M):
                        coordinates.append((G.GetX(j), G.GetY(j)))

                    # Record entire line as an Mx2 numpy array
                    geometry.append(numpy.array(coordinates,
                                                dtype='d',
                                                copy=False))
                elif self.geometry_type == ogr.wkbPolygon:
                    ring = G.GetGeometryRef(0)
                    M = ring.GetPointCount()
                    coordinates = []
                    for j in range(M):
                        coordinates.append((ring.GetX(j), ring.GetY(j)))

                    # Record entire polygon ring as an Mx2 numpy array
                    geometry.append(numpy.array(coordinates,
                                                dtype='d',
                                                copy=False))
                #elif self.geometry_type == ogr.wkbMultiPolygon:
                #    # FIXME: Unpact multiple polygons to simple polygons
                #    # For hints on how to unpack see
#http://osgeo-org.1803224.n2.nabble.com/
#gdal-dev-Shapefile-Multipolygon-with-interior-rings-td5391090.html

                #    ring = G.GetGeometryRef(0)
                #    M = ring.GetPointCount()
                #    coordinates = []
                #    for j in range(M):
                #        coordinates.append((ring.GetX(j), ring.GetY(j)))

                #    # Record entire polygon ring as an Mx2 numpy array
                #    geometry.append(numpy.array(coordinates,
                #                                dtype='d',
                #                                copy=False))

                else:
                    msg = ('Only point, line and polygon geometries are '
                           'supported. '
                           'Geometry type in filename %s '
                           'was %s.' % (filename,
                                        self.geometry_type))
                    raise Exception(msg)

            # Record attributes by name
            number_of_fields = feature.GetFieldCount()
            fields = {}
            for j in range(number_of_fields):
                name = feature.GetFieldDefnRef(j).GetName()

                # FIXME (Ole): Ascertain the type of each field?
                #              We need to cast each appropriately?
                #              This is issue #66
                #              (https://github.com/AIFDR/riab/issues/66)
                #feature_type = feature.GetFieldDefnRef(j).GetType()
                fields[name] = feature.GetField(j)
                #print 'Field', name, feature_type, j, fields[name]

            data.append(fields)

        # Store geometry coordinates as a compact numeric array
        self.geometry = geometry
        self.data = data
Example #39
0
 def __init__( self, **kwargs ):
   ## get the Radius of Influence for the Barnes Analysis
   Projection.__init__( self, **kwargs )
   self.RoI = kwargs.get( 'RoI', 80000 )
Example #40
0
class Layer(object):
    """Common class for geospatial layers
    """

    def __init__(self, name=None, projection=None,
                 keywords=None, style_info=None,
                 sublayer=None):
        """Common constructor for all types of layers

        See docstrings for class Raster and class Vector for details.
        """

        # Name
        msg = ('Specified name  must be a string or None. '
               'I got %s with type %s' % (name, str(type(name))[1:-1]))
        verify(isinstance(name, basestring) or name is None, msg)
        self.name = name

        # Projection
        self.projection = Projection(projection)

        # Keywords
        if keywords is None:
            self.keywords = {}
        else:
            msg = ('Specified keywords must be either None or a '
                   'dictionary. I got %s' % keywords)
            verify(isinstance(keywords, dict), msg)
            self.keywords = keywords

        # Style info
        if style_info is None:
            self.style_info = {}
        else:
            msg = ('Specified style_info must be either None or a '
                   'dictionary. I got %s' % style_info)
            verify(isinstance(style_info, dict), msg)
            self.style_info = style_info

        # Defaults
        self.sublayer = sublayer
        self.filename = None
        self.data = None

    def __ne__(self, other):
        """Override '!=' to allow comparison with other projection objecs
        """
        return not self == other

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_filename(self):
        return self.filename

    def get_projection(self, proj4=False):
        """Return projection of this layer as a string
        """
        return self.projection.get_projection(proj4)

    def get_keywords(self, key=None):
        """Return a copy of the keywords dictionary

        Args:
            * key (optional): If specified value will be returned for key only
        """
        if key is None:
            return self.keywords.copy()
        else:
            if key in self.keywords:
                return self.keywords[key]
            else:
                msg = ('Keyword %s does not exist in %s: Options are '
                       '%s' % (key, self.get_name(), self.keywords.keys()))
                raise Exception(msg)

    def get_style_info(self):
        """Return style_info dictionary
        """
        return self.style_info

    def get_impact_summary(self):
        """Return 'impact_summary' keyword if present. Otherwise ''.
        """
        if 'impact_summary' in self.keywords:
            return self.keywords['impact_summary']
        else:
            return ''

    def get_total_needs(self):
        """Return 'total_needs' keyword if present. Otherwise ''.
        """
        if 'total_needs' in self.keywords:
            return self.keywords['total_needs']
        else:
            return ''

    def get_style_type(self):
        """Return style type of a layer. If not found, return None
        """
        if self.style_info is None:
            return None
        return self.style_info.get('style_type', None)

    # Layer properties used to identify their types
    @property
    def is_inasafe_spatial_object(self):
        return True

    @property
    def is_raster(self):
        if 'Raster' in str(self.__class__):
            return True
        else:
            return False

    @property
    def is_vector(self):
        if 'Vector' in str(self.__class__):
            return True
        else:
            return False