Skip to content

Commit a3329e7

Browse files
committed
Remove remaining pre-3.10 typing syntax
1 parent a210443 commit a3329e7

File tree

10 files changed

+57
-59
lines changed

10 files changed

+57
-59
lines changed

cmdstanpy/stanfit/laplace.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Container for the result of running a laplace approximation.
33
"""
44

5-
from typing import Any, Hashable, MutableMapping, Optional, Union
5+
from typing import Any, Hashable, MutableMapping
66

77
import numpy as np
88
import pandas as pd
@@ -41,8 +41,8 @@ def __init__(self, runset: RunSet, mode: CmdStanMLE) -> None:
4141
self._metadata = InferenceMetadata.from_csv(self._runset.csv_files[0])
4242

4343
def create_inits(
44-
self, seed: Optional[int] = None, chains: int = 4
45-
) -> Union[list[dict[str, np.ndarray]], dict[str, np.ndarray]]:
44+
self, seed: int | None = None, chains: int = 4
45+
) -> list[dict[str, np.ndarray]] | dict[str, np.ndarray]:
4646
"""
4747
Create initial values for the parameters of the model
4848
by randomly selecting draws from the Laplace approximation.
@@ -168,7 +168,7 @@ def draws(self) -> np.ndarray:
168168

169169
def draws_pd(
170170
self,
171-
vars: Union[list[str], str, None] = None,
171+
vars: list[str] | str | None = None,
172172
) -> pd.DataFrame:
173173
if vars is not None:
174174
if isinstance(vars, str):
@@ -197,7 +197,7 @@ def draws_pd(
197197

198198
def draws_xr(
199199
self,
200-
vars: Union[str, list[str], None] = None,
200+
vars: str | list[str] | None = None,
201201
) -> "xr.Dataset":
202202
"""
203203
Returns the sampler draws as a xarray Dataset.
@@ -308,7 +308,7 @@ def column_names(self) -> tuple[str, ...]:
308308
"""
309309
return self._metadata.column_names
310310

311-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
311+
def save_csvfiles(self, dir: str | None = None) -> None:
312312
"""
313313
Move output CSV files to specified directory. If files were
314314
written to the temporary session directory, clean filename.

cmdstanpy/stanfit/mcmc.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import math
66
import os
77
from io import StringIO
8-
from typing import Any, Hashable, MutableMapping, Optional, Sequence, Union
8+
from typing import Any, Hashable, MutableMapping, Sequence
99

1010
import numpy as np
1111
import pandas as pd
@@ -97,8 +97,8 @@ def __init__(
9797
self._check_sampler_diagnostics()
9898

9999
def create_inits(
100-
self, seed: Optional[int] = None, chains: int = 4
101-
) -> Union[list[dict[str, np.ndarray]], dict[str, np.ndarray]]:
100+
self, seed: int | None = None, chains: int = 4
101+
) -> list[dict[str, np.ndarray]] | dict[str, np.ndarray]:
102102
"""
103103
Create initial values for the parameters of the model by
104104
randomly selecting draws from the MCMC samples. If the samples
@@ -211,7 +211,7 @@ def column_names(self) -> tuple[str, ...]:
211211
return self._metadata.column_names
212212

213213
@property
214-
def metric_type(self) -> Optional[str]:
214+
def metric_type(self) -> str | None:
215215
"""
216216
Metric type used for adaptation, either 'diag_e' or 'dense_e', according
217217
to CmdStan arg 'metric'.
@@ -225,7 +225,7 @@ def metric_type(self) -> Optional[str]:
225225

226226
# TODO(2.0): remove
227227
@property
228-
def metric(self) -> Optional[np.ndarray]:
228+
def metric(self) -> np.ndarray | None:
229229
"""Deprecated. Use ``.inv_metric`` instead."""
230230
get_logger().warning(
231231
'The "metric" property is deprecated, use "inv_metric" instead. '
@@ -234,7 +234,7 @@ def metric(self) -> Optional[np.ndarray]:
234234
return self.inv_metric
235235

236236
@property
237-
def inv_metric(self) -> Optional[np.ndarray]:
237+
def inv_metric(self) -> np.ndarray | None:
238238
"""
239239
Inverse mass matrix used by sampler for each chain.
240240
Returns a ``nchains x nparams`` array when metric_type is 'diag_e',
@@ -248,7 +248,7 @@ def inv_metric(self) -> Optional[np.ndarray]:
248248
return self._metric
249249

250250
@property
251-
def step_size(self) -> Optional[np.ndarray]:
251+
def step_size(self) -> np.ndarray | None:
252252
"""
253253
Step size used by sampler for each chain.
254254
When sampler algorithm 'fixed_param' is specified, step size is None.
@@ -264,15 +264,15 @@ def thin(self) -> int:
264264
return self._thin
265265

266266
@property
267-
def divergences(self) -> Optional[np.ndarray]:
267+
def divergences(self) -> np.ndarray | None:
268268
"""
269269
Per-chain total number of post-warmup divergent iterations.
270270
When sampler algorithm 'fixed_param' is specified, returns None.
271271
"""
272272
return self._divergences if not self._is_fixed_param else None
273273

274274
@property
275-
def max_treedepths(self) -> Optional[np.ndarray]:
275+
def max_treedepths(self) -> np.ndarray | None:
276276
"""
277277
Per-chain total number of post-warmup iterations where the NUTS sampler
278278
reached the maximum allowed treedepth.
@@ -564,7 +564,7 @@ def summary(
564564
summary_data.index.name = None
565565
return summary_data[mask]
566566

567-
def diagnose(self) -> Optional[str]:
567+
def diagnose(self) -> str | None:
568568
"""
569569
Run cmdstan/bin/diagnose over all output CSV files,
570570
return console output.
@@ -586,7 +586,7 @@ def diagnose(self) -> Optional[str]:
586586

587587
def draws_pd(
588588
self,
589-
vars: Union[list[str], str, None] = None,
589+
vars: list[str] | str | None = None,
590590
inc_warmup: bool = False,
591591
) -> pd.DataFrame:
592592
"""
@@ -664,7 +664,7 @@ def draws_pd(
664664
)[cols]
665665

666666
def draws_xr(
667-
self, vars: Union[str, list[str], None] = None, inc_warmup: bool = False
667+
self, vars: str | list[str] | None = None, inc_warmup: bool = False
668668
) -> "xr.Dataset":
669669
"""
670670
Returns the sampler draws as a xarray Dataset.
@@ -822,7 +822,7 @@ def method_variables(self) -> dict[str, np.ndarray]:
822822
for name, var in self._metadata.method_vars.items()
823823
}
824824

825-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
825+
def save_csvfiles(self, dir: str | None = None) -> None:
826826
"""
827827
Move output CSV files to specified directory. If files were
828828
written to the temporary session directory, clean filename.

cmdstanpy/stanfit/metadata.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import copy
44
import os
5-
from typing import Any, Iterator, Union
5+
from typing import Any, Iterator
66

77
import stanio
88

@@ -17,7 +17,7 @@ class InferenceMetadata:
1717
"""
1818

1919
def __init__(
20-
self, config: dict[str, Union[str, int, float, tuple[str, ...]]]
20+
self, config: dict[str, str | int | float | tuple[str, ...]]
2121
) -> None:
2222
"""Initialize object from CSV headers"""
2323
self._cmdstan_config = config
@@ -33,7 +33,7 @@ def __init__(
3333

3434
@classmethod
3535
def from_csv(
36-
cls, stan_csv: Union[str, os.PathLike, Iterator[bytes]]
36+
cls, stan_csv: str | os.PathLike | Iterator[bytes]
3737
) -> 'InferenceMetadata':
3838
try:
3939
comments, header, _ = stancsv.parse_comments_header_and_draws(
@@ -48,7 +48,7 @@ def from_csv(
4848
def __repr__(self) -> str:
4949
return 'Metadata:\n{}\n'.format(self._cmdstan_config)
5050

51-
def __getitem__(self, key: str) -> Union[str, int, float, tuple[str, ...]]:
51+
def __getitem__(self, key: str) -> str | int | float | tuple[str, ...]:
5252
return self._cmdstan_config[key]
5353

5454
@property

cmdstanpy/stanfit/mle.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Container for the result of running optimization"""
22

33
from collections import OrderedDict
4-
from typing import Optional
54

65
import numpy as np
76
import pandas as pd
@@ -58,7 +57,7 @@ def __init__(self, runset: RunSet) -> None:
5857
self._all_iters: np.ndarray = all_draws
5958

6059
def create_inits(
61-
self, seed: Optional[int] = None, chains: int = 4
60+
self, seed: int | None = None, chains: int = 4
6261
) -> dict[str, np.ndarray]:
6362
"""
6463
Create initial values for the parameters of the model
@@ -134,7 +133,7 @@ def optimized_params_np(self) -> np.ndarray:
134133
return self._mle
135134

136135
@property
137-
def optimized_iterations_np(self) -> Optional[np.ndarray]:
136+
def optimized_iterations_np(self) -> np.ndarray | None:
138137
"""
139138
Returns all saved iterations from the optimizer and final estimate
140139
as a numpy.ndarray which contains all optimizer outputs, i.e.,
@@ -167,7 +166,7 @@ def optimized_params_pd(self) -> pd.DataFrame:
167166
return pd.DataFrame([self._mle], columns=self.column_names)
168167

169168
@property
170-
def optimized_iterations_pd(self) -> Optional[pd.DataFrame]:
169+
def optimized_iterations_pd(self) -> pd.DataFrame | None:
171170
"""
172171
Returns all saved iterations from the optimizer and final estimate
173172
as a pandas.DataFrame which contains all optimizer outputs, i.e.,
@@ -294,7 +293,7 @@ def stan_variables(
294293
)
295294
return result
296295

297-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
296+
def save_csvfiles(self, dir: str | None = None) -> None:
298297
"""
299298
Move output CSV files to specified directory. If files were
300299
written to the temporary session directory, clean filename.

cmdstanpy/stanfit/pathfinder.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
Container for the result of running Pathfinder.
33
"""
44

5-
from typing import Optional, Union
6-
75
import numpy as np
86

97
from cmdstanpy.cmdstan_args import Method
@@ -30,8 +28,8 @@ def __init__(self, runset: RunSet):
3028
self._metadata = InferenceMetadata.from_csv(self._runset.csv_files[0])
3129

3230
def create_inits(
33-
self, seed: Optional[int] = None, chains: int = 4
34-
) -> Union[list[dict[str, np.ndarray]], dict[str, np.ndarray]]:
31+
self, seed: int | None = None, chains: int = 4
32+
) -> list[dict[str, np.ndarray]] | dict[str, np.ndarray]:
3533
"""
3634
Create initial values for the parameters of the model
3735
by randomly selecting draws from the Pathfinder approximation.
@@ -216,7 +214,7 @@ def is_resampled(self) -> bool:
216214
in (1, 'true')
217215
)
218216

219-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
217+
def save_csvfiles(self, dir: str | None = None) -> None:
220218
"""
221219
Move output CSV files to specified directory. If files were
222220
written to the temporary session directory, clean filename.

cmdstanpy/stanfit/runset.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import tempfile
1010
from datetime import datetime
1111
from time import time
12-
from typing import Optional
1312

1413
from cmdstanpy import _TMPDIR
1514
from cmdstanpy.cmdstan_args import CmdStanArgs, Method
@@ -31,7 +30,7 @@ def __init__(
3130
args: CmdStanArgs,
3231
chains: int = 1,
3332
*,
34-
chain_ids: Optional[list[int]] = None,
33+
chain_ids: list[int] | None = None,
3534
time_fmt: str = "%Y%m%d%H%M%S",
3635
one_process_per_chain: bool = True,
3736
) -> None:
@@ -162,23 +161,29 @@ def cmd(self, idx: int) -> list[str]:
162161
return self._args.compose_command(
163162
idx,
164163
csv_file=self.csv_files[idx],
165-
diagnostic_file=self.diagnostic_files[idx]
166-
if self._args.save_latent_dynamics
167-
else None,
168-
profile_file=self.profile_files[idx]
169-
if self._args.save_profile
170-
else None,
164+
diagnostic_file=(
165+
self.diagnostic_files[idx]
166+
if self._args.save_latent_dynamics
167+
else None
168+
),
169+
profile_file=(
170+
self.profile_files[idx] if self._args.save_profile else None
171+
),
171172
)
172173
else:
173174
return self._args.compose_command(
174175
idx,
175176
csv_file=self.file_path('.csv'),
176-
diagnostic_file=self.file_path(".csv", extra="-diagnostic")
177-
if self._args.save_latent_dynamics
178-
else None,
179-
profile_file=self.file_path(".csv", extra="-profile")
180-
if self._args.save_profile
181-
else None,
177+
diagnostic_file=(
178+
self.file_path(".csv", extra="-diagnostic")
179+
if self._args.save_latent_dynamics
180+
else None
181+
),
182+
profile_file=(
183+
self.file_path(".csv", extra="-profile")
184+
if self._args.save_profile
185+
else None
186+
),
182187
)
183188

184189
@property
@@ -213,7 +218,7 @@ def profile_files(self) -> list[str]:
213218

214219
# pylint: disable=invalid-name
215220
def file_path(
216-
self, suffix: str, *, extra: str = "", id: Optional[int] = None
221+
self, suffix: str, *, extra: str = "", id: int | None = None
217222
) -> str:
218223
if id is not None:
219224
suffix = f"_{id}{suffix}"
@@ -256,7 +261,7 @@ def get_err_msgs(self) -> str:
256261
msgs.append('\n\t'.join(errors))
257262
return '\n'.join(msgs)
258263

259-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
264+
def save_csvfiles(self, dir: str | None = None) -> None:
260265
"""
261266
Moves CSV files to specified directory.
262267

cmdstanpy/stanfit/vb.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Container for the results of running autodiff variational inference"""
22

33
from collections import OrderedDict
4-
from typing import Optional, Union
54

65
import numpy as np
76
import pandas as pd
@@ -53,8 +52,8 @@ def __init__(self, runset: RunSet) -> None:
5352
self._variational_sample: np.ndarray = draws_np[1:]
5453

5554
def create_inits(
56-
self, seed: Optional[int] = None, chains: int = 4
57-
) -> Union[list[dict[str, np.ndarray]], dict[str, np.ndarray]]:
55+
self, seed: int | None = None, chains: int = 4
56+
) -> list[dict[str, np.ndarray]] | dict[str, np.ndarray]:
5857
"""
5958
Create initial values for the parameters of the model
6059
by randomly selecting draws from the variational approximation
@@ -248,7 +247,7 @@ def variational_sample_pd(self) -> pd.DataFrame:
248247
"""
249248
return pd.DataFrame(self._variational_sample, columns=self.column_names)
250249

251-
def save_csvfiles(self, dir: Optional[str] = None) -> None:
250+
def save_csvfiles(self, dir: str | None = None) -> None:
252251
"""
253252
Move output CSV files to specified directory. If files were
254253
written to the temporary session directory, clean filename.

test/test_log_prob.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import os
55
import re
66
from test import check_present
7-
from typing import List, Optional
87

98
import numpy as np
109
import pytest
@@ -34,7 +33,7 @@
3433
],
3534
)
3635
def test_lp_good(
37-
sig_figs: Optional[int], expected: List[str], expected_unadjusted: List[str]
36+
sig_figs: int | None, expected: list[str], expected_unadjusted: list[str]
3837
) -> None:
3938
model = CmdStanModel(stan_file=BERN_STAN)
4039
params = {"theta": 0.34903938392023830482}

0 commit comments

Comments
 (0)