eyck 0.0.2__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.
eyck-0.0.2/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ __pycache__
2
+ *.egg-info
eyck-0.0.2/PKG-INFO ADDED
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: eyck
3
+ Version: 0.0.2
4
+ Summary: High-definition modeling of (single-cell) chromatin + transcriptomics data
5
+ Author-email: Wouter Saelens <wouter.saelens@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/probabilistic-cell/eyck
8
+ Project-URL: Bug Tracker, https://github.com/probabilistic-cell/eyck/issues
9
+ Keywords: bioinformatics,chromatin accessibility,transcriptomics
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: matplotlib
14
+ Requires-Dist: numpy
15
+ Provides-Extra: sam
16
+ Requires-Dist: pysam; extra == "sam"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Requires-Dist: ruff; extra == "test"
22
+ Provides-Extra: full
23
+ Requires-Dist: eyck[sam]; extra == "full"
Binary file
eyck-0.0.2/dist.sh ADDED
@@ -0,0 +1,23 @@
1
+ python -m setuptools_git_versioning
2
+
3
+ version="0.0.1"
4
+
5
+ git add .
6
+ git commit -m "version v${version}"
7
+
8
+ git tag -a v${version} -m "v${version}"
9
+
10
+ python -m build
11
+
12
+ # optional: upload test
13
+ # twine upload --repository testpypi dist/eyck-${version}.tar.gz --verbose
14
+
15
+ git push --tags
16
+
17
+ # conda install gh --channel conda-forge
18
+ gh release create v${version} -t "v${version}" -n "v${version}" dist/eyck-${version}.tar.gz
19
+
20
+ # pip install twine
21
+ twine upload dist/eyck-${version}.tar.gz --verbose
22
+
23
+ python -m build --wheel
@@ -0,0 +1,67 @@
1
+ [build-system]
2
+ requires = ["setuptools>=41", "wheel", "setuptools_scm[toml]>=6.2", "numpy"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.setuptools-git-versioning]
6
+ enabled = true
7
+
8
+ [project]
9
+ name = "eyck"
10
+ authors = [
11
+ {name = "Wouter Saelens", email = "wouter.saelens@gmail.com"},
12
+ ]
13
+ description = "High-definition modeling of (single-cell) chromatin + transcriptomics data"
14
+ requires-python = ">=3.8"
15
+ keywords = ["bioinformatics", "chromatin accessibility", "transcriptomics"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+ dependencies = [
20
+ "matplotlib",
21
+ "numpy",
22
+ ]
23
+ dynamic = ["version", "readme"]
24
+ license = {text = "MIT"}
25
+
26
+ [project.urls]
27
+ "Homepage" = "https://github.com/probabilistic-cell/eyck"
28
+ "Bug Tracker" = "https://github.com/probabilistic-cell/eyck/issues"
29
+
30
+ [tool.setuptools.dynamic]
31
+ readme = {file = "README.md", content-type = "text/markdown"}
32
+
33
+ [project.optional-dependencies]
34
+ sam = [
35
+ "pysam",
36
+ ]
37
+ dev = [
38
+ "pytest",
39
+ ]
40
+ test = [
41
+ "pytest",
42
+ "ruff",
43
+ ]
44
+ full = ["eyck[sam]"]
45
+
46
+ [tool.setuptools_scm]
47
+
48
+ [tool.pytest.ini_options]
49
+ filterwarnings = [
50
+ "ignore",
51
+ ]
52
+
53
+ [tool.pylint.'MESSAGES CONTROL']
54
+ max-line-length = 120
55
+ disable = [
56
+ "too-many-arguments",
57
+ "not-callable",
58
+ "redefined-builtin",
59
+ "redefined-outer-name",
60
+ ]
61
+
62
+ [tool.ruff]
63
+ line-length = 500
64
+ ignore-init-module-imports = true
65
+ ignore = ['F401']
66
+ include = ['src/**/*.py']
67
+ exclude = ['scripts/*']
eyck-0.0.2/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: eyck
3
+ Version: 0.0.2
4
+ Summary: High-definition modeling of (single-cell) chromatin + transcriptomics data
5
+ Author-email: Wouter Saelens <wouter.saelens@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/probabilistic-cell/eyck
8
+ Project-URL: Bug Tracker, https://github.com/probabilistic-cell/eyck/issues
9
+ Keywords: bioinformatics,chromatin accessibility,transcriptomics
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: matplotlib
14
+ Requires-Dist: numpy
15
+ Provides-Extra: sam
16
+ Requires-Dist: pysam; extra == "sam"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Requires-Dist: ruff; extra == "test"
22
+ Provides-Extra: full
23
+ Requires-Dist: eyck[sam]; extra == "full"
@@ -0,0 +1,16 @@
1
+ .gitignore
2
+ dist.sh
3
+ pyproject.toml
4
+ dist/eyck-0.0.2.dev1+g32d3f6b-py3-none-any.whl
5
+ dist/eyck-0.0.2.dev1+g32d3f6b.tar.gz
6
+ dist/genomeplot-0.0.1-py3-none-any.whl
7
+ dist/genomeplot-0.0.1.tar.gz
8
+ src/eyck.egg-info/PKG-INFO
9
+ src/eyck.egg-info/SOURCES.txt
10
+ src/eyck.egg-info/dependency_links.txt
11
+ src/eyck.egg-info/requires.txt
12
+ src/eyck.egg-info/top_level.txt
13
+ src/genomeplot/__init__.py
14
+ src/genomeplot/grid/__init__.py
15
+ src/genomeplot/grid/broken.py
16
+ src/genomeplot/grid/grid.py
@@ -0,0 +1,15 @@
1
+ matplotlib
2
+ numpy
3
+
4
+ [dev]
5
+ pytest
6
+
7
+ [full]
8
+ eyck[sam]
9
+
10
+ [sam]
11
+ pysam
12
+
13
+ [test]
14
+ pytest
15
+ ruff
@@ -0,0 +1 @@
1
+ genomeplot
@@ -0,0 +1 @@
1
+ from . import grid
@@ -0,0 +1,2 @@
1
+ from .grid import Grid, Figure, Panel, Wrap, Ax
2
+ from .broken import Broken, BrokenGrid, Breaking
@@ -0,0 +1,155 @@
1
+ from eyck.grid.grid import Grid, Panel
2
+ import numpy as np
3
+ import pandas as pd
4
+ import dataclasses
5
+
6
+
7
+ @dataclasses.dataclass
8
+ class Breaking:
9
+ regions: pd.DataFrame
10
+ gap: int = 0.05
11
+ resolution: int = 2500
12
+
13
+ @property
14
+ def width(self):
15
+ return (self.regions["length"] / self.resolution).sum() + self.gap * (len(self.regions) - 1)
16
+
17
+
18
+ class Broken(Grid):
19
+ """
20
+ A grid build from distinct regions that are using the same coordinate space
21
+ """
22
+
23
+ def __init__(self, breaking, height=0.5, margin_height=0.0, *args, **kwargs):
24
+ super().__init__(padding_width=breaking.gap, margin_height=margin_height, *args, **kwargs)
25
+
26
+ regions = breaking.regions
27
+
28
+ regions["width"] = regions["end"] - regions["start"]
29
+ regions["ix"] = np.arange(len(regions))
30
+
31
+ for i, (region, region_info) in enumerate(regions.iterrows()):
32
+ if "resolution" in region_info.index:
33
+ resolution = region_info["resolution"]
34
+ else:
35
+ resolution = breaking.resolution
36
+ subpanel_width = region_info["width"] / resolution
37
+ panel, ax = self.add_right(
38
+ Panel((subpanel_width, height + 1e-4)),
39
+ )
40
+
41
+ ax.set_xlim(region_info["start"], region_info["end"])
42
+ ax.set_xticks([])
43
+ ax.set_ylim(0, 1)
44
+ if i != 0:
45
+ ax.set_yticks([])
46
+ if region_info["ix"] != 0:
47
+ ax.spines.left.set_visible(False)
48
+ if region_info["ix"] != len(regions) - 1:
49
+ ax.spines.right.set_visible(False)
50
+ ax.spines.top.set_visible(False)
51
+ ax.set_facecolor("none")
52
+
53
+ # ax.plot([0, 0], [0, 1], transform=ax.transAxes, color="k", lw=1, clip_on=False)
54
+
55
+
56
+ class BrokenGrid(Grid):
57
+ """
58
+ A grid build from distinct regions that are using the same coordinate space
59
+ """
60
+
61
+ def __init__(self, breaking, height=0.5, padding_height=0.05, margin_height=0.0, *args, **kwargs):
62
+ super().__init__(padding_width=breaking.gap, margin_height=margin_height, *args, **kwargs)
63
+
64
+ regions = breaking.regions
65
+
66
+ regions["width"] = regions["end"] - regions["start"]
67
+ regions["ix"] = np.arange(len(regions))
68
+
69
+ regions["panel_width"] = regions["width"] / breaking.resolution
70
+
71
+ self.panel_widths = regions["panel_width"].values
72
+
73
+ for i, (region, region_info) in enumerate(regions.iterrows()):
74
+ _ = self.add_right(
75
+ Grid(padding_height=padding_height, margin_height=0.0),
76
+ )
77
+
78
+
79
+ def add_slanted_x(ax1, ax2, size=4, **kwargs):
80
+ d = 1.0 # proportion of vertical to horizontal extent of the slanted line
81
+ kwargs = dict(
82
+ marker=[(-1, -d), (1, d)],
83
+ markersize=size,
84
+ linestyle="none",
85
+ mew=1,
86
+ clip_on=False,
87
+ **{"color": "k", "mec": "k", **kwargs},
88
+ )
89
+ ax1.plot([1, 1], [0, 1], transform=ax1.transAxes, **kwargs)
90
+ ax2.plot([0, 0], [0, 1], transform=ax2.transAxes, **kwargs)
91
+
92
+
93
+ class TransformBroken:
94
+ def __init__(self, breaking, width=None):
95
+ """
96
+ Transforms from data coordinates to (broken) data coordinates
97
+
98
+ Parameters
99
+ ----------
100
+ breaking : pd.DataFrame
101
+ Regions to break
102
+ resolution : float
103
+ Resolution of the data to go from data to points
104
+ gap : float
105
+ Gap between the regions in points
106
+
107
+ """
108
+
109
+ regions = breaking.regions
110
+
111
+ regions["width"] = regions["end"] - regions["start"]
112
+ regions["ix"] = np.arange(len(regions))
113
+
114
+ regions["cumstart"] = (np.pad(np.cumsum(regions["width"])[:-1], (1, 0))) + regions["ix"] * breaking.gap * breaking.resolution
115
+ regions["cumend"] = np.cumsum(regions["width"]) + regions["ix"] * breaking.gap / breaking.resolution
116
+
117
+ self.regions = regions
118
+ self.resolution = breaking.resolution
119
+ self.gap = breaking.gap
120
+
121
+ def __call__(self, x):
122
+ """
123
+ Transform from data coordinates to (broken) data coordinates
124
+
125
+ Parameters
126
+ ----------
127
+ x : float
128
+ Position in data coordinates
129
+
130
+ Returns
131
+ -------
132
+ float
133
+ Position in (broken) data coordinates
134
+
135
+ """
136
+
137
+ assert isinstance(x, (int, float, np.ndarray, np.float64, np.int64))
138
+
139
+ if isinstance(x, (int, float, np.float64, np.int64)):
140
+ x = np.array([x])
141
+
142
+ match = (x[:, None] >= self.regions["start"].values) & (x[:, None] <= self.regions["end"].values)
143
+
144
+ argmax = np.argmax(
145
+ match,
146
+ axis=1,
147
+ )
148
+ allzero = (match == False).all(axis=1)
149
+
150
+ # argmax[allzero] = np.nan
151
+
152
+ y = self.regions.iloc[argmax]["cumstart"].values + (x - self.regions.iloc[argmax]["start"].values)
153
+ y[allzero] = np.nan
154
+
155
+ return y
@@ -0,0 +1,538 @@
1
+ import matplotlib as mpl
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+
5
+ active_fig = None
6
+
7
+
8
+ class Element:
9
+ """
10
+ A basic element in a figure with a (top-left) position and dimensions
11
+ """
12
+
13
+ pos = None
14
+ dim = None
15
+
16
+ @property
17
+ def width(self):
18
+ return self.dim[0]
19
+
20
+ @property
21
+ def height(self):
22
+ return self.dim[1]
23
+
24
+
25
+ TITLE_HEIGHT = 0.3
26
+ AXIS_WIDTH = AXIS_HEIGHT = 0.0
27
+
28
+
29
+ class Ax(Element):
30
+ ax2 = None
31
+ insets = None
32
+
33
+ def __init__(self, dim=None, pos=(0.0, 0.0)):
34
+ global active_fig
35
+ self.ax = mpl.figure.Axes(active_fig, [0, 0, 1, 1])
36
+ self.dim = dim
37
+ self.pos = pos
38
+
39
+ @property
40
+ def dim(self):
41
+ return self._dim
42
+
43
+ @dim.setter
44
+ def dim(self, value):
45
+ if len(value) != 2:
46
+ raise ValueError("dim must be a tuple of length 2")
47
+ if value[0] <= 0 or value[1] <= 0:
48
+ raise ValueError("dim must be positive")
49
+ self._dim = value
50
+
51
+ @property
52
+ def height(self):
53
+ h = self.dim[1]
54
+
55
+ # add some extra height if we have a title
56
+ if self.ax.get_title() != "":
57
+ h += TITLE_HEIGHT
58
+ if self.ax.axison:
59
+ h += AXIS_HEIGHT
60
+ return h
61
+
62
+ @height.setter
63
+ def height(self, value):
64
+ self.dim = (self.dim[0], value)
65
+
66
+ @property
67
+ def width(self):
68
+ w = self.dim[0]
69
+ if self.ax.axison:
70
+ w += AXIS_WIDTH
71
+ return w
72
+
73
+ @width.setter
74
+ def width(self, value):
75
+ self.dim = (value, self.dim[1])
76
+
77
+ def align(self):
78
+ pass
79
+
80
+ def position(self, fig, pos=(0, 0)):
81
+ fig_width, fig_height = fig.get_size_inches()
82
+ width, height = self.dim
83
+ x, y = self.pos[0] + pos[0], self.pos[1] + pos[1]
84
+
85
+ axes = [self.ax]
86
+ if self.ax2 is not None:
87
+ axes.append(self.ax2)
88
+
89
+ for ax in axes:
90
+ ax.set_position(
91
+ [
92
+ x / fig_width,
93
+ (fig_height - y - height) / fig_height,
94
+ width / fig_width,
95
+ height / fig_height,
96
+ ]
97
+ )
98
+
99
+ fig.add_axes(ax)
100
+
101
+ for inset, inset_position, inset_offset, inset_anchor in self.insets or []:
102
+ inset.position(
103
+ fig,
104
+ pos=(
105
+ x + (width - inset.dim[0]) * inset_anchor[0] + (width) * inset_position[0] + inset_offset[0],
106
+ y + (height - inset.dim[1]) * inset_anchor[1] + (height) * inset_position[1] + inset_offset[1],
107
+ ),
108
+ )
109
+
110
+ def add_twinx(self):
111
+ global active_fig
112
+ self.ax2 = mpl.figure.Axes(active_fig, [0, 0, 1, 1])
113
+ self.ax2.xaxis.set_visible(False)
114
+ self.ax2.patch.set_visible(False)
115
+ self.ax2.yaxis.tick_right()
116
+ self.ax2.yaxis.set_label_position("right")
117
+ self.ax2.yaxis.set_offset_position("right")
118
+ self.ax.yaxis.tick_left()
119
+ return self.ax2
120
+
121
+ def add_inset(self, inset, pos=(0, 0), offset=(0, 0), anchor=(0, 0)):
122
+ if self.insets is None:
123
+ self.insets = []
124
+ self.insets.append([inset, pos, offset, anchor])
125
+ return inset
126
+
127
+ def __iter__(self):
128
+ yield self
129
+ yield self.ax
130
+
131
+
132
+ class Panel(Ax):
133
+ pass
134
+
135
+
136
+ class Title(Panel):
137
+ def __init__(self, label, dim=None):
138
+ if dim is None:
139
+ dim = (1, TITLE_HEIGHT)
140
+ super().__init__(dim=dim)
141
+ self.label = label
142
+ self.ax.set_axis_off()
143
+ self.ax.text(0.5, 0.5, label, ha="center", va="center", size="large")
144
+
145
+
146
+ class Wrap(Element):
147
+ """
148
+ Grid-like layout with a fixed number of columns that will automatically wrap panels in the next row
149
+ """
150
+
151
+ title = None
152
+
153
+ def __init__(
154
+ self,
155
+ ncol=6,
156
+ padding_width=0.5,
157
+ padding_height=None,
158
+ margin_height=0.5,
159
+ margin_width=0.5,
160
+ ):
161
+ self.ncol = ncol
162
+ self.padding_width = padding_width
163
+ self.padding_height = padding_height if padding_height is not None else padding_width
164
+ self.margin_width = margin_width
165
+ self.margin_height = margin_height
166
+ self.elements = []
167
+ self.pos = (0, 0)
168
+
169
+ def add(self, element):
170
+ self.elements.append(element)
171
+ return element
172
+
173
+ def align(self):
174
+ width = 0
175
+ height = 0
176
+ nrow = 1
177
+ x = 0
178
+ y = 0
179
+ next_y = 0
180
+
181
+ if self.title is not None:
182
+ y += self.title.height
183
+
184
+ for i, el in enumerate(self.elements):
185
+ el.align()
186
+
187
+ el.pos = (x, y)
188
+
189
+ next_y = max(next_y, y + el.height + self.padding_height)
190
+ height = max(height, next_y)
191
+
192
+ width = max(width, x + el.width)
193
+
194
+ if (self.ncol > 1) and ((i == 0) or (((i + 1) % (self.ncol)) != 0)):
195
+ x += el.width + self.padding_width
196
+ else:
197
+ nrow += 1
198
+ x = 0
199
+ y = next_y
200
+
201
+ if self.title is not None:
202
+ self.title.dim = (width, self.title.dim[1])
203
+
204
+ self.dim = (width, height)
205
+
206
+ def set_title(self, label):
207
+ if self.title is not None:
208
+ try:
209
+ self.title.ax.remove()
210
+ except KeyError:
211
+ pass
212
+ except AttributeError:
213
+ pass
214
+
215
+ self.title = Title(label)
216
+
217
+ def position(self, fig, pos=(0, 0)):
218
+ pos = self.pos[0] + pos[0], self.pos[1] + pos[1]
219
+ if self.title is not None:
220
+ self.title.position(fig, pos)
221
+ for el in self.elements:
222
+ el.position(fig, pos)
223
+
224
+ def __getitem__(self, key):
225
+ return list(self.elements)[key]
226
+
227
+ def get_bottom_left_corner(self):
228
+ nrow = (len(self.elements) - 1) // self.ncol
229
+ ix = (nrow) * self.ncol
230
+ return self.elements[ix]
231
+ # return self.elements[self.ncol * ((len(self.elements) % self.ncol) - 1)]
232
+
233
+
234
+ class WrapAutobreak(Wrap):
235
+ title = None
236
+
237
+ def __init__(
238
+ self,
239
+ max_width,
240
+ max_n_row=-1,
241
+ padding_width=0.5,
242
+ padding_height=None,
243
+ margin_height=0.5,
244
+ margin_width=0.5,
245
+ ):
246
+ self.max_width = max_width
247
+ self.max_n_row = max_n_row
248
+ super().__init__(
249
+ ncol=1,
250
+ padding_width=padding_width,
251
+ padding_height=padding_height,
252
+ margin_height=margin_height,
253
+ margin_width=margin_width,
254
+ )
255
+
256
+ def align(self):
257
+ width = 0
258
+ height = 0
259
+ self.nrow = 1
260
+ x = 0
261
+ y = 0
262
+ next_y = 0
263
+
264
+ if self.title is not None:
265
+ y += self.title.height
266
+ for i, el in enumerate(self.elements):
267
+ el.align()
268
+
269
+ el.pos = (x, y)
270
+
271
+ next_y = max(next_y, y + el.height + self.padding_height)
272
+ height = max(height, next_y)
273
+
274
+ width = max(width, x + el.width)
275
+
276
+ x += el.width + self.padding_width
277
+
278
+ if x > self.max_width:
279
+ self.nrow += 1
280
+ x = 0
281
+ y = next_y
282
+
283
+ if self.title is not None:
284
+ self.title.dim = (width, self.title.dim[1])
285
+
286
+ self.dim = (width, height)
287
+
288
+
289
+ class Grid(Element):
290
+ """
291
+ Grid layout with a fixed number of columns and rows
292
+ """
293
+
294
+ title = None
295
+
296
+ def __init__(
297
+ self,
298
+ nrow=1,
299
+ ncol=1,
300
+ padding_width=0.5,
301
+ padding_height=None,
302
+ margin_height=0.5,
303
+ margin_width=0.5,
304
+ ):
305
+ self.padding_width = padding_width
306
+ self.padding_height = padding_height if padding_height is not None else padding_width
307
+ self.margin_width = margin_width
308
+ self.margin_height = margin_height
309
+ self.elements = [[None for _ in range(ncol)] for _ in range(nrow)]
310
+
311
+ self.pos = (0, 0)
312
+
313
+ self.nrow = nrow
314
+ self.ncol = ncol
315
+
316
+ self.paddings_height = [None] * (nrow)
317
+ self.paddings_width = [None] * (ncol)
318
+
319
+ def align(self):
320
+ width = 0
321
+ height = 0
322
+ x = 0
323
+ y = 0
324
+ next_y = 0
325
+
326
+ if self.title is not None:
327
+ y += self.title.height
328
+
329
+ widths = [0] * self.ncol
330
+ heights = [0] * self.nrow
331
+
332
+ assert len(self.paddings_height) == self.nrow, (
333
+ len(self.paddings_height),
334
+ self.nrow,
335
+ )
336
+ assert len(self.paddings_width) == self.ncol, (
337
+ len(self.paddings_width),
338
+ self.ncol,
339
+ )
340
+
341
+ for row, row_elements in enumerate(self.elements):
342
+ for col, el in enumerate(row_elements):
343
+ if el is not None:
344
+ el.align()
345
+ if el.width > widths[col]:
346
+ widths[col] = el.width
347
+ if el.height > heights[row]:
348
+ heights[row] = el.height
349
+
350
+ for row, (row_elements, el_height) in enumerate(zip(self.elements, heights)):
351
+ padding_height = self.paddings_height[min(row + 1, self.nrow - 1)]
352
+ if padding_height is None:
353
+ padding_height = self.padding_height
354
+
355
+ x = 0
356
+ for col, (el, el_width) in enumerate(zip(row_elements, widths)):
357
+ if el is not None:
358
+ el.pos = (x, y)
359
+
360
+ next_y = max(next_y, y + el.height + padding_height)
361
+ height = max(height, next_y)
362
+
363
+ width = max(width, x + el.width)
364
+
365
+ padding_width = self.paddings_width[min(col + 1, self.ncol - 1)]
366
+ if padding_width is None:
367
+ padding_width = self.padding_width
368
+
369
+ x += el_width + padding_width
370
+ y += el_height + padding_height
371
+
372
+ if self.title is not None:
373
+ self.title.dim = (width, self.title.dim[1])
374
+
375
+ self.dim = (width, height)
376
+
377
+ def set_title(self, label):
378
+ self.title = Title(label)
379
+
380
+ def position(self, fig, pos=(0, 0)):
381
+ pos = self.pos[0] + pos[0], self.pos[1] + pos[1]
382
+ if self.title is not None:
383
+ self.title.position(fig, pos)
384
+
385
+ for row_elements in self.elements:
386
+ for el in row_elements:
387
+ if el is not None:
388
+ el.position(fig, pos)
389
+
390
+ def __getitem__(self, index):
391
+ if not isinstance(index, tuple):
392
+ raise TypeError("index must be a tuple, not " + str(index))
393
+ return self.elements[index[0]][index[1]]
394
+
395
+ def __setitem__(self, index, v):
396
+ row = index[0]
397
+ col = index[1]
398
+
399
+ if not isinstance(row, int) or not isinstance(col, int):
400
+ raise TypeError("row and col must be integers")
401
+
402
+ if row >= (self.nrow):
403
+ # add new row(s)
404
+ for i in range(self.nrow, row + 1):
405
+ self.elements.append([None for _ in range(self.ncol)])
406
+ self.nrow = row + 1
407
+ self.paddings_height.append(None)
408
+
409
+ if col >= (self.ncol):
410
+ # add new col(s)
411
+ for i in range(self.ncol, col + 1):
412
+ for row_ in self.elements:
413
+ row_.append(None)
414
+ self.ncol = col + 1
415
+ self.paddings_width.append(None)
416
+
417
+ self.elements[row][col] = v
418
+
419
+ def add(self, el, row=0, column=0, padding_height=None, padding_width=None):
420
+ self[row, column] = el
421
+ if padding_height is not None:
422
+ self.paddings_height[row] = padding_height
423
+ if padding_width is not None:
424
+ self.paddings_width[column] = padding_width
425
+ return el
426
+
427
+ def add_under(self, el, column=0, padding=None):
428
+ if (self.nrow == 1) and self[0, 0] is None:
429
+ row = 0
430
+ else:
431
+ row = self.nrow
432
+
433
+ # get column index if column is a panel
434
+ if "grid.Element" in column.__class__.__mro__.__repr__():
435
+ try:
436
+ print(row)
437
+ column = np.array(self.elements).flatten().tolist().index(column) % self.ncol
438
+ except ValueError as e:
439
+ raise ValueError("The panel specified as column was not found in the grid") from e
440
+ if not isinstance(column, int):
441
+ raise TypeError("column must be an integer, not " + str(column))
442
+ self[row, column] = el
443
+ if padding is not None:
444
+ self.paddings_height[row] = padding
445
+ return el
446
+
447
+ def add_right(self, el, row=0, padding=None):
448
+ if (self.ncol == 1) and (self[0, 0] is None):
449
+ column = 0
450
+ else:
451
+ column = self.ncol
452
+
453
+ # get column index if row is a panel
454
+ if "grid.Element" in row.__class__.__mro__.__repr__():
455
+ try:
456
+ row = np.array(self.elements).flatten().tolist().index(row) // self.ncol
457
+ except ValueError as e:
458
+ raise ValueError("The panel specified as row was not found in the grid") from e
459
+
460
+ self[row, column] = el
461
+ if padding is not None:
462
+ self.paddings_width[column] = padding
463
+ return el
464
+
465
+ def get_panel_position(self, panel):
466
+ for row, row_elements in enumerate(self.elements):
467
+ for col, el in enumerate(row_elements):
468
+ if el is panel:
469
+ return row, col
470
+
471
+ def __iter__(self):
472
+ for row in self.elements:
473
+ for el in row:
474
+ if el is not None:
475
+ yield el
476
+
477
+ def get_bottom_left_corner(self):
478
+ return self.elements[self.nrow - 1][0]
479
+
480
+
481
+ class _Figure(mpl.figure.Figure):
482
+ """
483
+ Figure but with panel support
484
+ """
485
+
486
+ main: Panel
487
+
488
+ def __init__(self, main: Panel, *args, **kwargs):
489
+ self.main = main
490
+ global active_fig
491
+ active_fig = self
492
+ super().__init__(*args, **kwargs)
493
+
494
+ def plot(self):
495
+ """
496
+ Align all panels within the figure
497
+ """
498
+
499
+ self.main.align()
500
+ self.set_size_inches(*self.main.dim)
501
+ self.main.position(self)
502
+
503
+ def set_tight_bounds(self):
504
+ """
505
+ Sets the bounds of the figure so that all elements are visible
506
+ """
507
+ new_bounds = self.get_tightbbox().extents
508
+ current_size = self.get_size_inches()
509
+ new_bounds[2] - new_bounds[0], new_bounds[3] - new_bounds[1]
510
+
511
+ self.set_figwidth(new_bounds[2] - new_bounds[0])
512
+ self.set_figheight(new_bounds[3] - new_bounds[1])
513
+
514
+ for ax in self.axes:
515
+ new_bbox = ax.get_position()
516
+ current_axis_bounds = ax.get_position().extents
517
+ new_bbox = mpl.figure.Bbox(
518
+ np.array(
519
+ [
520
+ (current_axis_bounds[0] - (new_bounds[0] / current_size[0]))
521
+ / ((new_bounds[2] - new_bounds[0]) / current_size[0]),
522
+ (current_axis_bounds[1] - (new_bounds[1] / current_size[1]))
523
+ / ((new_bounds[3] - new_bounds[1]) / current_size[1]),
524
+ (current_axis_bounds[2] - (new_bounds[0] / current_size[0]))
525
+ / ((new_bounds[2] - new_bounds[0]) / current_size[0]),
526
+ (current_axis_bounds[3] - (new_bounds[1] / current_size[1]))
527
+ / ((new_bounds[3] - new_bounds[1]) / current_size[1]),
528
+ ]
529
+ ).reshape((2, 2))
530
+ )
531
+ ax.set_position(new_bbox)
532
+
533
+
534
+ def Figure(main, *args, **kwargs):
535
+ """
536
+ Create a figure with panel support
537
+ """
538
+ return plt.figure(*args, main=main, **kwargs, FigureClass=_Figure)