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 _remove_reduction_blocks(self, architecture): """Removes any reduction blocks from the architecture.""" result = [] for block in architecture: if self._is_reduction_block(block): continue result.append(block) return np.array(result)
Removes any reduction blocks from the architecture.
_remove_reduction_blocks
python
google/model_search
model_search/search/constrained_descent.py
https://github.com/google/model_search/blob/master/model_search/search/constrained_descent.py
Apache-2.0
def _add_reduction_blocks(self, architecture, every, reduction_type): """Adds a reduction block of given type after `every` few blocks.""" result = [] for i, block in enumerate(architecture): result.append(block) if (i + 1) % every == 0: result.append(block_builder.BlockType[reduction_ty...
Adds a reduction block of given type after `every` few blocks.
_add_reduction_blocks
python
google/model_search
model_search/search/constrained_descent.py
https://github.com/google/model_search/blob/master/model_search/search/constrained_descent.py
Apache-2.0
def _get_allowed_depth(self, num_completed_trials): """Returns the allowed depth not including reductions and flatten blocks.""" if self._phoenix_spec.replicate_cell: allowed_depth = self._phoenix_spec.maximum_depth else: allowed_depth = common.get_allowed_depth( num_completed_trials, ...
Returns the allowed depth not including reductions and flatten blocks.
_get_allowed_depth
python
google/model_search
model_search/search/constrained_descent.py
https://github.com/google/model_search/blob/master/model_search/search/constrained_descent.py
Apache-2.0
def get_suggestion(self, trials, hparams, my_trial_id=None, model_dir=None): """See the base class for details.""" del my_trial_id # Unused. new_block = block_builder.BlockType[common.get_random_block( self._phoenix_spec.blocks_to_use)] if self._is_reduction_block(new_block): raise Value...
See the base class for details.
get_suggestion
python
google/model_search
model_search/search/constrained_descent.py
https://github.com/google/model_search/blob/master/model_search/search/constrained_descent.py
Apache-2.0
def __init__(self, phoenix_spec, alpha=0.05, degree=3, n_mono=5, min_for_regression=3, num_random_samples=10000, seed=None): """Initializes the Harmonica instance. Args: phoenix_spec: PhoenixSpec prot...
Initializes the Harmonica instance. Args: phoenix_spec: PhoenixSpec proto. alpha: The alpha of lasso solver (please read on lasso solver to understand this constant. In a nutshell, this control regularization for lasso. alpha equal zero means regular linear regression - however, try ...
__init__
python
google/model_search
model_search/search/harmonica.py
https://github.com/google/model_search/blob/master/model_search/search/harmonica.py
Apache-2.0
def translate_architecture_to_feature_assignment(self, architecture): """Translates the trial architecture to a {-1, 1} assignment.""" x = np.empty(self._num_params) x.fill(-1) depth = 0 for block in architecture: # These are connector blocks (non-trainable) that connect CNN and DNN. # T...
Translates the trial architecture to a {-1, 1} assignment.
translate_architecture_to_feature_assignment
python
google/model_search
model_search/search/harmonica.py
https://github.com/google/model_search/blob/master/model_search/search/harmonica.py
Apache-2.0
def get_good_architecture(self, num_samples, coefficients): """Randomly samples architectures, predict loss, and return minimal.""" if self._seed: np.random.seed(seed=self._seed) assignments = [] architectures = [] for _ in range(num_samples): rand_arc = np.random.randint( len...
Randomly samples architectures, predict loss, and return minimal.
get_good_architecture
python
google/model_search
model_search/search/harmonica.py
https://github.com/google/model_search/blob/master/model_search/search/harmonica.py
Apache-2.0
def get_suggestion(self, trials, hparams, my_trial_id=None, model_dir=None): """Suggests a new architecture for Phoenix using the harmonica model. For details please see: https://arxiv.org/pdf/1706.00764.pdf Args: trials: a list of metadata.trial.Trial hparams: The suggested hparams. ...
Suggests a new architecture for Phoenix using the harmonica model. For details please see: https://arxiv.org/pdf/1706.00764.pdf Args: trials: a list of metadata.trial.Trial hparams: The suggested hparams. my_trial_id: integer - the trial id which is making the call. model_dir: stri...
get_suggestion
python
google/model_search
model_search/search/harmonica.py
https://github.com/google/model_search/blob/master/model_search/search/harmonica.py
Apache-2.0
def _one_nonzero_per_row(matrix): """For each row in matrix, randomly zero all but one of the nonzero values.""" # TODO(b/172564129): can it be done without a loop? out = np.zeros_like(matrix) for i in range(matrix.shape[0]): nonzero_indices = np.flatnonzero(matrix[i]) keep = np.random.choice(nonzero_in...
For each row in matrix, randomly zero all but one of the nonzero values.
_one_nonzero_per_row
python
google/model_search
model_search/search/linear_model.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model.py
Apache-2.0
def _predict_best_architecture(self, architectures, losses): """Fits a linear model for loss = f(architecture) and finds its argmin. Main computational subroutine for trial data already in feature vector form. Args: architectures: (n_trials, depth) integer matrix of architectures. losses: (n_t...
Fits a linear model for loss = f(architecture) and finds its argmin. Main computational subroutine for trial data already in feature vector form. Args: architectures: (n_trials, depth) integer matrix of architectures. losses: (n_trials) positive validation error. Returns: predicted_loss...
_predict_best_architecture
python
google/model_search
model_search/search/linear_model.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model.py
Apache-2.0
def _suggest_by_padding(self, architectures, losses): """Pads architectures with EMPTY_BLOCK and call _predict_best_architecture. Variable-length architectures are padded into fixed dimensionality at either head or base, as determined by spec.network_alignment. Args: architectures: List of itera...
Pads architectures with EMPTY_BLOCK and call _predict_best_architecture. Variable-length architectures are padded into fixed dimensionality at either head or base, as determined by spec.network_alignment. Args: architectures: List of iterables of block_builder.BlockType values (or integers)....
_suggest_by_padding
python
google/model_search
model_search/search/linear_model.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model.py
Apache-2.0
def _pad_architecture(self, arch, maxdepth): """Pad with empty blocks according to spec network alignment.""" empties = [block_builder.BlockType.EMPTY_BLOCK.value] * ( maxdepth - len(arch)) align = self._phoenix_spec.linear_model.network_alignment if align == phoenix_spec_pb2.LinearModelSpec.NET...
Pad with empty blocks according to spec network alignment.
_pad_architecture
python
google/model_search
model_search/search/linear_model.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model.py
Apache-2.0
def _get_suggestion(architectures, blocks_to_use, losses, grow=False, remove_outliers=False, pass_flatten=False): """Testing subroutine to handle boilerplate Trial construction, dirs, etc.""" # TODO(b/172564129): Fi...
Testing subroutine to handle boilerplate Trial construction, dirs, etc.
_get_suggestion
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_one_trial(self): """Degenerate case: one data point. Just make sure it doesn't explode.""" blocks_to_use = np.arange(1, 4) architectures = np.array([[1, 2, 1]]) losses = ([1.0]) best = _get_suggestion(architectures, blocks_to_use, losses) # The degenerate model might end up suggesting s...
Degenerate case: one data point. Just make sure it doesn't explode.
test_one_trial
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_two_trials(self): """Underdetermined case - should find pattern in subset of dimensions.""" blocks_to_use = np.arange(1, 4) architectures = np.array([[1, 2, 1], [1, 1, 2]]) losses = ([1.0, 2.0]) best = _get_suggestion(architectures, blocks_to_use, losses) # The model won't be able to pr...
Underdetermined case - should find pattern in subset of dimensions.
test_two_trials
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_three_trials(self): """Suggestion should combine trial 1 and 2's improvements over trial 0.""" blocks_to_use = np.arange(1, 4) architectures = np.array([[1, 1, 1], [1, 2, 1], [1, 1, 2]]) losses = ([2.0, 1.0, 1.0]) best = _get_suggestion(architectures, blocks_to_use, losses) self.assertE...
Suggestion should combine trial 1 and 2's improvements over trial 0.
test_three_trials
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_loss_equals_id(self): """Larger-scale overdetermined case with easily predicted model output. Each block contributes its own id worth of loss, so tower of all block 1 should be best. """ nblocks = 4 blocks_to_use = np.arange(1, nblocks + 1) depth = 9 ntrials = 10 * nblocks * de...
Larger-scale overdetermined case with easily predicted model output. Each block contributes its own id worth of loss, so tower of all block 1 should be best.
test_loss_equals_id
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_randomized(self): """Overdetermined case with randomly chosen linear model. Hard to predict the argmin, but can check its expected performance. """ np.random.seed(0) nblocks = 10 blocks_to_use = np.arange(1, nblocks + 1) depth = 10 ntrials = 2 * nblocks * depth architecture...
Overdetermined case with randomly chosen linear model. Hard to predict the argmin, but can check its expected performance.
test_randomized
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_ids_nonrange(self): """Make sure we correctly handle non-contiguous range of blocks.""" np.random.seed(0) # TODO(b/172564129): This test is not correct. block_ints = [ b.value for b in block_builder.BlockType if b.value not in [126, 127, 128, 129] ] blocks_to_use...
Make sure we correctly handle non-contiguous range of blocks.
test_ids_nonrange
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_flatten_modelfitting(self): """Ensure that we correctly deal with the flatten block in fitting. 1) Flatten blocks won't be in spec.blocks_to_use, even though the trial architectures loaded from filesystem will contain them. 2) The model shouldn't try to place a flatten block, since there i...
Ensure that we correctly deal with the flatten block in fitting. 1) Flatten blocks won't be in spec.blocks_to_use, even though the trial architectures loaded from filesystem will contain them. 2) The model shouldn't try to place a flatten block, since there is only one valid position at the conv...
test_flatten_modelfitting
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def test_flatten_output(self, grow): """Ensure we output suggestions with a flatten block correctly placed.""" # Make trials s.t. the linear model will output all convolutions. architectures = [ np.repeat(block_builder.BlockType.EMPTY_BLOCK, 4), np.repeat(block_builder.BlockType.CONVOLUTION...
Ensure we output suggestions with a flatten block correctly placed.
test_flatten_output
python
google/model_search
model_search/search/linear_model_test.py
https://github.com/google/model_search/blob/master/model_search/search/linear_model_test.py
Apache-2.0
def get_suggestion(self, trials, hparams, my_trial_id=None, model_dir=None): """Suggests a new architecture for a Phoenix model. Note that this algorithm performs on top of hparams oracle. Meaning, it will receive suggested trial hparams, and determine the Phoenix architecture. This algorithm has the f...
Suggests a new architecture for a Phoenix model. Note that this algorithm performs on top of hparams oracle. Meaning, it will receive suggested trial hparams, and determine the Phoenix architecture. This algorithm has the final say. We implemented a simple "Identity" algorithm, that passes oracle's sug...
get_suggestion
python
google/model_search
model_search/search/search_algorithm.py
https://github.com/google/model_search/blob/master/model_search/search/search_algorithm.py
Apache-2.0
def create_spec(problem_type, complexity_thresholds=None, max_depth=None, min_depth=None, blocks_to_use=None): """Creates a phoenix_spec_pb2.PhoenixSpec with the given options.""" output = phoenix_spec_pb2.PhoenixSpec() if complexity_thresholds is no...
Creates a phoenix_spec_pb2.PhoenixSpec with the given options.
create_spec
python
google/model_search
model_search/search/test_utils.py
https://github.com/google/model_search/blob/master/model_search/search/test_utils.py
Apache-2.0
def is_mutation_or_equal(previous_architecture, new_architecture): """Returns whether if new arch is mutation of or equal to previous arch.""" if previous_architecture.shape != new_architecture.shape: return False mismatch = ( previous_architecture.size - np.sum(previous_architecture == new_archit...
Returns whether if new arch is mutation of or equal to previous arch.
is_mutation_or_equal
python
google/model_search
model_search/search/test_utils.py
https://github.com/google/model_search/blob/master/model_search/search/test_utils.py
Apache-2.0
def str2bool(v): """ Converts string to bool type; enables command line arguments in the format of '--arg1 true --arg2 false' """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): ...
Converts string to bool type; enables command line arguments in the format of '--arg1 true --arg2 false'
str2bool
python
Jingkang50/OpenOOD
openood/attacks/misc.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/attacks/misc.py
MIT
def __init__( self, net: nn.Module, id_name: str, data_root: str = './data', config_root: str = './configs', preprocessor: Callable = None, batch_size: int = 200, shuffle: bool = False, num_workers: int = 4, ) -> None: """A unified, eas...
A unified, easy-to-use API for evaluating (most) discriminative OOD detection methods. Args: net (nn.Module): The base classifier. id_name (str): The name of the in-distribution dataset. data_root (str, optional): The p...
__init__
python
Jingkang50/OpenOOD
openood/evaluation_api/attackdataset.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/evaluation_api/attackdataset.py
MIT
def topk(output, target, ks=(1, )): """Returns one boolean vector for each k, whether the target is within the output's top-k.""" _, pred = output.topk(max(ks), 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) return [correct[:k].max(0)[0] for k in ks]
Returns one boolean vector for each k, whether the target is within the output's top-k.
topk
python
Jingkang50/OpenOOD
openood/evaluators/mos_evaluator.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/evaluators/mos_evaluator.py
MIT
def __init__(self, config: Config): """OOD Evaluator. Args: config (Config): Config file from """ super(OODEvaluator, self).__init__(config) self.id_pred = None self.id_conf = None self.id_gt = None
OOD Evaluator. Args: config (Config): Config file from
__init__
python
Jingkang50/OpenOOD
openood/evaluators/ood_evaluator.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/evaluators/ood_evaluator.py
MIT
def eval_acc(self, net: nn.Module, data_loader: DataLoader, postprocessor: BasePostprocessor = None, epoch_idx: int = -1, fsood: bool = False, csid_data_loaders: DataLoader = None): """Returns the accuracy scor...
Returns the accuracy score of the labels and predictions. :return: float
eval_acc
python
Jingkang50/OpenOOD
openood/evaluators/ood_evaluator.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/evaluators/ood_evaluator.py
MIT
def _get_item_by_idx(self, iterator, idx): """Get the idx-th item of the iterator.""" size = len(self) idx = operator.index(idx) if not -size <= idx < size: raise IndexError('index {} is out of range'.format(idx)) idx %= size return next(islice(iterator, idx, ...
Get the idx-th item of the iterator.
_get_item_by_idx
python
Jingkang50/OpenOOD
openood/networks/arpl_net.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/networks/arpl_net.py
MIT
def _make_layer(self, block, planes, num_blocks, stride): ''' strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion ''' norm_lay...
strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion
_make_layer
python
Jingkang50/OpenOOD
openood/networks/resnet18_256x256.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/networks/resnet18_256x256.py
MIT
def __init__(self, backbone, feature_size, num_classes, dof=16): ''' dof: degree of freedom of variance ''' super(RTSNet, self).__init__() self.backbone = backbone self.feature_size = feature_size self.num_classes = num_classes self.dof = dof self....
dof: degree of freedom of variance
__init__
python
Jingkang50/OpenOOD
openood/networks/rts_net.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/networks/rts_net.py
MIT
def get_GMM_stat(model, train_loader, num_clusters_list, feature_type_list, reduce_dim_list): """ Compute GMM. Args: model (nn.Module): pretrained model to extract features train_loader (DataLoader): use all training data to perform GMM num_clusters_list (list): number o...
Compute GMM. Args: model (nn.Module): pretrained model to extract features train_loader (DataLoader): use all training data to perform GMM num_clusters_list (list): number of clusters for each layer feature_type_list (list): feature type for each layer reduce_dim_list (list)...
get_GMM_stat
python
Jingkang50/OpenOOD
openood/postprocessors/gmm_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/gmm_postprocessor.py
MIT
def compute_GMM_score(model, data, feature_mean, feature_prec, component_weight, transform_matrix, layer_idx, feature_type_list, return_pred=Fal...
Compute GMM. Args: model (nn.Module): pretrained model to extract features data (DataLoader): input one training batch feature_mean (list): a list of torch.cuda.Tensor() feature_prec (list): a list of torch.cuda.Tensor() component_weight (list): a list of torch.cuda.Tensor()...
compute_GMM_score
python
Jingkang50/OpenOOD
openood/postprocessors/gmm_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/gmm_postprocessor.py
MIT
def get_MDS_stat(model, train_loader, num_classes, feature_type_list, reduce_dim_list): """ Compute sample mean and precision (inverse of covariance) return: sample_class_mean: list of class mean precision: list of precisions transform_matrix_list: list of transform_matr...
Compute sample mean and precision (inverse of covariance) return: sample_class_mean: list of class mean precision: list of precisions transform_matrix_list: list of transform_matrix
get_MDS_stat
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def get_Mahalanobis_scores(model, test_loader, num_classes, sample_mean, precision, transform_matrix, layer_index, feature_type_list, magnitude): ''' Compute the proposed Mahalanobis confidence score on input dataset return: Mahalanobis score from layer_...
Compute the proposed Mahalanobis confidence score on input dataset return: Mahalanobis score from layer_index
get_Mahalanobis_scores
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def _cov(X, shrinkage=None, covariance_estimator=None): """Estimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. shrinkage : {'empirical', 'auto'} or float, default=None Shrinkage parameter,...
Estimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. shrinkage : {'empirical', 'auto'} or float, default=None Shrinkage parameter, possible values: - None or 'empirical': no shrinkage...
_cov
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def _class_means(X, y): """Compute class means. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Returns ------- means : array-like of shape (n_classes, n_featur...
Compute class means. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Returns ------- means : array-like of shape (n_classes, n_features) Class means.
_class_means
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def _class_cov(X, y, priors, shrinkage=None, covariance_estimator=None): """Compute weighted within-class covariance matrix. The per-class covariance are weighted by the class priors. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shap...
Compute weighted within-class covariance matrix. The per-class covariance are weighted by the class priors. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. priors : arr...
_class_cov
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def _solve_eigen(self, X, y, shrinkage): """Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduc...
Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduction (with optional shrinkage). Parameters ...
_solve_eigen
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def compute_channel_distances(mavs, features, eu_weight=0.5): """ Input: mavs (channel, C) features: (N, channel, C) Output: channel_distances: dict of distance distribution from MAV for each channel. """ eucos_dists, eu_dists, cos_dists = [], [], [] for channel, ...
Input: mavs (channel, C) features: (N, channel, C) Output: channel_distances: dict of distance distribution from MAV for each channel.
compute_channel_distances
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def fit_weibull(means, dists, categories, tailsize=20, distance_type='eucos'): """ Input: means (C, channel, C) dists (N_c, channel, C) * C Output: weibull_model : Perform EVT based analysis using tails of distances and save weibull model parameters for re-adj...
Input: means (C, channel, C) dists (N_c, channel, C) * C Output: weibull_model : Perform EVT based analysis using tails of distances and save weibull model parameters for re-adjusting softmax scores
fit_weibull
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def openmax(weibull_model, categories, input_score, eu_weight, alpha=10, distance_type='eucos'): """Re-calibrate scores via OpenMax layer Output: openmax probability and softmax probability """ nb_classes = len(categories) ranked_l...
Re-calibrate scores via OpenMax layer Output: openmax probability and softmax probability
openmax
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def update_distances(self, cluster_centers, only_new=True, reset_dist=False): """Update min distances given cluster centers. Args: cluster_centers: indices of cluster centers only_new: only calculate distance...
Update min distances given cluster centers. Args: cluster_centers: indices of cluster centers only_new: only calculate distance for newly selected points and update min_distances. rest_dist: whether to reset min_distances.
update_distances
python
Jingkang50/OpenOOD
openood/postprocessors/patchcore_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/patchcore_postprocessor.py
MIT
def select_batch_(self, model, already_selected, N, **kwargs): """Diversity promoting active learning method that greedily forms a batch to minimize the maximum distance to a cluster center among all unlabeled datapoints. Args: model: model with scikit-like API with decision_f...
Diversity promoting active learning method that greedily forms a batch to minimize the maximum distance to a cluster center among all unlabeled datapoints. Args: model: model with scikit-like API with decision_function implemented already_selected: index of datapoints alread...
select_batch_
python
Jingkang50/OpenOOD
openood/postprocessors/patchcore_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/patchcore_postprocessor.py
MIT
def kernel(feat, feat_t, prob, prob_t, split=2): """Kernel function (assume feature is normalized)""" size = ceil(len(feat_t) / split) rel_full = [] for i in range(split): feat_t_ = feat_t[i * size:(i + 1) * size] prob_t_ = prob_t[i * size:(i + 1) * size] with torch.no_grad(): ...
Kernel function (assume feature is normalized)
kernel
python
Jingkang50/OpenOOD
openood/postprocessors/relation_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/relation_postprocessor.py
MIT
def get_relation(feat, feat_t, prob, prob_t, pow=1, chunk=50, thres=0.03): """Get relation values (top-k and summation) Args: feat (torch.Tensor [N,D]): features of the source data feat_t (torch.Tensor [N',D]): features of the target data prob (torch.Tensor [N,C]): probabilty vectors of...
Get relation values (top-k and summation) Args: feat (torch.Tensor [N,D]): features of the source data feat_t (torch.Tensor [N',D]): features of the target data prob (torch.Tensor [N,C]): probabilty vectors of the source data prob_t (torch.Tensor [N',C]): probabilty vectors of the t...
get_relation
python
Jingkang50/OpenOOD
openood/postprocessors/relation_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/relation_postprocessor.py
MIT
def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it. """ h = img.size(1) w = img.size(2) mask = np.ones((h, w), np.floa...
Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it.
__call__
python
Jingkang50/OpenOOD
openood/preprocessors/cutout_preprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/preprocessors/cutout_preprocessor.py
MIT
def get_similarity_matrix(outputs, chunk=2, multi_gpu=False): """Compute similarity matrix. - outputs: (B', d) tensor for B' = B * chunk - sim_matrix: (B', B') tensor """ if multi_gpu: outputs_gathered = [] for out in outputs.chunk(chunk): gather_t = [ t...
Compute similarity matrix. - outputs: (B', d) tensor for B' = B * chunk - sim_matrix: (B', B') tensor
get_similarity_matrix
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def Supervised_NT_xent(sim_matrix, labels, temperature=0.5, chunk=2, eps=1e-8, multi_gpu=False): """Compute NT_xent loss. - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples...
Compute NT_xent loss. - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples)
Supervised_NT_xent
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def __init__(self, size=None, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)): """Inception Crop size (tuple): size of forwarding image (C, W, H) scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped. """ sup...
Inception Crop size (tuple): size of forwarding image (C, W, H) scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped.
__init__
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def __init__(self): """ img_size : (int, int, int) Height and width must be powers of 2. E.g. (32, 32, 1) or (64, 128, 3). Last number indicates number of channels, e.g. 1 for grayscale or 3 for RGB """ super(HorizontalFlipLayer, self).__init__() ...
img_size : (int, int, int) Height and width must be powers of 2. E.g. (32, 32, 1) or (64, 128, 3). Last number indicates number of channels, e.g. 1 for grayscale or 3 for RGB
__init__
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def init_center_c(train_loader, net, eps=0.1): """Initialize hypersphere center c as the mean from an initial forward pass on the data.""" n_samples = 0 first_iter = True train_dataiter = iter(train_loader) net.eval() with torch.no_grad(): for train_step in tqdm(range(1, ...
Initialize hypersphere center c as the mean from an initial forward pass on the data.
init_center_c
python
Jingkang50/OpenOOD
openood/trainers/dsvdd_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/dsvdd_trainer.py
MIT
def prepare_mixup(batch, alpha=1.0, use_cuda=True): """Returns mixed inputs, pairs of targets, and lambda.""" if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = batch['data'].size()[0] if use_cuda: index = torch.randperm(batch_size).cuda() else: ...
Returns mixed inputs, pairs of targets, and lambda.
prepare_mixup
python
Jingkang50/OpenOOD
openood/trainers/mixup_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mixup_trainer.py
MIT
def get_lr(step, dataset_size, base_lr=0.003): """Returns learning-rate for `step` or None at the end.""" supports = get_schedule(dataset_size) # Linear warmup if step < supports[0]: return base_lr * step / supports[0] # End of training elif step >= supports[-1]: return None ...
Returns learning-rate for `step` or None at the end.
get_lr
python
Jingkang50/OpenOOD
openood/trainers/mos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mos_trainer.py
MIT
def KNN_dis_search_distance(target, index, K=50, num_points=10, length=2000, depth=342): ''' data_point: Queue for searching k-th points target: the target of the searc...
data_point: Queue for searching k-th points target: the target of the search K
KNN_dis_search_distance
python
Jingkang50/OpenOOD
openood/trainers/npos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/npos_trainer.py
MIT
def preprocess_features(npdata, pca=256): """Preprocess an array of features. Args: npdata (np.array N * ndim): features to preprocess pca (int): dim of output Returns: np.array of dim N * pca: data PCA-reduced, whitened and L2-normalized """ _, ndim = npdata.shape npdata...
Preprocess an array of features. Args: npdata (np.array N * ndim): features to preprocess pca (int): dim of output Returns: np.array of dim N * pca: data PCA-reduced, whitened and L2-normalized
preprocess_features
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def run_kmeans(x, nmb_clusters, verbose=False): """Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clusters Returns: list: ids of data in each cluster """ n_data, d = x.shape # faiss implementation of k-means clus = faiss.Clustering(d, nmb_clusters...
Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clusters Returns: list: ids of data in each cluster
run_kmeans
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def cluster(self, data, verbose=True): """Performs k-means clustering. Args: x_data (np.array N * dim): data to cluster """ # PCA-reducing, whitening and L2-normalization xb = preprocess_features(data, pca=self.pca_dim) if np.isnan(xb).any(): row_...
Performs k-means clustering. Args: x_data (np.array N * dim): data to cluster
cluster
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def log_sum_exp(value, num_classes=10, dim=None, keepdim=False): """Numerically stable implementation of the operation.""" value.exp().sum(dim, keepdim).log() # TODO: torch.max(value, dim=None) threw an error at time of writing weight_energy = torch.nn.Linear(num_classes, 1).cuda() if dim is not No...
Numerically stable implementation of the operation.
log_sum_exp
python
Jingkang50/OpenOOD
openood/trainers/vos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/vos_trainer.py
MIT
def get_local_rank() -> int: """ Returns: The rank of the current process within the local (per-machine) process group. """ if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 assert ( _LOCAL_PROCESS_GROUP is not None ), 'Local ...
Returns: The rank of the current process within the local (per-machine) process group.
get_local_rank
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def get_local_size() -> int: """ Returns: The size of the per-machine process group, i.e. the number of processes per machine. """ if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
get_local_size
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def synchronize(): """Helper function to synchronize (barrier) among all processes when using distributed training.""" if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return if dist.get_bac...
Helper function to synchronize (barrier) among all processes when using distributed training.
synchronize
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def _get_global_gloo_group(): """Return a process group based on gloo backend, containing all the ranks The result is cached.""" if dist.get_backend() == 'nccl': return dist.new_group(backend='gloo') else: return dist.group.WORLD
Return a process group based on gloo backend, containing all the ranks The result is cached.
_get_global_gloo_group
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def all_gather(data, group=None): """Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of ...
Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank
all_gather
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def gather(data, dst=0, group=None): """Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Re...
Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: on dst, a list of...
gather
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def shared_random_seed(): """ Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock. """ ints = np.random.randint(2**31) ...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
shared_random_seed
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def reduce_dict(input_dict, average=True): """Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average o...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same k...
reduce_dict
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def setup_config(config_process_order=('merge', 'parse_args', 'parse_refs')): """Parsing configuration files and command line augments. This method reads the command line to 1. extract and stack YAML config files, 2. collect modification in command line arguments, so that the finalized conf...
Parsing configuration files and command line augments. This method reads the command line to 1. extract and stack YAML config files, 2. collect modification in command line arguments, so that the finalized configuration file is generated. Note: The default arguments allow the follo...
setup_config
python
Jingkang50/OpenOOD
openood/utils/config.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/config.py
MIT
def launch( main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=(), timeout=DEFAULT_TIMEOUT, ): """Launch multi-gpu or distributed training. This function must be called on all machines involved in the training. It will spa...
Launch multi-gpu or distributed training. This function must be called on all machines involved in the training. It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine. Args: main_func: a function that will be called by `main_func(*args)` num_gpus_per_machine (i...
launch
python
Jingkang50/OpenOOD
openood/utils/launch.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/launch.py
MIT
def mkdir_if_missing(dirname): """Create dirname if it is missing.""" if not osp.exists(dirname): try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise
Create dirname if it is missing.
mkdir_if_missing
python
Jingkang50/OpenOOD
openood/utils/logger.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/logger.py
MIT
def setup_logger(config): """generate exp directory to save configs, logger, checkpoints, etc. Args: config: all configs of the experiment """ print('------------------ Config --------------------------', flush=True) print(config, flush=True) print(u'\u2500' * 70, flush=True) outpu...
generate exp directory to save configs, logger, checkpoints, etc. Args: config: all configs of the experiment
setup_logger
python
Jingkang50/OpenOOD
openood/utils/logger.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/logger.py
MIT
async def maigret( username: str, site_dict: Dict[str, MaigretSite], logger, query_notify=None, proxy=None, tor_proxy=None, i2p_proxy=None, timeout=3, is_parsing_enabled=False, id_type="username", debug=False, forced=False, max_connections=100, no_progressbar=Fals...
Main search func Checks for existence of username on certain sites. Keyword Arguments: username -- Username string will be used for search. site_dict -- Dictionary containing sites data in MaigretSite objects. query_notify -- Object with base type of QueryNotif...
maigret
python
soxoj/maigret
maigret/checking.py
https://github.com/soxoj/maigret/blob/master/maigret/checking.py
MIT
def timeout_check(value): """Check Timeout Argument. Checks timeout for validity. Keyword Arguments: value -- Time in seconds to wait before timing out request. Return Value: Floating point number representing the time (in seconds) that should be used for the timeout. ...
Check Timeout Argument. Checks timeout for validity. Keyword Arguments: value -- Time in seconds to wait before timing out request. Return Value: Floating point number representing the time (in seconds) that should be used for the timeout. NOTE: Will raise an exception ...
timeout_check
python
soxoj/maigret
maigret/checking.py
https://github.com/soxoj/maigret/blob/master/maigret/checking.py
MIT
def notify_about_errors( search_results: QueryResultWrapper, query_notify, show_statistics=False ) -> List[Tuple]: """ Prepare error notifications in search results, text + symbol, to be displayed by notify object. Example: [ ("Too many errors of type "timeout" (50.0%)", "!") ("...
Prepare error notifications in search results, text + symbol, to be displayed by notify object. Example: [ ("Too many errors of type "timeout" (50.0%)", "!") ("Verbose error statistics:", "-") ]
notify_about_errors
python
soxoj/maigret
maigret/errors.py
https://github.com/soxoj/maigret/blob/master/maigret/errors.py
MIT
async def increment_progress(self, count): """Update progress by calling the provided progress function.""" if self.progress: if asyncio.iscoroutinefunction(self.progress): await self.progress(count) else: self.progress(count) await...
Update progress by calling the provided progress function.
increment_progress
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def worker(self): """Consume tasks from the queue and process them.""" while True: try: f, args, kwargs = self.queue.get_nowait() except asyncio.QueueEmpty: return query_future = f(*args, **kwargs) query_task = create...
Consume tasks from the queue and process them.
worker
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def _run(self, queries: Iterable[QueryDraft]): """Main runner function to execute tasks with progress tracking.""" self.results: List[Any] = [] queries_list = list(queries) min_workers = min(len(queries_list), self.workers_count) workers = [create_task_func()(self.worker())...
Main runner function to execute tasks with progress tracking.
_run
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def worker(self): """Process tasks from the queue and put results into the results queue.""" while True: task = await self.queue.get() if task is self._stop_signal: self.queue.task_done() break try: f, args, kwarg...
Process tasks from the queue and put results into the results queue.
worker
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def run(self, queries: Iterable[Callable[..., Any]]): """Run workers to process queries in parallel.""" start_time = time.time() # Add tasks to the queue for t in queries: await self.queue.put(t) # Create workers workers = [ asyncio.create_...
Run workers to process queries in parallel.
run
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
def __init__( self, result=None, verbose=False, print_found_only=False, skip_check_errors=False, color=True, ): """Create Query Notify Print Object. Contains information about a specific method of notifying the results of a query. Key...
Create Query Notify Print Object. Contains information about a specific method of notifying the results of a query. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing resu...
__init__
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def start(self, message, id_type): """Notify Start. Will print the title to the standard output. Keyword Arguments: self -- This object. message -- String containing username that the series of queries are about...
Notify Start. Will print the title to the standard output. Keyword Arguments: self -- This object. message -- String containing username that the series of queries are about. Return Value: Nothing. ...
start
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def update(self, result, is_similar=False): """Notify Update. Will print the query result to the standard output. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing result...
Notify Update. Will print the query result to the standard output. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing results for this query. Return Value: Nothin...
update
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def __init__( self, username, site_name, site_url_user, status, ids_data=None, query_time=None, context=None, error=None, tags=[], ): """ Keyword Arguments: self -- This object. username...
Keyword Arguments: self -- This object. username -- String indicating username that query result was about. site_name -- String which identifies site. site_url_user -- String containing URL f...
__init__
python
soxoj/maigret
maigret/result.py
https://github.com/soxoj/maigret/blob/master/maigret/result.py
MIT
def __str__(self): """Convert Object To String. Keyword Arguments: self -- This object. Return Value: Nicely formatted string to get information about this object. """ status = str(self.status) if self.context is not None: #...
Convert Object To String. Keyword Arguments: self -- This object. Return Value: Nicely formatted string to get information about this object.
__str__
python
soxoj/maigret
maigret/result.py
https://github.com/soxoj/maigret/blob/master/maigret/result.py
MIT
def extract_id_from_url(self, url: str) -> Optional[Tuple[str, str]]: """ Extracts username from url. It's outdated, detects only a format of https://example.com/{username} """ if not self.url_regexp: return None match_groups = self.url_regexp.match(url) ...
Extracts username from url. It's outdated, detects only a format of https://example.com/{username}
extract_id_from_url
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def ranked_sites_dict( self, reverse=False, top=sys.maxsize, tags=[], names=[], disabled=True, id_type="username", ): """ Ranking and filtering of the sites list Args: reverse (bool, optional): Reverse the sorting order. De...
Ranking and filtering of the sites list Args: reverse (bool, optional): Reverse the sorting order. Defaults to False. top (int, optional): Maximum number of sites to return. Defaults to sys.maxsize. tags (list, optional): List of tags to filter sites by. Defaults to...
ranked_sites_dict
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def _format_top_items( self, title, items_dict, limit, is_markdown, valid_items=None ): """Helper method to format top items lists""" output = f"Top {limit} {title}:\n" for item, count in sorted(items_dict.items(), key=lambda x: x[1], reverse=True)[ :limit ]: ...
Helper method to format top items lists
_format_top_items
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def attribute(self, attribute_name, db=None, default=None): # type: (str, CanMatrix, typing.Any) -> typing.Any """Get Board unit attribute by its name. :param str attribute_name: attribute name. :param CanMatrix db: Optional database parameter to get global default attribute value. :pa...
Get Board unit attribute by its name. :param str attribute_name: attribute name. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exist. :return: Return the attribute value if found, else `default`...
attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_attribute(self, attribute, value): # type (attribute: str, value: typing.Any) -> None """ Add the Attribute to current ECU. If the attribute already exists, update the value. :param str attribute: Attribute name :param any value: Attribute value """ try: ...
Add the Attribute to current ECU. If the attribute already exists, update the value. :param str attribute: Attribute name :param any value: Attribute value
add_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def attribute(self, attributeName, db=None, default=None): # type: (str, CanMatrix, typing.Any) -> typing.Any """Get any Signal attribute by its name. :param str attributeName: attribute name, can be mandatory (ex: start_bit, size) or optional (customer) attribute. :param CanMatrix db: ...
Get any Signal attribute by its name. :param str attributeName: attribute name, can be mandatory (ex: start_bit, size) or optional (customer) attribute. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exi...
attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_attribute(self, attribute, value): """ Add user defined attribute to the Signal. Update the value if the attribute already exists. :param str attribute: attribute name :param value: attribute value """ try: self.attributes[attribute] = str(value) ...
Add user defined attribute to the Signal. Update the value if the attribute already exists. :param str attribute: attribute name :param value: attribute value
add_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_values(self, value, valueName): """ Add named Value Description to the Signal. :param int or str value: signal value (0xFF) :param str valueName: Human readable value description ("Init") """ if isinstance(value, defaultFloatFactory): self.values[valu...
Add named Value Description to the Signal. :param int or str value: signal value (0xFF) :param str valueName: Human readable value description ("Init")
add_values
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_startbit(self, start_bit, bitNumbering=None, startLittle=None): """ Set start_bit. bitNumbering is 1 for LSB0/LSBFirst, 0 for MSB0/MSBFirst. If bit numbering is consistent with byte order (little=LSB0, big=MSB0) (KCD, SYM), start bit unmodified. Otherwise reverse...
Set start_bit. bitNumbering is 1 for LSB0/LSBFirst, 0 for MSB0/MSBFirst. If bit numbering is consistent with byte order (little=LSB0, big=MSB0) (KCD, SYM), start bit unmodified. Otherwise reverse bit numbering. For DBC, ArXML (OSEK), both little endian and big endian us...
set_startbit
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def get_startbit(self, bit_numbering=None, start_little=None): """Get signal start bit. Handle byte and bit order.""" startBitInternal = self.start_bit # convert from big endian start bit at # start bit(msbit) to end bit(lsbit) if start_little is True and self.is_little_endian is...
Get signal start bit. Handle byte and bit order.
get_startbit
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calculate_raw_range(self): """Compute raw signal range based on Signal bit width and whether the Signal is signed or not. :return: Signal range, i.e. (0, 15) for unsigned 4 bit Signal or (-8, 7) for signed one. :rtype: tuple """ factory = ( self.float_factory ...
Compute raw signal range based on Signal bit width and whether the Signal is signed or not. :return: Signal range, i.e. (0, 15) for unsigned 4 bit Signal or (-8, 7) for signed one. :rtype: tuple
calculate_raw_range
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_min(self, min=None): # type: (canmatrix.types.OptionalPhysicalValue) -> canmatrix.types.OptionalPhysicalValue """Set minimal physical Signal value. :param min: minimal physical value. If None and enabled (`calc_min_for_none`), compute using `calc_min` """ self.min = min ...
Set minimal physical Signal value. :param min: minimal physical value. If None and enabled (`calc_min_for_none`), compute using `calc_min`
set_min
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calc_min(self): # type: () -> canmatrix.types.PhysicalValue """Compute minimal physical Signal value based on offset and factor and `calculate_raw_range`.""" rawMin = self.calculate_raw_range()[0] return self.offset + (self.float_factory(rawMin) * self.factor)
Compute minimal physical Signal value based on offset and factor and `calculate_raw_range`.
calc_min
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_max(self, max=None): # type: (canmatrix.types.OptionalPhysicalValue) -> canmatrix.types.OptionalPhysicalValue """Set maximal signal value. :param max: minimal physical value. If None and enabled (`calc_max_for_none`), compute using `calc_max` """ self.max = max ...
Set maximal signal value. :param max: minimal physical value. If None and enabled (`calc_max_for_none`), compute using `calc_max`
set_max
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calc_max(self): # type: () -> canmatrix.types.PhysicalValue """Compute maximal physical Signal value based on offset, factor and `calculate_raw_range`.""" rawMax = self.calculate_raw_range()[1] return self.offset + (self.float_factory(rawMax) * self.factor)
Compute maximal physical Signal value based on offset, factor and `calculate_raw_range`.
calc_max
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause