Ejemplo n.º 1
0
 def test_load_from_empty_svg(self):
     with self.assertRaises(TypeError):
         reg_1 = Region.from_svg_d(None)
     reg_2 = Region.from_svg_d("   ")
     self.assertListEqual(reg_2.data, [[]])
     reg_3 = Region.from_svg_d("")
     self.assertListEqual(reg_3.data, [[]])
Ejemplo n.º 2
0
 def setUp(self):
     # test image filepath
     self.filepath = "./image_26333663.png"
     # color data
     self.color_data_2d = {
         (0.0, 0.0): (1.0, 1.0, 1.0),
         (0.0, 1.0): (1.0, 0.0, 0.0),
         (1.0, 1.0): (0.0, 0.0, 0.0),
         (1.0, 0.0): (0.0, 0.1, 1.0),
         (0.3, 0.6): (0.8, 1.0, 0.2),
         (0.8, 0.8): (0.1, 0.8, 0.9),
     }
     self.black_white_data_2d = {
         (0.0, 0.0): 3 * [1],
         (0.0, 1.0): 3 * [0],
         (1.0, 1.0): 3 * [0.5],
         (1.0, 0.0): 3 * [0.5],
         (0.5, 0.2): 3 * [0],
         (0.5, 0.8): 3 * [1],
     }
     # regions
     region_1 = Region.from_json(
         "[[[[0.0, 4.0], [2.0, 4.0], [2.0, 2.0], [0.0, 2.0]]]]")
     region_2 = Region.from_json(
         "[[[[2.0, 0.0], [2.0, 4.0], [4.0, 4.0], [4.0, 0.0]]]]")
     region_3 = Region.from_json(
         "[[[[0.0, 0.0], [0.0, 2.0], [2.0, 2.0], [2.0, 0.0]], "
         "[[0.5, 0.5], [1.5, 0.5], [1.0, 1.5]]]]")
     self.regions = [region_1, region_2, region_3]
     self.whole_region = Region.from_json(
         "[[[[0.2, 0.2], [0.2, 3.8], [3.8, 3.8], [3.8, 0.2]]]]")
Ejemplo n.º 3
0
 def test_to_mpl_collection(self):
     """ Tests two methods, integration. """
     # arrange
     region = Region(self.region_data)
     region_2 = Region(self.region_data)
     region_3 = Region(self.empty_region_data)
     color = (0.5, 0.6, 0.7)
     color_2 = (0.2, 0.3, 0.4)
     color_3 = (0.7, 0.8, 0.9)
     kwargs_list = [{
         "color": color_i
     } for color_i in [color, color_2, color_3]]
     alpha = 0.82
     # act
     with self.assertRaises(ValueError) as e:
         mpl_collection = Region.to_mpl_collection(
             regions=[region, region_2],
             kwargs_list=kwargs_list,
             alpha=alpha)
     mpl_collection = Region.to_mpl_collection(
         regions=[region, region_2, region_3],
         kwargs_list=kwargs_list,
         alpha=alpha)
     # assert
     self.assertEqual(
         e.exception.args[0],
         "`regions` and `kwargs_list` must be of same length.")
     self.assertEqual(len(mpl_collection.get_paths()), 2)
     self.assertIsInstance(mpl_collection, PatchCollection)
Ejemplo n.º 4
0
    def _visualize(self):
        # split db into units
        dbs = self._split_db()

        # process data
        regions = []
        values = []

        for db in dbs:
            # make region
            geo = db[self.granularity].find_one({}, fields="geo")
            region = Region.from_json(geo)
            regions.append(region)

            # evaluate value
            value = self.function(db)
            values.append(value)

        # determine outline units
        outline_geos = self.source_db[self.outlines_granularity].find(
            {}, fields="geo")
        outline_regions = [Region.from_json(geo) for geo in outline_geos]

        # make visualizer object
        self.vis = Visualizer(regions,
                              values,
                              self.colormap,
                              contours=outline_regions,
                              interpolation=self.interpolation,
                              title=self.title,
                              color_legend=self.show_legend,
                              grid=self.show_grid)

        # normalize values if set
        if self.normalization:
            self.vis.normalize_values()

        # apply colormap to values
        self.vis.render_colors()

        # prepare plot
        self.vis.prepare()

        ### TODO # add title, legend, grid, values, etc.

        # render plot to window or file
        if self.output_filename:
            visualized_dir = self.elections.visualized_dir
            if not os.path.exists(visualized_dir):
                ### TODO - make image dir, not only main dir
                os.makedirs(visualized_dir)
            output_path = visualized_dir + self.output_filename
            self.vis.save_image(output_path)
        else:
            self.vis.show()
Ejemplo n.º 5
0
 def test_round_decimal(self):
     # arrange
     mock_a = MagicMock()
     mock_b = MagicMock()
     _MockDecimalClass = MagicMock()
     _MockDecimalClass.side_effect = [mock_a, mock_b]
     # act
     with self.assertRaises(TypeError):
         Region._round_decimal("5.2")
     with patch("pkwscraper.lib.region.Decimal", _MockDecimalClass):
         decimal_a = Region._round_decimal(1.2357, precision=2)
         decimal_b = Region._round_decimal(-4.19999999999999999)
     # assert
     self.assertEqual(_MockDecimalClass.call_count, 2)
     _MockDecimalClass.assert_has_calls([call('1.24'), call('-4.2')])
     self.assertIs(decimal_a, mock_a)
     self.assertIs(decimal_b, mock_b)
