Skip to content

Commit

Permalink
helper functions for creating targeting flags
Browse files Browse the repository at this point in the history
  • Loading branch information
andycasey committed Oct 11, 2023
1 parent 482b53d commit 1b17910
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
9 changes: 6 additions & 3 deletions python/sdss_semaphore/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

import numpy as np
import warnings
from typing import Union, Tuple, Iterable, List, Tuple
from typing import Union, Tuple, Iterable, List, Optional, Tuple


class BaseFlags:

"""A base class for communicating with flags."""

def __init__(self, array: Union[np.ndarray, Iterable[Iterable[int]], Iterable[bytearray]]) -> None:
if isinstance(array, (list, tuple)) and isinstance(array[0], bytearray):
def __init__(self, array: Optional[Union[np.ndarray, Iterable[Iterable[int]], Iterable[bytearray]]] = None) -> None:
if array is None:
# Assume single object flag.
self.array = np.zeros((1, 0), dtype=self.dtype)
elif isinstance(array, (list, tuple)) and isinstance(array[0], bytearray):
# TODO: If the self.dtype is not uint8, then we might need to compute these initial offsets ourselves,
# because I think bytearray is natively uint8
if self.dtype != np.uint8:
Expand Down
23 changes: 23 additions & 0 deletions python/sdss_semaphore/targeting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import numpy as np
from typing import Tuple
from functools import cached_property
from typing import Optional
from sdss_semaphore import BaseFlags


Expand Down Expand Up @@ -103,6 +105,27 @@ def count(self, skip_empty: bool = False) -> dict:
skip_empty=skip_empty
)

def set_bit_by_carton_pk(self, index: int, carton_pk: int):
"""
Set the bit for the carton with the given primary key.
:param index:
The index of the item to set.
:param carton_pk:
The carton primary key.
"""
bit = self.get_bit_position_from_carton_pk[carton_pk]
return self.set_bit(index, bit)

@cached_property
def get_bit_position_from_carton_pk(self):
"""
Return a dictionary with carton primary keys as keys, and bit positions as values.
This is a helper method for efficiency creating large `TargetingFlags` objects.
"""
return { attrs["carton_pk"]: bit for bit, attrs in self.mapping.items() }

class TargetingFlags(BaseTargetingFlags):

Expand Down

0 comments on commit 1b17910

Please sign in to comment.