qforge-sdk 0.1.0__py3-none-any.whl

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.
qforge/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """QForge: generate crystal structures with target properties, from Python.
2
+
3
+ from qforge import QForge
4
+
5
+ qf = QForge() # QFORGE_API_KEY and QFORGE_URL from the environment
6
+ job = qf.generate({"band_gap": 2.5}, elements=["Fe", "O"], n_structures=4)
7
+ for m in job.wait().materials:
8
+ print(m.formula, m.e_above_hull)
9
+ """
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ from .client import QForge # noqa: E402
14
+ from .errors import ( # noqa: E402
15
+ AuthenticationError,
16
+ Conflict,
17
+ InsufficientCredits,
18
+ JobFailed,
19
+ NotFound,
20
+ PermissionDenied,
21
+ QForgeError,
22
+ RateLimited,
23
+ ServerError,
24
+ Timeout,
25
+ )
26
+ from .models import Campaign, DftCheck, Job, Material # noqa: E402
27
+
28
+ __all__ = [
29
+ "QForge",
30
+ "Job",
31
+ "Material",
32
+ "Campaign",
33
+ "DftCheck",
34
+ "QForgeError",
35
+ "AuthenticationError",
36
+ "PermissionDenied",
37
+ "InsufficientCredits",
38
+ "NotFound",
39
+ "Conflict",
40
+ "RateLimited",
41
+ "ServerError",
42
+ "JobFailed",
43
+ "Timeout",
44
+ "__version__",
45
+ ]
qforge/_http.py ADDED
@@ -0,0 +1,123 @@
1
+ """HTTP layer: auth, retries with backoff, idempotency keys, error mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ import time
7
+ import uuid
8
+ from collections.abc import Iterator
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ from . import __version__
14
+ from .errors import QForgeError, error_for
15
+
16
+ RETRY_STATUSES = {429, 502, 503, 504}
17
+
18
+
19
+ class Http:
20
+ def __init__(
21
+ self,
22
+ base_url: str,
23
+ api_key: str,
24
+ *,
25
+ timeout: float = 30.0,
26
+ max_retries: int = 3,
27
+ transport: httpx.BaseTransport | None = None,
28
+ ) -> None:
29
+ self.max_retries = max_retries
30
+ self._client = httpx.Client(
31
+ base_url=base_url.rstrip("/") + "/api",
32
+ timeout=timeout,
33
+ transport=transport,
34
+ headers={
35
+ "Authorization": f"Bearer {api_key}",
36
+ "User-Agent": f"qforge-sdk-python/{__version__}",
37
+ "Accept": "application/json",
38
+ },
39
+ )
40
+
41
+ def close(self) -> None:
42
+ self._client.close()
43
+
44
+ def request(
45
+ self,
46
+ method: str,
47
+ path: str,
48
+ *,
49
+ params: dict[str, Any] | None = None,
50
+ json: Any = None,
51
+ idempotent: bool = False,
52
+ ) -> Any:
53
+ """One API call. POSTs that spend credits send an Idempotency-Key, kept
54
+ across retries, so a retry never charges twice."""
55
+ headers: dict[str, str] = {"X-Request-ID": f"py-{uuid.uuid4().hex[:12]}"}
56
+ if idempotent:
57
+ headers["Idempotency-Key"] = uuid.uuid4().hex
58
+ params = {k: v for k, v in (params or {}).items() if v is not None}
59
+ attempt = 0
60
+ while True:
61
+ try:
62
+ res = self._client.request(method, path, params=params, json=json, headers=headers)
63
+ except httpx.TransportError as exc:
64
+ if attempt >= self.max_retries:
65
+ raise QForgeError(f"Couldn't reach QForge: {exc}") from exc
66
+ attempt += 1
67
+ time.sleep(_backoff(attempt))
68
+ continue
69
+ if res.status_code in RETRY_STATUSES and attempt < self.max_retries:
70
+ attempt += 1
71
+ time.sleep(_retry_after(res) or _backoff(attempt))
72
+ continue
73
+ return _result(res)
74
+
75
+ def get(self, path: str, **params: Any) -> Any:
76
+ return self.request("GET", path, params=params)
77
+
78
+ def pages(
79
+ self, path: str, params: dict[str, Any] | None = None, page_size: int = 50
80
+ ) -> Iterator[dict[str, Any]]:
81
+ """Every item of a paginated list, fetching pages as needed."""
82
+ page = 1
83
+ while True:
84
+ data = self.get(path, **(params or {}), page=page, page_size=page_size)
85
+ items = data.get("results", []) if isinstance(data, dict) else data
86
+ yield from items
87
+ if not isinstance(data, dict) or not data.get("next") or not items:
88
+ return
89
+ page += 1
90
+
91
+
92
+ def _backoff(attempt: int) -> float:
93
+ return min(30.0, 0.5 * 2.0**attempt) * (0.75 + random.random() / 2)
94
+
95
+
96
+ def _retry_after(res: httpx.Response) -> float | None:
97
+ value = res.headers.get("Retry-After")
98
+ try:
99
+ return min(60.0, float(str(value))) if value else None
100
+ except ValueError:
101
+ return None
102
+
103
+
104
+ def _result(res: httpx.Response) -> Any:
105
+ if res.status_code == 204 or not res.content:
106
+ if res.is_success:
107
+ return None
108
+ try:
109
+ body = res.json()
110
+ except ValueError:
111
+ body = res.text
112
+ if res.is_success:
113
+ return body
114
+ detail = body.get("detail") if isinstance(body, dict) else None
115
+ code = body.get("code") if isinstance(body, dict) else None
116
+ message = detail if isinstance(detail, str) else f"HTTP {res.status_code}"
117
+ raise error_for(res.status_code)(
118
+ message,
119
+ status=res.status_code,
120
+ code=code,
121
+ request_id=res.headers.get("X-Request-ID"),
122
+ body=body,
123
+ )
qforge/client.py ADDED
@@ -0,0 +1,195 @@
1
+ """The QForge client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterator
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from ._http import Http
12
+ from .errors import InsufficientCredits, QForgeError
13
+ from .models import Campaign, DftCheck, Job, Material
14
+
15
+
16
+ class QForge:
17
+ """A client for one QForge server.
18
+
19
+ >>> qf = QForge(base_url="https://your-qforge", api_key="qfk_…")
20
+ >>> job = qf.generate({"band_gap": 2.5, "elements": ["Fe", "O"]}, n_structures=4)
21
+ >>> for m in job.wait().materials:
22
+ ... print(m.formula, m.e_above_hull)
23
+
24
+ ``api_key`` defaults to ``$QFORGE_API_KEY`` and ``base_url`` to
25
+ ``$QFORGE_URL`` (the address you open QForge at).
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ api_key: str | None = None,
31
+ base_url: str | None = None,
32
+ *,
33
+ timeout: float = 30.0,
34
+ max_retries: int = 3,
35
+ transport: httpx.BaseTransport | None = None,
36
+ ) -> None:
37
+ key = api_key or os.environ.get("QFORGE_API_KEY")
38
+ url = base_url or os.environ.get("QFORGE_URL")
39
+ if not key:
40
+ raise QForgeError(
41
+ "No API key: pass api_key= or set QFORGE_API_KEY (create one under Developers → API keys)"
42
+ )
43
+ if not url:
44
+ raise QForgeError("No server: pass base_url= or set QFORGE_URL (the address you open QForge at)")
45
+ self._http = Http(url, key, timeout=timeout, max_retries=max_retries, transport=transport)
46
+
47
+ def __enter__(self) -> QForge:
48
+ return self
49
+
50
+ def __exit__(self, *exc: object) -> None:
51
+ self.close()
52
+
53
+ def close(self) -> None:
54
+ self._http.close()
55
+
56
+ # ── Runs ────────────────────────────────────────────────────────────────
57
+
58
+ def generate(
59
+ self,
60
+ properties: dict[str, Any] | None = None,
61
+ *,
62
+ elements: list[str] | None = None,
63
+ n_structures: int = 3,
64
+ model: str = "auto",
65
+ exclude_formulas: list[str] | None = None,
66
+ check_novelty: bool = False,
67
+ require_novel: bool = False,
68
+ ) -> Job:
69
+ """Start a run. ``properties`` are keyed by property id (see Developers →
70
+ Properties); ``elements`` is a shortcut for ``properties["elements"]``.
71
+ ``model`` is ``auto``, a model id (``frost``) or a pinned version
72
+ (``frost@1``)."""
73
+ props = dict(properties or {})
74
+ if elements is not None:
75
+ props["elements"] = list(elements)
76
+ if not props:
77
+ raise ValueError("Give at least one property or elements")
78
+ body: dict[str, Any] = {"properties": props, "n_structures": n_structures, "adapter": model}
79
+ if exclude_formulas:
80
+ body["exclude_formulas"] = list(exclude_formulas)
81
+ if check_novelty:
82
+ body["check_novelty"] = True
83
+ if require_novel:
84
+ body["require_novel"] = True
85
+ return Job(self, self._http.request("POST", "/lab/jobs/", json=body, idempotent=True))
86
+
87
+ def job(self, job_id: str) -> Job:
88
+ return Job(self, self._http.get(f"/lab/jobs/{job_id}/"))
89
+
90
+ def jobs(self, status: str | None = None, search: str | None = None) -> Iterator[Job]:
91
+ """Your runs, newest first (``status``: queued, running, done, failed)."""
92
+ for raw in self._http.pages("/lab/jobs/", {"status": status, "search": search}):
93
+ yield Job(self, raw)
94
+
95
+ # ── Campaigns ───────────────────────────────────────────────────────────
96
+
97
+ def campaign(
98
+ self,
99
+ name: str,
100
+ properties: dict[str, Any],
101
+ *,
102
+ goal: dict[str, Any] | None = None,
103
+ max_credits: float = 30,
104
+ max_batches: int = 10,
105
+ model: str = "auto",
106
+ n_structures: int = 4,
107
+ exclude_formulas: list[str] | None = None,
108
+ ) -> Campaign:
109
+ """Start a campaign. ``goal`` defaults to 5 novel, stable materials:
110
+ ``{"count": 5, "novel": True, "stable": True}``."""
111
+ body: dict[str, Any] = {
112
+ "name": name,
113
+ "properties": dict(properties),
114
+ "adapter": model,
115
+ "n_structures": n_structures,
116
+ "goal": goal or {"count": 5, "novel": True, "stable": True},
117
+ "max_credits": max_credits,
118
+ "max_batches": max_batches,
119
+ }
120
+ if exclude_formulas:
121
+ body["exclude_formulas"] = list(exclude_formulas)
122
+ return Campaign(self, self._http.request("POST", "/lab/campaigns/", json=body, idempotent=True))
123
+
124
+ def get_campaign(self, campaign_id: str) -> Campaign:
125
+ return Campaign(self, self._http.get(f"/lab/campaigns/{campaign_id}/"))
126
+
127
+ def campaigns(self) -> Iterator[Campaign]:
128
+ for raw in self._http.pages("/lab/campaigns/"):
129
+ yield Campaign(self, raw)
130
+
131
+ # ── Library ─────────────────────────────────────────────────────────────
132
+
133
+ def library(
134
+ self,
135
+ search: str | None = None,
136
+ favourite: bool | None = None,
137
+ public: bool | None = None,
138
+ ) -> Iterator[Material]:
139
+ """Every material in your Library (one per material), paged for you."""
140
+ params = {
141
+ "search": search,
142
+ "favourite": _flag(favourite),
143
+ "public": _flag(public),
144
+ }
145
+ for raw in self._http.pages("/library/materials/", params):
146
+ yield Material(raw.get("material") or {"formula": raw.get("formula")}, library_id=raw.get("id"))
147
+
148
+ # ── DFT ─────────────────────────────────────────────────────────────────
149
+
150
+ def dft(self, material: Material | str) -> DftCheck:
151
+ """The DFT check of a Library material: its price, progress or result."""
152
+ library_id = _library_id(material)
153
+ return DftCheck(self, library_id, self._http.get(f"/lab/materials/{library_id}/dft/"))
154
+
155
+ def verify_dft(self, material: Material | str, max_credits: float | None = None) -> DftCheck:
156
+ """Start a DFT check at the quoted price. With ``max_credits``, refuses
157
+ (raises :class:`InsufficientCredits`) if the quote is higher."""
158
+ check = self.dft(material)
159
+ if check.status in ("queued", "running", "done"):
160
+ return check
161
+ price = check.quote
162
+ if price is None:
163
+ raise QForgeError("The server didn't quote a price for this check")
164
+ if max_credits is not None and price > max_credits:
165
+ raise InsufficientCredits(
166
+ f"A DFT check costs {price} credits, more than max_credits={max_credits}"
167
+ )
168
+ raw = self._http.request(
169
+ "POST", f"/lab/materials/{check.library_id}/dft/", json={"accept_credits": price}, idempotent=True
170
+ )
171
+ return DftCheck(self, check.library_id, raw)
172
+
173
+ # ── Account and catalogue ───────────────────────────────────────────────
174
+
175
+ def credits(self) -> dict[str, Any]:
176
+ """Balance, prices per structure and usage limits."""
177
+ data: dict[str, Any] = self._http.get("/credits/")
178
+ return data
179
+
180
+ def models(self) -> list[dict[str, Any]]:
181
+ """Generation models, their versions and the inputs each accepts."""
182
+ data = self._http.get("/lab/models/")
183
+ return list(data.get("models", [])) if isinstance(data, dict) else []
184
+
185
+
186
+ def _flag(value: bool | None) -> str | None:
187
+ return None if value is None else ("true" if value else "false")
188
+
189
+
190
+ def _library_id(material: Material | str) -> str:
191
+ if isinstance(material, str):
192
+ return material
193
+ if not material.library_id:
194
+ raise ValueError(f"{material.formula} isn't in your Library yet (no library_id)")
195
+ return material.library_id
qforge/errors.py ADDED
@@ -0,0 +1,77 @@
1
+ """Errors raised by the client. Every API error is a :class:`QForgeError`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class QForgeError(Exception):
9
+ """An error from the QForge API (or a run that ended badly).
10
+
11
+ ``status`` is the HTTP status, ``code`` the API's error code when it sent
12
+ one (e.g. ``"insufficient_credits"``), and ``request_id`` the
13
+ ``X-Request-ID`` to quote to support.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ message: str,
19
+ *,
20
+ status: int | None = None,
21
+ code: str | None = None,
22
+ request_id: str | None = None,
23
+ body: Any = None,
24
+ ) -> None:
25
+ self.status = status
26
+ self.code = code
27
+ self.request_id = request_id
28
+ self.body = body
29
+ ref = f" (request {request_id})" if request_id else ""
30
+ super().__init__(f"{message}{ref}")
31
+
32
+
33
+ class AuthenticationError(QForgeError):
34
+ """401: the API key is missing, wrong or expired."""
35
+
36
+
37
+ class PermissionDenied(QForgeError):
38
+ """403: the key doesn't have the scope for this (code ``key_scope``)."""
39
+
40
+
41
+ class InsufficientCredits(QForgeError):
42
+ """402: not enough credits, or the key's monthly cap is reached."""
43
+
44
+
45
+ class NotFound(QForgeError):
46
+ """404: it doesn't exist, or isn't yours."""
47
+
48
+
49
+ class Conflict(QForgeError):
50
+ """409: e.g. a DFT price changed since it was quoted."""
51
+
52
+
53
+ class RateLimited(QForgeError):
54
+ """429 after the client's own retries ran out."""
55
+
56
+
57
+ class ServerError(QForgeError):
58
+ """5xx after the client's own retries ran out."""
59
+
60
+
61
+ class JobFailed(QForgeError):
62
+ """A run, campaign or DFT check ended without succeeding."""
63
+
64
+
65
+ class Timeout(QForgeError):
66
+ """``wait()`` gave up before it finished."""
67
+
68
+
69
+ def error_for(status: int) -> type[QForgeError]:
70
+ return {
71
+ 401: AuthenticationError,
72
+ 402: InsufficientCredits,
73
+ 403: PermissionDenied,
74
+ 404: NotFound,
75
+ 409: Conflict,
76
+ 429: RateLimited,
77
+ }.get(status, ServerError if status >= 500 else QForgeError)
qforge/models.py ADDED
@@ -0,0 +1,302 @@
1
+ """Objects returned by the client: materials, runs (jobs), campaigns, DFT checks.
2
+
3
+ Each keeps the API's full JSON in ``.raw`` for anything not wrapped here.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import io
9
+ import time
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Any, Callable
12
+
13
+ from .errors import JobFailed, Timeout
14
+
15
+ if TYPE_CHECKING: # pragma: no cover
16
+ from .client import QForge
17
+
18
+ ACTIVE = {"queued", "pending", "running"}
19
+
20
+
21
+ def _wait(
22
+ refresh: Callable[[], str],
23
+ *,
24
+ active: set[str],
25
+ timeout: float | None,
26
+ poll: float,
27
+ what: str,
28
+ ) -> str:
29
+ """Call ``refresh`` until the status leaves ``active``; return the status."""
30
+ start = time.monotonic()
31
+ status = refresh()
32
+ while status in active:
33
+ if timeout is not None and time.monotonic() - start >= timeout:
34
+ raise Timeout(f"{what} still {status} after {timeout:.0f} s")
35
+ time.sleep(poll)
36
+ status = refresh()
37
+ return status
38
+
39
+
40
+ class Material:
41
+ """One generated structure."""
42
+
43
+ def __init__(self, raw: dict[str, Any], library_id: str | None = None) -> None:
44
+ self.raw = raw
45
+ self.library_id: str | None = library_id or raw.get("library_id")
46
+
47
+ def __repr__(self) -> str:
48
+ return f"Material({self.formula!r}, space_group={self.space_group!r}, novelty={self.novelty!r})"
49
+
50
+ @property
51
+ def formula(self) -> str:
52
+ return str(self.raw.get("formula", ""))
53
+
54
+ @property
55
+ def space_group(self) -> int | None:
56
+ sg = self.raw.get("space_group")
57
+ try:
58
+ return int(sg) if sg is not None else None
59
+ except (TypeError, ValueError):
60
+ return None
61
+
62
+ @property
63
+ def cif(self) -> str:
64
+ return str(self.raw.get("cif") or "")
65
+
66
+ @property
67
+ def relaxed_cif(self) -> str | None:
68
+ return self.raw.get("relaxed_cif")
69
+
70
+ @property
71
+ def predicted(self) -> dict[str, Any]:
72
+ """Model predictions (e.g. ``e_above_hull_mattersim``)."""
73
+ return dict(self.raw.get("predicted_properties") or {})
74
+
75
+ @property
76
+ def e_above_hull(self) -> float | None:
77
+ """Estimated energy above the convex hull, eV/atom (lower is more stable)."""
78
+ for key in ("e_above_hull_mattersim", "e_above_hull", "energy_above_hull"):
79
+ value = self.predicted.get(key)
80
+ if isinstance(value, (int, float)):
81
+ return float(value)
82
+ return None
83
+
84
+ @property
85
+ def novelty(self) -> str | None:
86
+ """``known``, ``near_known``, ``new_structure``, ``new_composition`` or
87
+ ``new_chemical_system``; None when novelty wasn't checked."""
88
+ return self.raw.get("novelty_category")
89
+
90
+ @property
91
+ def model(self) -> str | None:
92
+ """The model and version that made it, e.g. ``frost@1``."""
93
+ return self.raw.get("model_version") or self.raw.get("adapter_used")
94
+
95
+ def to_pymatgen(self, relaxed: bool = False) -> Any:
96
+ """The structure as a ``pymatgen.core.Structure`` (``pip install "qforge-sdk[pymatgen]"``)."""
97
+ try:
98
+ from pymatgen.core import Structure
99
+ except ImportError as exc: # pragma: no cover
100
+ raise ImportError('to_pymatgen() needs pymatgen: pip install "qforge-sdk[pymatgen]"') from exc
101
+ return Structure.from_str(self._cif(relaxed), fmt="cif")
102
+
103
+ def to_ase(self, relaxed: bool = False) -> Any:
104
+ """The structure as an ``ase.Atoms`` (``pip install "qforge-sdk[ase]"``)."""
105
+ try:
106
+ from ase.io import read
107
+ except ImportError as exc: # pragma: no cover
108
+ raise ImportError('to_ase() needs ase: pip install "qforge-sdk[ase]"') from exc
109
+ return read(io.StringIO(self._cif(relaxed)), format="cif")
110
+
111
+ def save(self, path: str | Path | None = None, relaxed: bool = False) -> Path:
112
+ """Write the CIF; defaults to ``<formula>.cif`` in the current folder."""
113
+ target = Path(path) if path is not None else Path(f"{self.formula or 'structure'}.cif")
114
+ target.write_text(self._cif(relaxed))
115
+ return target
116
+
117
+ def _cif(self, relaxed: bool) -> str:
118
+ cif = (self.relaxed_cif if relaxed else None) or self.cif
119
+ if not cif:
120
+ raise ValueError(f"{self.formula} has no structure")
121
+ return cif
122
+
123
+
124
+ class Job:
125
+ """A run: it queues, generates on a GPU, then ends done, failed or cancelled."""
126
+
127
+ def __init__(self, client: QForge, raw: dict[str, Any]) -> None:
128
+ self._client = client
129
+ self.raw = raw
130
+
131
+ def __repr__(self) -> str:
132
+ return f"Job({self.id!r}, status={self.status!r})"
133
+
134
+ @property
135
+ def id(self) -> str:
136
+ return str(self.raw["id"])
137
+
138
+ @property
139
+ def status(self) -> str:
140
+ status = str(self.raw.get("status", ""))
141
+ return "queued" if status == "pending" else status
142
+
143
+ @property
144
+ def progress(self) -> float | None:
145
+ """0–1 while running."""
146
+ if isinstance(self.raw.get("progress"), (int, float)):
147
+ return float(self.raw["progress"])
148
+ pct = self.raw.get("progress_percent")
149
+ return pct / 100 if isinstance(pct, (int, float)) else None
150
+
151
+ @property
152
+ def eta_seconds(self) -> int | None:
153
+ return self.raw.get("eta_seconds")
154
+
155
+ @property
156
+ def error(self) -> str | None:
157
+ return self.raw.get("error") or self.raw.get("failure_reason")
158
+
159
+ @property
160
+ def materials(self) -> list[Material]:
161
+ """The results (fetched if this object came from a list)."""
162
+ if "results" not in self.raw:
163
+ self.refresh()
164
+ return [Material(r) for r in self.raw.get("results") or []]
165
+
166
+ def refresh(self) -> Job:
167
+ self.raw = self._client._http.get(f"/lab/jobs/{self.id}/")
168
+ return self
169
+
170
+ def wait(
171
+ self,
172
+ timeout: float | None = None,
173
+ poll: float = 15,
174
+ raise_on_failure: bool = True,
175
+ on_progress: Callable[[Job], None] | None = None,
176
+ ) -> Job:
177
+ """Block until the run finishes. Raises :class:`JobFailed` if it failed
178
+ (the credits are refunded) unless ``raise_on_failure=False``."""
179
+
180
+ def step() -> str:
181
+ self.refresh()
182
+ if on_progress:
183
+ on_progress(self)
184
+ return self.status
185
+
186
+ status = _wait(step, active=ACTIVE, timeout=timeout, poll=poll, what=f"Run {self.id}")
187
+ if status in ("failed", "cancelled", "canceled") and raise_on_failure:
188
+ raise JobFailed(f"Run {self.id} {status}: {self.error or 'no reason given'}", body=self.raw)
189
+ return self
190
+
191
+ def cancel(self) -> None:
192
+ """Stop the run (refunded) or delete it if it finished."""
193
+ self._client._http.request("DELETE", f"/lab/jobs/{self.id}/")
194
+
195
+
196
+ class Campaign:
197
+ """Runs batches until enough materials meet the goal or a limit is hit."""
198
+
199
+ def __init__(self, client: QForge, raw: dict[str, Any]) -> None:
200
+ self._client = client
201
+ self.raw = raw
202
+
203
+ def __repr__(self) -> str:
204
+ return f"Campaign({self.id!r}, status={self.status!r}, found={self.found})"
205
+
206
+ @property
207
+ def id(self) -> str:
208
+ return str(self.raw["id"])
209
+
210
+ @property
211
+ def status(self) -> str:
212
+ """``running``, ``done`` (goal met), ``stopped`` (a limit) or ``failed``."""
213
+ return str(self.raw.get("status", ""))
214
+
215
+ @property
216
+ def found(self) -> int:
217
+ return int(self.raw.get("found") or 0)
218
+
219
+ @property
220
+ def materials(self) -> list[Material]:
221
+ """The materials it found that meet the goal."""
222
+ jobs: dict[str, list[dict[str, Any]]] = {}
223
+ out: list[Material] = []
224
+ for ref in self.raw.get("found_materials") or []:
225
+ job_id = str(ref.get("job_id"))
226
+ if job_id not in jobs:
227
+ jobs[job_id] = self._client._http.get(f"/lab/jobs/{job_id}/").get("results") or []
228
+ results = jobs[job_id]
229
+ index = ref.get("result_index")
230
+ if isinstance(index, int) and 0 <= index < len(results):
231
+ out.append(Material(results[index]))
232
+ return out
233
+
234
+ def refresh(self) -> Campaign:
235
+ self.raw = self._client._http.get(f"/lab/campaigns/{self.id}/")
236
+ return self
237
+
238
+ def wait(self, timeout: float | None = None, poll: float = 60) -> Campaign:
239
+ """Block until it stops (goal met, or a credit or batch limit)."""
240
+ _wait(
241
+ lambda: self.refresh().status,
242
+ active={"running"},
243
+ timeout=timeout,
244
+ poll=poll,
245
+ what=f"Campaign {self.id}",
246
+ )
247
+ return self
248
+
249
+ def stop(self) -> None:
250
+ self._client._http.request("POST", f"/lab/campaigns/{self.id}/stop/")
251
+
252
+
253
+ class DftCheck:
254
+ """A DFT verification of a Library material (run by QForge)."""
255
+
256
+ def __init__(self, client: QForge, library_id: str, raw: dict[str, Any]) -> None:
257
+ self._client = client
258
+ self.library_id = library_id
259
+ self.raw = raw
260
+
261
+ def __repr__(self) -> str:
262
+ return f"DftCheck({self.library_id!r}, status={self.status!r}, verdict={self.verdict!r})"
263
+
264
+ @property
265
+ def status(self) -> str:
266
+ """``none`` (not started), ``queued``, ``running``, ``done`` or ``failed``."""
267
+ return str(self.raw.get("status", ""))
268
+
269
+ @property
270
+ def quote(self) -> float | None:
271
+ """Credits a check costs (while not started)."""
272
+ q = self.raw.get("quote") or {}
273
+ return float(q["credits"]) if q.get("credits") is not None else None
274
+
275
+ @property
276
+ def result(self) -> dict[str, Any]:
277
+ return dict(self.raw.get("result") or {})
278
+
279
+ @property
280
+ def verdict(self) -> str | None:
281
+ """``stable``, ``metastable``, ``unstable`` or ``not_converged``."""
282
+ return self.result.get("verdict")
283
+
284
+ @property
285
+ def e_above_hull(self) -> float | None:
286
+ return self.result.get("e_above_hull")
287
+
288
+ def refresh(self) -> DftCheck:
289
+ self.raw = self._client._http.get(f"/lab/materials/{self.library_id}/dft/")
290
+ return self
291
+
292
+ def wait(self, timeout: float | None = None, poll: float = 60, raise_on_failure: bool = True) -> DftCheck:
293
+ status = _wait(
294
+ lambda: self.refresh().status,
295
+ active={"queued", "running"},
296
+ timeout=timeout,
297
+ poll=poll,
298
+ what=f"DFT check of {self.library_id}",
299
+ )
300
+ if status == "failed" and raise_on_failure:
301
+ raise JobFailed(f"DFT check failed: {self.raw.get('error') or 'no reason given'}", body=self.raw)
302
+ return self
qforge/py.typed ADDED
File without changes
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: qforge-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for QForge: generate crystal structures with target properties.
5
+ Project-URL: Documentation, https://github.com/Hilbert-Forge/QForge-python#readme
6
+ Author: QForge
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: ase,crystal structures,generative models,materials,pymatgen
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
15
+ Classifier: Topic :: Scientific/Engineering :: Physics
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: httpx>=0.25
18
+ Provides-Extra: all
19
+ Requires-Dist: ase>=3.22; extra == 'all'
20
+ Requires-Dist: pymatgen>=2023.1; extra == 'all'
21
+ Provides-Extra: ase
22
+ Requires-Dist: ase>=3.22; extra == 'ase'
23
+ Provides-Extra: dev
24
+ Requires-Dist: mypy>=1.8; extra == 'dev'
25
+ Requires-Dist: pytest>=7; extra == 'dev'
26
+ Requires-Dist: ruff>=0.5; extra == 'dev'
27
+ Provides-Extra: pymatgen
28
+ Requires-Dist: pymatgen>=2023.1; extra == 'pymatgen'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # qforge-sdk
32
+
33
+ Python client for QForge: generate crystal structures with the properties you want, then work with them in pymatgen or ASE.
34
+
35
+ ```bash
36
+ pip install qforge-sdk # the client
37
+ pip install "qforge-sdk[pymatgen]" # + Material.to_pymatgen()
38
+ pip install "qforge-sdk[ase]" # + Material.to_ase()
39
+ ```
40
+
41
+ The package installs as `qforge-sdk` and imports as `qforge`.
42
+
43
+ ## Setup
44
+
45
+ 1. In QForge, open **Developers → API keys** and create a key.
46
+ - Give it only the scopes it needs. "Run" spends credits.
47
+ - Set a monthly credit cap.
48
+ 2. Set two environment variables:
49
+
50
+ ```bash
51
+ export QFORGE_API_KEY=qfk_…
52
+ export QFORGE_URL=https://your-qforge # the address you open QForge at
53
+ ```
54
+
55
+ You can also pass them in code: `QForge(api_key=..., base_url=...)`.
56
+
57
+ ## Generate
58
+
59
+ ```python
60
+ from qforge import QForge
61
+
62
+ qf = QForge()
63
+
64
+ job = qf.generate(
65
+ {"band_gap": 3.0}, # property ids: Developers → Properties
66
+ elements=["Fe", "O"],
67
+ n_structures=8,
68
+ model="frost", # "auto", a model id, or pinned: "frost@1"
69
+ check_novelty=True,
70
+ )
71
+ job.wait(on_progress=lambda j: print(j.status, j.progress))
72
+
73
+ for m in job.materials:
74
+ print(m.formula, m.space_group, m.e_above_hull, m.novelty)
75
+ m.save() # FeO.cif
76
+ s = m.to_pymatgen() # pymatgen Structure
77
+ ```
78
+
79
+ The **code builder** in QForge (Developers → Code builder) writes this call for any query you build in the browser.
80
+
81
+ ## Campaigns
82
+
83
+ A campaign keeps generating until it finds enough materials that meet a goal, or it hits a credit or batch limit.
84
+
85
+ ```python
86
+ c = qf.campaign(
87
+ "Wide-gap oxides",
88
+ {"band_gap": 4.0},
89
+ goal={"count": 5, "novel": True, "stable": True},
90
+ max_credits=30,
91
+ max_batches=10,
92
+ )
93
+ c.wait()
94
+ print(c.status, [m.formula for m in c.materials])
95
+ ```
96
+
97
+ ## Library and DFT
98
+
99
+ ```python
100
+ for m in qf.library(search="Fe-O", favourite=True):
101
+ print(m.formula, m.library_id)
102
+
103
+ check = qf.verify_dft(m, max_credits=20) # starts at the quoted price, never above 20
104
+ check.wait() # DFT takes hours; poll every minute
105
+ print(check.verdict, check.e_above_hull)
106
+ ```
107
+
108
+ ## Errors and retries
109
+
110
+ - **Every API error is a `qforge.QForgeError`**, with `.status`, `.code` and `.request_id`. Quote the request id to support.
111
+ - **Specific error classes:**
112
+ - `AuthenticationError` (401)
113
+ - `InsufficientCredits` (402)
114
+ - `PermissionDenied` (403, the key lacks a scope)
115
+ - `NotFound` (404)
116
+ - `Conflict` (409)
117
+ - `RateLimited` (429)
118
+ - `ServerError` (5xx)
119
+ - `JobFailed` (a run, campaign or DFT check failed; failed runs are refunded)
120
+ - `Timeout` (`wait(timeout=…)` ran out)
121
+ - **Automatic retries:** busy (429) and unavailable (502, 503, 504) responses are retried with backoff, honouring `Retry-After`.
122
+ - **No double charges:** calls that spend credits send an `Idempotency-Key`, so a retry is never charged twice.
123
+
124
+ ## Development
125
+
126
+ ```bash
127
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
128
+ .venv/bin/pytest
129
+ .venv/bin/ruff check . && .venv/bin/mypy src
130
+ ```
131
+
132
+ The tests use an in-memory fake server and never call a real one.
133
+
134
+ ### Releasing
135
+
136
+ 1. Bump `version` in `pyproject.toml` and `src/qforge/__init__.py`.
137
+ 2. Tag `vX.Y.Z` and push the tag.
138
+ 3. GitHub Actions builds the package and publishes it to PyPI. This uses trusted publishing: add this repo and the `release.yml` workflow as a trusted publisher for `qforge-sdk` on PyPI first.
139
+
140
+ Until it's on PyPI, install from the repo:
141
+
142
+ ```bash
143
+ pip install "git+https://github.com/Hilbert-Forge/QForge-python.git"
144
+ ```
@@ -0,0 +1,10 @@
1
+ qforge/__init__.py,sha256=5fMSfbWV5BadM9xJqSn9ksUdCZ6YVJiTGWFDgULKYgY,975
2
+ qforge/_http.py,sha256=VAWGW0D_k93vh43Z-_piaSWOcVY8jvPs7UK_zhM5Ra8,3938
3
+ qforge/client.py,sha256=bIhHrMz0oDnp2wfc0fYN_kHF_h5eUD3W7Q9IboMBDIs,8156
4
+ qforge/errors.py,sha256=EoGSle6jjnyOLG6ZpTDWC-bNtAQKjiWPoqiMANo6J9Q,2020
5
+ qforge/models.py,sha256=tPkPNA-KXpedemGMIPcdPH0sE0tzoytfGmtUBxaZ7GE,10447
6
+ qforge/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ qforge_sdk-0.1.0.dist-info/METADATA,sha256=XKcctPX8QIThuRHT4ohKTLv4u6dYX0bide3rRRK2Mls,4607
8
+ qforge_sdk-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ qforge_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=MobTOSBoEHg_iIg4jt7i545uGVyItSzYB8p4vZZ6x9U,1063
10
+ qforge_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QForge
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.