Ejemplo n.º 6
0
    def prepare(self):
        """ Put all data and format the plot, before rendering. """
        # get ranges
        ranges = [
            region.get_xy_range() for region in self.regions
            if not region.is_empty()
        ]
        x_min = min(r["x_min"] for r in ranges)
        x_max = max(r["x_max"] for r in ranges)
        y_min = min(r["y_min"] for r in ranges)
        y_max = max(r["y_max"] for r in ranges)

        # get patch collection of units
        kwargs_list = [{"color": color} for color in self.colors]
        path_collection = Region.to_mpl_collection(regions=self.regions,
                                                   kwargs_list=kwargs_list,
                                                   antialiased=True)

        # get patch collection of bigger units contours
        if self.contours:
            contours_kwargs = len(self.contours) * [{
                "facecolor": None,
                "fill": False,
                "edgecolor": "k"
            }]
            contours_collection = Region.to_mpl_collection(
                regions=self.contours,
                kwargs_list=contours_kwargs,
                antialiased=True)

        # make plot
        fig, ax = plt.subplots()
        ax.axis('equal')
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_min, y_max)
        ax.invert_yaxis()

        # put patches on axes
        ax.add_collection(path_collection)
        if self.contours:
            ax.add_collection(contours_collection)
Ejemplo n.º 7
0
 def test_load_from_svg(self):
     reg = Region.from_svg_d(self.geo_txt)
     self.assertEqual(len(reg.data), len(self.region_data))
     for shape_a, shape_b in zip(reg.data, self.region_data):
         self.assertEqual(len(shape_a), len(shape_b))
         for curve_a, curve_b in zip(shape_a, shape_b):
             self.assertEqual(len(curve_a), len(curve_b))
             for point_a, point_b in zip(curve_a, curve_b):
                 self.assertEqual(len(point_a), len(point_b))
                 for coord_a, coord_b in zip(point_a, point_b):
                     self.assertEqual(len(shape_a), len(shape_b))
                     self.assertEqual(coord_a, coord_b)
Ejemplo n.º 8
0
 def test_get_line_start(self):
     # arrange
     mock_element = MagicMock()
     mock_element.start = 5.0 + 1.237j
     mock_element.end = -2.24 + 0.1j
     mock_x = MagicMock()
     mock_y = MagicMock()
     mock_region_round = MagicMock()
     mock_region_round.side_effect = [mock_x, mock_y]
     # act
     with patch("pkwscraper.lib.region.Region._round_decimal",
                mock_region_round):
         result = Region._get_line_start(mock_element)
     # assert
     self.assertEqual(mock_region_round.call_count, 2)
     mock_region_round.assert_has_calls([call(5.), call(1.237)])
     self.assertIsInstance(result, list)
     self.assertListEqual(result, [mock_x, mock_y])
Ejemplo n.º 9
0
def main():
    # open DB
    db = DbDriver(SEJM_2015_DATA_DIRECTORY, read_only=True)

    # choose units to visualize
    tables = ["gminy", "powiaty", "województwa", "okręgi"]
    regions = []
    for table_name in tables:
        geos = db[table_name].find({}, fields="geo")
        regions += [Region.from_json(geo) for geo in geos]

    # prepare regions and values
    n = len(regions)
    values = n * [0]
    colormap = lambda x: [random.random() for _ in range(3)] + [0.4]

    # make visualizer
    vis = Visualizer(regions, values, colormap)
    vis.render_colors()
    vis.prepare()
    vis.show()
Ejemplo n.º 10
0
 def _parse_geo(geo_txt):
     region = Region.from_svg_d(geo_txt)
     jsoned_txt = region.to_json()
     return jsoned_txt
Ejemplo n.º 11
0
 def test_xy_range(self):
     region = Region(self.region_data)
     xy_range = region.get_xy_range()
     self.assertDictEqual(xy_range, self.xy_range)
Ejemplo n.º 12
0
 def test_is_empty(self):
     region_1 = Region(self.region_data)
     self.assertFalse(region_1.is_empty())
     region_2 = Region(self.empty_region_data)
     self.assertTrue(region_2.is_empty())
Ejemplo n.º 13
0
 def test_to_mpl_path(self):
     """ This is only creation test. """
     region = Region(self.region_data)
     mpl_path = region.to_mpl_path(color=(0.5, 0.6, 0.7))
     self.assertIsInstance(mpl_path, PathPatch)
Ejemplo n.º 14
0
 def test_load_from_json(self):
     region = Region.from_json(self.json_txt)
     self.assertEqual(region.data, self.region_data)
Ejemplo n.º 15
0
 def test_save_to_json(self):
     region = Region(self.region_data)
     json_txt = region.to_json()
     self.assertEqual(json_txt, self.json_txt)
Ejemplo n.º 16
0
 def test_init(self):
     region = Region(self.region_data)
     self.assertListEqual(region.data, self.region_data)