pixel-map 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pixel-map
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: A Python CLI tool for plotting geo files in the terminal
5
5
  Author-Email: Kamil Raczycki <kraczycki@kraina.ai>
6
6
  License: MIT
@@ -1,4 +1,4 @@
1
1
  """Pixel-map library."""
2
2
 
3
3
  __app_name__ = "pixel-map"
4
- __version__ = "0.1.2"
4
+ __version__ = "0.2.0"
@@ -39,14 +39,14 @@ def _version_callback(value: bool) -> None:
39
39
  raise typer.Exit()
40
40
 
41
41
 
42
- class BboxGeometryParser(click.ParamType): # type: ignore
42
+ class BboxParser(click.ParamType): # type: ignore
43
43
  """Parser for bounding boxes."""
44
44
 
45
45
  name = "BBOX"
46
46
 
47
47
  def convert(self, value, param=None, ctx=None): # type: ignore
48
48
  """Convert parameter value."""
49
- with suppress(ValueError): # ValueError raised when passing non-numbers to float()
49
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
50
50
  bbox_values = tuple(float(x.strip()) for x in value.split(","))
51
51
  if len(bbox_values) == 4:
52
52
  return bbox_values
@@ -58,6 +58,36 @@ class BboxGeometryParser(click.ParamType): # type: ignore
58
58
  ) from None
59
59
 
60
60
 
61
+ class ColorParser(click.ParamType): # type: ignore
62
+ """Parser for colours."""
63
+
64
+ name = "COLOR"
65
+
66
+ def convert(self, value, param=None, ctx=None): # type: ignore
67
+ """Convert parameter value."""
68
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
69
+ colors = [x.strip() for x in value.split(",")]
70
+ return colors
71
+
72
+
73
+ class AlphaParser(click.ParamType): # type: ignore
74
+ """Parser for bounding boxes."""
75
+
76
+ name = "FLOAT"
77
+
78
+ def convert(self, value, param=None, ctx=None): # type: ignore
79
+ """Convert parameter value."""
80
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
81
+ alpha_values = [float(x.strip()) for x in value.split(",")]
82
+ return alpha_values
83
+
84
+ raise typer.BadParameter(
85
+ "Cannot parse provided alpha values."
86
+ " Valid value must contain floating point numbers"
87
+ " separated by commas."
88
+ ) from None
89
+
90
+
61
91
  @app.command() # type: ignore
