Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d889465
Apply ruff autofix with strict settings
philipp-seitz Feb 20, 2026
825c732
Add docstring for top level modules
philipp-seitz Jan 14, 2026
d8085da
Fix typing in parser.py to make tests run
philipp-seitz Jan 15, 2026
0aace5f
Update failing test
philipp-seitz Jan 15, 2026
d4f6294
Fix tests
philipp-seitz Jan 15, 2026
f249f7d
Lint Tests
philipp-seitz Jan 15, 2026
c25c2f7
Update builtin
philipp-seitz Jan 15, 2026
194fdd2
Update builtin stubs
philipp-seitz Jan 15, 2026
d1a70a9
Update cli
philipp-seitz Jan 15, 2026
338dff6
Update workers first batch
philipp-seitz Jan 15, 2026
011463a
Update worker
philipp-seitz Jan 15, 2026
9d177f1
Logger docstrings
philipp-seitz Jan 16, 2026
8f6ba09
Update graphs
philipp-seitz Jan 16, 2026
08a0ef4
Update idl
philipp-seitz Jan 16, 2026
bdf181e
Add fixes for non-docstring related issues
philipp-seitz Jan 16, 2026
1c964c7
Add docsrings for storage classes
philipp-seitz Jan 16, 2026
2bbf198
Add remaining docs for storage
philipp-seitz Jan 19, 2026
e483db4
Add docstrings for executors
philipp-seitz Jan 19, 2026
599b827
Add docstrings for hpc executors
philipp-seitz Jan 19, 2026
29dda08
Add docstrings for graph
philipp-seitz Jan 19, 2026
d70d677
Add docstrings for core
philipp-seitz Jan 19, 2026
b96bc97
Apply small fixes
philipp-seitz Feb 20, 2026
ad5bbbd
Apply first batch of fixes
philipp-seitz Feb 23, 2026
72c20b1
Properly fix test
philipp-seitz Feb 23, 2026
a556984
Add second batch of changes
philipp-seitz Feb 24, 2026
1eb7124
Add batch of changes
philipp-seitz Feb 24, 2026
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
3 changes: 2 additions & 1 deletion docs/source/examples/data/typed_eval.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import NamedTuple

from tierkreis.builder import GraphBuilder
from tierkreis.builtins.stubs import iadd, itimes
from tierkreis.controller.data.core import EmptyModel
from tierkreis.builder import GraphBuilder
from tierkreis.controller.data.models import TKR


