code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _create_learning_rate_scheduler(learning_rate_config, optimizer, total_step): """Create optimizer learning rate scheduler based on config. Args: learning_rate_config: A LearningRate proto message. Returns: A learning rate. Raises: ValueError: when using an unsupported input data type. """ ...
Create optimizer learning rate scheduler based on config. Args: learning_rate_config: A LearningRate proto message. Returns: A learning rate. Raises: ValueError: when using an unsupported input data type.
_create_learning_rate_scheduler
python
traveller59/second.pytorch
second/pytorch/builder/lr_scheduler_builder.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/builder/lr_scheduler_builder.py
MIT
def second_box_encode(boxes, anchors, encode_angle_to_vector=False, smooth_dim=False): """box encode for VoxelNet Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, l, w, h, r anchors ([N, 7] Tensor): anchors """ box_ndim = anchors.shape[-1] cas, cgs = [], [] if box_ndim > 7: ...
box encode for VoxelNet Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, l, w, h, r anchors ([N, 7] Tensor): anchors
second_box_encode
python
traveller59/second.pytorch
second/pytorch/core/box_torch_ops.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/box_torch_ops.py
MIT
def corners_nd(dims, origin=0.5): """generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. dtype (output dtype, optional)...
generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. dtype (output dtype, optional): Defaults to np.float32 Return...
corners_nd
python
traveller59/second.pytorch
second/pytorch/core/box_torch_ops.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/box_torch_ops.py
MIT
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): """convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float ...
convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in kitti label file. Returns: ...
center_to_corner_box2d
python
traveller59/second.pytorch
second/pytorch/core/box_torch_ops.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/box_torch_ops.py
MIT
def _compute_loss(self, prediction_tensor, target_tensor, weights, class_indices=None): """ Args: input [batch_num, class_num]: The direct prediction of classification fc layer. target [ba...
Args: input [batch_num, class_num]: The direct prediction of classification fc layer. target [batch_num, class_num]: Binary target (0 or 1) for each sample each class. The value is -1 when the sample is ignored.
_compute_loss
python
traveller59/second.pytorch
second/pytorch/core/ghm_loss.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/ghm_loss.py
MIT
def indices_to_dense_vector(indices, size, indices_value=1., default_value=0, dtype=np.float32): """Creates dense vector with indices set to specific value and rest to zeros. This function exists because...
Creates dense vector with indices set to specific value and rest to zeros. This function exists because it is unclear if it is safe to use tf.sparse_to_dense(indices, [size], 1, validate_indices=False) with indices which are not ordered. This function accepts a dynamic size (e.g. tf.shape(tensor)[0]) Args...
indices_to_dense_vector
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def __call__(self, prediction_tensor, target_tensor, ignore_nan_targets=False, scope=None, **params): """Call the loss function. Args: prediction_tensor: an N-d tensor of shape [batch, anchors, ...] representing predicted ...
Call the loss function. Args: prediction_tensor: an N-d tensor of shape [batch, anchors, ...] representing predicted quantities. target_tensor: an N-d tensor of shape [batch, anchors, ...] representing regression or classification targets. ignore_nan_targets: whether to ignore nan...
__call__
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def _compute_loss(self, prediction_tensor, target_tensor, weights): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the (encoded) predicted locations of objects. target_tensor: A float tensor of shape [batch_size, ...
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the (encoded) predicted locations of objects. target_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the regression targets w...
_compute_loss
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def _compute_loss(self, prediction_tensor, target_tensor, weights, class_indices=None): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing th...
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing one-hot encoded classification targe...
_compute_loss
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def __init__(self, gamma=2.0, alpha=0.25): """Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. else, will treat ...
Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. else, will treat first label as background. only affect alpha.
__init__
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def __init__(self, gamma=2.0, alpha=0.25): """Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. """ self._alpha = alpha self._gamma = gamma
Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives.
__init__
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def _compute_loss(self, prediction_tensor, target_tensor, weights): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anch...
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing one-hot encoded classification targe...
_compute_loss
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def __init__(self, alpha, bootstrap_type='soft'): """Constructor. Args: alpha: a float32 scalar tensor between 0 and 1 representing interpolation weight bootstrap_type: set to either 'hard' or 'soft' (default) Raises: ValueError: if bootstrap_type is not either 'hard' or 'soft' ...
Constructor. Args: alpha: a float32 scalar tensor between 0 and 1 representing interpolation weight bootstrap_type: set to either 'hard' or 'soft' (default) Raises: ValueError: if bootstrap_type is not either 'hard' or 'soft'
__init__
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def _compute_loss(self, prediction_tensor, target_tensor, weights): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anch...
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing one-hot encoded classification targe...
_compute_loss
python
traveller59/second.pytorch
second/pytorch/core/losses.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/core/losses.py
MIT
def __init__(self, in_channels, out_channels, use_norm=True, last_layer=False): """ Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only ...
Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. This layer performs a similar role as second.pytorch.voxelnet.VFELayer. :param in_channels: <int>. Number of input channels. ...
__init__
python
traveller59/second.pytorch
second/pytorch/models/pointpillars.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/pointpillars.py
MIT
def __init__(self, num_input_features=4, use_norm=True, num_filters=(64, ), with_distance=False, voxel_size=(0.2, 0.2, 4), pc_range=(0, -40, -3, 70.4, 40, 1)): """ Pillar Feature Net. The networ...
Pillar Feature Net. The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a similar role to SECOND's second.pytorch.voxelnet.VoxelFeatureExtractor. :param num_input_features: <int>. Number of input features, either x, y, z or x, y, z, r....
__init__
python
traveller59/second.pytorch
second/pytorch/models/pointpillars.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/pointpillars.py
MIT
def __init__(self, output_shape, use_norm=True, num_input_features=64, num_filters_down1=[64], num_filters_down2=[64, 64], name='SpMiddle2K'): """ Point Pillar's Scatter. Converts learned featur...
Point Pillar's Scatter. Converts learned features from dense tensor to sparse pseudo image. This replaces SECOND's second.pytorch.voxelnet.SparseMiddleExtractor. :param output_shape: ([int]: 4). Required output shape of features. :param num_input_features: <int>. Number of input...
__init__
python
traveller59/second.pytorch
second/pytorch/models/pointpillars.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/pointpillars.py
MIT
def __init__(self, use_norm=True, num_class=2, layer_nums=(3, 5, 5), layer_strides=(2, 2, 2), num_filters=(128, 128, 256), upsample_strides=(1, 2, 4), num_upsample_filters=(256, 256, 256), ...
deprecated. exists for checkpoint backward compilability (SECOND v1.0)
__init__
python
traveller59/second.pytorch
second/pytorch/models/rpn.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/rpn.py
MIT
def __init__(self, use_norm=True, num_class=2, layer_nums=(3, 5, 5), layer_strides=(2, 2, 2), num_filters=(128, 128, 256), upsample_strides=(1, 2, 4), num_upsample_filters=(256, 256, 256), ...
upsample_strides support float: [0.25, 0.5, 1] if upsample_strides < 1, conv2d will be used instead of convtranspose2d.
__init__
python
traveller59/second.pytorch
second/pytorch/models/rpn.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/rpn.py
MIT
def network_forward(self, voxels, num_points, coors, batch_size): """this function is used for subclass. you can add custom network architecture by subclass VoxelNet class and override this function. Returns: preds_dict: { box_preds: ... cls_p...
this function is used for subclass. you can add custom network architecture by subclass VoxelNet class and override this function. Returns: preds_dict: { box_preds: ... cls_preds: ... dir_cls_preds: ... }
network_forward
python
traveller59/second.pytorch
second/pytorch/models/voxelnet.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/voxelnet.py
MIT
def forward(self, example): """module's forward should always accept dict and return loss. """ voxels = example["voxels"] num_points = example["num_points"] coors = example["coordinates"] if len(num_points.shape) == 2: # multi-gpu num_voxel_per_batch = exampl...
module's forward should always accept dict and return loss.
forward
python
traveller59/second.pytorch
second/pytorch/models/voxelnet.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/voxelnet.py
MIT
def predict(self, example, preds_dict): """start with v1.6.0, this function don't contain any kitti-specific code. Returns: predict: list of pred_dict. pred_dict: { box3d_lidar: [N, 7] 3d box. scores: [N] label_preds: [N] ...
start with v1.6.0, this function don't contain any kitti-specific code. Returns: predict: list of pred_dict. pred_dict: { box3d_lidar: [N, 7] 3d box. scores: [N] label_preds: [N] metadata: meta-data which contains dataset-sp...
predict
python
traveller59/second.pytorch
second/pytorch/models/voxelnet.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/voxelnet.py
MIT
def convert_norm_to_float(net): ''' BatchNorm layers to have parameters in single precision. Find all layers and convert them back to float. This can't be done with built in .apply as that function will apply fn to all modules, parameters, and buffers. Thus we wouldn't be...
BatchNorm layers to have parameters in single precision. Find all layers and convert them back to float. This can't be done with built in .apply as that function will apply fn to all modules, parameters, and buffers. Thus we wouldn't be able to guard the float conversion based o...
convert_norm_to_float
python
traveller59/second.pytorch
second/pytorch/models/voxelnet.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/voxelnet.py
MIT
def get_paddings_indicator(actual_num, max_num, axis=0): """Create boolean mask by actually number of a padded tensor. Args: actual_num ([type]): [description] max_num ([type]): [description] Returns: [type]: [description] """ actual_num = torch.unsqueeze(actual_num, axis ...
Create boolean mask by actually number of a padded tensor. Args: actual_num ([type]): [description] max_num ([type]): [description] Returns: [type]: [description]
get_paddings_indicator
python
traveller59/second.pytorch
second/pytorch/models/voxel_encoder.py
https://github.com/traveller59/second.pytorch/blob/master/second/pytorch/models/voxel_encoder.py
MIT
def box3d_overlap_kernel(boxes, qboxes, rinc, criterion=-1, z_axis=1, z_center=1.0): """ z_axis: the z (height) axis. z_center: unified z (height) center of box. """ ...
z_axis: the z (height) axis. z_center: unified z (height) center of box.
box3d_overlap_kernel
python
traveller59/second.pytorch
second/utils/eval.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/eval.py
MIT
def calculate_iou_partly(gt_annos, dt_annos, metric, num_parts=50, z_axis=1, z_center=1.0): """fast iou algorithm. this function can be used independently to do result analysis. Args...
fast iou algorithm. this function can be used independently to do result analysis. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py metric: eval type. 0: bbox, 1: bev, 2: 3d num_parts: int. a para...
calculate_iou_partly
python
traveller59/second.pytorch
second/utils/eval.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/eval.py
MIT
def eval_class_v3(gt_annos, dt_annos, current_classes, difficultys, metric, min_overlaps, compute_aos=False, z_axis=1, z_center=1.0, num_parts=50): """Kit...
Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py current_class: int, 0: car, 1: pedestrian, 2: cyclist difficulty: int. eval diffi...
eval_class_v3
python
traveller59/second.pytorch
second/utils/eval.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/eval.py
MIT
def get_official_eval_result(gt_annos, dt_annos, current_classes, difficultys=[0, 1, 2], z_axis=1, z_center=1.0): """ gt_annos and dt_annos must contains following...
gt_annos and dt_annos must contains following keys: [bbox, location, dimensions, rotation_y, score]
get_official_eval_result
python
traveller59/second.pytorch
second/utils/eval.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/eval.py
MIT
def flat_nested_json_dict(json_dict, sep=".") -> dict: """flat a nested json-like dict. this function make shadow copy. """ flatted = {} for k, v in json_dict.items(): if isinstance(v, dict): _flat_nested_json_dict(v, flatted, sep, str(k)) else: flatted[str(k)] = ...
flat a nested json-like dict. this function make shadow copy.
flat_nested_json_dict
python
traveller59/second.pytorch
second/utils/log_tool.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/log_tool.py
MIT
def log_text(self, text, step, tag="regular log"): """This function only add text to log.txt and tensorboard texts """ print(text) print(text, file=self.log_file) if step > self._text_current_gstep and self._text_current_gstep != -1: total_text = '\n'.join(self._tb_te...
This function only add text to log.txt and tensorboard texts
log_text
python
traveller59/second.pytorch
second/utils/log_tool.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/log_tool.py
MIT
def points_to_bev(points, voxel_size, coors_range, with_reflectivity=False, density_norm_num=16, max_voxels=40000): """convert kitti points(N, 4) to a bev map. return [C, H, W] map. this function based on algorithm in poin...
convert kitti points(N, 4) to a bev map. return [C, H, W] map. this function based on algorithm in points_to_voxel. takes 5ms in a reduced pointcloud with voxel_size=[0.1, 0.1, 0.8] Args: points: [N, ndim] float tensor. points[:, :3] contain xyz points and points[:, 3] contain reflectiv...
points_to_bev
python
traveller59/second.pytorch
second/utils/simplevis.py
https://github.com/traveller59/second.pytorch/blob/master/second/utils/simplevis.py
MIT
def scatter_nd(indices, updates, shape): """pytorch edition of tensorflow scatter_nd. this function don't contain except handle code. so use this carefully when indice repeats, don't support repeat add which is supported in tensorflow. """ ret = torch.zeros(*shape, dtype=updates.dtype, device=up...
pytorch edition of tensorflow scatter_nd. this function don't contain except handle code. so use this carefully when indice repeats, don't support repeat add which is supported in tensorflow.
scatter_nd
python
traveller59/second.pytorch
torchplus/ops/array_ops.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/ops/array_ops.py
MIT
def latest_checkpoint(model_dir, model_name): """return path of latest checkpoint in a model_dir Args: model_dir: string, indicate your model dir(save ckpts, summarys, logs, etc). model_name: name of your model. we find ckpts by name Returns: path: None if isn't exist or ...
return path of latest checkpoint in a model_dir Args: model_dir: string, indicate your model dir(save ckpts, summarys, logs, etc). model_name: name of your model. we find ckpts by name Returns: path: None if isn't exist or latest checkpoint path.
latest_checkpoint
python
traveller59/second.pytorch
torchplus/train/checkpoint.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/checkpoint.py
MIT
def save(model_dir, model, model_name, global_step, max_to_keep=8, keep_latest=True): """save a model into model_dir. Args: model_dir: string, indicate your model dir(save ckpts, summarys, logs, etc). model: torch.nn.Module instance. ...
save a model into model_dir. Args: model_dir: string, indicate your model dir(save ckpts, summarys, logs, etc). model: torch.nn.Module instance. model_name: name of your model. we find ckpts by name global_step: int, indicate current global step. max_to_keep: int,...
save
python
traveller59/second.pytorch
torchplus/train/checkpoint.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/checkpoint.py
MIT
def split_bn_bias(layer_groups): "Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups." split_groups = [] for l in layer_groups: l1, l2 = [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) ...
Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups.
split_bn_bias
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def get_master(layer_groups, flat_master: bool = False): "Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32." split_groups = split_bn_bias(layer_groups) model_params = [[ param for param in lg.parameters() if param.requires_grad ] for lg in split_gr...
Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32.
get_master
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def model_g2master_g(model_params, master_params, flat_master: bool = False) -> None: "Copy the `model_params` gradients to `master_params` for the optimizer step." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(master_group) !=...
Copy the `model_params` gradients to `master_params` for the optimizer step.
model_g2master_g
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def listify(p=None, q=None): "Make `p` listy and the same length as `q`." if p is None: p = [] elif isinstance(p, str): p = [p] elif not isinstance(p, Iterable): p = [p] n = q if type(q) == int else len(p) if q is None else len(q) if len(p) == 1: p = p * n assert len(p) == n, f'List len mism...
Make `p` listy and the same length as `q`.
listify
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def trainable_params(m: nn.Module): "Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res
Return list of trainable params in `m`.
trainable_params
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def create(cls, opt_func, lr, layer_groups, **kwargs): "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." split_groups = split_bn_bias(layer_groups) opt = opt_func([{ 'params': trainable_params(l), 'lr': 0 } for l in split_groups]) ...
Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`.
create
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def new(self, layer_groups): "Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters." opt_func = getattr(self, 'opt_func', self.opt.__class__) split_groups = split_bn_bias(layer_groups) opt = opt_func([{ 'params': trainable_params(l...
Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters.
new
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def step(self) -> None: "Set weight decay and step optimizer." # weight decay outside of optimizer step (AdamW) if self.true_wd: for lr, wd, pg1, pg2 in zip(self._lr, self._wd, self.opt.param_groups[::2], ...
Set weight decay and step optimizer.
step
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def clear(self): "Reset the state of the inner optimizer." sd = self.state_dict() sd['state'] = {} self.load_state_dict(sd)
Reset the state of the inner optimizer.
clear
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def beta(self, val: float) -> None: "Set beta (or alpha as makes sense for given optimizer)." if val is None: return if 'betas' in self.opt_keys: self.set_val('betas', (self._mom, listify(val, self._beta))) elif 'alpha' in self.opt_keys: self.set_val('alpha', list...
Set beta (or alpha as makes sense for given optimizer).
beta
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def read_defaults(self) -> None: "Read the values inside the optimizer for the hyper-parameters." self._beta = None if 'lr' in self.opt_keys: self._lr = self.read_val('lr') if 'momentum' in self.opt_keys: self._mom = self.read_val('momentum') if 'alpha' in self.opt_keys: self._be...
Read the values inside the optimizer for the hyper-parameters.
read_defaults
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def set_val(self, key: str, val, bn_groups: bool = True): "Set `val` inside the optimizer dictionary at `key`." if is_tuple(val): val = [(v1, v2) for v1, v2 in zip(*val)] for v, pg1, pg2 in zip(val, self.opt.param_groups[::2], self.opt.param_groups[1::2]): ...
Set `val` inside the optimizer dictionary at `key`.
set_val
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def read_val(self, key: str): "Read a hyperparameter `key` in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] return val
Read a hyperparameter `key` in the optimizer dictionary.
read_val
python
traveller59/second.pytorch
torchplus/train/fastai_optim.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/fastai_optim.py
MIT
def annealing_cos(start, end, pct): # print(pct, start, end) "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start - end) / 2 * cos_out
Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0.
annealing_cos
python
traveller59/second.pytorch
torchplus/train/learning_schedules_fastai.py
https://github.com/traveller59/second.pytorch/blob/master/torchplus/train/learning_schedules_fastai.py
MIT
def install_with_constraints(session, *args, **kwargs): """Install packages constrained by Poetry's lock file. This function is a wrapper for nox.sessions.Session.install. It invokes pip to install packages inside of the session's virtualenv. Additionally, pip is passed a constraints file generated fro...
Install packages constrained by Poetry's lock file. This function is a wrapper for nox.sessions.Session.install. It invokes pip to install packages inside of the session's virtualenv. Additionally, pip is passed a constraints file generated from Poetry's lock file, to ensure that the packages are pinne...
install_with_constraints
python
JakobGM/patito
noxfile.py
https://github.com/JakobGM/patito/blob/master/noxfile.py
MIT
def test(session): """Run test suite using pytest + coverage + xdoctest.""" if session.python == "3.9": # Only run test coverage and docstring tests on python 3.10 args = session.posargs # or ["--cov", "--xdoctest"] else: args = session.posargs session.run( "poetry", ...
Run test suite using pytest + coverage + xdoctest.
test
python
JakobGM/patito
noxfile.py
https://github.com/JakobGM/patito/blob/master/noxfile.py
MIT
def type_check(session): """Run type-checking on project using pyright.""" args = session.posargs or locations session.run( "poetry", "install", "--only=main", "--extras", "caching pandas", external=True, ) install_with_constraints( session, "m...
Run type-checking on project using pyright.
type_check
python
JakobGM/patito
noxfile.py
https://github.com/JakobGM/patito/blob/master/noxfile.py
MIT
def format(session): """Run the ruff formatter on the entire code base.""" args = session.posargs or locations install_with_constraints(session, "ruff") session.run("ruff format", *args)
Run the ruff formatter on the entire code base.
format
python
JakobGM/patito
noxfile.py
https://github.com/JakobGM/patito/blob/master/noxfile.py
MIT
def __init__(self, exc: Exception, loc: Union[str, "Loc"]) -> None: """Wrap an error in an ErrorWrapper.""" self.exc = exc self._loc = loc
Wrap an error in an ErrorWrapper.
__init__
python
JakobGM/patito
src/patito/exceptions.py
https://github.com/JakobGM/patito/blob/master/src/patito/exceptions.py
MIT
def collect( self, *args, **kwargs, ) -> DataFrame[ModelType]: # noqa: DAR101, DAR201 """Collect into a DataFrame. See documentation of polars.DataFrame.collect for full description of parameters. """ background = kwargs.pop("background", False) ...
Collect into a DataFrame. See documentation of polars.DataFrame.collect for full description of parameters.
collect
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def from_existing(cls: type[LDF], lf: pl.LazyFrame) -> LDF: """Construct a patito.DataFrame object from an existing polars.DataFrame object.""" if getattr(cls, "model", False): return cls.model.LazyFrame._from_pyldf(super().lazy()._ldf) # type: ignore return LazyFrame._from_pyldf(l...
Construct a patito.DataFrame object from an existing polars.DataFrame object.
from_existing
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def lazy(self: DataFrame[ModelType]) -> LazyFrame[ModelType]: """Convert DataFrame into LazyFrame. See documentation of polars.DataFrame.lazy() for full description. Returns: A new LazyFrame object. """ if getattr(self, "model", False): return self.mode...
Convert DataFrame into LazyFrame. See documentation of polars.DataFrame.lazy() for full description. Returns: A new LazyFrame object.
lazy
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def validate(self, columns: Sequence[str] | None = None, **kwargs: Any): """Validate the schema and content of the dataframe. You must invoke ``.set_model()`` before invoking ``.validate()`` in order to specify how the dataframe should be validated. Returns: DataFrame[Model...
Validate the schema and content of the dataframe. You must invoke ``.set_model()`` before invoking ``.validate()`` in order to specify how the dataframe should be validated. Returns: DataFrame[Model]: The original patito dataframe, if correctly validated. Raises: ...
validate
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def get(self, predicate: pl.Expr | None = None) -> ModelType: """Fetch the single row that matches the given polars predicate. If you expect a data frame to already consist of one single row, you can use ``.get()`` without any arguments to return that row. Raises: RowDoesNo...
Fetch the single row that matches the given polars predicate. If you expect a data frame to already consist of one single row, you can use ``.get()`` without any arguments to return that row. Raises: RowDoesNotExist: If zero rows evaluate to true for the given predicate. ...
get
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def iter_models( self, validate_df: bool = True, validate_model: bool = False ) -> ModelGenerator[ModelType]: """Iterate over all rows in the dataframe as pydantic models. Args: validate_df: If set to ``True``, the dataframe will be validated before making models...
Iterate over all rows in the dataframe as pydantic models. Args: validate_df: If set to ``True``, the dataframe will be validated before making models out of each row. If set to ``False``, beware that columns need to be the exact same as the model fields. ...
iter_models
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def _pydantic_model(self) -> type[Model]: """Dynamically construct patito model compliant with dataframe. Returns: A pydantic model class where all the rows have been specified as `typing.Any` fields. """ from patito.pydantic import Model pydantic_a...
Dynamically construct patito model compliant with dataframe. Returns: A pydantic model class where all the rows have been specified as `typing.Any` fields.
_pydantic_model
python
JakobGM/patito
src/patito/polars.py
https://github.com/JakobGM/patito/blob/master/src/patito/polars.py
MIT
def __init__(cls, name: str, bases: tuple, clsdict: dict, **kwargs) -> None: """Construct new patito model. Args: name: Name of model class. bases: Tuple of superclasses. clsdict: Dictionary containing class properties. **kwargs: Additional keyword argume...
Construct new patito model. Args: name: Name of model class. bases: Tuple of superclasses. clsdict: Dictionary containing class properties. **kwargs: Additional keyword arguments.
__init__
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def valid_dtypes( cls: type[Model], ) -> Mapping[str, frozenset[DataTypeClass | DataType]]: """Return a list of polars dtypes which Patito considers valid for each field. The first item of each list is the default dtype chosen by Patito. Returns: A dictionary mapping ea...
Return a list of polars dtypes which Patito considers valid for each field. The first item of each list is the default dtype chosen by Patito. Returns: A dictionary mapping each column string name to a list of valid dtypes. Raises: NotImplementedError: If one or more m...
valid_dtypes
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def defaults(cls: type[Model]) -> dict[str, Any]: """Return default field values specified on the model. Returns: Dictionary containing fields with their respective default values. Example: >>> from typing_extensions import Literal >>> import patito as pt ...
Return default field values specified on the model. Returns: Dictionary containing fields with their respective default values. Example: >>> from typing_extensions import Literal >>> import patito as pt >>> class Product(pt.Model): ... na...
defaults
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def non_nullable_columns(cls: type[Model]) -> set[str]: """Return names of those columns that are non-nullable in the schema. Returns: Set of column name strings. Example: >>> from typing import Optional >>> import patito as pt >>> class MyModel(...
Return names of those columns that are non-nullable in the schema. Returns: Set of column name strings. Example: >>> from typing import Optional >>> import patito as pt >>> class MyModel(pt.Model): ... nullable_field: Optional[int] ...
non_nullable_columns
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def unique_columns(cls: type[Model]) -> set[str]: """Return columns with uniqueness constraint. Returns: Set of column name strings. Example: >>> from typing import Optional >>> import patito as pt >>> class Product(pt.Model): ... ...
Return columns with uniqueness constraint. Returns: Set of column name strings. Example: >>> from typing import Optional >>> import patito as pt >>> class Product(pt.Model): ... product_id: int = pt.Field(unique=True) ... ...
unique_columns
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def derived_columns(cls: type[Model]) -> set[str]: """Return set of columns which are derived from other columns.""" infos = cls.column_infos return { column for column in cls.columns if infos[column].derived_from is not None }
Return set of columns which are derived from other columns.
derived_columns
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def validate_schema(cls: type[ModelType]): """Users should run this after defining or edit a model. We withhold the checks at model definition time to avoid expensive queries of the model schema.""" for column in cls.columns: col_info = cls.column_infos[column] field_info = cls.m...
Users should run this after defining or edit a model. We withhold the checks at model definition time to avoid expensive queries of the model schema.
validate_schema
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def from_row( cls: type[ModelType], row: pd.DataFrame | pl.DataFrame, validate: bool = True, ) -> ModelType: """Represent a single data frame row as a Patito model. Args: row: A dataframe, either polars and pandas, consisting of a single row. validate...
Represent a single data frame row as a Patito model. Args: row: A dataframe, either polars and pandas, consisting of a single row. validate: If ``False``, skip pydantic validation of the given row data. Returns: Model: A patito model representing the given row data....
from_row
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def _from_polars( cls: type[ModelType], dataframe: pl.DataFrame, validate: bool = True, ) -> ModelType: """Construct model from a single polars row. Args: dataframe: A polars dataframe consisting of one single row. validate: If ``True``, run the pydan...
Construct model from a single polars row. Args: dataframe: A polars dataframe consisting of one single row. validate: If ``True``, run the pydantic validators. If ``False``, pydantic will not cast any types in the resulting object. Returns: Model: A ...
_from_polars
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def validate( cls: type[ModelType], dataframe: pd.DataFrame | pl.DataFrame, columns: Sequence[str] | None = None, allow_missing_columns: bool = False, allow_superfluous_columns: bool = False, drop_superfluous_columns: bool = False, ) -> DataFrame[ModelType]: "...
Validate the schema and content of the given dataframe. Args: dataframe: Polars DataFrame to be validated. columns: Optional list of columns to validate. If not provided, all columns of the dataframe will be validated. allow_missing_columns: If True, missing ...
validate
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def iter_models( cls: type[ModelType], dataframe: pd.DataFrame | pl.DataFrame ) -> ModelGenerator[ModelType]: """Validate the dataframe and iterate over the rows, yielding Patito models. Args: dataframe: Polars or pandas DataFrame to be validated. Returns: L...
Validate the dataframe and iterate over the rows, yielding Patito models. Args: dataframe: Polars or pandas DataFrame to be validated. Returns: ListableIterator: An iterator of patito models over the validated data. Raises: patito.exceptions.DataFrameValida...
iter_models
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def example_value( # noqa: C901 cls, field: str | None = None, properties: dict[str, Any] | None = None, ) -> date | datetime | time | timedelta | float | int | str | None | Mapping | list: """Return a valid example value for the given model field. Args: field: ...
Return a valid example value for the given model field. Args: field: Field name identifier. properties: Pydantic v2-style properties dict Returns: A single value which is consistent with the given field definition. Raises: NotImplementedError: I...
example_value
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def example( cls: type[ModelType], **kwargs: Any, # noqa: ANN401 ) -> ModelType: """Produce model instance with filled dummy data for all unspecified fields. The type annotation of unspecified field is used to fill in type-correct dummy data, e.g. ``-1`` for ``int``, ``"dum...
Produce model instance with filled dummy data for all unspecified fields. The type annotation of unspecified field is used to fill in type-correct dummy data, e.g. ``-1`` for ``int``, ``"dummy_string"`` for ``str``, and so on... The first item of ``typing.Literal`` annotations are used...
example
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def pandas_examples( cls: type[ModelType], data: dict | Iterable, columns: Iterable[str] | None = None, ) -> pd.DataFrame: """Generate dataframe with dummy data for all unspecified columns. Offers the same API as the pandas.DataFrame constructor. Non-iterable values,...
Generate dataframe with dummy data for all unspecified columns. Offers the same API as the pandas.DataFrame constructor. Non-iterable values, besides strings, are repeated until they become as long as the iterable arguments. Args: data: Data to populate the dummy dataframe ...
pandas_examples
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def join( cls: type[Model], other: type[Model], how: Literal["inner", "left", "outer", "asof", "cross", "semi", "anti"], ) -> type[Model]: """Dynamically create a new model compatible with an SQL Join operation. For instance, ``ModelA.join(ModelB, how="left")`` will create a...
Dynamically create a new model compatible with an SQL Join operation. For instance, ``ModelA.join(ModelB, how="left")`` will create a model containing all the fields of ``ModelA`` and ``ModelB``, but where all fields of ``ModelB`` has been made ``Optional``, i.e. nullable. This is consistent wi...
join
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def select(cls: type[ModelType], fields: str | Iterable[str]) -> type[Model]: """Create a new model consisting of only a subset of the model fields. Args: fields: A single field name as a string or a collection of strings. Returns: A new model containing only the fields...
Create a new model consisting of only a subset of the model fields. Args: fields: A single field name as a string or a collection of strings. Returns: A new model containing only the fields specified by ``fields``. Raises: ValueError: If one or more non-exi...
select
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def drop(cls: type[ModelType], name: str | Iterable[str]) -> type[Model]: """Return a new model where one or more fields are excluded. Args: name: A single string field name, or a list of such field names, which will be dropped. Returns: New model class ...
Return a new model where one or more fields are excluded. Args: name: A single string field name, or a list of such field names, which will be dropped. Returns: New model class where the given fields have been removed. Examples: >>> class My...
drop
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def prefix(cls: type[ModelType], prefix: str) -> type[Model]: """Return a new model where all field names have been prefixed. Args: prefix: String prefix to add to all field names. Returns: New model class with all the same fields only prefixed with the given prefix. ...
Return a new model where all field names have been prefixed. Args: prefix: String prefix to add to all field names. Returns: New model class with all the same fields only prefixed with the given prefix. Example: >>> class MyModel(Model): ... ...
prefix
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def suffix(cls: type[ModelType], suffix: str) -> type[Model]: """Return a new model where all field names have been suffixed. Args: suffix: String suffix to add to all field names. Returns: New model class with all the same fields only suffixed with the given ...
Return a new model where all field names have been suffixed. Args: suffix: String suffix to add to all field names. Returns: New model class with all the same fields only suffixed with the given suffix. Example: >>> class MyModel(Model): ...
suffix
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def rename(cls: type[ModelType], mapping: dict[str, str]) -> type[Model]: """Return a new model class where the specified fields have been renamed. Args: mapping: A dictionary where the keys are the old field names and the values are the new names. Returns: ...
Return a new model class where the specified fields have been renamed. Args: mapping: A dictionary where the keys are the old field names and the values are the new names. Returns: A new model class where the given fields have been renamed. Raises: ...
rename
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def with_fields( cls: type[ModelType], **field_definitions: Any, # noqa: ANN401 ) -> type[Model]: """Return a new model class where the given fields have been added. Args: **field_definitions: the keywords are of the form: ``field_name=(field_type, field...
Return a new model class where the given fields have been added. Args: **field_definitions: the keywords are of the form: ``field_name=(field_type, field_default)``. Specify ``...`` if no default value is provided. For instance, ``column_name=(int, .....
with_fields
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def _derive_model( cls: type[ModelType], model_name: str, field_mapping: dict[str, Any], ) -> type[Model]: """Derive a new model with new field definitions. Args: model_name: Name of new model class. field_mapping: A mapping where the keys represent f...
Derive a new model with new field definitions. Args: model_name: Name of new model class. field_mapping: A mapping where the keys represent field names and the values represent field definitions. String field definitions are used as pointers to the origin...
_derive_model
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def Field( *args: Any, **kwargs: Any ) -> Any: # annotate with Any to make the downstream type annotations happy """Annotate model field with additional type and validation information. This class is built on ``pydantic.Field`` and you can find the list of parameters in the `API reference <https://doc...
Annotate model field with additional type and validation information. This class is built on ``pydantic.Field`` and you can find the list of parameters in the `API reference <https://docs.pydantic.dev/latest/api/fields/>`_. Patito adds additional parameters which are used when validating dataframes, th...
Field
python
JakobGM/patito
src/patito/pydantic.py
https://github.com/JakobGM/patito/blob/master/src/patito/pydantic.py
MIT
def _transform_df(dataframe: pl.DataFrame, schema: type[Model]) -> pl.DataFrame: """Transform any properties of the dataframe according to the model. Currently only supports using AliasGenerator to transform column names to match a model. Args: dataframe: Polars DataFrame to be validated. ...
Transform any properties of the dataframe according to the model. Currently only supports using AliasGenerator to transform column names to match a model. Args: dataframe: Polars DataFrame to be validated. schema: Patito model which specifies how the dataframe should be structured.
_transform_df
python
JakobGM/patito
src/patito/validators.py
https://github.com/JakobGM/patito/blob/master/src/patito/validators.py
MIT
def _find_errors( # noqa: C901 dataframe: pl.DataFrame, schema: type[Model], columns: Sequence[str] | None = None, allow_missing_columns: bool = False, allow_superfluous_columns: bool = False, ) -> list[ErrorWrapper]: """Validate the given dataframe. Args: dataframe: Polars DataFra...
Validate the given dataframe. Args: dataframe: Polars DataFrame to be validated. schema: Patito model which specifies how the dataframe should be structured. columns: If specified, only validate the given columns. Missing columns will check if any specified columns are missing f...
_find_errors
python
JakobGM/patito
src/patito/validators.py
https://github.com/JakobGM/patito/blob/master/src/patito/validators.py
MIT
def validate( dataframe: pd.DataFrame | pl.DataFrame, schema: type[Model], columns: Sequence[str] | None = None, allow_missing_columns: bool = False, allow_superfluous_columns: bool = False, drop_superfluous_columns: bool = False, ) -> pl.DataFrame: """Validate the given dataframe. Args...
Validate the given dataframe. Args: dataframe: Polars DataFrame to be validated. schema: Patito model which specifies how the dataframe should be structured. columns: Optional list of columns to validate. If not provided, all columns of the dataframe will be validated. a...
validate
python
JakobGM/patito
src/patito/validators.py
https://github.com/JakobGM/patito/blob/master/src/patito/validators.py
MIT
def expr_deserializer( expr: str | pl.Expr | list[pl.Expr] | None, ) -> pl.Expr | list[pl.Expr] | None: """Deserialize a polars expression or list thereof from json. This is applied both during deserialization and validation. """ if expr is None: return None elif isinstance(expr, pl.Exp...
Deserialize a polars expression or list thereof from json. This is applied both during deserialization and validation.
expr_deserializer
python
JakobGM/patito
src/patito/_pydantic/column_info.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py
MIT
def expr_or_col_name_deserializer(expr: str | pl.Expr | None) -> pl.Expr | str | None: """Deserialize a polars expression or column name from json. This is applied both during deserialization and validation. """ if expr is None: return None elif isinstance(expr, pl.Expr): return exp...
Deserialize a polars expression or column name from json. This is applied both during deserialization and validation.
expr_or_col_name_deserializer
python
JakobGM/patito
src/patito/_pydantic/column_info.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py
MIT
def __repr__(self) -> str: """Print only Field attributes whose values are not default (mainly None).""" not_default_field = { field: getattr(self, field) for field in self.model_fields if getattr(self, field) is not self.model_fields[field].default } ...
Print only Field attributes whose values are not default (mainly None).
__repr__
python
JakobGM/patito
src/patito/_pydantic/column_info.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py
MIT
def __repr_args__(self) -> "ReprArgs": """Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden. Can either return: * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` * or, just values, e.g.: `[(None, 'foo'), (No...
Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden. Can either return: * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
__repr_args__
python
JakobGM/patito
src/patito/_pydantic/repr.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py
MIT
def __pretty__( self, fmt: Callable[[Any], Any], **kwargs: Any ) -> Generator[Any, None, None]: """Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects.""" yield self.__repr_name__() + "(" yield 1 for name, value in ...
Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects.
__pretty__
python
JakobGM/patito
src/patito/_pydantic/repr.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py
MIT
def display_as_type(obj: Any) -> str: """Pretty representation of a type, should be as close as possible to the original type definition string. Takes some logic from `typing._type_repr`. """ if isinstance(obj, types.FunctionType): return obj.__name__ elif obj is ...: return "..." ...
Pretty representation of a type, should be as close as possible to the original type definition string. Takes some logic from `typing._type_repr`.
display_as_type
python
JakobGM/patito
src/patito/_pydantic/repr.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py
MIT
def schema_for_model(cls: type[ModelType]) -> dict[str, dict[str, Any]]: """Return schema properties where definition references have been resolved. Returns: Field information as a dictionary where the keys are field names and the values are dictionaries containing metadata information abou...
Return schema properties where definition references have been resolved. Returns: Field information as a dictionary where the keys are field names and the values are dictionaries containing metadata information about the field itself. Raises: TypeError: if a field is an...
schema_for_model
python
JakobGM/patito
src/patito/_pydantic/schema.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/schema.py
MIT
def validate_polars_dtype( annotation: type[Any] | None, dtype: DataType | DataTypeClass | None, column: str | None = None, ) -> None: """Check that the polars dtype is valid for the given annotation. Raises ValueError if not. Args: annotation (type[Any] | None): python type annotation ...
Check that the polars dtype is valid for the given annotation. Raises ValueError if not. Args: annotation (type[Any] | None): python type annotation dtype (DataType | DataTypeClass | None): polars dtype column (Optional[str], optional): column name. Defaults to None.
validate_polars_dtype
python
JakobGM/patito
src/patito/_pydantic/dtypes/dtypes.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/dtypes.py
MIT
def validate_annotation( annotation: type[Any] | Any | None, column: str | None = None ) -> None: """Check that the provided annotation has polars/patito support (we can resolve it to a default dtype). Raises ValueError if not. Args: annotation (type[Any] | None): python type annotation col...
Check that the provided annotation has polars/patito support (we can resolve it to a default dtype). Raises ValueError if not. Args: annotation (type[Any] | None): python type annotation column (Optional[str], optional): column name. Defaults to None.
validate_annotation
python
JakobGM/patito
src/patito/_pydantic/dtypes/dtypes.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/dtypes.py
MIT
def is_optional(type_annotation: type[Any] | Any | None) -> bool: """Return True if the given type annotation is an Optional annotation. Args: type_annotation: The type annotation to be checked. Returns: True if the outermost type is Optional. """ return (get_origin(type_annotatio...
Return True if the given type annotation is an Optional annotation. Args: type_annotation: The type annotation to be checked. Returns: True if the outermost type is Optional.
is_optional
python
JakobGM/patito
src/patito/_pydantic/dtypes/utils.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/utils.py
MIT
def unwrap_optional(type_annotation: type[Any] | Any) -> type: """Return the inner, wrapped type of an Optional. Is a no-op for non-Optional types. Args: type_annotation: The type annotation to be dewrapped. Returns: The input type, but with the outermost Optional removed. """ ...
Return the inner, wrapped type of an Optional. Is a no-op for non-Optional types. Args: type_annotation: The type annotation to be dewrapped. Returns: The input type, but with the outermost Optional removed.
unwrap_optional
python
JakobGM/patito
src/patito/_pydantic/dtypes/utils.py
https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/utils.py
MIT
def test_valids_basic_annotations() -> None: """Test type annotations match polars dtypes.""" # base types assert DtypeResolver(str).valid_polars_dtypes() == STRING_DTYPES assert DtypeResolver(int).valid_polars_dtypes() == DataTypeGroup(INTEGER_DTYPES) assert DtypeResolver(float).valid_polars_dtypes...
Test type annotations match polars dtypes.
test_valids_basic_annotations
python
JakobGM/patito
tests/test_dtypes.py
https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py
MIT
def test_valids_nested_annotations() -> None: """Test type annotations match nested polars types like List.""" assert len(DtypeResolver(list).valid_polars_dtypes()) == 0 # needs inner annotation assert ( DtypeResolver(tuple).valid_polars_dtypes() == DtypeResolver(list).valid_polars_dtypes()...
Test type annotations match nested polars types like List.
test_valids_nested_annotations
python
JakobGM/patito
tests/test_dtypes.py
https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py
MIT
def test_dtype_validation() -> None: """Ensure python types match polars types.""" validate_polars_dtype(int, pl.Int16) # no issue with pytest.raises(ValueError, match="Invalid dtype"): validate_polars_dtype(int, pl.Float64) with pytest.raises(ValueError, match="Invalid dtype"): valid...
Ensure python types match polars types.
test_dtype_validation
python
JakobGM/patito
tests/test_dtypes.py
https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py
MIT