matmalib 0.3.2__tar.gz → 0.3.4__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.
Files changed (33) hide show
  1. {matmalib-0.3.2 → matmalib-0.3.4}/PKG-INFO +25 -15
  2. {matmalib-0.3.2 → matmalib-0.3.4}/README.md +24 -14
  3. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/viz.py +99 -84
  4. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib.egg-info/PKG-INFO +25 -15
  5. {matmalib-0.3.2 → matmalib-0.3.4}/pyproject.toml +2 -2
  6. matmalib-0.3.4/tests/test_trajectory_plot.py +312 -0
  7. matmalib-0.3.2/tests/test_trajectory_plot.py +0 -238
  8. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/__init__.py +0 -0
  9. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/_carbohydrates.py +0 -0
  10. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/_geometry.py +0 -0
  11. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/_glycan_analysis.py +0 -0
  12. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/_pucker_reference.py +0 -0
  13. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/calc.py +0 -0
  14. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/conformers.py +0 -0
  15. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/core.py +0 -0
  16. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/elements.py +0 -0
  17. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/glycan.py +0 -0
  18. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/puckering.py +0 -0
  19. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/snfg.py +0 -0
  20. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib/util.py +0 -0
  21. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib.egg-info/SOURCES.txt +0 -0
  22. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib.egg-info/dependency_links.txt +0 -0
  23. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib.egg-info/requires.txt +0 -0
  24. {matmalib-0.3.2 → matmalib-0.3.4}/matmalib.egg-info/top_level.txt +0 -0
  25. {matmalib-0.3.2 → matmalib-0.3.4}/setup.cfg +0 -0
  26. {matmalib-0.3.2 → matmalib-0.3.4}/setup.py +0 -0
  27. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_carbohydrate_analysis.py +0 -0
  28. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_conformers.py +0 -0
  29. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_elements.py +0 -0
  30. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_glycan.py +0 -0
  31. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_puckering.py +0 -0
  32. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_snfg.py +0 -0
  33. {matmalib-0.3.2 → matmalib-0.3.4}/tests/test_sugar_detection.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: matmalib
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -124,25 +124,35 @@ Plot().trajectory(trajectory_data, col=2, var_name="theta (degrees)")
124
124
  print(trajectory_data.glycan.monomers[0].atom_assignment)
125
125
  ```
126
126
 
127
- For six-membered rings, plot the trajectory on a Mollweide projection of the
127
+ For six-membered rings, plot conformer counts on a Mollweide projection of the
128
128
  Cremer–Pople sphere using `Plot.cremer_pople_sphere`, with the 38 canonical
129
- chair, boat, skew-boat, half-chair, and envelope labels. The trajectory color
130
- shows time, with a colorbar below the sphere:
129
+ chair, boat, skew-boat, half-chair, and envelope labels. Each grid cell is
130
+ colored by the number of conformers it contains, with a count colorbar on
131
+ the right. The default grid uses 10° × 10° cells:
131
132
 
132
133
  ```python
133
134
  plot = Plot()
134
- fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0, cmap="viridis")
135
+ plot.cmap(map="ice", reverse=True) # Configure the count palette.
136
+ fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0)
135
137
  fig.savefig("puckering-mollweide.svg", bbox_inches="tight")
136
138
  # Set pucker_labels=False to hide the reference labels.
137
- # Overlay trajectories with [data_a, data_b] and headers=["Run A", "Run B"].
139
+ # Use bins=(72, 36) for a finer 5° × 5° grid (phi bins, theta bins).
140
+ # Pool conformers from multiple runs with [data_a, data_b].
138
141
  ```
139
142
 
140
- Frame colors use the recorded `time` column, including uneven time spacing,
141
- in the input `time_unit` (for example fs). Connecting segments use the mean
142
- time of their endpoints. `cmap` accepts a Matplotlib colormap name or object.
143
- Overlaid runs share one time scale and must have the same `time_unit`;
144
- different marker shapes distinguish them. The colorbar is also available as
145
- `plot.colorbar`.
143
+ Every valid frame contributes one count, regardless of time spacing or frame
144
+ order. Counts are pooled when multiple datasets are supplied; a `time`
145
+ column and matching time units are not required. These are raw counts per
146
+ angular cell, without normalization by spherical area. `bins` accepts a
147
+ positive integer for both dimensions or a `(phi, theta)` pair of bin counts.
148
+ `Plot.cmap()` configures the palette using its
149
+ `map`, `reverse`, `offset`, and `color_num` options. Without a configured
150
+ palette, the heatmap defaults to viridis. Passing `cmap="plasma"` (or a
151
+ Matplotlib colormap object) to `cremer_pople_sphere` overrides the palette for
152
+ that call. The default figure size is `(8, 4)` inches; use `figsize=` to adjust it.
153
+ Use a shared `alpha` value to change the heatmap opacity (default 1).
154
+ Optional `headers` are joined into a default title. The mesh and colorbar
155
+ are also available as `plot.heatmap` and `plot.colorbar`.
146
156
 
147
157
  `monomer` is a zero-based ring index. Both degree and radian trajectory data
148
158
  are supported; displayed angles are degrees. The map has φ decreasing from
@@ -153,9 +163,9 @@ the automatic assignment order; as in classification, ketose labels describe
153
163
  ring positions rather than chemical carbon numbers. Labels mark ideal CP
154
164
  coordinates, independently of whether `classify=True` was requested.
155
165
 
156
- Points are connected in frame order, with gaps at the map seam. Pure chairs
157
- with undefined φ are retained at the poles; planar frames are omitted and
158
- break the path. Five-membered rings have no θ and cannot use this projection.
166
+ Angles wrap at the 0°/360° seam. Pure chairs are counted at the poles using
167
+ φ=180°, since their phase is arbitrary; planar frames and other undefined
168
+ angles are omitted. Five-membered rings have no θ and cannot use this projection.
159
169
  Configured `xrange`/`yrange` are unsupported for the sphere.
160
170
  `Plot.trajectory(data, projection="mollweide", ...)` remains a shortcut to
161
171
  `cremer_pople_sphere`; its `col`, `var_name`, and `hist` options do not apply,
@@ -110,25 +110,35 @@ Plot().trajectory(trajectory_data, col=2, var_name="theta (degrees)")
110
110
  print(trajectory_data.glycan.monomers[0].atom_assignment)
111
111
  ```
112
112
 
113
- For six-membered rings, plot the trajectory on a Mollweide projection of the
113
+ For six-membered rings, plot conformer counts on a Mollweide projection of the
114
114
  Cremer–Pople sphere using `Plot.cremer_pople_sphere`, with the 38 canonical
115
- chair, boat, skew-boat, half-chair, and envelope labels. The trajectory color
116
- shows time, with a colorbar below the sphere:
115
+ chair, boat, skew-boat, half-chair, and envelope labels. Each grid cell is
116
+ colored by the number of conformers it contains, with a count colorbar on
117
+ the right. The default grid uses 10° × 10° cells:
117
118
 
118
119
  ```python
119
120
  plot = Plot()
120
- fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0, cmap="viridis")
121
+ plot.cmap(map="ice", reverse=True) # Configure the count palette.
122
+ fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0)
121
123
  fig.savefig("puckering-mollweide.svg", bbox_inches="tight")
122
124
  # Set pucker_labels=False to hide the reference labels.
123
- # Overlay trajectories with [data_a, data_b] and headers=["Run A", "Run B"].
125
+ # Use bins=(72, 36) for a finer 5° × 5° grid (phi bins, theta bins).
126
+ # Pool conformers from multiple runs with [data_a, data_b].
124
127
  ```
125
128
 