Expand Down
19 changes: 8 additions & 11 deletions docs/source/examples/errors_and_debugging.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@
"metadata": {},
"outputs": [],
"source": [
"from example_workers.error_worker.api.stubs import fail\n",
"\n",
"from tierkreis.builder import GraphBuilder\n",
"from tierkreis.controller.data.core import EmptyModel\n",
"from tierkreis.controller.data.models import TKR\n",
"\n",
"from example_workers.error_worker.api.stubs import fail\n",
"\n",
"\n",
"def error_graph() -> GraphBuilder:\n",
" g = GraphBuilder(EmptyModel, TKR[str])\n",
Expand Down Expand Up @@ -60,16 +60,15 @@
"from uuid import UUID\n",
"\n",
"from tierkreis.controller import run_graph\n",
"from tierkreis.controller.storage.filestorage import ControllerFileStorage\n",
"from tierkreis.controller.executor.uv_executor import UvExecutor\n",
"from tierkreis.controller.storage.filestorage import ControllerFileStorage\n",
"from tierkreis.exceptions import TierkreisError\n",
"\n",
"workflow_id = UUID(int=103)\n",
"storage = ControllerFileStorage(workflow_id, name=\"error_handling\", do_cleanup=True)\n",
"\n",
"registry_path = Path().parent / \"example_workers\"\n",
"executor = UvExecutor(registry_path=registry_path, logs_path=storage.logs_path)\n",
"print(\"Starting workflow at location:\", storage.logs_path)\n",
"try:\n",
" run_graph(\n",
" storage,\n",
Expand All @@ -79,8 +78,7 @@
" polling_interval_seconds=0.1,\n",
" )\n",
"except TierkreisError: # we will catch this here\n",
" output = storage.read_errors()\n",
" print(\"Errors are at:\", output)"
" output = storage.read_errors()"
]
},
{
Expand All @@ -105,6 +103,7 @@
"metadata": {},
"outputs": [],
"source": [
"import contextlib\n",
"import logging\n",
"\n",
"logging.basicConfig(\n",
Expand All @@ -114,16 +113,14 @@
")\n",
"\n",
"storage.clean_graph_files()\n",
"try:\n",
"with contextlib.suppress(TierkreisError):\n",
" run_graph(\n",
" storage,\n",
" executor,\n",
" error_graph(),\n",
" {\"value\": \"world!\"},\n",
" polling_interval_seconds=0.1,\n",
" )\n",
"except TierkreisError:\n",
" pass"
" )"
]
},
{
Expand All @@ -143,8 +140,8 @@
"metadata": {},
"outputs": [],
"source": [
"from tierkreis.storage import InMemoryStorage\n",
"from tierkreis.controller.executor.in_memory_executor import InMemoryExecutor\n",
"from tierkreis.storage import InMemoryStorage\n",
"\n",
"storage = InMemoryStorage(UUID(int=103))\n",
"executor = InMemoryExecutor(registry_path, storage)\n",
Expand Down
24 changes: 15 additions & 9 deletions docs/source/examples/example_workers/auth_worker/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,22 @@
import secrets
from sys import argv
from time import time
from typing import NamedTuple, cast
from typing import TYPE_CHECKING, NamedTuple, cast

from tierkreis.controller.data.models import portmapping
import pyscrypt # type: ignore
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
from cryptography.hazmat.primitives.hashes import SHA256

from tierkreis import Worker
from tierkreis.controller.data.models import portmapping

if TYPE_CHECKING:
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateKey,
RSAPublicKey,
)

worker = Worker("auth_worker")
logger = logging.getLogger(__name__)
Expand All @@ -34,7 +40,7 @@ def encrypt(plaintext: str, work_factor: int) -> EncryptionResult:
start_time = time()
salt = secrets.token_bytes(32)
ciphertext = pyscrypt.hash( # type:ignore
password=plaintext.encode(), salt=salt, N=work_factor, r=1, p=1, dkLen=32
password=plaintext.encode(), salt=salt, N=work_factor, r=1, p=1, dkLen=32,
)
time_taken = time() - start_time

Expand All @@ -45,13 +51,13 @@ def encrypt(plaintext: str, work_factor: int) -> EncryptionResult:
def sign(private_key: bytes, passphrase: bytes, message: str) -> SigningResult:
start_time = time()
key = cast(
RSAPrivateKey,
"RSAPrivateKey",
serialization.load_pem_private_key(private_key, password=passphrase),
)
signature = key.sign(
message.encode(),
padding=padding.PSS(
mgf=padding.MGF1(SHA256()), salt_length=padding.PSS.MAX_LENGTH
mgf=padding.MGF1(SHA256()), salt_length=padding.PSS.MAX_LENGTH,
),
algorithm=SHA256(),
).hex()
Expand All @@ -62,13 +68,13 @@ def sign(private_key: bytes, passphrase: bytes, message: str) -> SigningResult:

@worker.task()
def verify(public_key: bytes, signature: str, message: str) -> bool:
key = cast(RSAPublicKey, serialization.load_pem_public_key(public_key))
key = cast("RSAPublicKey", serialization.load_pem_public_key(public_key))
try:
key.verify(
bytes.fromhex(signature),
message.encode(),
padding=padding.PSS(
mgf=padding.MGF1(SHA256()), salt_length=padding.PSS.MAX_LENGTH
mgf=padding.MGF1(SHA256()), salt_length=padding.PSS.MAX_LENGTH,
),
algorithm=SHA256(),
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
from sys import argv

from tierkreis import Worker

logger = logging.getLogger(__name__)
Expand All @@ -8,7 +9,8 @@

@worker.task()
def fail() -> str:
raise Exception("I refuse!")
msg = "I refuse!"
raise Exception(msg)
return "I failed to refuse"


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
from sys import argv

from tierkreis import Worker

logger = logging.getLogger(__name__)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ def get_frozen(
n_orbs = len(mo_occ)
n_core = get_n_core(mo_occ, n_elecas)
if n_core + n_cas > n_orbs:
raise ValueError("active space is larger than basis set")
msg = "active space is larger than basis set"
raise ValueError(msg)
for i in range(n_orbs):
# print(i, i < n_core, i >= n_core + n_cas)
if i < n_core or i >= n_core + n_cas:
Expand All @@ -20,8 +21,7 @@ def get_n_core(
n_elecas: int,
) -> int:
n_elec = int(sum(mo_occ))
n_core = (n_elec - n_elecas) // 2
return n_core
return (n_elec - n_elecas) // 2


def get_n_active(
Expand All @@ -30,8 +30,7 @@ def get_n_active(
n_elecas: int,
) -> int:
n_frozen = len(get_frozen(mo_occ, n_cas, n_elecas))
n_active = len(mo_occ) - n_frozen
return n_active
return len(mo_occ) - n_frozen


def get_n_virtual(
Expand All @@ -41,5 +40,4 @@ def get_n_virtual(
) -> int:
n_frozen = len(get_frozen(mo_occ, n_cas, n_elecas))
n_core = get_n_core(mo_occ, n_elecas)
n_virtual = n_frozen - n_core
return n_virtual
return n_frozen - n_core
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from typing import Optional, cast
from typing import TYPE_CHECKING, cast

import numpy as np
from numpy.typing import NDArray
from pyscf import ao2mo, gto, scf

if TYPE_CHECKING:
from numpy.typing import NDArray


def _extract_hamiltonian_rhf(
mol: gto.Mole, frozen: Optional[list[int]] = None
mol: gto.Mole, frozen: list[int] | None = None,
) -> tuple[float, np.ndarray, np.ndarray]:
"""Extract the fermionic Hamiltonian from a mean-field calculation.

Expand All @@ -23,7 +25,7 @@ def _extract_hamiltonian_rhf(
mf.kernel()

# Get the MOs
mo = cast(NDArray, mf.mo_coeff)
mo = cast("NDArray", mf.mo_coeff)
if frozen:
mo = np.delete(mo, frozen, axis=1)
nmo = mo.shape[1]
Expand Down Expand Up @@ -55,7 +57,7 @@ def extract_hamiltonian_rhf(
basis: str,
charge: int = 0,
spin: int = 0,
frozen: Optional[list[int]] = None,
frozen: list[int] | None = None,
) -> tuple[float, np.ndarray, np.ndarray]:
"""Generate the Hamiltonian in a qubit representation.

Expand Down
40 changes: 19 additions & 21 deletions docs/source/examples/example_workers/qsci_worker/src/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import logging
from collections import Counter
from sys import argv
from typing import Counter, NamedTuple, cast
from typing import NamedTuple, cast

import numpy as np
from chemistry.active_space import get_frozen
from chemistry.molecule import extract_hamiltonian_rhf
from pytket._tket.circuit import Circuit
from pytket.backends.backendresult import BackendResult
from pytket.circuit import Qubit
Expand All @@ -13,9 +16,6 @@
from qsci.postprocess import get_ci_matrix, postprocess_configs
from qsci.state_prep import perform_state_preparation
from qsci.utils import get_config_from_cas_init, make_time_evolution_circuits, rhf2ghf
from chemistry.active_space import get_frozen
from chemistry.molecule import extract_hamiltonian_rhf


from tierkreis import Worker

Expand Down Expand Up @@ -53,36 +53,35 @@ def state_prep(
) -> Circuit:
ham_init_operator = QubitPauliOperator(
cast(
dict[QubitPauliString, CoeffTypeAccepted],
"dict[QubitPauliString, CoeffTypeAccepted]",
qubit_mapping_jordan_wigner(
*rhf2ghf(
ham_init.h0,
np.array(ham_init.h1),
np.array(ham_init.h2),
)
),
),
)
),
)
# time-evolve CASCI ground state.
n_core_init = get_n_core(mo_occ, cas_init.n_ele)
n_core_hsim = get_n_core(mo_occ, cas_hsim.n_ele)
n_core = n_core_init - n_core_hsim
logging.info(
f"mo_occ={mo_occ} n_cas_hsim={cas_hsim.n} n_elecas_hsim={cas_hsim.n_ele}"
f"mo_occ={mo_occ} n_cas_hsim={cas_hsim.n} n_elecas_hsim={cas_hsim.n_ele}",
)
n_active_hsim = get_n_active(mo_occ, cas_hsim.n, cas_hsim.n_ele)
prepared_circ = Circuit(n_active_hsim * 2)
for i in range(n_core * 2):
prepared_circ.X(i)
adapt_circ = perform_state_preparation(
return perform_state_preparation(
reference_state=reference_state,
ham_init=ham_init_operator,
n_cas_init=cas_init.n,
max_iteration=max_iteration_prep,
atol=atol,
)

return adapt_circ


@worker.task()
Expand All @@ -98,27 +97,27 @@ def circuits_from_hamiltonians(
) -> list[Circuit]:
ham_init_operator = QubitPauliOperator(
cast(
dict[QubitPauliString, CoeffTypeAccepted],
"dict[QubitPauliString, CoeffTypeAccepted]",
qubit_mapping_jordan_wigner(
*rhf2ghf(
ham_init.h0,
np.array(ham_init.h1),
np.array(ham_init.h2),
)
),
),
)
),
)
ham_hsim_operator = QubitPauliOperator(
cast(
dict[QubitPauliString, CoeffTypeAccepted],
"dict[QubitPauliString, CoeffTypeAccepted]",
qubit_mapping_jordan_wigner(
*rhf2ghf(
ham_hsim.h0,
np.array(ham_hsim.h1),
np.array(ham_hsim.h2),
)
),
),
)
),
)
# Load the input data.
n_core_init = get_n_core(mo_occ, cas_init.n_ele)
Expand All @@ -138,19 +137,18 @@ def circuits_from_hamiltonians(
{
Qubit(qubit.index[0] + 2 * n_core): pauli
for qubit, pauli in qps.map.items()
}
},
): coeff
for qps, coeff in ham_init_operator._dict.items()
}
},
)
circuits = make_time_evolution_circuits(
return make_time_evolution_circuits(
t_step_list,
prepared_circ,
h_hsim=ham_hsim_operator,
h_init=ham_init_shifted,
max_cx_gates=max_cx_gates,
)
return circuits


@worker.task()
Expand All @@ -167,7 +165,7 @@ def energy_from_results(
counts[k] += v
phis = list(counts.keys())
phis_init_orig = get_config_from_cas_init(
mo_occ, cas_init.n, cas_init.n_ele, cas_hsim.n, cas_hsim.n_ele
mo_occ, cas_init.n, cas_init.n_ele, cas_hsim.n, cas_hsim.n_ele,
)
for p in phis_init_orig:
if p not in phis:
Expand Down
Loading