Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

more tests, remove old style files #8

Merged
merged 8 commits into from
Apr 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ repos:
rev: v0.23.0
hooks:
- id: toml-sort-fix
- repo: https://github.com/bwhmather/ssort
rev: v0.11.6
hooks:
- id: ssort
exclude: __init__.py
# - repo: https://github.com/bwhmather/ssort
# rev: v0.11.6
# hooks:
# - id: ssort
# exclude: __init__.py
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ Issues = "https://github.com/cgahr/latexplotlib/issues"
[tool.black]
line_length = 88

[tool.coverage.report]
exclude_lines = ["if TYPE_CHECKING:"]

[tool.coverage.run]
source = ["src"]

Expand Down
19 changes: 5 additions & 14 deletions src/latexplotlib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from ._cleanup import purge_old_styles
from ._config import size
from ._latexplotlib import (
convert_inches_to_pt,
convert_pt_to_inches,
figsize,
size,
subplots,
)
from ._styles import make_styles_available
from ._version import __version__

__all__ = [
Expand All @@ -16,16 +18,5 @@
"__version__",
]


def _make_styles_available() -> None:
from pathlib import Path

import matplotlib.pyplot as plt

lpl_styles = plt.style.core.read_style_directory(Path(__path__[0]) / "styles")

plt.style.core.update_nested_dict(plt.style.library, lpl_styles)
plt.style.core.available[:] = sorted(plt.style.library.keys())


_make_styles_available()
purge_old_styles(__path__)
make_styles_available(__path__)
41 changes: 41 additions & 0 deletions src/latexplotlib/_cleanup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import filecmp
from pathlib import Path
from typing import List

from matplotlib import get_configdir

from ._config import _PURGED_OLD, config

STYLELIB = "stylelib"
STYLES = {
"latex9pt-minimal.mplstyle",
"latex9pt.mplstyle",
"latex10pt-minimal.mplstyle",
"latex10pt.mplstyle",
"latex11pt-minimal.mplstyle",
"latex11pt.mplstyle",
"latex12pt-minimal.mplstyle",
"latex12pt.mplstyle",
}
STYLES_FOLDER = "styles"


def purge_old_styles(path: List[str]) -> None:
if config[_PURGED_OLD]:
return

old_styledir = Path(get_configdir()) / STYLELIB

if not old_styledir.is_dir():
config[_PURGED_OLD] = True
return

old_styles = {s.name for s in old_styledir.glob("latex*.mplstyle")}

for style in STYLES & old_styles:
if filecmp.cmp(
Path(path[0]) / STYLES_FOLDER / style, old_styledir / style, shallow=False
):
(old_styledir / style).unlink()

config[_PURGED_OLD] = True
125 changes: 125 additions & 0 deletions src/latexplotlib/_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import json
from contextlib import contextmanager
from pathlib import Path
from typing import Dict, Iterator, Mapping, Tuple, Union

from appdirs import user_config_dir

GOLDEN_RATIO: float = (5**0.5 + 1) / 2
NAME: str = "latexplotlib"
_PURGED_OLD = "_purged_old_styles"

CONFIGFILE: str = "config.ini"
CONFIGDIR: Path = Path(user_config_dir(NAME))
CONFIGPATH: Path = CONFIGDIR / CONFIGFILE
DEFAULT_CONFIG: Dict[str, int] = {"width": 630, "height": 412, _PURGED_OLD: False}


ConfigData = Union[int, bool]


class Config:
def __init__(self, path: Path) -> None:
self.path = path

if not self.path.exists():
self.reset()

self._config = self._open(path)

def _open(self, path: Path) -> Dict[str, ConfigData]:
with path.open(encoding="utf-8") as fh:
config: Dict[str, ConfigData] = json.load(fh)
return config

def _write(self, cfg: Mapping[str, ConfigData]) -> None:
if not self.path.parent.exists():
self.path.parent.mkdir(parents=True)

with self.path.open("w", encoding="utf-8") as fh:
json.dump(cfg, fh, indent=4)

def reset(self) -> None:
if self.path.exists():
self.path.unlink()

self._write(DEFAULT_CONFIG)

def reload(self) -> None:
self._config = self._open(self.path)

def __getitem__(self, name: str) -> ConfigData:
return self._config.get(name, DEFAULT_CONFIG[name])

def __setitem__(self, name: str, value: ConfigData) -> None:
self._config[name] = value
self._write(self._config)


config = Config(CONFIGPATH)


class Size:
_width: int
_height: int

def __init__(self) -> None:
self._width, self._height = config["width"], config["height"]

def reload(self) -> None:
config.reload()
self._width, self._height = config["width"], config["height"]

def get(self) -> Tuple[int, int]:
"""Returns the current size of the figure in pts.

Returns
-------
int, int
(width, height) of the page in pts.
"""
return self._width, self._height

def set(self, width: int, height: int) -> None: # noqa: A003
"""Sets the size of the latex page in pts.

You can find the size of the latex page with the following commands:

\\the\\textwidth
\\the\\textheight

Parameters
----------
width : int
The width of the latex page in pts.
height : int
The height of the latex page in pts.
"""
config["width"], config["height"] = width, height
self._width, self._height = width, height

@contextmanager
def context(self, width: int, height: int) -> Iterator[None]:
"""This context manager temporarily sets the size of the figure in pts.

Parameters
----------
width : int
The width of the latex page in pts.
height : int
The height of the latex page in pts.
"""
_width, _height = self._width, self._height
self._width, self._height = width, height
yield

self._width, self._height = _width, _height

def __repr__(self) -> str:
return repr(f"{self._width}pt, {self._height}pt")

def __str__(self) -> str:
return str(f"{self._width}pt, {self._height}pt")


size = Size()
Loading