126
- Frame colors use the recorded `time` column, including uneven time spacing,
127
- in the input `time_unit` (for example fs). Connecting segments use the mean
128
- time of their endpoints. `cmap` accepts a Matplotlib colormap name or object.
129
- Overlaid runs share one time scale and must have the same `time_unit`;
130
- different marker shapes distinguish them. The colorbar is also available as
131
- `plot.colorbar`.
129
+ Every valid frame contributes one count, regardless of time spacing or frame
130
+ order. Counts are pooled when multiple datasets are supplied; a `time`
131
+ column and matching time units are not required. These are raw counts per
132
+ angular cell, without normalization by spherical area. `bins` accepts a
133
+ positive integer for both dimensions or a `(phi, theta)` pair of bin counts.
134
+ `Plot.cmap()` configures the palette using its
135
+ `map`, `reverse`, `offset`, and `color_num` options. Without a configured
136
+ palette, the heatmap defaults to viridis. Passing `cmap="plasma"` (or a
137
+ Matplotlib colormap object) to `cremer_pople_sphere` overrides the palette for
138
+ that call. The default figure size is `(8, 4)` inches; use `figsize=` to adjust it.
139
+ Use a shared `alpha` value to change the heatmap opacity (default 1).
140
+ Optional `headers` are joined into a default title. The mesh and colorbar
141
+ are also available as `plot.heatmap` and `plot.colorbar`.
132
142
 
133
143
  `monomer` is a zero-based ring index. Both degree and radian trajectory data
134
144
  are supported; displayed angles are degrees. The map has φ decreasing from
@@ -139,9 +149,9 @@ the automatic assignment order; as in classification, ketose labels describe
139
149
  ring positions rather than chemical carbon numbers. Labels mark ideal CP
140
150
  coordinates, independently of whether `classify=True` was requested.
141
151
 
142
- Points are connected in frame order, with gaps at the map seam. Pure chairs
143
- with undefined φ are retained at the poles; planar frames are omitted and
144
- break the path. Five-membered rings have no θ and cannot use this projection.
152
+ Angles wrap at the 0°/360° seam. Pure chairs are counted at the poles using
153
+ φ=180°, since their phase is arbitrary; planar frames and other undefined
154
+ angles are omitted. Five-membered rings have no θ and cannot use this projection.
145
155
  Configured `xrange`/`yrange` are unsupported for the sphere.
146
156
  `Plot.trajectory(data, projection="mollweide", ...)` remains a shortcut to
147
157
  `cremer_pople_sphere`; its `col`, `var_name`, and `hist` options do not apply,
@@ -11,9 +11,8 @@ from dataclasses import dataclass, asdict
11
11
  import matplotlib as mpl
12
12
  from matplotlib.ticker import NullFormatter
13
13
  from matplotlib.ticker import FormatStrFormatter
14
- from matplotlib.collections import LineCollection
15
14
  from matplotlib.colors import LinearSegmentedColormap, ListedColormap, Normalize
16
- from matplotlib.ticker import FuncFormatter
15
+ from matplotlib.ticker import FuncFormatter, MaxNLocator
17
16
  from numpy.ma.extras import average
18
17
 
19
18
 
@@ -119,6 +118,9 @@ class Plot():
119
118
  :param color_num: (int) Number of discrete colors.
120
119
  :param offset: (float) Fractional offset to shift the colormap.
121
120
  :param map: (str) Name of the colormap from the colormaps library.
121
+
122
+ Also configures the count palette for cremer_pople_sphere. An explicit
123
+ cmap argument on that plot overrides this palette for that call only.
122
124
  """
123
125
  # Check if the colormap exists in colormaps
124
126
  if not hasattr(colormaps, map):
@@ -169,7 +171,9 @@ class Plot():
169
171
  discrete_colors = np.linspace(0, len(colormap_colors) - 1, color_num, dtype=int)
170
172
  self.colors = [colormap_colors[i] for i in discrete_colors]
171
173
  else:
172
- self.colors = colormap_colors.tolist()
174
+ self.colors = np.asarray(colormap_colors).tolist()
175
+
176
+ self._pucker_cmap = ListedColormap(self.colors, name=map)
173
177
 
174
178
  def savefig(self, filename='fig', format: str = 'png'):
175
179
  self.fig.savefig(f"{self.path}/{filename}.{format}", dpi=300, bbox_inches='tight')
@@ -220,16 +224,16 @@ class Plot():
220
224
 
221
225
  def trajectory(self, data_list, var_name='colvar', col=1, average=None, title=None, hist=True, alpha=None,
222
226
  calc_qa=False, overlap=False, headers=None, *, projection=None, monomer=0,
223
- pucker_labels=True, cmap="viridis"):
227
+ pucker_labels=True, cmap=None, bins=(36, 18)):
224
228
 
225
229
  """ Plots MD trajectory with histogram. Takes in data for CP2K or Gromacs via Mol.
226
230
  :param data_list: (Mol / List) Either a Data object, or a list of Data objs if you want to overlay data.
227
231
  :param var_name: (list) Name of the collective variable you are plotting on your y-axis.
228
232
  :param col: (int) Index of the column containing your colvar data, in the case that you have multiple.
229
233
 
230
- For a time-colored Cremer–Pople sphere, use cremer_pople_sphere.
234
+ For a conformer-count Cremer–Pople heatmap, use cremer_pople_sphere.
231
235
  ``projection="mollweide"`` forwards to that method, including monomer,
232
- pucker_labels and cmap. In that view col, var_name and hist do not
236
+ pucker_labels, cmap and bins. In that view col, var_name and hist do not
233
237
  apply; smoothing, overlap and calc_qa are unsupported. With
234
238
  projection=None or "rectilinear", the time-series view is used.
235
239
  """
@@ -243,9 +247,10 @@ class Plot():
243
247
 
244
248
  if projection == "mollweide":
245
249
  if (average is not None and np.any(np.asarray(average) > 1)) or overlap or calc_qa:
246
- raise ValueError("Mollweide trajectories do not support average, overlap, or calc_qa.")
250
+ raise ValueError("Mollweide heatmaps do not support average, overlap, or calc_qa.")
247
251
  return self.cremer_pople_sphere(data_list, monomer=monomer, title=title, alpha=alpha,
248
- headers=headers, pucker_labels=pucker_labels, cmap=cmap)
252
+ headers=headers, pucker_labels=pucker_labels, cmap=cmap,
253
+ bins=bins)
249
254
 
250
255
  self.path = data_list[0].path
251
256
  # CP2K default timestep unit is in fs, Gromacs is in ps:
@@ -404,30 +409,35 @@ class Plot():
404
409
  self.fig = fig
405
410
  self.ax = ax
406
411
 
407
- def cremer_pople_sphere(self, data_list, *, monomer=0, cmap="viridis", title=None,
408
- alpha=None, headers=None, pucker_labels=True):
409
- """Plot a time-colored trajectory on a Mollweide Cremer–Pople sphere.
412
+ def cremer_pople_sphere(self, data_list, *, monomer=0, cmap=None, title=None,
413
+ alpha=None, headers=None, pucker_labels=True, figsize=(8, 4),
414
+ bins=(36, 18)):
415
+ """Plot conformer counts on a gridded Mollweide Cremer–Pople sphere.
410
416
 
411
417
  Accept a Data or list of Data returned by cremer_pople_trajectory.
412
- Select a zero-based six-membered ``monomer`` (default 0). Named time,
413
- theta and phi columns are required; angle_unit is degrees or radians.
414
- Frame markers use their recorded times; connecting segments use the
415
- mean time of their endpoints. ``cmap`` is a Matplotlib colormap name
416
- or object. The colorbar shows Time in the input time_unit, without
417
- rescaling. Overlaid trajectories must share a time_unit and use one
418
- common color scale, with different marker shapes and optional headers.
419
- A trajectory with a single time has one colorbar tick at that time.
418
+ Select a zero-based six-membered ``monomer`` (default 0). Named theta
419
+ and phi columns are required; angle_unit is degrees or radians. Each
420
+ valid row contributes one conformer, irrespective of time or order.
421
+ Multiple datasets are pooled into one histogram. ``bins`` is a positive
422
+ integer or a (phi, theta) pair of bin counts; the default (36, 18) gives
423
+ 10-degree cells. Colors show raw counts, not density per unit area.
424
+ By default, use the palette configured by Plot.cmap(), or viridis.
425
+ An explicit ``cmap`` Matplotlib name or object overrides it for this
426
+ plot. The vertical colorbar on the right shows Conformers per bin.
420
427
 
421
428
  Longitude is 180-phi degrees and latitude is 90-theta; tick labels show
422
- CP angles in degrees. Frames are joined in order, with breaks at the
423
- 0/360-degree seam and undefined angles. Pure chairs appear at the poles;
424
- planar frames are omitted. The 38 ideal puckers are labelled by default;
425
- pucker_labels=False hides them. Labels assume O, C1, ..., C5 ring order,
426
- with O denoting position 6 in classification results.
427
-
428
- Supports alpha, title and label/font configuration; configured axis
429
- limits are unsupported. Return (figure, axes), also stored as fig and
430
- ax on this Plot; colorbar holds the Matplotlib Colorbar object.
429
+ CP angles in degrees. Phi wraps at 0/360 degrees. Pure chairs are
430
+ counted at the poles using phi=180, where phase is arbitrary; planar
431
+ frames and other undefined angles are omitted. The 38 ideal puckers
432
+ are labelled by default; pucker_labels=False hides them. Labels assume
433
+ O, C1, ..., C5 ring order, with O denoting position 6 in classification
434
+ results.
435
+
436
+ ``figsize`` defaults to (8, 4) inches and ``alpha`` to 1. Alpha must be
437
+ common to all pooled datasets. Headers are joined into a default title.
438
+ Supports title and label/font configuration; configured axis limits
439
+ are unsupported. Return (figure, axes), also stored as fig and ax on
440
+ this Plot; heatmap and colorbar hold the Matplotlib mesh and Colorbar.
431
441
  """