62
92
  def plot(
63
93
  files: Annotated[
@@ -70,11 +100,13 @@ def plot(
70
100
  bbox: Annotated[
71
101
  Optional[str],
72
102
  typer.Option(
103
+ "--bbox",
104
+ "-b",
73
105
  help=(
74
106
  "Clip the map to a given [bold dark_orange]bounding box[/bold dark_orange]."
75
107
  " Expects 4 floating point numbers separated by commas."
76
108
  ),
77
- click_type=BboxGeometryParser(),
109
+ click_type=BboxParser(),
78
110
  show_default=False,
79
111
  ),
80
112
  ] = None,
@@ -92,15 +124,82 @@ def plot(
92
124
  is_eager=True,
93
125
  ),
94
126
  ] = "block",
127
+ is_dark_style: Annotated[
128
+ bool,
129
+ typer.Option(
130
+ "--dark/--light",
131
+ help=(
132
+ "Uses the predefined dark or light style. Can be overriden with user defined style."
133
+ ),
134
+ show_default=True,
135
+ ),
136
+ ] = True,
137
+ colors: Annotated[
138
+ Optional[str],
139
+ typer.Option(
140
+ "--color",
141
+ "-c",
142
+ help=("Pass color or list of colours per each geo file."),
143
+ click_type=ColorParser(),
144
+ show_default=False,
145
+ ),
146
+ ] = None,
147
+ alphas: Annotated[
148
+ Optional[str],
149
+ typer.Option(
150
+ "--alpha",
151
+ "--opacity",
152
+ "-a",
153
+ help=("Pass opacity or list of opacities per each geo file."),
154
+ click_type=AlphaParser(),
155
+ show_default=False,
156
+ ),
157
+ ] = None,
158
+ basemap_provider: Annotated[
159
+ Optional[str],
160
+ typer.Option(
161
+ "--basemap",
162
+ "--tileset",
163
+ "-t",
164
+ metavar="TILES",
165
+ help=(
166
+ "Set the basemap provider. Can be any value parsed by xyzservices library."
167
+ " Defaults to [bold dark_orange]CartoDB.DarkMatterNoLabels[/bold dark_orange]"
168
+ " if --dark or [bold dark_orange]CartoDB.PositronNoLabels[/bold dark_orange]"
169
+ " if --light."
170
+ ),
171
+ show_default=False,
172
+ ),
173
+ ] = None,
95
174
  no_border: Annotated[
96
175
  bool,
97
176
  typer.Option(
98
177
  "--no-border/",
99
178
  "--fullscreen/",
179
+ "-f/",
100
180
  help=("Removes the border around the map."),
101
181
  show_default=False,
102
182
  ),
103
183
  ] = False,
184
+ no_background: Annotated[
185
+ bool,
186
+ typer.Option(
187
+ "--no-background/",
188
+ "--no-bg/",
189
+ help=("Removes the background of the map and plots only geo data."),
190
+ show_default=False,
191
+ ),
192
+ ] = False,
193
+ background_color: Annotated[
194
+ Optional[str],
195
+ typer.Option(
196
+ "--background-color",
197
+ "--bg-color",
198
+ metavar="COLOR",
199
+ help=("Set the background color. Can be used together with --no-background."),
200
+ show_default=False,
201
+ ),
202
+ ] = None,
104
203
  example_files: Annotated[
105
204
  bool,
106
205
  typer.Option(
@@ -132,7 +231,11 @@ def plot(
132
231
  """
133
232
  import warnings
134
233
 
135
- from pixel_map.plotter import plot_geo_data
234
+ from pixel_map.plotter import (
235
+ get_predefined_dark_style,
236
+ get_predefined_light_style,
237
+ plot_geo_data,
238
+ )
136
239
 
137
240
  if renderer not in AVAILABLE_RENDERERS:
138
241
  raise typer.BadParameter(f"Provided renderer {renderer} doesn't exist.") from None
@@ -151,12 +254,46 @@ def plot(
151
254
  )
152
255
  files = loaded_example_files
153
256
 
257
+ if is_dark_style:
258
+ provider, color = get_predefined_dark_style()
259
+ else:
260
+ provider, color = get_predefined_light_style()
261
+
262
+ if not basemap_provider:
263
+ basemap_provider = provider
264
+
265
+ parsed_colors: Optional[list[str]] = colors # type: ignore[assignment]
266
+ if not parsed_colors:
267
+ parsed_colors = [color]
268
+
269
+ parsed_alphas: Optional[list[float]] = alphas # type: ignore[assignment]
270
+ if not parsed_alphas:
271
+ parsed_alphas = [1]
272
+
273
+ if len(parsed_colors) > 1 and len(parsed_colors) != len(files):
274
+ raise typer.BadParameter(
275
+ f"Number of colors ({len(parsed_colors)}) and geo files ({len(files)}) doesn't match."
276
+ ) from None
277
+
278
+ if len(parsed_alphas) > 1 and len(parsed_alphas) != len(files):
279
+ raise typer.BadParameter(
280
+ f"Number of alphas ({len(parsed_alphas)}) and geo files ({len(files)}) doesn't match."
281
+ ) from None
282
+
283
+ if no_background:
284
+ basemap_provider = None
285
+ background_color = background_color or ("black" if is_dark_style else "white")
286
+
154
287
  with warnings.catch_warnings():
155
288
  warnings.filterwarnings("ignore")
156
289
  plot_geo_data(
157
290
  files,
158
291
  renderer=renderer,
159
292
  bbox=cast(Optional[tuple[float, float, float, float]], bbox),
293
+ color=parsed_colors,
294
+ alpha=parsed_alphas,
295
+ basemap_provider=basemap_provider,
296
+ background_color=background_color or "black",
160
297
  no_border=no_border,
161
298
  )
162
299
 
@@ -6,7 +6,7 @@ unicode characters.
6
6
  """
7
7
 
8
8
  from pathlib import Path
9
- from typing import Any, Optional
9
+ from typing import Any, Optional, Union
10
10
 
11
11
  import contextily as cx
12
12
  import geopandas as gpd
@@ -27,14 +27,15 @@ from pixel_map.renderers import AVAILABLE_RENDERERS
27
27
 
28
28
  TRANSFORMER = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
29
29
 
30
- # TODO:
31
- # - change geopandas loading to get multiple dfs instead of one
32
- # - add option to load contextily from string or name
33
30
 
34
31
  def plot_geo_data(
35
32
  files: list[str],
36
33
  renderer: str,
37
34
  bbox: Optional[tuple[float, float, float, float]] = None,
35
+ color: Union[str, list[str]] = "C0",
36
+ alpha: Union[float, list[float]] = 1.0,
37
+ basemap_provider: Optional[str] = None,
38
+ background_color: Optional[str] = None,
38
39
  no_border: bool = False,
39
40
  ) -> None:
40
41
  """
@@ -49,7 +50,15 @@ def plot_geo_data(
49
50
  Defaults to "block".
50
51
  bbox (Optional[tuple[float, float, float, float]], optional): Bounding box used to clip the
51
52
  geo data. Defaults to None.
52
- no_border (Optional[bool], optional): Removes the border around the map. Defaults to False.
53
+ color (Union[str, list[str]], optional): Color or list of colors used to plot geo data.
54
+ If a list, must be the same length as a number of files. Defaults to "C0".
55
+ alpha (Union[str, list[float]], optional): Opacity or list of opacities used to plot
56
+ geo data. If a list, must be the same length as a number of files. Defaults to 1.
57
+ basemap_provider (str, optional): A basemap used to plot under the geo data.
58
+ Defaults to None.
59
+ background_color (str, optional): Background color. Used then basemap_provider is None.
60
+ Defaults to None.
61
+ no_border (bool, optional): Removes the border around the map. Defaults to False.
53
62
  """
54
63
  console = get_console()
55
64
 
@@ -83,9 +92,9 @@ def plot_geo_data(
83
92
  console=console,
84
93
  ) as progress:
85
94
  progress.add_task("Loading Geo data", total=None)
86
- gdf = _load_geo_data(files, bbox=bbox)
95
+ gdfs = _load_geo_data(files, bbox=bbox)
87
96
  if bbox:
88
- gdf = gdf.clip_by_rect(*bbox)
97
+ gdfs = [gdf.clip_by_rect(*bbox) for gdf in gdfs]
89
98
 
90
99
  with Progress(
91
100
  SpinnerColumn(),
@@ -95,12 +104,18 @@ def plot_geo_data(
95
104
  ) as progress:
96
105
  progress.add_task("Plotting geo data", total=None)
97
106
  f, ax = plt.subplots(figsize=(map_width, map_height), dpi=10)
98
- f.patch.set_facecolor("black")
107
+ f.patch.set_facecolor(background_color)
99
108
  canvas = f.canvas
100
109
  # gdf.to_crs(3857).plot(ax=ax, alpha=0.4)
101
- gdf.to_crs(3857).plot(ax=ax)
110
+ if isinstance(color, str):
111
+ color = [color]
112
+ if isinstance(alpha, (int, float)):
113
+ alpha = [alpha]
114
+ for idx, gdf in enumerate(gdfs):
115
+ plot_color = color[idx % len(color)]
116
+ plot_alpha = alpha[idx % len(alpha)]
117
+ gdf.to_crs(3857).plot(ax=ax, color=plot_color, alpha=plot_alpha)
102
118
  ax.axis("off")
103
- ax.margins(0)
104
119
 
105
120
  if bbox_axes_bounds:
106
121
  left, bottom, right, top = bbox_axes_bounds
@@ -108,25 +123,16 @@ def plot_geo_data(
108
123
  ax.set_ylim([bottom, top])
109
124
 
110
125
  left, bottom, right, top = _expand_axes_limit_to_match_ratio(ax, ratio=map_ratio)
111
- # cx.add_basemap(
112
- # ax,
113
- # source=cx.providers.CartoDB.PositronNoLabels,
114
- # crs=3857,
115
- # attribution=False,
116
- # )
117
- cx.add_basemap(
118
- ax,
119
- source=cx.providers.CartoDB.DarkMatterNoLabels,
120
- crs=3857,
121
- attribution=False,
122
- )
123
- # cx.add_basemap(
124
- # ax,
125
- # source=cx.providers.CartoDB.VoyagerNoLabels,
126
- # crs=3857,
127
- # attribution=False,
128
- # )
129
- f.tight_layout()
126
+
127
+ if basemap_provider:
128
+ cx.add_basemap(
129
+ ax,
130
+ source=basemap_provider,
131
+ crs=3857,
132
+ attribution=False,
133
+ )
134
+
135
+ ax.set_position((0, 0, 1, 1))
130
136
  canvas.draw()
131
137
  image_flat = np.frombuffer(canvas.tostring_rgb(), dtype="uint8") # (H * W * 3,)
132
138
  image = image_flat.reshape(*reversed(canvas.get_width_height()), 3)
@@ -146,39 +152,52 @@ def plot_geo_data(
146
152
  characters, foreground_colors, background_colors
147
153
  )
148
154
 
149
- map_minx, map_miny = TRANSFORMER.transform(left, bottom, direction=TransformDirection.INVERSE)
150
- map_maxx, map_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
151
-
152
155
  if no_border:
153
156
  console.print(full_rich_string)
154
157
  else:
155
158
  title = _generate_panel_title(files, terminal_width)
156
159
 
160
+ map_minx, map_miny = TRANSFORMER.transform(
161
+ left, bottom, direction=TransformDirection.INVERSE
162
+ )
163
+ map_maxx, map_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
164
+ subtitle = _generate_panel_subtitle(
165
+ map_minx, map_miny, map_maxx, map_maxy, terminal_width, terminal_height
166
+ )
167
+
157
168
  console.print(
158
169
  Panel.fit(
159
170
  full_rich_string,
160
171
  padding=0,
161
172
  title=title,
162
- subtitle=f"BBOX: {map_minx:.5f},{map_miny:.5f},{map_maxx:.5f},{map_maxy:.5f}",
173
+ subtitle=subtitle,
163
174
  box=HEAVY,
164
175
  )
165
176
  )
166
177
 
167
178
 
179
+ def get_predefined_dark_style() -> tuple[str, str]:
180
+ """Get default background and color for dark style."""
181
+ return "CartoDB.DarkMatterNoLabels", "C1"
182
+
183
+
184
+ def get_predefined_light_style() -> tuple[str, str]:
185
+ """Get default background and color for light style."""
186
+ return "CartoDB.PositronNoLabels", "C0"
187
+
188
+
168
189
  def _load_geo_data(
169
190
  files: list[str], bbox: Optional[tuple[float, float, float, float]] = None
170
- ) -> gpd.GeoSeries:
191
+ ) -> list[gpd.GeoSeries]:
171
192
  paths = [Path(file_path) for file_path in files]
172
- return gpd.pd.concat(
173
- [
174
- (
175
- _read_geoparquet_file(path, bbox=bbox).geometry
176
- if path.suffix == ".parquet"
177
- else gpd.read_file(path, bbox=bbox).geometry
178
- )
179
- for path in paths
180
- ]
181
- )
193
+ return [
194
+ (
195
+ _read_geoparquet_file(path, bbox=bbox).geometry
196
+ if path.suffix == ".parquet"
197
+ else gpd.read_file(path, bbox=bbox).geometry
198
+ )
199
+ for path in paths
200
+ ]
182
201
 
183
202
 
184
203
  def _read_geoparquet_file(
@@ -289,3 +308,19 @@ def _generate_panel_title(files: list[str], terminal_width: int) -> str:
289
308
  title = new_title
290
309
 
291
310
  return title
311
+
312
+
313
+ def _generate_panel_subtitle(
314
+ minx: float, miny: float, maxx: float, maxy: float, terminal_width: int, terminal_height: int
315
+ ) -> str:
316
+ bbox_str = f"BBOX: {minx:.5f},{miny:.5f},{maxx:.5f},{maxy:.5f}"
317
+ terminal_wh_str = f"MAP W:{terminal_width} H:{terminal_height}"
318
+
319
+ subtitle = f"{bbox_str} | {terminal_wh_str}"
320
+
321
+ if len(subtitle) <= (terminal_width - 4):
322
+ return subtitle
323
+ elif len(bbox_str) <= (terminal_width - 4):
324
+ return bbox_str
325
+ else:
326
+ return ""
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pixel-map"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "A Python CLI tool for plotting geo files in the terminal"
5
5
  authors = [
6
6
  { name = "Kamil Raczycki", email = "kraczycki@kraina.ai" },
@@ -129,7 +129,7 @@ close-quotes-on-newline = true
129
129
  wrap-one-line = true
130
130
 
131
131
  [tool.bumpver]
132
- current_version = "0.1.2"
132
+ current_version = "0.2.0"
133
133
  version_pattern = "MAJOR.MINOR.PATCH[PYTAGNUM]"
134
134
  commit_message = "chore(CI/CD): bump version {old_version} -> {new_version}"
135
135
  commit = true
@@ -7,7 +7,7 @@ import pytest
7
7
  import typer
8
8
  from parametrization import Parametrization as P
9
9
 
10
- from pixel_map.__main__ import BboxGeometryParser
10
+ from pixel_map.__main__ import BboxParser
11
11
 
12
12
 
13
13
  @P.parameters("value", "expectation") # type: ignore
@@ -44,6 +44,6 @@ from pixel_map.__main__ import BboxGeometryParser
44
44
  def test_bbox_loading(value: str, expectation: Any) -> None:
45
45
  """Test if extracts finding by name works."""
46
46
  with expectation:
47
- bbox = BboxGeometryParser().convert(value) # type: ignore[no-untyped-call]
47
+ bbox = BboxParser().convert(value) # type: ignore[no-untyped-call]
48
48
  assert len(bbox) == 4
49
49
  assert all(isinstance(v, float) for v in bbox)
File without changes
File without changes
File without changes