Skip to content

Commit 15d23ca

Browse files
matt-grahamtamuri
andauthored
Enable all pycodestyle and isort rules in Ruff and fix violations (#1463)
Co-authored-by: Asif Tamuri <[email protected]>
1 parent 50aad40 commit 15d23ca

34 files changed

+245
-201
lines changed

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ markers = ["group2", "slow"]
123123
target-version = "py311"
124124
line-length = 120
125125

126+
[tool.ruff.lint]
127+
select = ["E", "F", "I", "W"]
128+
per-file-ignores = {"src/scripts/**" = ["E501", "W"]}
129+
126130
[tool.setuptools.packages.find]
127131
where = ["src"]
128132

src/scripts/hiv/projections_jan2023/analysis_full_model.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import datetime
77
import pickle
8-
# import random
98
from pathlib import Path
109

1110
from tlo import Date, Simulation, logging

src/scripts/profiling/run_profiling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def run_profiling(
298298
print(f"Writing {output_ipysession_file}", end="...", flush=True)
299299
scale_run_session.save(output_ipysession_file)
300300
print("done")
301-
301+
302302
if write_flat_html:
303303
output_html_file = output_dir / f"{output_name}.flat.html"
304304
console_renderer = ConsoleRenderer(

src/scripts/task_runner/generate_html.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,8 @@ def get_html_for_commit(commit_dir: Path) -> str:
101101
<body>
102102
<h1>$title</h1>
103103
<p style="font-size: small;">
104-
This page was generated on $generated_time. The
105-
<a href="https://github.com/UCL/TLOmodel/actions/workflows/calibration.yaml">calibration workflow</a> runs every
104+
This page was generated on $generated_time. The
105+
<a href="https://github.com/UCL/TLOmodel/actions/workflows/calibration.yaml">calibration workflow</a> runs every
106106
night on the latest new commit on the master branch. <a href="#" id="toggleIncomplete">toggle incomplete</a>
107107
</p>
108108
$body

src/tlo/analysis/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,10 @@ def extract_draw_names(results_folder: Path) -> dict[int, str]:
241241
draws = [f for f in os.scandir(results_folder) if f.is_dir()]
242242
return {
243243
int(d.name):
244-
load_pickled_dataframes(results_folder, d.name, 0, name="tlo.scenario")["tlo.scenario"]["draw_name"]["draw_name"].values[0]
244+
load_pickled_dataframes(results_folder,
245+
d.name,
246+
0,
247+
name="tlo.scenario")["tlo.scenario"]["draw_name"]["draw_name"].values[0]
245248
for d in draws
246249
}
247250

@@ -388,7 +391,8 @@ def compute_summary_statistics(
388391

389392
if use_standard_error:
390393
if not central_measure == 'mean':
391-
warnings.warn("When using 'standard-error' the central measure in the summary statistics is always the mean.")
394+
warnings.warn(
395+
"When using 'standard-error' the central measure in the summary statistics is always the mean.")
392396
central_measure = 'mean'
393397
elif central_measure is None:
394398
# If no argument is provided for 'central_measure' (and not using standard-error), default to using 'median'

src/tlo/bitset_handler/bitset_extension.py

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -46,16 +46,16 @@
4646

4747
class BitsetDtype(ExtensionDtype):
4848
"""
49-
A Bitset is represented by a fixed-width string, whose characters are each a uint8.
50-
Elements of the set map 1:1 to these characters.
49+
A Bitset is represented by a fixed-width string, whose characters are each a uint8. Elements of the set map 1:1 to
50+
these characters.
5151
52-
If the elements set is indexed starting from 0, then:
53-
- The quotient of these indices (modulo 8) is the character within the string that contains the bit representing the element,
54-
- The remainder (modulo 8) is the index within said character that represents the element itself.
52+
If the elements set is indexed starting from 0, then: - The quotient of these indices (modulo 8) is the character
53+
within the string that contains the bit representing the element, - The remainder (modulo 8) is the index within
54+
said character that represents the element itself.
5555
5656
The element map takes an element of the bitset as a key, and returns a tuple whose first element is the
57-
corresponding string-character index, and the latter the uint8 representation of the element within that
58-
string character.
57+
corresponding string-character index, and the latter the uint8 representation of the element within that string
58+
character.
5959
"""
6060
_element_map: Dict[ElementType, Tuple[int, np.uint8]]
6161
_elements: Tuple[ElementType]
@@ -71,7 +71,7 @@ def construct_from_string(cls, string: str) -> BitsetDtype:
7171
"""
7272
Construct an instance of this class by passing in a string of the form
7373
that str(<instance of this class>) produces.
74-
74+
7575
That is, given a string of the form
7676
bitset(#elements): e1, e2, e3, ...
7777
@@ -101,7 +101,8 @@ def construct_from_string(cls, string: str) -> BitsetDtype:
101101
iterable_values = tuple(s.strip() for s in string.split(","))
102102
if n_elements is not None and len(iterable_values) != n_elements:
103103
raise ValueError(
104-
f"Requested bitset with {n_elements} elements, but provided {len(iterable_values)} elements: {iterable_values}"
104+
f"Requested bitset with {n_elements} elements, "
105+
f"but provided {len(iterable_values)} elements: {iterable_values}"
105106
)
106107
return BitsetDtype(s.strip() for s in string.split(","))
107108

@@ -351,7 +352,7 @@ def _uint8_view(self) -> NDArray[np.bytes_]:
351352
Each row ``i`` of this view corresponds to a bitset stored in this array.
352353
The value at index ``i, j`` in this view is the ``uint8`` that represents
353354
character ``j`` in ``self._data[i]``, which can have bitwise operations
354-
performed on it.
355+
performed on it.
355356
"""
356357
return self._data.view(self._uint8_view_format)
357358

@@ -463,17 +464,17 @@ def __cast_to_uint8(self, other: CastableForPandasOps) -> NDArray[np.uint8]:
463464
464465
Scalar elements:
465466
Cast to single-element sets, then treated as set.
466-
467+
467468
Sets:
468469
Are converted to the (array of) uint8s that represents the set.
469-
470+
470471
``np.ndarray``s of ``np.uint8``
471472
Are returned if they have the same number of columns as ``self._uint8_view``.
472-
473+
473474
``np.ndarray``s of ``np.dtype("Sx")``
474475
If ``x`` corresponds to the same fixed-width as ``self.dtype.np_array_dtype``, are cast
475476
to the corresponding ``np.uint8`` view, like ``self._uint8_view`` is from ``self._data``.
476-
477+
477478
BitsetArrays
478479
Return their ``_uint8_view`` attribute.
479480
"""
@@ -508,13 +509,17 @@ def __cast_to_uint8(self, other: CastableForPandasOps) -> NDArray[np.uint8]:
508509
cast = self.dtype.as_uint8_array(other)
509510
return cast
510511

511-
def __comparison_op(self, other: CastableForPandasOps, op: Callable[[Set[ElementType], Set[ElementType]], bool]) -> BooleanArray:
512+
def __comparison_op(
513+
self,
514+
other: CastableForPandasOps,
515+
op: Callable[[Set[ElementType], Set[ElementType]], bool],
516+
) -> BooleanArray:
512517
"""
513518
Abstract method for strict and non-strict comparison operations.
514519
515520
Notably, __eq__ does not redirect here since it is more efficient for us to convert
516521
the single value to a bytestring and use numpy array comparison.
517-
522+
518523
For the other set comparison methods however, it's easier as a first implementation
519524
for us to convert to sets and run the set operations. If there was a Pythonic way
520525
of doing "bitwise less than" and "bitwise greater than", we could instead take the
@@ -678,7 +683,8 @@ def copy(self) -> BitsetArray:
678683

679684
def isna(self) -> NDArray:
680685
"""
681-
TODO: This isn't a great way to express missing data, but equally a bitset doesn't really ever contain missing data...
686+
TODO: This isn't a great way to express missing data, but equally a bitset doesn't really ever contain
687+
missing data...
682688
"""
683689
return np.isnan(self._data)
684690

src/tlo/core.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def _default_value(self) -> Any:
170170
"""
171171
Default value for this property, which will be used to fill the respective columns
172172
of the population dataframe, for example.
173-
173+
174174
If not explicitly set, it will fall back on the ``PANDAS_TYPE_DEFAULT_TYPE_MAP``.
175175
If a value is provided, it must:
176176
@@ -386,8 +386,8 @@ def initialise_population(self, population: Population) -> None:
386386
387387
Modules that wish to implement this behaviour do not need to implement this method,
388388
it will be inherited automatically. Modules that wish to perform additional steps
389-
during the initialise_population stage should reimplement this method and call
390-
389+
during the initialise_population stage should reimplement this method and call
390+
391391
```python
392392
super().initialise_population(population=population)
393393
```

src/tlo/logging/helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,11 @@ def get_dataframe_row_as_dict_for_logging(
5959
columns: Optional[Iterable[str]] = None,
6060
) -> dict:
6161
"""Get row of a pandas dataframe in a format suitable for logging.
62-
62+
6363
Retrieves entries for all or a subset of columns for a particular row in a dataframe
6464
and returns a dict keyed by column name, with values NumPy or pandas extension types
6565
which should be the same for all rows in dataframe.
66-
66+
6767
:param dataframe: Population properties dataframe to get properties from.
6868
:param row_label: Unique index label identifying row in dataframe.
6969
:param columns: Set of column names to extract - if ``None``, the default, all

src/tlo/methods/alri.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3039,7 +3039,8 @@ def apply(self, person_id):
30393039

30403040
assert 'fast_breathing_pneumonia' == \
30413041
self.module.get_imci_classification_based_on_symptoms(
3042-
child_is_younger_than_2_months=False, symptoms=self.sim.modules['SymptomManager'].has_what(person_id=person_id)
3042+
child_is_younger_than_2_months=False,
3043+
symptoms=self.sim.modules['SymptomManager'].has_what(person_id=person_id)
30433044
)
30443045

30453046

src/tlo/methods/contraception.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,6 +1171,8 @@ def _get_appt_footprint(self, current_method: str):
11711171
stacklevel=3,
11721172
)
11731173
return self.make_appt_footprint({})
1174+
warnings.warn(UserWarning("Assumed empty footprint for Contraception Routine appt because couldn't find"
1175+
"actual case."))
11741176

11751177
def apply(self, person_id, squeeze_factor):
11761178
"""If the relevant consumable is available, do change in contraception and log it"""

0 commit comments

Comments
 (0)