432
442
  from ._pucker_reference import CREMER_POPLE_PUCKERS
433
443
 
@@ -439,18 +449,36 @@ class Plot():
439
449
  raise ValueError("monomer must be a nonnegative integer.")
440
450
  if self.config.xrange is not None or self.config.yrange is not None:
441
451
  raise ValueError("Mollweide axes have fixed limits; remove xrange and yrange from the plot config.")
452
+ try:
453
+ bin_counts = (bins, bins) if isinstance(bins, Integral) else tuple(bins)
454
+ except TypeError:
455
+ raise ValueError("bins must be a positive integer or a (phi, theta) pair of positive integers.") from None
456
+ if len(bin_counts) != 2 or any(isinstance(n, bool) or not isinstance(n, Integral) or n <= 0
457
+ for n in bin_counts):
458
+ raise ValueError("bins must be a positive integer or a (phi, theta) pair of positive integers.")
442
459
  if headers is None and self.config.headers is not None:
443
460
  headers = self.config.headers
444
461
  if headers is None:
445
462
  headers = [None] * len(data_list)
463
+ if len(headers) != len(data_list):
464
+ raise ValueError("Supply one header per dataset.")
446
465
  if alpha is None or np.isscalar(alpha):
447
- alpha = [0.8 if alpha is None else alpha] * len(data_list)
448
- if len(headers) != len(data_list) or len(alpha) != len(data_list):
449
- raise ValueError("Supply one header and alpha value per trajectory.")
450
-
451
- colormap = mpl.colormaps.get_cmap(cmap)
452
- time_unit = getattr(data_list[0], "time_unit", None)
453
- coordinates = []
466
+ alpha = [1.0 if alpha is None else alpha] * len(data_list)
467
+ if len(alpha) != len(data_list):
468
+ raise ValueError("Supply one alpha value per dataset, or a single shared value.")
469
+ alpha = np.asarray(alpha, dtype=float)
470
+ if not np.all(np.isfinite(alpha) & (alpha >= 0) & (alpha <= 1)):
471
+ raise ValueError("alpha must lie between 0 and 1.")
472
+ if not np.all(alpha == alpha[0]):
473
+ raise ValueError("Pooled heatmaps require the same alpha for all datasets.")
474
+
475
+ if cmap is None:
476
+ colormap = getattr(self, "_pucker_cmap", mpl.colormaps["viridis"])
477
+ else:
478
+ colormap = mpl.colormaps.get_cmap(cmap)
479
+ phi_edges = np.linspace(0, 2 * np.pi, bin_counts[0] + 1)
480
+ theta_edges = np.linspace(0, np.pi, bin_counts[1] + 1)
481
+ counts = np.zeros(bin_counts, dtype=np.int64)
454
482
  for datum in data_list:
455
483
  columns = tuple(getattr(datum, "columns", ()))
456
484
  theta_name, phi_name = f"monomer_{monomer}.theta", f"monomer_{monomer}.phi"
@@ -462,13 +490,6 @@ class Plot():
462
490
  values = np.asarray(datum.data, dtype=float)
463
491
  if values.ndim != 2 or values.shape[0] == 0 or values.shape[1] != len(columns):
464
492
  raise ValueError("Trajectory data must be a nonempty 2D array matching its columns.")
465
- if "time" not in columns:
466
- raise ValueError("Cremer–Pople sphere data must have a named time column.")
467
- times = values[:, columns.index("time")]
468
- if not np.all(np.isfinite(times)):
469
- raise ValueError("Trajectory times must be finite.")
470
- if getattr(datum, "time_unit", None) != time_unit:
471
- raise ValueError("Overlaid trajectories must have the same time_unit.")
472
493
  theta, phi = values[:, [columns.index(theta_name), columns.index(phi_name)]].T
473
494
  unit = getattr(datum, "angle_unit", None)
474
495
  if unit == "degrees":
@@ -478,48 +499,40 @@ class Plot():
478
499
  if np.any(np.isfinite(theta) & ((theta < 0) | (theta > np.pi))):
479
500
  raise ValueError("Cremer–Pople theta must lie between 0 and 180 degrees (0 and pi radians).")
480
501
 
481
- # A chair's undefined phase still represents a well-defined pole.
502
+ # Phase is arbitrary at a pole: count all pure chairs together.
482
503
  poles = np.isclose(theta, 0, atol=1e-12, rtol=0) | np.isclose(theta, np.pi, atol=1e-12, rtol=0)
483
- phi = np.where(poles & np.isnan(phi), np.pi, phi)
504
+ phi = np.where(poles, np.pi, phi)
484
505
  valid = np.isfinite(theta) & np.isfinite(phi)
485
- longitude = np.full(theta.shape, np.nan)
486
- latitude = np.full(theta.shape, np.nan)
487
- longitude[valid] = np.pi - phi[valid] % (2 * np.pi)
488
- latitude[valid] = np.pi / 2 - theta[valid]
489
- coordinates.append((longitude, latitude, times))
490
-
491
- start = min(times.min() for _, _, times in coordinates)
492
- end = max(times.max() for _, _, times in coordinates)
493
- # Keep a single-time trajectory visible without implying a time range
494
- # in the colorbar tick labels.
495
- norm = Normalize(start, end) if start != end else Normalize(start - .5, end + .5)
496
- fig, ax = plt.subplots(figsize=(12, 7.5), subplot_kw={"projection": "mollweide"},
506
+ histogram, _, _ = np.histogram2d(phi[valid] % (2 * np.pi), theta[valid],
507
+ bins=(phi_edges, theta_edges))
508
+ counts += histogram.astype(np.int64)
509
+
510
+ maximum = int(counts.max())
511
+ norm = Normalize(0, max(1, maximum))
512
+ fig, ax = plt.subplots(figsize=figsize, subplot_kw={"projection": "mollweide"},
497
513
  layout="constrained")
498
- markers = ("o", "s", "^", "D", "v", "P", "X")
499
- for i, ((longitude, latitude, times), header) in enumerate(zip(coordinates, headers)):
500
- valid = np.isfinite(longitude) & np.isfinite(latitude)
501
- # Keep only adjacent valid frames on the same side of the seam.
502
- connected = valid[:-1] & valid[1:] & (np.abs(np.diff(longitude)) <= np.pi)
503
- points = np.column_stack((longitude, latitude))
504
- segments = np.stack((points[:-1], points[1:]), axis=1)[connected]
505
- line = LineCollection(segments, cmap=colormap, norm=norm, linewidths=1.2,
506
- alpha=alpha[i], zorder=2)
507
- line.set_array((times[:-1] / 2 + times[1:] / 2)[connected])
508
- ax.add_collection(line)
509
- ax.scatter(longitude[valid], latitude[valid], c=times[valid], cmap=colormap,
510
- norm=norm, s=9, marker=markers[i % len(markers)], alpha=alpha[i],
511
- label=header, zorder=3)
514
+ # Both CP angles decrease along the displayed axes, so reverse the
515
+ # histogram as well as its edges before drawing the geographic mesh.
516
+ heatmap = ax.pcolormesh(np.pi - phi_edges[::-1], np.pi / 2 - theta_edges[::-1],
517
+ counts.T[::-1, ::-1], cmap=colormap, norm=norm,
518
+ shading="flat", alpha=alpha[0], edgecolors="0.4",
519
+ linewidth=.2, rasterized=True, zorder=1)
512
520
 
513
521
  ax.set_longitude_grid(30)
514
- ax.set_latitude_grid(30)
522
+ ax.set_latitude_grid(45)
515
523
  # Geographic axes place the secondary x labels below the equator,
516
524
  # leaving space above it for boat and skew-boat annotations.
517
525
  ax.tick_params(axis="x", labeltop=True, labelbottom=False)
526
+ ax.tick_params(axis="both", labelsize=8)
518
527
  ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: f"{180 - np.degrees(x):.0f}°"))
519
528
  ax.yaxis.set_major_formatter(FuncFormatter(lambda y, pos: f"{90 - np.degrees(y):.0f}°"))
520
- ax.set_xlabel(r"$\phi$ (degrees)")
521
- ax.set_ylabel(r"$\theta$ (degrees)")
522
- ax.grid(True, alpha=0.3)
529
+ # Longitude labels sit inside the map and must remain readable over
530
+ # both the darkest and lightest heatmap cells.
531
+ for label in ax.get_xticklabels():
532
+ label.set_bbox(dict(facecolor="white", edgecolor="none", alpha=.7, pad=.5))
533
+ ax.set_xlabel(r"$\phi$ (degrees)", fontsize=9)
534
+ ax.set_ylabel(r"$\theta$ (degrees)", fontsize=9)
535
+ ax.grid(True, color="0.55", linewidth=0.7, alpha=0.8)
523
536
 
524
537
  if pucker_labels:
525
538
  reference_points = []
@@ -533,24 +546,26 @@ class Plot():
533
546
  for longitude in longitudes:
534
547
  latitude = np.radians(90 - theta)
535
548
  reference_points.append((longitude, latitude))
536
- dx = 5 if longitude == -np.pi else -5 if longitude == np.pi else 0
537
- dy = -9 if theta == 0 else -12 if family == "E" else 7
549
+ dx = 4 if longitude == -np.pi else -4 if longitude == np.pi else 0
550
+ dy = -7 if theta == 0 else -10 if family == "E" else 6
538
551
  ax.annotate(text, (longitude, latitude), xytext=(dx, dy),
539
- textcoords="offset points", fontsize=10, color="0.25",
552
+ textcoords="offset points", fontsize=8, color="0.25",
540
553
  ha="left" if dx > 0 else "right" if dx < 0 else "center",
541
554
  va="top" if theta == 0 else "bottom", zorder=4,
542
555
  bbox=dict(facecolor="white", edgecolor="none", alpha=0.7, pad=0.5))
543
556
  ax.scatter(*np.asarray(reference_points).T, s=9, color="0.35", zorder=2)
544
557
 
545
- if any(header is not None for header in headers):
546
- ax.legend(loc="upper right", bbox_to_anchor=(1.08, 1.12))
558
+ if title is None and any(header is not None for header in headers):
559
+ title = ", ".join(str(header) for header in headers if header is not None)
547
560
  if title is not None:
548
- ax.set_title(title)
561
+ ax.set_title(title, fontsize=11, pad=6)
549
562
  self.set_axes(ax)
550
- self.colorbar = fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=colormap), ax=ax,
551
- orientation="horizontal", fraction=0.045, pad=0.08,
552
- ticks=[start] if start == end else None)
553
- self.colorbar.set_label(f"Time ({time_unit})" if time_unit else "Time")
563
+ self.heatmap = heatmap
564
+ self.colorbar = fig.colorbar(heatmap, ax=ax,
565
+ orientation="vertical", fraction=0.035, pad=0.035,
566
+ ticks=MaxNLocator(nbins=5, integer=True) if maximum else [0])
567
+ self.colorbar.set_label("Conformers per bin", fontsize=9)
568
+ self.colorbar.ax.tick_params(labelsize=8)
554
569
  self.path = getattr(data_list[0], "path", "")
555
570
  self.fig, self.ax = fig, ax
556
571
  return fig, ax
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: matmalib
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -124,25 +124,35 @@ Plot().trajectory(trajectory_data, col=2, var_name="theta (degrees)")
124
124
  print(trajectory_data.glycan.monomers[0].atom_assignment)
125
125
  ```
126
126
 
127
- For six-membered rings, plot the trajectory on a Mollweide projection of the
127
+ For six-membered rings, plot conformer counts on a Mollweide projection of the
128
128
  Cremer–Pople sphere using `Plot.cremer_pople_sphere`, with the 38 canonical
129
- chair, boat, skew-boat, half-chair, and envelope labels. The trajectory color
130
- shows time, with a colorbar below the sphere:
129
+ chair, boat, skew-boat, half-chair, and envelope labels. Each grid cell is
130
+ colored by the number of conformers it contains, with a count colorbar on
131
+ the right. The default grid uses 10° × 10° cells:
131
132
 
132
133
  ```python
133
134
  plot = Plot()
134
- fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0, cmap="viridis")
135
+ plot.cmap(map="ice", reverse=True) # Configure the count palette.
136
+ fig, ax = plot.cremer_pople_sphere(trajectory_data, monomer=0)
135
137
  fig.savefig("puckering-mollweide.svg", bbox_inches="tight")
136
138
  # Set pucker_labels=False to hide the reference labels.
137
- # Overlay trajectories with [data_a, data_b] and headers=["Run A", "Run B"].
139
+ # Use bins=(72, 36) for a finer 5° × 5° grid (phi bins, theta bins).
140
+ # Pool conformers from multiple runs with [data_a, data_b].
138
141
  ```
139
142
 
140
- Frame colors use the recorded `time` column, including uneven time spacing,
141
- in the input `time_unit` (for example fs). Connecting segments use the mean
142
- time of their endpoints. `cmap` accepts a Matplotlib colormap name or object.
143
- Overlaid runs share one time scale and must have the same `time_unit`;
144
- different marker shapes distinguish them. The colorbar is also available as
145
- `plot.colorbar`.
143
+ Every valid frame contributes one count, regardless of time spacing or frame
144
+ order. Counts are pooled when multiple datasets are supplied; a `time`
145
+ column and matching time units are not required. These are raw counts per
146
+ angular cell, without normalization by spherical area. `bins` accepts a
147
+ positive integer for both dimensions or a `(phi, theta)` pair of bin counts.
148
+ `Plot.cmap()` configures the palette using its
149
+ `map`, `reverse`, `offset`, and `color_num` options. Without a configured
150
+ palette, the heatmap defaults to viridis. Passing `cmap="plasma"` (or a
151
+ Matplotlib colormap object) to `cremer_pople_sphere` overrides the palette for
152
+ that call. The default figure size is `(8, 4)` inches; use `figsize=` to adjust it.
153
+ Use a shared `alpha` value to change the heatmap opacity (default 1).
154
+ Optional `headers` are joined into a default title. The mesh and colorbar
155
+ are also available as `plot.heatmap` and `plot.colorbar`.
146
156
 
147
157
  `monomer` is a zero-based ring index. Both degree and radian trajectory data
148
158
  are supported; displayed angles are degrees. The map has φ decreasing from
@@ -153,9 +163,9 @@ the automatic assignment order; as in classification, ketose labels describe
153
163
  ring positions rather than chemical carbon numbers. Labels mark ideal CP
154
164
  coordinates, independently of whether `classify=True` was requested.
155
165
 
156
- Points are connected in frame order, with gaps at the map seam. Pure chairs
157
- with undefined φ are retained at the poles; planar frames are omitted and
158
- break the path. Five-membered rings have no θ and cannot use this projection.
166
+ Angles wrap at the 0°/360° seam. Pure chairs are counted at the poles using
167
+ φ=180°, since their phase is arbitrary; planar frames and other undefined
168
+ angles are omitted. Five-membered rings have no θ and cannot use this projection.
159
169
  Configured `xrange`/`yrange` are unsupported for the sphere.
160
170
  `Plot.trajectory(data, projection="mollweide", ...)` remains a shortcut to
161
171
  `cremer_pople_sphere`; its `col`, `var_name`, and `hist` options do not apply,
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  dynamic = ["dependencies"]
3
3
  name = "matmalib"
4
- version = "0.3.2"
4
+ version = "0.3.4"
5
5
  description = "Add your description here"
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.12"
8
8
 
9
9
  [tool.bumpversion]
10
- current_version = "0.3.2"
10
+ current_version = "0.3.4"
11
11
  parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
12
12
  serialize = ["{major}.{minor}.{patch}"]
13
13
  search = "{current_version}"
@@ -0,0 +1,312 @@
1
+ from pathlib import Path
2
+
3
+ import matplotlib
4
+ matplotlib.use("Agg")
5
+ import matplotlib.pyplot as plt
6
+ from matplotlib.collections import QuadMesh
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from matmalib import Data, Plot, Space, cremer_pople, cremer_pople_trajectory
11
+ from matmalib._pucker_reference import CARPPY_PUCKERS, CREMER_POPLE_PUCKERS
12
+ from test_puckering import ring_coordinates
13
+
14
+
15
+ @pytest.fixture(autouse=True)
16
+ def close_figures():
17
+ yield
18
+ plt.close("all")
19
+
20
+
21
+ def trajectory(*, degrees=True, phases=(30, 180, 330)):
22
+ frames = [ring_coordinates(q2=.4, q3=q3, phi=phi)
23
+ for q3, phi in zip((.4, 0, -.4), phases)]
24
+ return cremer_pople_trajectory(frames, [range(6)], degrees=degrees)
25
+
26
+
27
+ def angle_data(theta, phi, *, degrees=True):
28
+ values = np.column_stack((theta, phi))
29
+ data = Data(data=values if degrees else np.radians(values))
30
+ data.columns = ("monomer_0.theta", "monomer_0.phi")
31
+ data.angle_unit = "degrees" if degrees else "radians"
32
+ return data
33
+
34
+
35
+ @pytest.mark.parametrize("degrees", [True, False])
36
+ def test_mollweide_coordinates_units_orientation_and_export(degrees, tmp_path):
37
+ data = angle_data([45, 95, 135], [35, 185, 335], degrees=degrees)
38
+ original = data.data.copy()
39
+ plot = Plot()
40
+ fig, ax = plot.cremer_pople_sphere(data, pucker_labels=False)
41
+ assert (fig, ax) == (plot.fig, plot.ax)
42
+ assert ax.name == "mollweide"
43
+ assert len(fig.axes) == 2 # Sphere and count colorbar.
44
+ assert len(ax.collections) == 1
45
+ assert isinstance(plot.heatmap, QuadMesh)
46
+ counts = plot.heatmap.get_array().reshape(18, 36)
47
+ expected = np.zeros((18, 36))
48
+ expected[[13, 8, 4], [32, 17, 2]] = 1
49
+ np.testing.assert_array_equal(counts, expected)
50
+ edges = plot.heatmap.get_coordinates()
51
+ np.testing.assert_allclose(np.degrees(np.diff(edges[0, :, 0])), 10)
52
+ np.testing.assert_allclose(np.degrees(np.diff(edges[:, 0, 1])), 10)
53
+ assert plot.heatmap.get_linewidths()[0] > 0
54
+ assert plot.colorbar.ax.get_ylabel() == "Conformers per bin"
55
+ np.testing.assert_array_equal(data.data, original)
56
+ assert ax.xaxis.get_major_formatter()(np.pi / 2) == "90°"
57
+ assert ax.yaxis.get_major_formatter()(np.pi / 6) == "60°"
58
+ assert not ax.texts
59
+ fig.savefig(tmp_path / "mollweide.svg", bbox_inches="tight")
60
+
61
+
62
+ @pytest.mark.parametrize("degrees", [True, False])
63
+ def test_seam_wrap_preserves_samples_on_both_sides(degrees):
64
+ data = angle_data([95] * 7, [-1, 359, 719, 0, 360, 720, 1], degrees=degrees)
65
+ plot = Plot()
66
+ plot.cremer_pople_sphere(data, pucker_labels=False)
67
+ counts = plot.heatmap.get_array().reshape(18, 36)
68
+ assert counts.sum() == 7
69
+ assert counts[8, 0] == 3
70
+ assert counts[8, -1] == 4
71
+
72
+
73
+ def test_chairs_are_counted_and_planar_frames_are_omitted():
74
+ frames = [ring_coordinates(q3=.5), ring_coordinates(), ring_coordinates(q3=-.5)]
75
+ data = cremer_pople_trajectory(frames, [range(6)])
76
+ plot = Plot()
77
+ _, ax = plot.cremer_pople_sphere(data, pucker_labels=False)
78
+ counts = plot.heatmap.get_array().reshape(18, 36)
79
+ assert counts.sum() == 2
80
+ assert counts[-1, 17] == counts[0, 17] == 1
81
+ ax.figure.canvas.draw()
82
+
83
+
84
+ def test_chairs_with_arbitrary_phases_share_one_bin_at_each_pole():
85
+ data = angle_data([0, 0, 180, 180], [np.nan, 35, np.nan, 335])
86
+ plot = Plot()
87
+ plot.cremer_pople_sphere(data, pucker_labels=False)
88
+ counts = plot.heatmap.get_array().reshape(18, 36)
89
+ assert counts.sum() == 4
90
+ assert counts[-1, 17] == counts[0, 17] == 2
91
+
92
+
93
+ def test_mixed_ring_selection_single_frame_and_pooled_configuration():
94
+ frame = np.vstack((ring_coordinates(5, q2=.3), ring_coordinates(q2=.3, phi=90) + 10))
95
+ data = cremer_pople_trajectory([frame], [range(5), range(5, 11)])
96
+ plot = Plot()
97
+ plot.set_config({"headers": ["First", "Second"], "title": "Ring 1"})
98
+ fig, ax = plot.cremer_pople_sphere([data, data], monomer=1, alpha=[.7, .7])
99
+ assert ax.get_title() == "Ring 1"
100
+ assert plot.heatmap.get_array().sum() == plot.heatmap.get_array().max() == 2
101
+ assert plot.heatmap.get_alpha() == .7
102
+ assert ax.get_legend() is None
103
+ np.testing.assert_allclose(plot.colorbar.get_ticks(), [0, 1, 2])
104
+ fig.canvas.draw()
105
+ with pytest.raises(ValueError, match="six-membered"):
106
+ plot.cremer_pople_sphere(data, headers=[None])
107
+
108
+
109
+ def test_all_reference_labels_and_seam_duplicates_render(tmp_path):
110
+ fig, ax = Plot().cremer_pople_sphere(trajectory(), title="Puckering", alpha=.6)
111
+ labels = {annotation.get_text(): annotation for annotation in ax.texts}
112
+ assert len(labels) == 38
113
+ assert len(ax.texts) == 41 # Three phi=0 references appear at both edges.
114
+ assert labels[r"$^{4}\mathrm{C}_{1}$"].xy == (0, np.pi / 2)
115
+ assert labels[r"$^{1}\mathrm{C}_{4}$"].xy == (0, -np.pi / 2)
116
+ assert labels[r"$^{O}\mathrm{S}_{2}$"].xy == pytest.approx((-5 * np.pi / 6, 0))
117
+ assert r"$^{O}\mathrm{E}_{}$" in labels
118
+ assert r"$^{O}\mathrm{H}_{1}$" in labels
119
+ assert r"$^{}\mathrm{B}_{3,O}$" in labels
120
+ assert ax.get_title() == "Puckering"
121
+ fig.canvas.draw()
122
+ renderer = fig.canvas.get_renderer()
123
+ for annotation in ax.texts:
124
+ if annotation.xy[1] == 0:
125
+ assert not any(annotation.get_window_extent(renderer).overlaps(tick.get_window_extent(renderer))
126
+ for tick in ax.get_xticklabels())
127
+ fig.savefig(tmp_path / "labelled-mollweide.svg", bbox_inches="tight")
128
+
129
+
130
+ def test_ideal_cp_references_agree_with_all_38_independent_benchmark_structures():
131
+ source = Path(__file__).parent / "data" / "glucose_puckers.xyz"
132
+ labels = [line.split("conf_")[1].split("/")[0]
133
+ for line in source.read_text().splitlines() if line.startswith("CarP/")]
134
+ assert set(CREMER_POPLE_PUCKERS) == set(CARPPY_PUCKERS) == set(labels)
135
+ for label, state in zip(labels, Space.from_xyz(source).states):
136
+ measured = cremer_pople(state.xyz[[0, 10, 9, 7, 6, 8]])
137
+ theta, phi = CREMER_POPLE_PUCKERS[label]
138
+ assert measured["theta"] == pytest.approx(theta, abs=3), label
139
+ if "C" not in label: # Phase is arbitrary at a pole.
140
+ assert abs((measured["phi"] - phi + 180) % 360 - 180) < 5, label
141
+
142
+
143
+ @pytest.mark.parametrize("kwargs,match", [
144
+ ({"projection": "polar"}, "projection"),
145
+ ({"monomer": -1}, "monomer"),
146
+ ({"monomer": True}, "monomer"),
147
+ ({"monomer": 0.5}, "monomer"),
148
+ ({"monomer": 1}, "six-membered"),
149
+ ({"headers": []}, "one header"),
150
+ ({"alpha": []}, "one alpha"),
151
+ ({"alpha": -0.1}, "alpha must lie"),
152
+ ({"alpha": np.nan}, "alpha must lie"),
153
+ ({"average": 2}, "do not support"),
154
+ ({"overlap": True}, "do not support"),
155
+ ({"calc_qa": True}, "do not support"),
156
+ ])
157
+ def test_invalid_plot_options(kwargs, match):
158
+ with pytest.raises(ValueError, match=match):
159
+ Plot().trajectory(trajectory(), **{"projection": "mollweide", **kwargs})
160
+
161
+
162
+ def test_missing_metadata_units_data_and_fixed_limits():
163
+ with pytest.raises(ValueError, match="at least one"):
164
+ Plot().cremer_pople_sphere([])
165
+ with pytest.raises(ValueError, match="six-membered"):
166
+ Plot().cremer_pople_sphere(Data(data=np.ones((3, 2))))
167
+ data = trajectory()
168
+ data.angle_unit = "unknown"
169
+ with pytest.raises(ValueError, match="angle_unit"):
170
+ Plot().cremer_pople_sphere(data)
171
+ data.angle_unit = "degrees"
172
+ data.data[0, 2] = 181
173
+ with pytest.raises(ValueError, match="theta must lie"):
174
+ Plot().cremer_pople_sphere(data)
175
+ data.data = data.data[:0]
176
+ with pytest.raises(ValueError, match="nonempty 2D"):
177
+ Plot().cremer_pople_sphere(data)
178
+ plot = Plot()
179
+ plot.set_config({"xrange": [0, 360]})
180
+ with pytest.raises(ValueError, match="fixed limits"):
181
+ plot.cremer_pople_sphere(trajectory())
182
+
183
+
184
+ def test_heatmap_uses_counts_and_selected_colormap():
185
+ data = angle_data([45, 45, 45, 135], [35, 35, 35, 335])
186
+ plot = Plot()
187
+ fig, ax = plot.cremer_pople_sphere(data, cmap="plasma", pucker_labels=False)
188
+ counts = plot.heatmap.get_array().reshape(18, 36)
189
+ assert counts[13, 32] == 3
190
+ assert counts[4, 2] == 1
191
+ assert counts.sum() == 4
192
+ assert plot.heatmap.norm is plot.colorbar.norm
193
+ assert (plot.colorbar.norm.vmin, plot.colorbar.norm.vmax) == (0, 3)
194
+ assert plot.heatmap.cmap.name == plot.colorbar.cmap.name == "plasma"
195
+ fig.canvas.draw()
196
+ colors = plot.heatmap.get_facecolors().reshape(18, 36, 4)
197
+ np.testing.assert_allclose(colors[[13, 4, 0], [32, 2, 0]], plot.heatmap.to_rgba([3, 1, 0]))
198
+
199
+
200
+ def test_multiple_datasets_pool_counts_regardless_of_time_units():
201
+ first, second = trajectory(), trajectory()
202
+ second.data[:, 0] += 10
203
+ second.time_unit = "ns"
204
+ second.angle_unit = "radians"
205
+ second.data[:, 2:4] = np.radians(second.data[:, 2:4])
206
+ plot = Plot()
207
+ _, ax = plot.cremer_pople_sphere([first, second], headers=["Run A", "Run B"], pucker_labels=False)
208
+ assert len(ax.figure.axes) == 2
209
+ assert len(ax.collections) == 1
210
+ assert ax.get_title() == "Run A, Run B"
211
+ assert plot.heatmap.get_array().sum() == 6
212
+ np.testing.assert_array_equal(np.unique(plot.heatmap.get_array()), [0, 2])
213
+ assert (plot.colorbar.norm.vmin, plot.colorbar.norm.vmax) == (0, 2)
214
+ with pytest.raises(ValueError, match="same alpha"):
215
+ plot.cremer_pople_sphere([first, second], alpha=[.5, .7])
216
+
217
+
218
+ @pytest.mark.parametrize("options", [
219
+ {"reverse": True}, {"offset": .1}, {"reverse": True, "offset": .1, "color_num": 4},
220
+ ])
221
+ def test_sphere_heatmap_uses_plot_cmap_settings_and_allows_override(options):
222
+ plot = Plot()
223
+ plot.cmap(map="ice", **options)
224
+ palette = np.asarray(plot.colors)
225
+ # Both public entry points use the configured palette for all artists.
226
+ for draw, kwargs in ((plot.cremer_pople_sphere, {}), (plot.trajectory, {"projection": "mollweide"})):
227
+ _, ax = draw(trajectory(), pucker_labels=False, **kwargs)
228
+ mesh, = ax.collections
229
+ assert mesh.cmap is plot.colorbar.cmap
230
+ assert mesh.cmap.name == "ice"
231
+ np.testing.assert_allclose(mesh.cmap([0., 1.])[:, :3], palette[[0, -1]])
232
+ np.testing.assert_allclose(mesh.cmap.colors, palette)
233
+
234
+ plot.cremer_pople_sphere(trajectory(), cmap="plasma")
235
+ assert plot.colorbar.cmap.name == "plasma"
236
+ plot.cremer_pople_sphere(trajectory())
237
+ assert plot.colorbar.cmap.name == "ice"
238
+ np.testing.assert_allclose(plot.colors, palette)
239
+
240
+
241
+ def test_compact_sphere_has_side_colorbar_and_readable_labels():
242
+ plot = Plot()
243
+ fig, ax = plot.cremer_pople_sphere(trajectory(), title="Ring puckering")
244
+ assert plot.colorbar.orientation == "vertical"
245
+ assert plot.colorbar.cmap.name == "viridis"
246
+ fig.canvas.draw()
247
+ renderer = fig.canvas.get_renderer()
248
+ sphere_box = ax.get_window_extent(renderer)
249
+ colorbar_box = plot.colorbar.ax.get_window_extent(renderer)
250
+ assert colorbar_box.x0 > sphere_box.x1
251
+ assert colorbar_box.height > colorbar_box.width
252
+ for annotation in ax.texts:
253
+ box = annotation.get_window_extent(renderer)
254
+ assert not box.overlaps(colorbar_box)
255
+ assert fig.bbox.contains(box.x0, box.y0)
256
+ assert fig.bbox.contains(box.x1, box.y1)
257
+
258
+
259
+ def test_column_order_time_values_and_frame_order_do_not_affect_counts():
260
+ data = trajectory()
261
+ plot = Plot()
262
+ plot.cremer_pople_sphere(data, pucker_labels=False)
263
+ expected = plot.heatmap.get_array().copy()
264
+ data.data[:, 0] = [np.nan, np.inf, -100]
265
+ order = [2, 0, 3, 1, 4, 5]
266
+ data.columns = tuple(data.columns[i] for i in order)
267
+ data.data = data.data[::-1, order]
268
+ fig, ax = plot.cremer_pople_sphere(data, cmap=matplotlib.colormaps["cividis"], pucker_labels=False)
269
+ np.testing.assert_array_equal(plot.heatmap.get_array(), expected)
270
+ assert plot.colorbar.cmap.name == "cividis"
271
+ fig.canvas.draw()
272
+
273
+
274
+ def test_undefined_angles_produce_an_empty_heatmap():
275
+ data = angle_data([np.nan, 45, np.inf, 90], [np.nan, np.nan, 30, np.inf])
276
+ plot = Plot()
277
+ fig, ax = plot.cremer_pople_sphere(data, pucker_labels=False)
278
+ assert not np.any(plot.heatmap.get_array())
279
+ np.testing.assert_array_equal(plot.colorbar.get_ticks(), [0])
280
+ fig.canvas.draw()
281
+
282
+
283
+ @pytest.mark.parametrize("bins,shape", [(12, (12, 12)), ((72, 36), (36, 72))])
284
+ def test_custom_bins_and_shortcut_without_time_column(bins, shape):
285
+ data = angle_data([45, 45, 135], [35, 35, 335])
286
+ plot = Plot()
287
+ fig, ax = plot.trajectory(data, projection="mollweide", bins=bins, cmap="plasma", pucker_labels=False)
288
+ assert (fig, ax) == (plot.fig, plot.ax)
289
+ assert plot.colorbar.cmap.name == "plasma"
290
+ assert plot.heatmap.get_array().size == np.prod(shape)
291
+ assert plot.heatmap.get_coordinates().shape == (shape[0] + 1, shape[1] + 1, 2)
292
+ assert plot.heatmap.get_array().sum() == 3
293
+ assert plot.heatmap.get_array().max() == 2
294
+
295
+
296
+ @pytest.mark.parametrize("bins", [0, -1, True, 1.5, (36,), (36, 0), (36, 18, 2), (36, 1.5), None])
297
+ def test_invalid_bin_counts(bins):
298
+ with pytest.raises(ValueError, match="bins must be"):
299
+ Plot().cremer_pople_sphere(trajectory(), bins=bins)
300
+
301
+
302
+ @pytest.mark.parametrize("projection", [None, "rectilinear"])
303
+ def test_existing_time_series_and_histogram(projection):
304
+ data = trajectory()
305
+ plot = Plot()
306
+ plot.trajectory(data, col=2, var_name="theta", headers=["Run"], projection=projection)
307
+ assert len(plot.fig.axes) == 2
308
+ assert plot.ax[0].name == "rectilinear"
309
+ np.testing.assert_allclose(plot.ax[0].lines[0].get_ydata(), [45, 90, 135])
310
+ np.testing.assert_allclose(plot.ax[0].lines[0].get_xdata(), [0, .001, .002])
311
+ assert plot.ax[0].get_ylabel() == "theta"
312
+ plot.fig.canvas.draw()
@@ -1,238 +0,0 @@
1
- from pathlib import Path
2
-
3
- import matplotlib
4
- matplotlib.use("Agg")
5
- import matplotlib.pyplot as plt
6
- import numpy as np
7
- import pytest
8
-
9
- from matmalib import Data, Plot, Space, cremer_pople, cremer_pople_trajectory
10
- from matmalib._pucker_reference import CARPPY_PUCKERS, CREMER_POPLE_PUCKERS
11
- from test_puckering import ring_coordinates
12
-
13
-
14
- @pytest.fixture(autouse=True)
15
- def close_figures():
16
- yield
17
- plt.close("all")
18
-
19
-
20
- def trajectory(*, degrees=True, phases=(30, 180, 330)):
21
- frames = [ring_coordinates(q2=.4, q3=q3, phi=phi)
22
- for q3, phi in zip((.4, 0, -.4), phases)]
23
- return cremer_pople_trajectory(frames, [range(6)], degrees=degrees)
24
-
25
-
26
- @pytest.mark.parametrize("degrees", [True, False])
27
- def test_mollweide_coordinates_units_orientation_and_export(degrees, tmp_path):
28
- data = trajectory(degrees=degrees)
29
- original = data.data.copy()
30
- plot = Plot()
31
- fig, ax = plot.cremer_pople_sphere(data, pucker_labels=False)
32
- assert (fig, ax) == (plot.fig, plot.ax)
33
- assert ax.name == "mollweide"
34
- assert len(fig.axes) == 2 # Sphere and time colorbar.
35
- points = ax.collections[1].get_offsets()
36
- np.testing.assert_allclose(points[:, 0], [5 * np.pi / 6, 0, -5 * np.pi / 6], atol=1e-12)
37
- np.testing.assert_allclose(points[:, 1], [np.pi / 4, 0, -np.pi / 4], atol=1e-12)
38
- assert len(ax.collections[0].get_segments()) == 2
39
- assert plot.colorbar.ax.get_xlabel() == "Time (fs)"
40
- np.testing.assert_array_equal(data.data, original)
41
- assert ax.xaxis.get_major_formatter()(np.pi / 2) == "90°"
42
- assert ax.yaxis.get_major_formatter()(np.pi / 6) == "60°"
43
- assert not ax.texts
44
- fig.savefig(tmp_path / "mollweide.svg", bbox_inches="tight")
45
-
46
-
47
- def test_seam_break_preserves_samples_on_both_sides():
48
- data = trajectory(phases=(350, 10, 20))
49
- _, ax = Plot().cremer_pople_sphere(data, pucker_labels=False)
50
- points = ax.collections[1].get_offsets()
51
- np.testing.assert_allclose(points[:, 0], np.radians([-170, 170, 160]), atol=1e-12)
52
- segments = ax.collections[0].get_segments()
53
- assert len(segments) == 1
54
- np.testing.assert_allclose(segments[0], points[1:])
55
- np.testing.assert_allclose(ax.collections[0].get_array(), [1.5])
56
- np.testing.assert_allclose(ax.collections[1].get_array(), [0, 1, 2])
57
-
58
-
59
- def test_chairs_are_retained_and_planar_frames_break_the_path():
60
- frames = [ring_coordinates(q3=.5), ring_coordinates(), ring_coordinates(q3=-.5)]
61
- data = cremer_pople_trajectory(frames, [range(6)])
62
- _, ax = Plot().cremer_pople_sphere(data, pucker_labels=False)
63
- assert not ax.collections[0].get_segments()
64
- np.testing.assert_allclose(ax.collections[1].get_offsets(), [[0, np.pi / 2], [0, -np.pi / 2]])
65
- np.testing.assert_allclose(ax.collections[1].get_array(), [0, 2])
66
- ax.figure.canvas.draw()
67
-
68
-
69
- def test_mixed_ring_selection_single_frame_and_overlay_configuration():
70
- frame = np.vstack((ring_coordinates(5, q2=.3), ring_coordinates(q2=.3, phi=90) + 10))
71
- data = cremer_pople_trajectory([frame], [range(5), range(5, 11)])
72
- plot = Plot()
73
- plot.set_config({"headers": ["First", "Second"], "title": "Ring 1"})
74
- fig, ax = plot.cremer_pople_sphere([data, data], monomer=1, alpha=[.5, .7])
75
- assert ax.get_title() == "Ring 1"
76
- first, second = ax.collections[1], ax.collections[3]
77
- assert [points.get_label() for points in (first, second)] == ["First", "Second"]
78
- assert [points.get_alpha() for points in (first, second)] == [.5, .7]
79
- assert first.get_paths()[0].vertices.shape != second.get_paths()[0].vertices.shape
80
- assert [text.get_text() for text in ax.get_legend().texts] == ["First", "Second"]
81
- np.testing.assert_allclose(first.get_offsets()[:, 0], [np.pi / 2])
82
- np.testing.assert_allclose(plot.colorbar.get_ticks(), [0])
83
- fig.canvas.draw()
84
- with pytest.raises(ValueError, match="six-membered"):
85
- plot.cremer_pople_sphere(data, headers=[None])
86
-
87
-
88
- def test_all_reference_labels_and_seam_duplicates_render(tmp_path):
89
- fig, ax = Plot().cremer_pople_sphere(trajectory(), title="Puckering", alpha=.6)
90
- labels = {annotation.get_text(): annotation for annotation in ax.texts}
91
- assert len(labels) == 38
92
- assert len(ax.texts) == 41 # Three phi=0 references appear at both edges.
93
- assert labels[r"$^{4}\mathrm{C}_{1}$"].xy == (0, np.pi / 2)
94
- assert labels[r"$^{1}\mathrm{C}_{4}$"].xy == (0, -np.pi / 2)
95
- assert labels[r"$^{O}\mathrm{S}_{2}$"].xy == pytest.approx((-5 * np.pi / 6, 0))
96
- assert r"$^{O}\mathrm{E}_{}$" in labels
97
- assert r"$^{O}\mathrm{H}_{1}$" in labels
98
- assert r"$^{}\mathrm{B}_{3,O}$" in labels
99
- assert ax.get_title() == "Puckering"
100
- fig.canvas.draw()
101
- renderer = fig.canvas.get_renderer()
102
- for annotation in ax.texts:
103
- if annotation.xy[1] == 0:
104
- assert not any(annotation.get_window_extent(renderer).overlaps(tick.get_window_extent(renderer))
105
- for tick in ax.get_xticklabels())
106
- fig.savefig(tmp_path / "labelled-mollweide.svg", bbox_inches="tight")
107
-
108
-
109
- def test_ideal_cp_references_agree_with_all_38_independent_benchmark_structures():
110
- source = Path(__file__).parent / "data" / "glucose_puckers.xyz"
111
- labels = [line.split("conf_")[1].split("/")[0]
112
- for line in source.read_text().splitlines() if line.startswith("CarP/")]
113
- assert set(CREMER_POPLE_PUCKERS) == set(CARPPY_PUCKERS) == set(labels)
114
- for label, state in zip(labels, Space.from_xyz(source).states):
115
- measured = cremer_pople(state.xyz[[0, 10, 9, 7, 6, 8]])
116
- theta, phi = CREMER_POPLE_PUCKERS[label]
117
- assert measured["theta"] == pytest.approx(theta, abs=3), label
118
- if "C" not in label: # Phase is arbitrary at a pole.
119
- assert abs((measured["phi"] - phi + 180) % 360 - 180) < 5, label
120
-
121
-
122
- @pytest.mark.parametrize("kwargs,match", [
123
- ({"projection": "polar"}, "projection"),
124
- ({"monomer": -1}, "monomer"),
125
- ({"monomer": True}, "monomer"),
126
- ({"monomer": 0.5}, "monomer"),
127
- ({"monomer": 1}, "six-membered"),
128
- ({"headers": []}, "one header"),
129
- ({"alpha": []}, "one header"),
130
- ({"average": 2}, "do not support"),
131
- ({"overlap": True}, "do not support"),
132
- ({"calc_qa": True}, "do not support"),
133
- ])
134
- def test_invalid_plot_options(kwargs, match):
135
- with pytest.raises(ValueError, match=match):
136
- Plot().trajectory(trajectory(), **{"projection": "mollweide", **kwargs})
137
-
138
-
139
- def test_missing_metadata_units_data_and_fixed_limits():
140
- with pytest.raises(ValueError, match="at least one"):
141
- Plot().cremer_pople_sphere([])
142
- with pytest.raises(ValueError, match="six-membered"):
143
- Plot().cremer_pople_sphere(Data(data=np.ones((3, 2))))
144
- data = trajectory()
145
- data.angle_unit = "unknown"
146
- with pytest.raises(ValueError, match="angle_unit"):
147
- Plot().cremer_pople_sphere(data)
148
- data.angle_unit = "degrees"
149
- data.data[0, 2] = 181
150
- with pytest.raises(ValueError, match="theta must lie"):
151
- Plot().cremer_pople_sphere(data)
152
- data.data = data.data[:0]
153
- with pytest.raises(ValueError, match="nonempty 2D"):
154
- Plot().cremer_pople_sphere(data)
155
- plot = Plot()
156
- plot.set_config({"xrange": [0, 360]})
157
- with pytest.raises(ValueError, match="fixed limits"):
158
- plot.cremer_pople_sphere(trajectory())
159
-
160
-
161
- def test_gradient_uses_recorded_times_and_selected_colormap():
162
- data = trajectory()
163
- data.data[:, 0] = [10, 13, 40]
164
- data.time_unit = "ps"
165
- plot = Plot()
166
- fig, ax = plot.cremer_pople_sphere(data, cmap="plasma", pucker_labels=False)
167
- line, points = ax.collections
168
- np.testing.assert_allclose(points.get_array(), [10, 13, 40])
169
- np.testing.assert_allclose(line.get_array(), [11.5, 26.5])
170
- assert points.norm is line.norm is plot.colorbar.norm
171
- np.testing.assert_allclose(points.norm(points.get_array()), [0, .1, 1])
172
- assert points.cmap.name == line.cmap.name == plot.colorbar.cmap.name == "plasma"
173
- assert plot.colorbar.ax.get_xlabel() == "Time (ps)"
174
- fig.canvas.draw()
175
- np.testing.assert_allclose(points.get_facecolors(), points.to_rgba([10, 13, 40], alpha=.8))
176
- np.testing.assert_allclose(line.get_colors(), line.to_rgba([11.5, 26.5], alpha=.8))
177
-
178
-
179
- def test_overlaid_trajectories_share_one_time_scale():
180
- first, second = trajectory(), trajectory()
181
- second.data[:, 0] += 10
182
- plot = Plot()
183
- _, ax = plot.cremer_pople_sphere([first, second], pucker_labels=False)
184
- assert len(ax.figure.axes) == 2
185
- assert all(collection.norm is plot.colorbar.norm for collection in ax.collections)
186
- assert (plot.colorbar.norm.vmin, plot.colorbar.norm.vmax) == (0, 12)
187
- np.testing.assert_allclose(ax.collections[3].get_array(), [10, 11, 12])
188
- second.time_unit = "ns"
189
- with pytest.raises(ValueError, match="same time_unit"):
190
- plot.cremer_pople_sphere([first, second])
191
-
192
-
193
- def test_single_time_and_named_time_column():
194
- data = trajectory()
195
- data.data[:, 0] = 100
196
- order = [2, 0, 3, 1, 4, 5]
197
- data.columns = tuple(data.columns[i] for i in order)
198
- data.data = data.data[:, order]
199
- plot = Plot()
200
- fig, ax = plot.cremer_pople_sphere(data, cmap=matplotlib.colormaps["cividis"], pucker_labels=False)
201
- np.testing.assert_allclose(ax.collections[1].get_array(), [100, 100, 100])
202
- np.testing.assert_allclose(plot.colorbar.get_ticks(), [100])
203
- fig.canvas.draw()
204
- colors = ax.collections[1].get_facecolors()
205
- np.testing.assert_allclose(colors, np.tile(colors[0], (3, 1)))
206
-
207
-
208
- @pytest.mark.parametrize("times", [[0, np.nan, 2], [0, 1, np.inf]])
209
- def test_invalid_times(times):
210
- data = trajectory()
211
- data.data[:, 0] = times
212
- with pytest.raises(ValueError, match="times must be finite"):
213
- Plot().cremer_pople_sphere(data)
214
-
215
-
216
- def test_time_column_required_and_shortcut_preserved():
217
- data = trajectory()
218
- plot = Plot()
219
- fig, ax = plot.trajectory(data, projection="mollweide", cmap="plasma", pucker_labels=False)
220
- assert (fig, ax) == (plot.fig, plot.ax)
221
- assert plot.colorbar.cmap.name == "plasma"
222
- np.testing.assert_allclose(ax.collections[1].get_array(), data.data[:, 0])
223
- data.columns = ("step", *data.columns[1:])
224
- with pytest.raises(ValueError, match="named time column"):
225
- Plot().cremer_pople_sphere(data)
226
-
227
-
228
- @pytest.mark.parametrize("projection", [None, "rectilinear"])
229
- def test_existing_time_series_and_histogram(projection):
230
- data = trajectory()
231
- plot = Plot()
232
- plot.trajectory(data, col=2, var_name="theta", headers=["Run"], projection=projection)
233
- assert len(plot.fig.axes) == 2
234
- assert plot.ax[0].name == "rectilinear"
235
- np.testing.assert_allclose(plot.ax[0].lines[0].get_ydata(), [45, 90, 135])
236
- np.testing.assert_allclose(plot.ax[0].lines[0].get_xdata(), [0, .001, .002])
237
- assert plot.ax[0].get_ylabel() == "theta"
238
- plot.fig.canvas.draw()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes