repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
albahnsen/CostSensitiveClassification | costcla/models/bagging.py | BaseBagging._fit_stacking_model | def _fit_stacking_model(self,X, y, cost_mat, max_iter=100):
"""Private function used to fit the stacking model."""
self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter)
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
self.f_staking.fit(X_stacking, y, cost_mat)
return self | python | def _fit_stacking_model(self,X, y, cost_mat, max_iter=100):
"""Private function used to fit the stacking model."""
self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter)
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
self.f_staking.fit(X_stacking, y, cost_mat)
return self | [
"def",
"_fit_stacking_model",
"(",
"self",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"max_iter",
"=",
"100",
")",
":",
"self",
".",
"f_staking",
"=",
"CostSensitiveLogisticRegression",
"(",
"verbose",
"=",
"self",
".",
"verbose",
",",
"max_iter",
"=",
"max_iter",
")",
"X_stacking",
"=",
"_create_stacking_set",
"(",
"self",
".",
"estimators_",
",",
"self",
".",
"estimators_features_",
",",
"self",
".",
"estimators_weight_",
",",
"X",
",",
"self",
".",
"combination",
")",
"self",
".",
"f_staking",
".",
"fit",
"(",
"X_stacking",
",",
"y",
",",
"cost_mat",
")",
"return",
"self"
] | Private function used to fit the stacking model. | [
"Private",
"function",
"used",
"to",
"fit",
"the",
"stacking",
"model",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L302-L308 | train | 236,900 |
albahnsen/CostSensitiveClassification | costcla/models/bagging.py | BaseBagging._evaluate_oob_savings | def _evaluate_oob_savings(self, X, y, cost_mat):
"""Private function used to calculate the OOB Savings of each estimator."""
estimators_weight = []
for estimator, samples, features in zip(self.estimators_, self.estimators_samples_,
self.estimators_features_):
# Test if all examples where used for training
if not np.any(~samples):
# Then use training
oob_pred = estimator.predict(X[:, features])
oob_savings = max(0, savings_score(y, oob_pred, cost_mat))
else:
# Then use OOB
oob_pred = estimator.predict((X[~samples])[:, features])
oob_savings = max(0, savings_score(y[~samples], oob_pred, cost_mat[~samples]))
estimators_weight.append(oob_savings)
# Control in case were all weights are 0
if sum(estimators_weight) == 0:
self.estimators_weight_ = np.ones(len(estimators_weight)) / len(estimators_weight)
else:
self.estimators_weight_ = (np.array(estimators_weight) / sum(estimators_weight)).tolist()
return self | python | def _evaluate_oob_savings(self, X, y, cost_mat):
"""Private function used to calculate the OOB Savings of each estimator."""
estimators_weight = []
for estimator, samples, features in zip(self.estimators_, self.estimators_samples_,
self.estimators_features_):
# Test if all examples where used for training
if not np.any(~samples):
# Then use training
oob_pred = estimator.predict(X[:, features])
oob_savings = max(0, savings_score(y, oob_pred, cost_mat))
else:
# Then use OOB
oob_pred = estimator.predict((X[~samples])[:, features])
oob_savings = max(0, savings_score(y[~samples], oob_pred, cost_mat[~samples]))
estimators_weight.append(oob_savings)
# Control in case were all weights are 0
if sum(estimators_weight) == 0:
self.estimators_weight_ = np.ones(len(estimators_weight)) / len(estimators_weight)
else:
self.estimators_weight_ = (np.array(estimators_weight) / sum(estimators_weight)).tolist()
return self | [
"def",
"_evaluate_oob_savings",
"(",
"self",
",",
"X",
",",
"y",
",",
"cost_mat",
")",
":",
"estimators_weight",
"=",
"[",
"]",
"for",
"estimator",
",",
"samples",
",",
"features",
"in",
"zip",
"(",
"self",
".",
"estimators_",
",",
"self",
".",
"estimators_samples_",
",",
"self",
".",
"estimators_features_",
")",
":",
"# Test if all examples where used for training",
"if",
"not",
"np",
".",
"any",
"(",
"~",
"samples",
")",
":",
"# Then use training",
"oob_pred",
"=",
"estimator",
".",
"predict",
"(",
"X",
"[",
":",
",",
"features",
"]",
")",
"oob_savings",
"=",
"max",
"(",
"0",
",",
"savings_score",
"(",
"y",
",",
"oob_pred",
",",
"cost_mat",
")",
")",
"else",
":",
"# Then use OOB",
"oob_pred",
"=",
"estimator",
".",
"predict",
"(",
"(",
"X",
"[",
"~",
"samples",
"]",
")",
"[",
":",
",",
"features",
"]",
")",
"oob_savings",
"=",
"max",
"(",
"0",
",",
"savings_score",
"(",
"y",
"[",
"~",
"samples",
"]",
",",
"oob_pred",
",",
"cost_mat",
"[",
"~",
"samples",
"]",
")",
")",
"estimators_weight",
".",
"append",
"(",
"oob_savings",
")",
"# Control in case were all weights are 0",
"if",
"sum",
"(",
"estimators_weight",
")",
"==",
"0",
":",
"self",
".",
"estimators_weight_",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"estimators_weight",
")",
")",
"/",
"len",
"(",
"estimators_weight",
")",
"else",
":",
"self",
".",
"estimators_weight_",
"=",
"(",
"np",
".",
"array",
"(",
"estimators_weight",
")",
"/",
"sum",
"(",
"estimators_weight",
")",
")",
".",
"tolist",
"(",
")",
"return",
"self"
] | Private function used to calculate the OOB Savings of each estimator. | [
"Private",
"function",
"used",
"to",
"calculate",
"the",
"OOB",
"Savings",
"of",
"each",
"estimator",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L311-L334 | train | 236,901 |
albahnsen/CostSensitiveClassification | costcla/models/bagging.py | BaggingClassifier.predict | def predict(self, X, cost_mat=None):
"""Predict class for X.
The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
cost_mat : optional array-like of shape = [n_samples, 4], (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
pred : array of shape = [n_samples]
The predicted classes.
"""
# Check data
# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15
if self.n_features_ != X.shape[1]:
raise ValueError("Number of features of the model must "
"match the input. Model n_features is {0} and "
"input n_features is {1}."
"".format(self.n_features_, X.shape[1]))
#TODO: check if combination in possible combinations
if self.combination in ['stacking', 'stacking_proba']:
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
return self.f_staking.predict(X_stacking)
elif self.combination in ['majority_voting', 'weighted_voting']:
# Parallel loop
n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators,
self.n_jobs)
all_pred = Parallel(n_jobs=n_jobs, verbose=self.verbose)(
delayed(_parallel_predict)(
self.estimators_[starts[i]:starts[i + 1]],
self.estimators_features_[starts[i]:starts[i + 1]],
X,
self.n_classes_,
self.combination,
self.estimators_weight_[starts[i]:starts[i + 1]])
for i in range(n_jobs))
# Reduce
pred = sum(all_pred) / self.n_estimators
return self.classes_.take(np.argmax(pred, axis=1), axis=0)
elif self.combination in ['majority_bmr', 'weighted_bmr', 'stacking_bmr', 'stacking_proba_bmr']:
#TODO: Add check if cost_mat == None
X_bmr = self.predict_proba(X)
return self.f_bmr.predict(X_bmr, cost_mat) | python | def predict(self, X, cost_mat=None):
"""Predict class for X.
The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
cost_mat : optional array-like of shape = [n_samples, 4], (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
pred : array of shape = [n_samples]
The predicted classes.
"""
# Check data
# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15
if self.n_features_ != X.shape[1]:
raise ValueError("Number of features of the model must "
"match the input. Model n_features is {0} and "
"input n_features is {1}."
"".format(self.n_features_, X.shape[1]))
#TODO: check if combination in possible combinations
if self.combination in ['stacking', 'stacking_proba']:
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
return self.f_staking.predict(X_stacking)
elif self.combination in ['majority_voting', 'weighted_voting']:
# Parallel loop
n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators,
self.n_jobs)
all_pred = Parallel(n_jobs=n_jobs, verbose=self.verbose)(
delayed(_parallel_predict)(
self.estimators_[starts[i]:starts[i + 1]],
self.estimators_features_[starts[i]:starts[i + 1]],
X,
self.n_classes_,
self.combination,
self.estimators_weight_[starts[i]:starts[i + 1]])
for i in range(n_jobs))
# Reduce
pred = sum(all_pred) / self.n_estimators
return self.classes_.take(np.argmax(pred, axis=1), axis=0)
elif self.combination in ['majority_bmr', 'weighted_bmr', 'stacking_bmr', 'stacking_proba_bmr']:
#TODO: Add check if cost_mat == None
X_bmr = self.predict_proba(X)
return self.f_bmr.predict(X_bmr, cost_mat) | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"cost_mat",
"=",
"None",
")",
":",
"# Check data",
"# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15",
"if",
"self",
".",
"n_features_",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Number of features of the model must \"",
"\"match the input. Model n_features is {0} and \"",
"\"input n_features is {1}.\"",
"\"\"",
".",
"format",
"(",
"self",
".",
"n_features_",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
")",
"#TODO: check if combination in possible combinations",
"if",
"self",
".",
"combination",
"in",
"[",
"'stacking'",
",",
"'stacking_proba'",
"]",
":",
"X_stacking",
"=",
"_create_stacking_set",
"(",
"self",
".",
"estimators_",
",",
"self",
".",
"estimators_features_",
",",
"self",
".",
"estimators_weight_",
",",
"X",
",",
"self",
".",
"combination",
")",
"return",
"self",
".",
"f_staking",
".",
"predict",
"(",
"X_stacking",
")",
"elif",
"self",
".",
"combination",
"in",
"[",
"'majority_voting'",
",",
"'weighted_voting'",
"]",
":",
"# Parallel loop",
"n_jobs",
",",
"n_estimators",
",",
"starts",
"=",
"_partition_estimators",
"(",
"self",
".",
"n_estimators",
",",
"self",
".",
"n_jobs",
")",
"all_pred",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"(",
"delayed",
"(",
"_parallel_predict",
")",
"(",
"self",
".",
"estimators_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"self",
".",
"estimators_features_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"X",
",",
"self",
".",
"n_classes_",
",",
"self",
".",
"combination",
",",
"self",
".",
"estimators_weight_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"n_jobs",
")",
")",
"# Reduce",
"pred",
"=",
"sum",
"(",
"all_pred",
")",
"/",
"self",
".",
"n_estimators",
"return",
"self",
".",
"classes_",
".",
"take",
"(",
"np",
".",
"argmax",
"(",
"pred",
",",
"axis",
"=",
"1",
")",
",",
"axis",
"=",
"0",
")",
"elif",
"self",
".",
"combination",
"in",
"[",
"'majority_bmr'",
",",
"'weighted_bmr'",
",",
"'stacking_bmr'",
",",
"'stacking_proba_bmr'",
"]",
":",
"#TODO: Add check if cost_mat == None",
"X_bmr",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"return",
"self",
".",
"f_bmr",
".",
"predict",
"(",
"X_bmr",
",",
"cost_mat",
")"
] | Predict class for X.
The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
cost_mat : optional array-like of shape = [n_samples, 4], (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
pred : array of shape = [n_samples]
The predicted classes. | [
"Predict",
"class",
"for",
"X",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L491-L554 | train | 236,902 |
albahnsen/CostSensitiveClassification | costcla/models/bagging.py | BaggingClassifier.predict_proba | def predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implement a ``predict_proba``
method, then it resorts to voting and the predicted class probabilities
of a an input sample represents the proportion of estimators predicting
each class.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
Returns
-------
p : array of shape = [n_samples, n_classes]
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
# Check data
# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15
if self.n_features_ != X.shape[1]:
raise ValueError("Number of features of the model must "
"match the input. Model n_features is {0} and "
"input n_features is {1}."
"".format(self.n_features_, X.shape[1]))
# Parallel loop
n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, self.n_jobs)
all_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose)(
delayed(_parallel_predict_proba)(
self.estimators_[starts[i]:starts[i + 1]],
self.estimators_features_[starts[i]:starts[i + 1]],
X,
self.n_classes_,
self.combination,
self.estimators_weight_[starts[i]:starts[i + 1]])
for i in range(n_jobs))
# Reduce
if self.combination in ['majority_voting', 'majority_bmr']:
proba = sum(all_proba) / self.n_estimators
elif self.combination in ['weighted_voting', 'weighted_bmr']:
proba = sum(all_proba)
elif self.combination in ['stacking', 'stacking_proba', 'stacking_bmr', 'stacking_proba_bmr']:
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
proba = self.f_staking.predict_proba(X_stacking)
return proba | python | def predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implement a ``predict_proba``
method, then it resorts to voting and the predicted class probabilities
of a an input sample represents the proportion of estimators predicting
each class.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
Returns
-------
p : array of shape = [n_samples, n_classes]
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
# Check data
# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15
if self.n_features_ != X.shape[1]:
raise ValueError("Number of features of the model must "
"match the input. Model n_features is {0} and "
"input n_features is {1}."
"".format(self.n_features_, X.shape[1]))
# Parallel loop
n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, self.n_jobs)
all_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose)(
delayed(_parallel_predict_proba)(
self.estimators_[starts[i]:starts[i + 1]],
self.estimators_features_[starts[i]:starts[i + 1]],
X,
self.n_classes_,
self.combination,
self.estimators_weight_[starts[i]:starts[i + 1]])
for i in range(n_jobs))
# Reduce
if self.combination in ['majority_voting', 'majority_bmr']:
proba = sum(all_proba) / self.n_estimators
elif self.combination in ['weighted_voting', 'weighted_bmr']:
proba = sum(all_proba)
elif self.combination in ['stacking', 'stacking_proba', 'stacking_bmr', 'stacking_proba_bmr']:
X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
self.estimators_weight_, X, self.combination)
proba = self.f_staking.predict_proba(X_stacking)
return proba | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"# Check data",
"# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15",
"if",
"self",
".",
"n_features_",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Number of features of the model must \"",
"\"match the input. Model n_features is {0} and \"",
"\"input n_features is {1}.\"",
"\"\"",
".",
"format",
"(",
"self",
".",
"n_features_",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
")",
"# Parallel loop",
"n_jobs",
",",
"n_estimators",
",",
"starts",
"=",
"_partition_estimators",
"(",
"self",
".",
"n_estimators",
",",
"self",
".",
"n_jobs",
")",
"all_proba",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"(",
"delayed",
"(",
"_parallel_predict_proba",
")",
"(",
"self",
".",
"estimators_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"self",
".",
"estimators_features_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"X",
",",
"self",
".",
"n_classes_",
",",
"self",
".",
"combination",
",",
"self",
".",
"estimators_weight_",
"[",
"starts",
"[",
"i",
"]",
":",
"starts",
"[",
"i",
"+",
"1",
"]",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"n_jobs",
")",
")",
"# Reduce",
"if",
"self",
".",
"combination",
"in",
"[",
"'majority_voting'",
",",
"'majority_bmr'",
"]",
":",
"proba",
"=",
"sum",
"(",
"all_proba",
")",
"/",
"self",
".",
"n_estimators",
"elif",
"self",
".",
"combination",
"in",
"[",
"'weighted_voting'",
",",
"'weighted_bmr'",
"]",
":",
"proba",
"=",
"sum",
"(",
"all_proba",
")",
"elif",
"self",
".",
"combination",
"in",
"[",
"'stacking'",
",",
"'stacking_proba'",
",",
"'stacking_bmr'",
",",
"'stacking_proba_bmr'",
"]",
":",
"X_stacking",
"=",
"_create_stacking_set",
"(",
"self",
".",
"estimators_",
",",
"self",
".",
"estimators_features_",
",",
"self",
".",
"estimators_weight_",
",",
"X",
",",
"self",
".",
"combination",
")",
"proba",
"=",
"self",
".",
"f_staking",
".",
"predict_proba",
"(",
"X_stacking",
")",
"return",
"proba"
] | Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implement a ``predict_proba``
method, then it resorts to voting and the predicted class probabilities
of a an input sample represents the proportion of estimators predicting
each class.
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
Returns
-------
p : array of shape = [n_samples, n_classes]
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`. | [
"Predict",
"class",
"probabilities",
"for",
"X",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L556-L610 | train | 236,903 |
albahnsen/CostSensitiveClassification | costcla/sampling/cost_sampling.py | cost_sampling | def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5):
"""Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
method : str, optional (default = RejectionSampling)
Method to perform the cost-proportionate sampling,
either 'RejectionSampling' or 'OverSampling'.
oversampling_norm: float, optional (default = 0.1)
normalize value of wc, the smaller the biggest the data.
max_wc: float, optional (default = 97.5)
outlier adjustment for the cost.
References
----------
.. [1] B. Zadrozny, J. Langford, N. Naoki, "Cost-sensitive learning by
cost-proportionate example weighting", in Proceedings of the
Third IEEE International Conference on Data Mining, 435-442, 2003.
.. [2] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.cross_validation import train_test_split
>>> from costcla.datasets import load_creditscoring1
>>> from costcla.sampling import cost_sampling, undersampling
>>> from costcla.metrics import savings_score
>>> data = load_creditscoring1()
>>> sets = train_test_split(data.data, data.target, data.cost_mat, test_size=0.33, random_state=0)
>>> X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = sets
>>> X_cps_o, y_cps_o, cost_mat_cps_o = cost_sampling(X_train, y_train, cost_mat_train, method='OverSampling')
>>> X_cps_r, y_cps_r, cost_mat_cps_r = cost_sampling(X_train, y_train, cost_mat_train, method='RejectionSampling')
>>> X_u, y_u, cost_mat_u = undersampling(X_train, y_train, cost_mat_train)
>>> y_pred_test_rf = RandomForestClassifier(random_state=0).fit(X_train, y_train).predict(X_test)
>>> y_pred_test_rf_cps_o = RandomForestClassifier(random_state=0).fit(X_cps_o, y_cps_o).predict(X_test)
>>> y_pred_test_rf_cps_r = RandomForestClassifier(random_state=0).fit(X_cps_r, y_cps_r).predict(X_test)
>>> y_pred_test_rf_u = RandomForestClassifier(random_state=0).fit(X_u, y_u).predict(X_test)
>>> # Savings using only RandomForest
>>> print(savings_score(y_test, y_pred_test_rf, cost_mat_test))
0.12454256594
>>> # Savings using RandomForest with cost-proportionate over-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_o, cost_mat_test))
0.192480226286
>>> # Savings using RandomForest with cost-proportionate rejection-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_r, cost_mat_test))
0.465830173459
>>> # Savings using RandomForest with under-sampling
>>> print(savings_score(y_test, y_pred_test_rf_u, cost_mat_test))
0.466630646543
>>> # Size of each training set
>>> print(X_train.shape[0], X_cps_o.shape[0], X_cps_r.shape[0], X_u.shape[0])
75653 109975 8690 10191
>>> # Percentage of positives in each training set
>>> print(y_train.mean(), y_cps_o.mean(), y_cps_r.mean(), y_u.mean())
0.0668182358928 0.358054103205 0.436939010357 0.49602590521
"""
#TODO: Check consistency of input
# The methods are construct only for the misclassification costs, not the full cost matrix.
cost_mis = cost_mat[:, 0]
cost_mis[y == 1] = cost_mat[y == 1, 1]
# wc = cost_mis / cost_mis.max()
wc = np.minimum(cost_mis / np.percentile(cost_mis, max_wc), 1)
n_samples = X.shape[0]
filter_ = list(range(n_samples))
if method == 'RejectionSampling':
# under-sampling by rejection [1]
#TODO: Add random state
rej_rand = np.random.rand(n_samples)
filter_ = rej_rand <= wc
elif method == 'OverSampling':
# over-sampling with normalized wn [2]
wc_n = np.ceil(wc / oversampling_norm).astype(np.int)
new_n = wc_n.sum()
filter_ = np.ones(new_n, dtype=np.int)
e = 0
#TODO replace for
for i in range(n_samples):
filter_[e: e + wc_n[i]] = i
e += wc_n[i]
x_cps = X[filter_]
y_cps = y[filter_]
cost_mat_cps = cost_mat[filter_]
return x_cps, y_cps, cost_mat_cps | python | def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5):
"""Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
method : str, optional (default = RejectionSampling)
Method to perform the cost-proportionate sampling,
either 'RejectionSampling' or 'OverSampling'.
oversampling_norm: float, optional (default = 0.1)
normalize value of wc, the smaller the biggest the data.
max_wc: float, optional (default = 97.5)
outlier adjustment for the cost.
References
----------
.. [1] B. Zadrozny, J. Langford, N. Naoki, "Cost-sensitive learning by
cost-proportionate example weighting", in Proceedings of the
Third IEEE International Conference on Data Mining, 435-442, 2003.
.. [2] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.cross_validation import train_test_split
>>> from costcla.datasets import load_creditscoring1
>>> from costcla.sampling import cost_sampling, undersampling
>>> from costcla.metrics import savings_score
>>> data = load_creditscoring1()
>>> sets = train_test_split(data.data, data.target, data.cost_mat, test_size=0.33, random_state=0)
>>> X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = sets
>>> X_cps_o, y_cps_o, cost_mat_cps_o = cost_sampling(X_train, y_train, cost_mat_train, method='OverSampling')
>>> X_cps_r, y_cps_r, cost_mat_cps_r = cost_sampling(X_train, y_train, cost_mat_train, method='RejectionSampling')
>>> X_u, y_u, cost_mat_u = undersampling(X_train, y_train, cost_mat_train)
>>> y_pred_test_rf = RandomForestClassifier(random_state=0).fit(X_train, y_train).predict(X_test)
>>> y_pred_test_rf_cps_o = RandomForestClassifier(random_state=0).fit(X_cps_o, y_cps_o).predict(X_test)
>>> y_pred_test_rf_cps_r = RandomForestClassifier(random_state=0).fit(X_cps_r, y_cps_r).predict(X_test)
>>> y_pred_test_rf_u = RandomForestClassifier(random_state=0).fit(X_u, y_u).predict(X_test)
>>> # Savings using only RandomForest
>>> print(savings_score(y_test, y_pred_test_rf, cost_mat_test))
0.12454256594
>>> # Savings using RandomForest with cost-proportionate over-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_o, cost_mat_test))
0.192480226286
>>> # Savings using RandomForest with cost-proportionate rejection-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_r, cost_mat_test))
0.465830173459
>>> # Savings using RandomForest with under-sampling
>>> print(savings_score(y_test, y_pred_test_rf_u, cost_mat_test))
0.466630646543
>>> # Size of each training set
>>> print(X_train.shape[0], X_cps_o.shape[0], X_cps_r.shape[0], X_u.shape[0])
75653 109975 8690 10191
>>> # Percentage of positives in each training set
>>> print(y_train.mean(), y_cps_o.mean(), y_cps_r.mean(), y_u.mean())
0.0668182358928 0.358054103205 0.436939010357 0.49602590521
"""
#TODO: Check consistency of input
# The methods are construct only for the misclassification costs, not the full cost matrix.
cost_mis = cost_mat[:, 0]
cost_mis[y == 1] = cost_mat[y == 1, 1]
# wc = cost_mis / cost_mis.max()
wc = np.minimum(cost_mis / np.percentile(cost_mis, max_wc), 1)
n_samples = X.shape[0]
filter_ = list(range(n_samples))
if method == 'RejectionSampling':
# under-sampling by rejection [1]
#TODO: Add random state
rej_rand = np.random.rand(n_samples)
filter_ = rej_rand <= wc
elif method == 'OverSampling':
# over-sampling with normalized wn [2]
wc_n = np.ceil(wc / oversampling_norm).astype(np.int)
new_n = wc_n.sum()
filter_ = np.ones(new_n, dtype=np.int)
e = 0
#TODO replace for
for i in range(n_samples):
filter_[e: e + wc_n[i]] = i
e += wc_n[i]
x_cps = X[filter_]
y_cps = y[filter_]
cost_mat_cps = cost_mat[filter_]
return x_cps, y_cps, cost_mat_cps | [
"def",
"cost_sampling",
"(",
"X",
",",
"y",
",",
"cost_mat",
",",
"method",
"=",
"'RejectionSampling'",
",",
"oversampling_norm",
"=",
"0.1",
",",
"max_wc",
"=",
"97.5",
")",
":",
"#TODO: Check consistency of input",
"# The methods are construct only for the misclassification costs, not the full cost matrix.",
"cost_mis",
"=",
"cost_mat",
"[",
":",
",",
"0",
"]",
"cost_mis",
"[",
"y",
"==",
"1",
"]",
"=",
"cost_mat",
"[",
"y",
"==",
"1",
",",
"1",
"]",
"# wc = cost_mis / cost_mis.max()",
"wc",
"=",
"np",
".",
"minimum",
"(",
"cost_mis",
"/",
"np",
".",
"percentile",
"(",
"cost_mis",
",",
"max_wc",
")",
",",
"1",
")",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"filter_",
"=",
"list",
"(",
"range",
"(",
"n_samples",
")",
")",
"if",
"method",
"==",
"'RejectionSampling'",
":",
"# under-sampling by rejection [1]",
"#TODO: Add random state",
"rej_rand",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"n_samples",
")",
"filter_",
"=",
"rej_rand",
"<=",
"wc",
"elif",
"method",
"==",
"'OverSampling'",
":",
"# over-sampling with normalized wn [2]",
"wc_n",
"=",
"np",
".",
"ceil",
"(",
"wc",
"/",
"oversampling_norm",
")",
".",
"astype",
"(",
"np",
".",
"int",
")",
"new_n",
"=",
"wc_n",
".",
"sum",
"(",
")",
"filter_",
"=",
"np",
".",
"ones",
"(",
"new_n",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"e",
"=",
"0",
"#TODO replace for",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
":",
"filter_",
"[",
"e",
":",
"e",
"+",
"wc_n",
"[",
"i",
"]",
"]",
"=",
"i",
"e",
"+=",
"wc_n",
"[",
"i",
"]",
"x_cps",
"=",
"X",
"[",
"filter_",
"]",
"y_cps",
"=",
"y",
"[",
"filter_",
"]",
"cost_mat_cps",
"=",
"cost_mat",
"[",
"filter_",
"]",
"return",
"x_cps",
",",
"y_cps",
",",
"cost_mat_cps"
] | Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
method : str, optional (default = RejectionSampling)
Method to perform the cost-proportionate sampling,
either 'RejectionSampling' or 'OverSampling'.
oversampling_norm: float, optional (default = 0.1)
normalize value of wc, the smaller the biggest the data.
max_wc: float, optional (default = 97.5)
outlier adjustment for the cost.
References
----------
.. [1] B. Zadrozny, J. Langford, N. Naoki, "Cost-sensitive learning by
cost-proportionate example weighting", in Proceedings of the
Third IEEE International Conference on Data Mining, 435-442, 2003.
.. [2] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.cross_validation import train_test_split
>>> from costcla.datasets import load_creditscoring1
>>> from costcla.sampling import cost_sampling, undersampling
>>> from costcla.metrics import savings_score
>>> data = load_creditscoring1()
>>> sets = train_test_split(data.data, data.target, data.cost_mat, test_size=0.33, random_state=0)
>>> X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = sets
>>> X_cps_o, y_cps_o, cost_mat_cps_o = cost_sampling(X_train, y_train, cost_mat_train, method='OverSampling')
>>> X_cps_r, y_cps_r, cost_mat_cps_r = cost_sampling(X_train, y_train, cost_mat_train, method='RejectionSampling')
>>> X_u, y_u, cost_mat_u = undersampling(X_train, y_train, cost_mat_train)
>>> y_pred_test_rf = RandomForestClassifier(random_state=0).fit(X_train, y_train).predict(X_test)
>>> y_pred_test_rf_cps_o = RandomForestClassifier(random_state=0).fit(X_cps_o, y_cps_o).predict(X_test)
>>> y_pred_test_rf_cps_r = RandomForestClassifier(random_state=0).fit(X_cps_r, y_cps_r).predict(X_test)
>>> y_pred_test_rf_u = RandomForestClassifier(random_state=0).fit(X_u, y_u).predict(X_test)
>>> # Savings using only RandomForest
>>> print(savings_score(y_test, y_pred_test_rf, cost_mat_test))
0.12454256594
>>> # Savings using RandomForest with cost-proportionate over-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_o, cost_mat_test))
0.192480226286
>>> # Savings using RandomForest with cost-proportionate rejection-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_r, cost_mat_test))
0.465830173459
>>> # Savings using RandomForest with under-sampling
>>> print(savings_score(y_test, y_pred_test_rf_u, cost_mat_test))
0.466630646543
>>> # Size of each training set
>>> print(X_train.shape[0], X_cps_o.shape[0], X_cps_r.shape[0], X_u.shape[0])
75653 109975 8690 10191
>>> # Percentage of positives in each training set
>>> print(y_train.mean(), y_cps_o.mean(), y_cps_r.mean(), y_u.mean())
0.0668182358928 0.358054103205 0.436939010357 0.49602590521 | [
"Cost",
"-",
"proportionate",
"sampling",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/cost_sampling.py#L11-L123 | train | 236,904 |
albahnsen/CostSensitiveClassification | costcla/datasets/base.py | _creditscoring_costmat | def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters):
""" Private function to calculate the cost matrix of credit scoring models.
Parameters
----------
income : array of shape = [n_samples]
Monthly income of each example
debt : array of shape = [n_samples]
Debt ratio each example
pi_1 : float
Percentage of positives in the training set
References
----------
.. [1] A. Correa Bahnsen, D.Aouada, B, Ottersten,
"Example-Dependent Cost-Sensitive Logistic Regression for Credit Scoring",
in Proceedings of the International Conference on Machine Learning and Applications,
, 2014.
Returns
-------
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
def calculate_a(cl_i, int_, n_term):
""" Private function """
return cl_i * ((int_ * (1 + int_) ** n_term) / ((1 + int_) ** n_term - 1))
def calculate_pv(a, int_, n_term):
""" Private function """
return a / int_ * (1 - 1 / (1 + int_) ** n_term)
#Calculate credit line Cl
def calculate_cl(k, inc_i, cl_max, debt_i, int_r, n_term):
""" Private function """
cl_k = k * inc_i
A = calculate_a(cl_k, int_r, n_term)
Cl_debt = calculate_pv(inc_i * min(A / inc_i, 1 - debt_i), int_r, n_term)
return min(cl_k, cl_max, Cl_debt)
#calculate costs
def calculate_cost_fn(cl_i, lgd):
return cl_i * lgd
def calculate_cost_fp(cl_i, int_r, n_term, int_cf, pi_1, lgd, cl_avg):
a = calculate_a(cl_i, int_r, n_term)
pv = calculate_pv(a, int_cf, n_term)
r = pv - cl_i
r_avg = calculate_pv(calculate_a(cl_avg, int_r, n_term), int_cf, n_term) - cl_avg
cost_fp = r - (1 - pi_1) * r_avg + pi_1 * calculate_cost_fn(cl_avg, lgd)
return max(0, cost_fp)
v_calculate_cost_fp = np.vectorize(calculate_cost_fp)
v_calculate_cost_fn = np.vectorize(calculate_cost_fn)
v_calculate_cl = np.vectorize(calculate_cl)
# Parameters
k = cost_mat_parameters['k']
int_r = cost_mat_parameters['int_r']
n_term = cost_mat_parameters['n_term']
int_cf = cost_mat_parameters['int_cf']
lgd = cost_mat_parameters['lgd']
cl_max = cost_mat_parameters['cl_max']
cl = v_calculate_cl(k, income, cl_max, debt, int_r, n_term)
cl_avg = cl.mean()
n_samples = income.shape[0]
cost_mat = np.zeros((n_samples, 4)) #cost_mat[FP,FN,TP,TN]
cost_mat[:, 0] = v_calculate_cost_fp(cl, int_r, n_term, int_cf, pi_1, lgd, cl_avg)
cost_mat[:, 1] = v_calculate_cost_fn(cl, lgd)
cost_mat[:, 2] = 0.0
cost_mat[:, 3] = 0.0
return cost_mat | python | def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters):
""" Private function to calculate the cost matrix of credit scoring models.
Parameters
----------
income : array of shape = [n_samples]
Monthly income of each example
debt : array of shape = [n_samples]
Debt ratio each example
pi_1 : float
Percentage of positives in the training set
References
----------
.. [1] A. Correa Bahnsen, D.Aouada, B, Ottersten,
"Example-Dependent Cost-Sensitive Logistic Regression for Credit Scoring",
in Proceedings of the International Conference on Machine Learning and Applications,
, 2014.
Returns
-------
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
def calculate_a(cl_i, int_, n_term):
""" Private function """
return cl_i * ((int_ * (1 + int_) ** n_term) / ((1 + int_) ** n_term - 1))
def calculate_pv(a, int_, n_term):
""" Private function """
return a / int_ * (1 - 1 / (1 + int_) ** n_term)
#Calculate credit line Cl
def calculate_cl(k, inc_i, cl_max, debt_i, int_r, n_term):
""" Private function """
cl_k = k * inc_i
A = calculate_a(cl_k, int_r, n_term)
Cl_debt = calculate_pv(inc_i * min(A / inc_i, 1 - debt_i), int_r, n_term)
return min(cl_k, cl_max, Cl_debt)
#calculate costs
def calculate_cost_fn(cl_i, lgd):
return cl_i * lgd
def calculate_cost_fp(cl_i, int_r, n_term, int_cf, pi_1, lgd, cl_avg):
a = calculate_a(cl_i, int_r, n_term)
pv = calculate_pv(a, int_cf, n_term)
r = pv - cl_i
r_avg = calculate_pv(calculate_a(cl_avg, int_r, n_term), int_cf, n_term) - cl_avg
cost_fp = r - (1 - pi_1) * r_avg + pi_1 * calculate_cost_fn(cl_avg, lgd)
return max(0, cost_fp)
v_calculate_cost_fp = np.vectorize(calculate_cost_fp)
v_calculate_cost_fn = np.vectorize(calculate_cost_fn)
v_calculate_cl = np.vectorize(calculate_cl)
# Parameters
k = cost_mat_parameters['k']
int_r = cost_mat_parameters['int_r']
n_term = cost_mat_parameters['n_term']
int_cf = cost_mat_parameters['int_cf']
lgd = cost_mat_parameters['lgd']
cl_max = cost_mat_parameters['cl_max']
cl = v_calculate_cl(k, income, cl_max, debt, int_r, n_term)
cl_avg = cl.mean()
n_samples = income.shape[0]
cost_mat = np.zeros((n_samples, 4)) #cost_mat[FP,FN,TP,TN]
cost_mat[:, 0] = v_calculate_cost_fp(cl, int_r, n_term, int_cf, pi_1, lgd, cl_avg)
cost_mat[:, 1] = v_calculate_cost_fn(cl, lgd)
cost_mat[:, 2] = 0.0
cost_mat[:, 3] = 0.0
return cost_mat | [
"def",
"_creditscoring_costmat",
"(",
"income",
",",
"debt",
",",
"pi_1",
",",
"cost_mat_parameters",
")",
":",
"def",
"calculate_a",
"(",
"cl_i",
",",
"int_",
",",
"n_term",
")",
":",
"\"\"\" Private function \"\"\"",
"return",
"cl_i",
"*",
"(",
"(",
"int_",
"*",
"(",
"1",
"+",
"int_",
")",
"**",
"n_term",
")",
"/",
"(",
"(",
"1",
"+",
"int_",
")",
"**",
"n_term",
"-",
"1",
")",
")",
"def",
"calculate_pv",
"(",
"a",
",",
"int_",
",",
"n_term",
")",
":",
"\"\"\" Private function \"\"\"",
"return",
"a",
"/",
"int_",
"*",
"(",
"1",
"-",
"1",
"/",
"(",
"1",
"+",
"int_",
")",
"**",
"n_term",
")",
"#Calculate credit line Cl",
"def",
"calculate_cl",
"(",
"k",
",",
"inc_i",
",",
"cl_max",
",",
"debt_i",
",",
"int_r",
",",
"n_term",
")",
":",
"\"\"\" Private function \"\"\"",
"cl_k",
"=",
"k",
"*",
"inc_i",
"A",
"=",
"calculate_a",
"(",
"cl_k",
",",
"int_r",
",",
"n_term",
")",
"Cl_debt",
"=",
"calculate_pv",
"(",
"inc_i",
"*",
"min",
"(",
"A",
"/",
"inc_i",
",",
"1",
"-",
"debt_i",
")",
",",
"int_r",
",",
"n_term",
")",
"return",
"min",
"(",
"cl_k",
",",
"cl_max",
",",
"Cl_debt",
")",
"#calculate costs",
"def",
"calculate_cost_fn",
"(",
"cl_i",
",",
"lgd",
")",
":",
"return",
"cl_i",
"*",
"lgd",
"def",
"calculate_cost_fp",
"(",
"cl_i",
",",
"int_r",
",",
"n_term",
",",
"int_cf",
",",
"pi_1",
",",
"lgd",
",",
"cl_avg",
")",
":",
"a",
"=",
"calculate_a",
"(",
"cl_i",
",",
"int_r",
",",
"n_term",
")",
"pv",
"=",
"calculate_pv",
"(",
"a",
",",
"int_cf",
",",
"n_term",
")",
"r",
"=",
"pv",
"-",
"cl_i",
"r_avg",
"=",
"calculate_pv",
"(",
"calculate_a",
"(",
"cl_avg",
",",
"int_r",
",",
"n_term",
")",
",",
"int_cf",
",",
"n_term",
")",
"-",
"cl_avg",
"cost_fp",
"=",
"r",
"-",
"(",
"1",
"-",
"pi_1",
")",
"*",
"r_avg",
"+",
"pi_1",
"*",
"calculate_cost_fn",
"(",
"cl_avg",
",",
"lgd",
")",
"return",
"max",
"(",
"0",
",",
"cost_fp",
")",
"v_calculate_cost_fp",
"=",
"np",
".",
"vectorize",
"(",
"calculate_cost_fp",
")",
"v_calculate_cost_fn",
"=",
"np",
".",
"vectorize",
"(",
"calculate_cost_fn",
")",
"v_calculate_cl",
"=",
"np",
".",
"vectorize",
"(",
"calculate_cl",
")",
"# Parameters",
"k",
"=",
"cost_mat_parameters",
"[",
"'k'",
"]",
"int_r",
"=",
"cost_mat_parameters",
"[",
"'int_r'",
"]",
"n_term",
"=",
"cost_mat_parameters",
"[",
"'n_term'",
"]",
"int_cf",
"=",
"cost_mat_parameters",
"[",
"'int_cf'",
"]",
"lgd",
"=",
"cost_mat_parameters",
"[",
"'lgd'",
"]",
"cl_max",
"=",
"cost_mat_parameters",
"[",
"'cl_max'",
"]",
"cl",
"=",
"v_calculate_cl",
"(",
"k",
",",
"income",
",",
"cl_max",
",",
"debt",
",",
"int_r",
",",
"n_term",
")",
"cl_avg",
"=",
"cl",
".",
"mean",
"(",
")",
"n_samples",
"=",
"income",
".",
"shape",
"[",
"0",
"]",
"cost_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"4",
")",
")",
"#cost_mat[FP,FN,TP,TN]",
"cost_mat",
"[",
":",
",",
"0",
"]",
"=",
"v_calculate_cost_fp",
"(",
"cl",
",",
"int_r",
",",
"n_term",
",",
"int_cf",
",",
"pi_1",
",",
"lgd",
",",
"cl_avg",
")",
"cost_mat",
"[",
":",
",",
"1",
"]",
"=",
"v_calculate_cost_fn",
"(",
"cl",
",",
"lgd",
")",
"cost_mat",
"[",
":",
",",
"2",
"]",
"=",
"0.0",
"cost_mat",
"[",
":",
",",
"3",
"]",
"=",
"0.0",
"return",
"cost_mat"
] | Private function to calculate the cost matrix of credit scoring models.
Parameters
----------
income : array of shape = [n_samples]
Monthly income of each example
debt : array of shape = [n_samples]
Debt ratio each example
pi_1 : float
Percentage of positives in the training set
References
----------
.. [1] A. Correa Bahnsen, D.Aouada, B, Ottersten,
"Example-Dependent Cost-Sensitive Logistic Regression for Credit Scoring",
in Proceedings of the International Conference on Machine Learning and Applications,
, 2014.
Returns
-------
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example. | [
"Private",
"function",
"to",
"calculate",
"the",
"cost",
"matrix",
"of",
"credit",
"scoring",
"models",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L336-L415 | train | 236,905 |
albahnsen/CostSensitiveClassification | costcla/probcal/probcal.py | ROCConvexHull.predict_proba | def predict_proba(self, p):
""" Calculate the calibrated probabilities
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be calibrated using calibration map
Returns
-------
y_prob_cal : array-like of shape = [n_samples, 1]
Predicted calibrated probabilities
"""
# TODO: Check input
if p.size != p.shape[0]:
p = p[:, 1]
calibrated_proba = np.zeros(p.shape[0])
for i in range(self.calibration_map.shape[0]):
calibrated_proba[np.logical_and(self.calibration_map[i, 1] <= p, self.calibration_map[i, 0] > p)] = \
self.calibration_map[i, 2]
# TODO: return 2D and refactor
return calibrated_proba | python | def predict_proba(self, p):
""" Calculate the calibrated probabilities
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be calibrated using calibration map
Returns
-------
y_prob_cal : array-like of shape = [n_samples, 1]
Predicted calibrated probabilities
"""
# TODO: Check input
if p.size != p.shape[0]:
p = p[:, 1]
calibrated_proba = np.zeros(p.shape[0])
for i in range(self.calibration_map.shape[0]):
calibrated_proba[np.logical_and(self.calibration_map[i, 1] <= p, self.calibration_map[i, 0] > p)] = \
self.calibration_map[i, 2]
# TODO: return 2D and refactor
return calibrated_proba | [
"def",
"predict_proba",
"(",
"self",
",",
"p",
")",
":",
"# TODO: Check input",
"if",
"p",
".",
"size",
"!=",
"p",
".",
"shape",
"[",
"0",
"]",
":",
"p",
"=",
"p",
"[",
":",
",",
"1",
"]",
"calibrated_proba",
"=",
"np",
".",
"zeros",
"(",
"p",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"calibration_map",
".",
"shape",
"[",
"0",
"]",
")",
":",
"calibrated_proba",
"[",
"np",
".",
"logical_and",
"(",
"self",
".",
"calibration_map",
"[",
"i",
",",
"1",
"]",
"<=",
"p",
",",
"self",
".",
"calibration_map",
"[",
"i",
",",
"0",
"]",
">",
"p",
")",
"]",
"=",
"self",
".",
"calibration_map",
"[",
"i",
",",
"2",
"]",
"# TODO: return 2D and refactor",
"return",
"calibrated_proba"
] | Calculate the calibrated probabilities
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be calibrated using calibration map
Returns
-------
y_prob_cal : array-like of shape = [n_samples, 1]
Predicted calibrated probabilities | [
"Calculate",
"the",
"calibrated",
"probabilities"
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L137-L161 | train | 236,906 |
albahnsen/CostSensitiveClassification | costcla/utils/cross_validation.py | cross_val_score | def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1,
verbose=0, fit_params=None, pre_dispatch='2*n_jobs'):
"""Evaluate a score by cross-validation
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : array-like
The data to fit. Can be, for example a list, or an array at least 2d.
y : array-like, optional, default: None
The target variable to try to predict in the case of
supervised learning.
scoring : string, callable or None, optional, default: None
A string (see model evaluation documentation) or
a scorer callable object / function with signature
``scorer(estimator, X, y)``.
cv : cross-validation generator or int, optional, default: None
A cross-validation generator to use. If int, determines
the number of folds in StratifiedKFold if y is binary
or multiclass and estimator is a classifier, or the number
of folds in KFold otherwise. If None, it is equivalent to cv=3.
n_jobs : integer, optional
The number of CPUs to use to do the computation. -1 means
'all CPUs'.
verbose : integer, optional
The verbosity level.
fit_params : dict, optional
Parameters to pass to the fit method of the estimator.
pre_dispatch : int, or string, optional
Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:
- None, in which case all the jobs are immediately
created and spawned. Use this for lightweight and
fast-running jobs, to avoid delays due to on-demand
spawning of the jobs
- An int, giving the exact number of total jobs that are
spawned
- A string, giving an expression as a function of n_jobs,
as in '2*n_jobs'
Returns
-------
scores : array of float, shape=(len(list(cv)),)
Array of scores of the estimator for each run of the cross validation.
"""
X, y = indexable(X, y)
cv = _check_cv(cv, X, y, classifier=is_classifier(estimator))
scorer = check_scoring(estimator, scoring=scoring)
# We clone the estimator to make sure that all the folds are
# independent, and that it is pickle-able.
parallel = Parallel(n_jobs=n_jobs, verbose=verbose,
pre_dispatch=pre_dispatch)
scores = parallel(delayed(_fit_and_score)(clone(estimator), X, y, scorer,
train, test, verbose, None,
fit_params)
for train, test in cv)
return np.array(scores)[:, 0] | python | def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1,
verbose=0, fit_params=None, pre_dispatch='2*n_jobs'):
"""Evaluate a score by cross-validation
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : array-like
The data to fit. Can be, for example a list, or an array at least 2d.
y : array-like, optional, default: None
The target variable to try to predict in the case of
supervised learning.
scoring : string, callable or None, optional, default: None
A string (see model evaluation documentation) or
a scorer callable object / function with signature
``scorer(estimator, X, y)``.
cv : cross-validation generator or int, optional, default: None
A cross-validation generator to use. If int, determines
the number of folds in StratifiedKFold if y is binary
or multiclass and estimator is a classifier, or the number
of folds in KFold otherwise. If None, it is equivalent to cv=3.
n_jobs : integer, optional
The number of CPUs to use to do the computation. -1 means
'all CPUs'.
verbose : integer, optional
The verbosity level.
fit_params : dict, optional
Parameters to pass to the fit method of the estimator.
pre_dispatch : int, or string, optional
Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:
- None, in which case all the jobs are immediately
created and spawned. Use this for lightweight and
fast-running jobs, to avoid delays due to on-demand
spawning of the jobs
- An int, giving the exact number of total jobs that are
spawned
- A string, giving an expression as a function of n_jobs,
as in '2*n_jobs'
Returns
-------
scores : array of float, shape=(len(list(cv)),)
Array of scores of the estimator for each run of the cross validation.
"""
X, y = indexable(X, y)
cv = _check_cv(cv, X, y, classifier=is_classifier(estimator))
scorer = check_scoring(estimator, scoring=scoring)
# We clone the estimator to make sure that all the folds are
# independent, and that it is pickle-able.
parallel = Parallel(n_jobs=n_jobs, verbose=verbose,
pre_dispatch=pre_dispatch)
scores = parallel(delayed(_fit_and_score)(clone(estimator), X, y, scorer,
train, test, verbose, None,
fit_params)
for train, test in cv)
return np.array(scores)[:, 0] | [
"def",
"cross_val_score",
"(",
"estimator",
",",
"X",
",",
"y",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"cv",
"=",
"None",
",",
"n_jobs",
"=",
"1",
",",
"verbose",
"=",
"0",
",",
"fit_params",
"=",
"None",
",",
"pre_dispatch",
"=",
"'2*n_jobs'",
")",
":",
"X",
",",
"y",
"=",
"indexable",
"(",
"X",
",",
"y",
")",
"cv",
"=",
"_check_cv",
"(",
"cv",
",",
"X",
",",
"y",
",",
"classifier",
"=",
"is_classifier",
"(",
"estimator",
")",
")",
"scorer",
"=",
"check_scoring",
"(",
"estimator",
",",
"scoring",
"=",
"scoring",
")",
"# We clone the estimator to make sure that all the folds are",
"# independent, and that it is pickle-able.",
"parallel",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"verbose",
",",
"pre_dispatch",
"=",
"pre_dispatch",
")",
"scores",
"=",
"parallel",
"(",
"delayed",
"(",
"_fit_and_score",
")",
"(",
"clone",
"(",
"estimator",
")",
",",
"X",
",",
"y",
",",
"scorer",
",",
"train",
",",
"test",
",",
"verbose",
",",
"None",
",",
"fit_params",
")",
"for",
"train",
",",
"test",
"in",
"cv",
")",
"return",
"np",
".",
"array",
"(",
"scores",
")",
"[",
":",
",",
"0",
"]"
] | Evaluate a score by cross-validation
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : array-like
The data to fit. Can be, for example a list, or an array at least 2d.
y : array-like, optional, default: None
The target variable to try to predict in the case of
supervised learning.
scoring : string, callable or None, optional, default: None
A string (see model evaluation documentation) or
a scorer callable object / function with signature
``scorer(estimator, X, y)``.
cv : cross-validation generator or int, optional, default: None
A cross-validation generator to use. If int, determines
the number of folds in StratifiedKFold if y is binary
or multiclass and estimator is a classifier, or the number
of folds in KFold otherwise. If None, it is equivalent to cv=3.
n_jobs : integer, optional
The number of CPUs to use to do the computation. -1 means
'all CPUs'.
verbose : integer, optional
The verbosity level.
fit_params : dict, optional
Parameters to pass to the fit method of the estimator.
pre_dispatch : int, or string, optional
Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:
- None, in which case all the jobs are immediately
created and spawned. Use this for lightweight and
fast-running jobs, to avoid delays due to on-demand
spawning of the jobs
- An int, giving the exact number of total jobs that are
spawned
- A string, giving an expression as a function of n_jobs,
as in '2*n_jobs'
Returns
-------
scores : array of float, shape=(len(list(cv)),)
Array of scores of the estimator for each run of the cross validation. | [
"Evaluate",
"a",
"score",
"by",
"cross",
"-",
"validation"
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1080-L1151 | train | 236,907 |
albahnsen/CostSensitiveClassification | costcla/utils/cross_validation.py | _safe_split | def _safe_split(estimator, X, y, indices, train_indices=None):
"""Create subset of dataset and properly handle kernels."""
if hasattr(estimator, 'kernel') and isinstance(estimator.kernel, collections.Callable):
# cannot compute the kernel values with custom function
raise ValueError("Cannot use a custom kernel function. "
"Precompute the kernel matrix instead.")
if not hasattr(X, "shape"):
if getattr(estimator, "_pairwise", False):
raise ValueError("Precomputed kernels or affinity matrices have "
"to be passed as arrays or sparse matrices.")
X_subset = [X[idx] for idx in indices]
else:
if getattr(estimator, "_pairwise", False):
# X is a precomputed square kernel matrix
if X.shape[0] != X.shape[1]:
raise ValueError("X should be a square kernel matrix")
if train_indices is None:
X_subset = X[np.ix_(indices, indices)]
else:
X_subset = X[np.ix_(indices, train_indices)]
else:
X_subset = safe_indexing(X, indices)
if y is not None:
y_subset = safe_indexing(y, indices)
else:
y_subset = None
return X_subset, y_subset | python | def _safe_split(estimator, X, y, indices, train_indices=None):
"""Create subset of dataset and properly handle kernels."""
if hasattr(estimator, 'kernel') and isinstance(estimator.kernel, collections.Callable):
# cannot compute the kernel values with custom function
raise ValueError("Cannot use a custom kernel function. "
"Precompute the kernel matrix instead.")
if not hasattr(X, "shape"):
if getattr(estimator, "_pairwise", False):
raise ValueError("Precomputed kernels or affinity matrices have "
"to be passed as arrays or sparse matrices.")
X_subset = [X[idx] for idx in indices]
else:
if getattr(estimator, "_pairwise", False):
# X is a precomputed square kernel matrix
if X.shape[0] != X.shape[1]:
raise ValueError("X should be a square kernel matrix")
if train_indices is None:
X_subset = X[np.ix_(indices, indices)]
else:
X_subset = X[np.ix_(indices, train_indices)]
else:
X_subset = safe_indexing(X, indices)
if y is not None:
y_subset = safe_indexing(y, indices)
else:
y_subset = None
return X_subset, y_subset | [
"def",
"_safe_split",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"indices",
",",
"train_indices",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"'kernel'",
")",
"and",
"isinstance",
"(",
"estimator",
".",
"kernel",
",",
"collections",
".",
"Callable",
")",
":",
"# cannot compute the kernel values with custom function",
"raise",
"ValueError",
"(",
"\"Cannot use a custom kernel function. \"",
"\"Precompute the kernel matrix instead.\"",
")",
"if",
"not",
"hasattr",
"(",
"X",
",",
"\"shape\"",
")",
":",
"if",
"getattr",
"(",
"estimator",
",",
"\"_pairwise\"",
",",
"False",
")",
":",
"raise",
"ValueError",
"(",
"\"Precomputed kernels or affinity matrices have \"",
"\"to be passed as arrays or sparse matrices.\"",
")",
"X_subset",
"=",
"[",
"X",
"[",
"idx",
"]",
"for",
"idx",
"in",
"indices",
"]",
"else",
":",
"if",
"getattr",
"(",
"estimator",
",",
"\"_pairwise\"",
",",
"False",
")",
":",
"# X is a precomputed square kernel matrix",
"if",
"X",
".",
"shape",
"[",
"0",
"]",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"X should be a square kernel matrix\"",
")",
"if",
"train_indices",
"is",
"None",
":",
"X_subset",
"=",
"X",
"[",
"np",
".",
"ix_",
"(",
"indices",
",",
"indices",
")",
"]",
"else",
":",
"X_subset",
"=",
"X",
"[",
"np",
".",
"ix_",
"(",
"indices",
",",
"train_indices",
")",
"]",
"else",
":",
"X_subset",
"=",
"safe_indexing",
"(",
"X",
",",
"indices",
")",
"if",
"y",
"is",
"not",
"None",
":",
"y_subset",
"=",
"safe_indexing",
"(",
"y",
",",
"indices",
")",
"else",
":",
"y_subset",
"=",
"None",
"return",
"X_subset",
",",
"y_subset"
] | Create subset of dataset and properly handle kernels. | [
"Create",
"subset",
"of",
"dataset",
"and",
"properly",
"handle",
"kernels",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1258-L1287 | train | 236,908 |
albahnsen/CostSensitiveClassification | costcla/utils/cross_validation.py | _score | def _score(estimator, X_test, y_test, scorer):
"""Compute the score of an estimator on a given test set."""
if y_test is None:
score = scorer(estimator, X_test)
else:
score = scorer(estimator, X_test, y_test)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | python | def _score(estimator, X_test, y_test, scorer):
"""Compute the score of an estimator on a given test set."""
if y_test is None:
score = scorer(estimator, X_test)
else:
score = scorer(estimator, X_test, y_test)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | [
"def",
"_score",
"(",
"estimator",
",",
"X_test",
",",
"y_test",
",",
"scorer",
")",
":",
"if",
"y_test",
"is",
"None",
":",
"score",
"=",
"scorer",
"(",
"estimator",
",",
"X_test",
")",
"else",
":",
"score",
"=",
"scorer",
"(",
"estimator",
",",
"X_test",
",",
"y_test",
")",
"if",
"not",
"isinstance",
"(",
"score",
",",
"numbers",
".",
"Number",
")",
":",
"raise",
"ValueError",
"(",
"\"scoring must return a number, got %s (%s) instead.\"",
"%",
"(",
"str",
"(",
"score",
")",
",",
"type",
"(",
"score",
")",
")",
")",
"return",
"score"
] | Compute the score of an estimator on a given test set. | [
"Compute",
"the",
"score",
"of",
"an",
"estimator",
"on",
"a",
"given",
"test",
"set",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1290-L1299 | train | 236,909 |
albahnsen/CostSensitiveClassification | costcla/utils/cross_validation.py | _shuffle | def _shuffle(y, labels, random_state):
"""Return a shuffled copy of y eventually shuffle among same labels."""
if labels is None:
ind = random_state.permutation(len(y))
else:
ind = np.arange(len(labels))
for label in np.unique(labels):
this_mask = (labels == label)
ind[this_mask] = random_state.permutation(ind[this_mask])
return y[ind] | python | def _shuffle(y, labels, random_state):
"""Return a shuffled copy of y eventually shuffle among same labels."""
if labels is None:
ind = random_state.permutation(len(y))
else:
ind = np.arange(len(labels))
for label in np.unique(labels):
this_mask = (labels == label)
ind[this_mask] = random_state.permutation(ind[this_mask])
return y[ind] | [
"def",
"_shuffle",
"(",
"y",
",",
"labels",
",",
"random_state",
")",
":",
"if",
"labels",
"is",
"None",
":",
"ind",
"=",
"random_state",
".",
"permutation",
"(",
"len",
"(",
"y",
")",
")",
"else",
":",
"ind",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"labels",
")",
")",
"for",
"label",
"in",
"np",
".",
"unique",
"(",
"labels",
")",
":",
"this_mask",
"=",
"(",
"labels",
"==",
"label",
")",
"ind",
"[",
"this_mask",
"]",
"=",
"random_state",
".",
"permutation",
"(",
"ind",
"[",
"this_mask",
"]",
")",
"return",
"y",
"[",
"ind",
"]"
] | Return a shuffled copy of y eventually shuffle among same labels. | [
"Return",
"a",
"shuffled",
"copy",
"of",
"y",
"eventually",
"shuffle",
"among",
"same",
"labels",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1311-L1320 | train | 236,910 |
albahnsen/CostSensitiveClassification | costcla/utils/cross_validation.py | check_cv | def check_cv(cv, X=None, y=None, classifier=False):
"""Input checker utility for building a CV in a user friendly way.
Parameters
----------
cv : int, a cv generator instance, or None
The input specifying which cv generator to use. It can be an
integer, in which case it is the number of folds in a KFold,
None, in which case 3 fold is used, or another object, that
will then be used as a cv generator.
X : array-like
The data the cross-val object will be applied on.
y : array-like
The target variable for a supervised learning problem.
classifier : boolean optional
Whether the task is a classification task, in which case
stratified KFold will be used.
Returns
-------
checked_cv: a cross-validation generator instance.
The return value is guaranteed to be a cv generator instance, whatever
the input type.
"""
return _check_cv(cv, X=X, y=y, classifier=classifier, warn_mask=True) | python | def check_cv(cv, X=None, y=None, classifier=False):
"""Input checker utility for building a CV in a user friendly way.
Parameters
----------
cv : int, a cv generator instance, or None
The input specifying which cv generator to use. It can be an
integer, in which case it is the number of folds in a KFold,
None, in which case 3 fold is used, or another object, that
will then be used as a cv generator.
X : array-like
The data the cross-val object will be applied on.
y : array-like
The target variable for a supervised learning problem.
classifier : boolean optional
Whether the task is a classification task, in which case
stratified KFold will be used.
Returns
-------
checked_cv: a cross-validation generator instance.
The return value is guaranteed to be a cv generator instance, whatever
the input type.
"""
return _check_cv(cv, X=X, y=y, classifier=classifier, warn_mask=True) | [
"def",
"check_cv",
"(",
"cv",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"classifier",
"=",
"False",
")",
":",
"return",
"_check_cv",
"(",
"cv",
",",
"X",
"=",
"X",
",",
"y",
"=",
"y",
",",
"classifier",
"=",
"classifier",
",",
"warn_mask",
"=",
"True",
")"
] | Input checker utility for building a CV in a user friendly way.
Parameters
----------
cv : int, a cv generator instance, or None
The input specifying which cv generator to use. It can be an
integer, in which case it is the number of folds in a KFold,
None, in which case 3 fold is used, or another object, that
will then be used as a cv generator.
X : array-like
The data the cross-val object will be applied on.
y : array-like
The target variable for a supervised learning problem.
classifier : boolean optional
Whether the task is a classification task, in which case
stratified KFold will be used.
Returns
-------
checked_cv: a cross-validation generator instance.
The return value is guaranteed to be a cv generator instance, whatever
the input type. | [
"Input",
"checker",
"utility",
"for",
"building",
"a",
"CV",
"in",
"a",
"user",
"friendly",
"way",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1323-L1350 | train | 236,911 |
albahnsen/CostSensitiveClassification | costcla/sampling/_smote.py | _borderlineSMOTE | def _borderlineSMOTE(X, y, minority_target, N, k):
"""
Returns synthetic minority samples.
Parameters
----------
X : array-like, shape = [n__samples, n_features]
Holds the minority and majority samples
y : array-like, shape = [n__samples]
Holds the class targets for samples
minority_target : value for minority class
N : percetange of new synthetic samples:
n_synthetic_samples = N/100 * n_minority_samples. Can be < 100.
k : int. Number of nearest neighbours.
h : high in random.uniform to scale dif of snythetic sample
Returns
-------
safe : Safe minorities
synthetic : Synthetic sample of minorities in danger zone
danger : Minorities of danger zone
"""
n_samples, _ = X.shape
#Learn nearest neighbours on complete training set
neigh = NearestNeighbors(n_neighbors = k)
neigh.fit(X)
safe_minority_indices = list()
danger_minority_indices = list()
for i in range(n_samples):
if y[i] != minority_target: continue
nn = neigh.kneighbors(X[i], return_distance=False)
majority_neighbours = 0
for n in nn[0]:
if y[n] != minority_target:
majority_neighbours += 1
if majority_neighbours == len(nn):
continue
elif majority_neighbours < (len(nn)/2):
logger.debug("Add sample to safe minorities.")
safe_minority_indices.append(i)
else:
#DANGER zone
danger_minority_indices.append(i)
#SMOTE danger minority samples
synthetic_samples = _SMOTE(X[danger_minority_indices], N, k, h = 0.5)
return (X[safe_minority_indices],
synthetic_samples,
X[danger_minority_indices]) | python | def _borderlineSMOTE(X, y, minority_target, N, k):
"""
Returns synthetic minority samples.
Parameters
----------
X : array-like, shape = [n__samples, n_features]
Holds the minority and majority samples
y : array-like, shape = [n__samples]
Holds the class targets for samples
minority_target : value for minority class
N : percetange of new synthetic samples:
n_synthetic_samples = N/100 * n_minority_samples. Can be < 100.
k : int. Number of nearest neighbours.
h : high in random.uniform to scale dif of snythetic sample
Returns
-------
safe : Safe minorities
synthetic : Synthetic sample of minorities in danger zone
danger : Minorities of danger zone
"""
n_samples, _ = X.shape
#Learn nearest neighbours on complete training set
neigh = NearestNeighbors(n_neighbors = k)
neigh.fit(X)
safe_minority_indices = list()
danger_minority_indices = list()
for i in range(n_samples):
if y[i] != minority_target: continue
nn = neigh.kneighbors(X[i], return_distance=False)
majority_neighbours = 0
for n in nn[0]:
if y[n] != minority_target:
majority_neighbours += 1
if majority_neighbours == len(nn):
continue
elif majority_neighbours < (len(nn)/2):
logger.debug("Add sample to safe minorities.")
safe_minority_indices.append(i)
else:
#DANGER zone
danger_minority_indices.append(i)
#SMOTE danger minority samples
synthetic_samples = _SMOTE(X[danger_minority_indices], N, k, h = 0.5)
return (X[safe_minority_indices],
synthetic_samples,
X[danger_minority_indices]) | [
"def",
"_borderlineSMOTE",
"(",
"X",
",",
"y",
",",
"minority_target",
",",
"N",
",",
"k",
")",
":",
"n_samples",
",",
"_",
"=",
"X",
".",
"shape",
"#Learn nearest neighbours on complete training set",
"neigh",
"=",
"NearestNeighbors",
"(",
"n_neighbors",
"=",
"k",
")",
"neigh",
".",
"fit",
"(",
"X",
")",
"safe_minority_indices",
"=",
"list",
"(",
")",
"danger_minority_indices",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
":",
"if",
"y",
"[",
"i",
"]",
"!=",
"minority_target",
":",
"continue",
"nn",
"=",
"neigh",
".",
"kneighbors",
"(",
"X",
"[",
"i",
"]",
",",
"return_distance",
"=",
"False",
")",
"majority_neighbours",
"=",
"0",
"for",
"n",
"in",
"nn",
"[",
"0",
"]",
":",
"if",
"y",
"[",
"n",
"]",
"!=",
"minority_target",
":",
"majority_neighbours",
"+=",
"1",
"if",
"majority_neighbours",
"==",
"len",
"(",
"nn",
")",
":",
"continue",
"elif",
"majority_neighbours",
"<",
"(",
"len",
"(",
"nn",
")",
"/",
"2",
")",
":",
"logger",
".",
"debug",
"(",
"\"Add sample to safe minorities.\"",
")",
"safe_minority_indices",
".",
"append",
"(",
"i",
")",
"else",
":",
"#DANGER zone",
"danger_minority_indices",
".",
"append",
"(",
"i",
")",
"#SMOTE danger minority samples",
"synthetic_samples",
"=",
"_SMOTE",
"(",
"X",
"[",
"danger_minority_indices",
"]",
",",
"N",
",",
"k",
",",
"h",
"=",
"0.5",
")",
"return",
"(",
"X",
"[",
"safe_minority_indices",
"]",
",",
"synthetic_samples",
",",
"X",
"[",
"danger_minority_indices",
"]",
")"
] | Returns synthetic minority samples.
Parameters
----------
X : array-like, shape = [n__samples, n_features]
Holds the minority and majority samples
y : array-like, shape = [n__samples]
Holds the class targets for samples
minority_target : value for minority class
N : percetange of new synthetic samples:
n_synthetic_samples = N/100 * n_minority_samples. Can be < 100.
k : int. Number of nearest neighbours.
h : high in random.uniform to scale dif of snythetic sample
Returns
-------
safe : Safe minorities
synthetic : Synthetic sample of minorities in danger zone
danger : Minorities of danger zone | [
"Returns",
"synthetic",
"minority",
"samples",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/_smote.py#L91-L147 | train | 236,912 |
albahnsen/CostSensitiveClassification | costcla/models/directcost.py | BayesMinimumRiskClassifier.fit | def fit(self,y_true_cal=None, y_prob_cal=None):
""" If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_prob_cal : array-like of shape = [n_samples, 2], optional default = None
Predicted probabilities to be used for calibrating the probabilities
Returns
-------
self : object
Returns self.
"""
if self.calibration:
self.cal = ROCConvexHull()
self.cal.fit(y_true_cal, y_prob_cal[:, 1]) | python | def fit(self,y_true_cal=None, y_prob_cal=None):
""" If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_prob_cal : array-like of shape = [n_samples, 2], optional default = None
Predicted probabilities to be used for calibrating the probabilities
Returns
-------
self : object
Returns self.
"""
if self.calibration:
self.cal = ROCConvexHull()
self.cal.fit(y_true_cal, y_prob_cal[:, 1]) | [
"def",
"fit",
"(",
"self",
",",
"y_true_cal",
"=",
"None",
",",
"y_prob_cal",
"=",
"None",
")",
":",
"if",
"self",
".",
"calibration",
":",
"self",
".",
"cal",
"=",
"ROCConvexHull",
"(",
")",
"self",
".",
"cal",
".",
"fit",
"(",
"y_true_cal",
",",
"y_prob_cal",
"[",
":",
",",
"1",
"]",
")"
] | If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_prob_cal : array-like of shape = [n_samples, 2], optional default = None
Predicted probabilities to be used for calibrating the probabilities
Returns
-------
self : object
Returns self. | [
"If",
"calibration",
"then",
"train",
"the",
"calibration",
"of",
"probabilities"
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L56-L74 | train | 236,913 |
albahnsen/CostSensitiveClassification | costcla/models/directcost.py | ThresholdingOptimization.fit | def fit(self, y_prob, cost_mat, y_true):
""" Calculate the optimal threshold using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
y_true : array-like of shape = [n_samples]
True class
Returns
-------
self
"""
#TODO: Check input
if self.calibration:
cal = ROCConvexHull()
cal.fit(y_true, y_prob[:, 1])
y_prob[:, 1] = cal.predict_proba(y_prob[:, 1])
y_prob[:, 0] = 1 - y_prob[:, 1]
thresholds = np.unique(y_prob)
cost = np.zeros(thresholds.shape)
for i in range(thresholds.shape[0]):
pred = np.floor(y_prob[:, 1]+(1-thresholds[i]))
cost[i] = cost_loss(y_true, pred, cost_mat)
self.threshold_ = thresholds[np.argmin(cost)]
return self | python | def fit(self, y_prob, cost_mat, y_true):
""" Calculate the optimal threshold using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
y_true : array-like of shape = [n_samples]
True class
Returns
-------
self
"""
#TODO: Check input
if self.calibration:
cal = ROCConvexHull()
cal.fit(y_true, y_prob[:, 1])
y_prob[:, 1] = cal.predict_proba(y_prob[:, 1])
y_prob[:, 0] = 1 - y_prob[:, 1]
thresholds = np.unique(y_prob)
cost = np.zeros(thresholds.shape)
for i in range(thresholds.shape[0]):
pred = np.floor(y_prob[:, 1]+(1-thresholds[i]))
cost[i] = cost_loss(y_true, pred, cost_mat)
self.threshold_ = thresholds[np.argmin(cost)]
return self | [
"def",
"fit",
"(",
"self",
",",
"y_prob",
",",
"cost_mat",
",",
"y_true",
")",
":",
"#TODO: Check input",
"if",
"self",
".",
"calibration",
":",
"cal",
"=",
"ROCConvexHull",
"(",
")",
"cal",
".",
"fit",
"(",
"y_true",
",",
"y_prob",
"[",
":",
",",
"1",
"]",
")",
"y_prob",
"[",
":",
",",
"1",
"]",
"=",
"cal",
".",
"predict_proba",
"(",
"y_prob",
"[",
":",
",",
"1",
"]",
")",
"y_prob",
"[",
":",
",",
"0",
"]",
"=",
"1",
"-",
"y_prob",
"[",
":",
",",
"1",
"]",
"thresholds",
"=",
"np",
".",
"unique",
"(",
"y_prob",
")",
"cost",
"=",
"np",
".",
"zeros",
"(",
"thresholds",
".",
"shape",
")",
"for",
"i",
"in",
"range",
"(",
"thresholds",
".",
"shape",
"[",
"0",
"]",
")",
":",
"pred",
"=",
"np",
".",
"floor",
"(",
"y_prob",
"[",
":",
",",
"1",
"]",
"+",
"(",
"1",
"-",
"thresholds",
"[",
"i",
"]",
")",
")",
"cost",
"[",
"i",
"]",
"=",
"cost_loss",
"(",
"y_true",
",",
"pred",
",",
"cost_mat",
")",
"self",
".",
"threshold_",
"=",
"thresholds",
"[",
"np",
".",
"argmin",
"(",
"cost",
")",
"]",
"return",
"self"
] | Calculate the optimal threshold using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
y_true : array-like of shape = [n_samples]
True class
Returns
-------
self | [
"Calculate",
"the",
"optimal",
"threshold",
"using",
"the",
"ThresholdingOptimization",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L199-L238 | train | 236,914 |
albahnsen/CostSensitiveClassification | costcla/models/directcost.py | ThresholdingOptimization.predict | def predict(self, y_prob):
""" Calculate the prediction using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
Returns
-------
y_pred : array-like of shape = [n_samples]
Predicted class
"""
y_pred = np.floor(y_prob[:, 1] + (1 - self.threshold_))
return y_pred | python | def predict(self, y_prob):
""" Calculate the prediction using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
Returns
-------
y_pred : array-like of shape = [n_samples]
Predicted class
"""
y_pred = np.floor(y_prob[:, 1] + (1 - self.threshold_))
return y_pred | [
"def",
"predict",
"(",
"self",
",",
"y_prob",
")",
":",
"y_pred",
"=",
"np",
".",
"floor",
"(",
"y_prob",
"[",
":",
",",
"1",
"]",
"+",
"(",
"1",
"-",
"self",
".",
"threshold_",
")",
")",
"return",
"y_pred"
] | Calculate the prediction using the ThresholdingOptimization.
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities.
Returns
-------
y_pred : array-like of shape = [n_samples]
Predicted class | [
"Calculate",
"the",
"prediction",
"using",
"the",
"ThresholdingOptimization",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L240-L255 | train | 236,915 |
albahnsen/CostSensitiveClassification | costcla/sampling/sampling.py | undersampling | def undersampling(X, y, cost_mat=None, per=0.5):
"""Under-sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4], optional (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
per: float, optional (default = 0.5)
Percentage of the minority class in the under-sampled data
"""
n_samples = X.shape[0]
#TODO: allow y different from (0, 1)
num_y1 = y.sum()
num_y0 = n_samples - num_y1
filter_rand = np.random.rand(int(num_y1 + num_y0))
#TODO: rewrite in a more readable way
if num_y1 < num_y0:
num_y0_new = num_y1 * 1.0 / per - num_y1
num_y0_new_per = num_y0_new * 1.0 / num_y0
filter_0 = np.logical_and(y == 0, filter_rand <= num_y0_new_per)
filter_ = np.nonzero(np.logical_or(y == 1, filter_0))[0]
else:
num_y1_new = num_y0 * 1.0 / per - num_y0
num_y1_new_per = num_y1_new * 1.0 / num_y1
filter_1 = np.logical_and(y == 1, filter_rand <= num_y1_new_per)
filter_ = np.nonzero(np.logical_or(y == 0, filter_1))[0]
X_u = X[filter_, :]
y_u = y[filter_]
if not cost_mat is None:
cost_mat_u = cost_mat[filter_, :]
return X_u, y_u, cost_mat_u
else:
return X_u, y_u | python | def undersampling(X, y, cost_mat=None, per=0.5):
"""Under-sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4], optional (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
per: float, optional (default = 0.5)
Percentage of the minority class in the under-sampled data
"""
n_samples = X.shape[0]
#TODO: allow y different from (0, 1)
num_y1 = y.sum()
num_y0 = n_samples - num_y1
filter_rand = np.random.rand(int(num_y1 + num_y0))
#TODO: rewrite in a more readable way
if num_y1 < num_y0:
num_y0_new = num_y1 * 1.0 / per - num_y1
num_y0_new_per = num_y0_new * 1.0 / num_y0
filter_0 = np.logical_and(y == 0, filter_rand <= num_y0_new_per)
filter_ = np.nonzero(np.logical_or(y == 1, filter_0))[0]
else:
num_y1_new = num_y0 * 1.0 / per - num_y0
num_y1_new_per = num_y1_new * 1.0 / num_y1
filter_1 = np.logical_and(y == 1, filter_rand <= num_y1_new_per)
filter_ = np.nonzero(np.logical_or(y == 0, filter_1))[0]
X_u = X[filter_, :]
y_u = y[filter_]
if not cost_mat is None:
cost_mat_u = cost_mat[filter_, :]
return X_u, y_u, cost_mat_u
else:
return X_u, y_u | [
"def",
"undersampling",
"(",
"X",
",",
"y",
",",
"cost_mat",
"=",
"None",
",",
"per",
"=",
"0.5",
")",
":",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"#TODO: allow y different from (0, 1)",
"num_y1",
"=",
"y",
".",
"sum",
"(",
")",
"num_y0",
"=",
"n_samples",
"-",
"num_y1",
"filter_rand",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"int",
"(",
"num_y1",
"+",
"num_y0",
")",
")",
"#TODO: rewrite in a more readable way",
"if",
"num_y1",
"<",
"num_y0",
":",
"num_y0_new",
"=",
"num_y1",
"*",
"1.0",
"/",
"per",
"-",
"num_y1",
"num_y0_new_per",
"=",
"num_y0_new",
"*",
"1.0",
"/",
"num_y0",
"filter_0",
"=",
"np",
".",
"logical_and",
"(",
"y",
"==",
"0",
",",
"filter_rand",
"<=",
"num_y0_new_per",
")",
"filter_",
"=",
"np",
".",
"nonzero",
"(",
"np",
".",
"logical_or",
"(",
"y",
"==",
"1",
",",
"filter_0",
")",
")",
"[",
"0",
"]",
"else",
":",
"num_y1_new",
"=",
"num_y0",
"*",
"1.0",
"/",
"per",
"-",
"num_y0",
"num_y1_new_per",
"=",
"num_y1_new",
"*",
"1.0",
"/",
"num_y1",
"filter_1",
"=",
"np",
".",
"logical_and",
"(",
"y",
"==",
"1",
",",
"filter_rand",
"<=",
"num_y1_new_per",
")",
"filter_",
"=",
"np",
".",
"nonzero",
"(",
"np",
".",
"logical_or",
"(",
"y",
"==",
"0",
",",
"filter_1",
")",
")",
"[",
"0",
"]",
"X_u",
"=",
"X",
"[",
"filter_",
",",
":",
"]",
"y_u",
"=",
"y",
"[",
"filter_",
"]",
"if",
"not",
"cost_mat",
"is",
"None",
":",
"cost_mat_u",
"=",
"cost_mat",
"[",
"filter_",
",",
":",
"]",
"return",
"X_u",
",",
"y_u",
",",
"cost_mat_u",
"else",
":",
"return",
"X_u",
",",
"y_u"
] | Under-sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4], optional (default=None)
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
per: float, optional (default = 0.5)
Percentage of the minority class in the under-sampled data | [
"Under",
"-",
"sampling",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/sampling.py#L11-L57 | train | 236,916 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._node_cost | def _node_cost(self, y_true, cost_mat):
""" Private function to calculate the cost of a node.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(cost_loss : float, node prediction : int, node predicted probability : float)
"""
n_samples = len(y_true)
# Evaluates the cost by predicting the node as positive and negative
costs = np.zeros(2)
costs[0] = cost_loss(y_true, np.zeros(y_true.shape), cost_mat)
costs[1] = cost_loss(y_true, np.ones(y_true.shape), cost_mat)
pi = np.array([1 - y_true.mean(), y_true.mean()])
if self.criterion == 'direct_cost':
costs = costs
elif self.criterion == 'pi_cost':
costs *= pi
elif self.criterion == 'gini_cost':
costs *= pi ** 2
elif self.criterion in 'entropy_cost':
if pi[0] == 0 or pi[1] == 0:
costs *= 0
else:
costs *= -np.log(pi)
y_pred = np.argmin(costs)
# Calculate the predicted probability of a node using laplace correction.
n_positives = y_true.sum()
y_prob = (n_positives + 1.0) / (n_samples + 2.0)
return costs[y_pred], y_pred, y_prob | python | def _node_cost(self, y_true, cost_mat):
""" Private function to calculate the cost of a node.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(cost_loss : float, node prediction : int, node predicted probability : float)
"""
n_samples = len(y_true)
# Evaluates the cost by predicting the node as positive and negative
costs = np.zeros(2)
costs[0] = cost_loss(y_true, np.zeros(y_true.shape), cost_mat)
costs[1] = cost_loss(y_true, np.ones(y_true.shape), cost_mat)
pi = np.array([1 - y_true.mean(), y_true.mean()])
if self.criterion == 'direct_cost':
costs = costs
elif self.criterion == 'pi_cost':
costs *= pi
elif self.criterion == 'gini_cost':
costs *= pi ** 2
elif self.criterion in 'entropy_cost':
if pi[0] == 0 or pi[1] == 0:
costs *= 0
else:
costs *= -np.log(pi)
y_pred = np.argmin(costs)
# Calculate the predicted probability of a node using laplace correction.
n_positives = y_true.sum()
y_prob = (n_positives + 1.0) / (n_samples + 2.0)
return costs[y_pred], y_pred, y_prob | [
"def",
"_node_cost",
"(",
"self",
",",
"y_true",
",",
"cost_mat",
")",
":",
"n_samples",
"=",
"len",
"(",
"y_true",
")",
"# Evaluates the cost by predicting the node as positive and negative",
"costs",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
"costs",
"[",
"0",
"]",
"=",
"cost_loss",
"(",
"y_true",
",",
"np",
".",
"zeros",
"(",
"y_true",
".",
"shape",
")",
",",
"cost_mat",
")",
"costs",
"[",
"1",
"]",
"=",
"cost_loss",
"(",
"y_true",
",",
"np",
".",
"ones",
"(",
"y_true",
".",
"shape",
")",
",",
"cost_mat",
")",
"pi",
"=",
"np",
".",
"array",
"(",
"[",
"1",
"-",
"y_true",
".",
"mean",
"(",
")",
",",
"y_true",
".",
"mean",
"(",
")",
"]",
")",
"if",
"self",
".",
"criterion",
"==",
"'direct_cost'",
":",
"costs",
"=",
"costs",
"elif",
"self",
".",
"criterion",
"==",
"'pi_cost'",
":",
"costs",
"*=",
"pi",
"elif",
"self",
".",
"criterion",
"==",
"'gini_cost'",
":",
"costs",
"*=",
"pi",
"**",
"2",
"elif",
"self",
".",
"criterion",
"in",
"'entropy_cost'",
":",
"if",
"pi",
"[",
"0",
"]",
"==",
"0",
"or",
"pi",
"[",
"1",
"]",
"==",
"0",
":",
"costs",
"*=",
"0",
"else",
":",
"costs",
"*=",
"-",
"np",
".",
"log",
"(",
"pi",
")",
"y_pred",
"=",
"np",
".",
"argmin",
"(",
"costs",
")",
"# Calculate the predicted probability of a node using laplace correction.",
"n_positives",
"=",
"y_true",
".",
"sum",
"(",
")",
"y_prob",
"=",
"(",
"n_positives",
"+",
"1.0",
")",
"/",
"(",
"n_samples",
"+",
"2.0",
")",
"return",
"costs",
"[",
"y_pred",
"]",
",",
"y_pred",
",",
"y_prob"
] | Private function to calculate the cost of a node.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(cost_loss : float, node prediction : int, node predicted probability : float) | [
"Private",
"function",
"to",
"calculate",
"the",
"cost",
"of",
"a",
"node",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L138-L183 | train | 236,917 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._calculate_gain | def _calculate_gain(self, cost_base, y_true, X, cost_mat, split):
""" Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
split : tuple of len = 2
split[0] = feature to split = j
split[1] = where to split = l
Returns
-------
tuple(gain : float, left node prediction : int)
"""
# Check if cost_base == 0, then no gain is possible
#TODO: This must be check in _best_split
if cost_base == 0.0:
return 0.0, int(np.sign(y_true.mean() - 0.5) == 1) # In case cost_b==0 and pi_1!=(0,1)
j, l = split
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples, n_features = X.shape
# Check if one of the leafs is empty
#TODO: This must be check in _best_split
if np.nonzero(filter_Xl)[0].shape[0] in [0, n_samples]: # One leaft is empty
return 0.0, 0.0
# Split X in Xl and Xr according to rule split
Xl_cost, Xl_pred, _ = self._node_cost(y_true[filter_Xl], cost_mat[filter_Xl, :])
Xr_cost, _, _ = self._node_cost(y_true[filter_Xr], cost_mat[filter_Xr, :])
if self.criterion_weight:
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
Xl_w = n_samples_Xl * 1.0 / n_samples
Xr_w = 1 - Xl_w
gain = round((cost_base - (Xl_w * Xl_cost + Xr_w * Xr_cost)) / cost_base, 6)
else:
gain = round((cost_base - (Xl_cost + Xr_cost)) / cost_base, 6)
return gain, Xl_pred | python | def _calculate_gain(self, cost_base, y_true, X, cost_mat, split):
""" Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
split : tuple of len = 2
split[0] = feature to split = j
split[1] = where to split = l
Returns
-------
tuple(gain : float, left node prediction : int)
"""
# Check if cost_base == 0, then no gain is possible
#TODO: This must be check in _best_split
if cost_base == 0.0:
return 0.0, int(np.sign(y_true.mean() - 0.5) == 1) # In case cost_b==0 and pi_1!=(0,1)
j, l = split
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples, n_features = X.shape
# Check if one of the leafs is empty
#TODO: This must be check in _best_split
if np.nonzero(filter_Xl)[0].shape[0] in [0, n_samples]: # One leaft is empty
return 0.0, 0.0
# Split X in Xl and Xr according to rule split
Xl_cost, Xl_pred, _ = self._node_cost(y_true[filter_Xl], cost_mat[filter_Xl, :])
Xr_cost, _, _ = self._node_cost(y_true[filter_Xr], cost_mat[filter_Xr, :])
if self.criterion_weight:
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
Xl_w = n_samples_Xl * 1.0 / n_samples
Xr_w = 1 - Xl_w
gain = round((cost_base - (Xl_w * Xl_cost + Xr_w * Xr_cost)) / cost_base, 6)
else:
gain = round((cost_base - (Xl_cost + Xr_cost)) / cost_base, 6)
return gain, Xl_pred | [
"def",
"_calculate_gain",
"(",
"self",
",",
"cost_base",
",",
"y_true",
",",
"X",
",",
"cost_mat",
",",
"split",
")",
":",
"# Check if cost_base == 0, then no gain is possible",
"#TODO: This must be check in _best_split",
"if",
"cost_base",
"==",
"0.0",
":",
"return",
"0.0",
",",
"int",
"(",
"np",
".",
"sign",
"(",
"y_true",
".",
"mean",
"(",
")",
"-",
"0.5",
")",
"==",
"1",
")",
"# In case cost_b==0 and pi_1!=(0,1)",
"j",
",",
"l",
"=",
"split",
"filter_Xl",
"=",
"(",
"X",
"[",
":",
",",
"j",
"]",
"<=",
"l",
")",
"filter_Xr",
"=",
"~",
"filter_Xl",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"# Check if one of the leafs is empty",
"#TODO: This must be check in _best_split",
"if",
"np",
".",
"nonzero",
"(",
"filter_Xl",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"in",
"[",
"0",
",",
"n_samples",
"]",
":",
"# One leaft is empty",
"return",
"0.0",
",",
"0.0",
"# Split X in Xl and Xr according to rule split",
"Xl_cost",
",",
"Xl_pred",
",",
"_",
"=",
"self",
".",
"_node_cost",
"(",
"y_true",
"[",
"filter_Xl",
"]",
",",
"cost_mat",
"[",
"filter_Xl",
",",
":",
"]",
")",
"Xr_cost",
",",
"_",
",",
"_",
"=",
"self",
".",
"_node_cost",
"(",
"y_true",
"[",
"filter_Xr",
"]",
",",
"cost_mat",
"[",
"filter_Xr",
",",
":",
"]",
")",
"if",
"self",
".",
"criterion_weight",
":",
"n_samples_Xl",
"=",
"np",
".",
"nonzero",
"(",
"filter_Xl",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"Xl_w",
"=",
"n_samples_Xl",
"*",
"1.0",
"/",
"n_samples",
"Xr_w",
"=",
"1",
"-",
"Xl_w",
"gain",
"=",
"round",
"(",
"(",
"cost_base",
"-",
"(",
"Xl_w",
"*",
"Xl_cost",
"+",
"Xr_w",
"*",
"Xr_cost",
")",
")",
"/",
"cost_base",
",",
"6",
")",
"else",
":",
"gain",
"=",
"round",
"(",
"(",
"cost_base",
"-",
"(",
"Xl_cost",
"+",
"Xr_cost",
")",
")",
"/",
"cost_base",
",",
"6",
")",
"return",
"gain",
",",
"Xl_pred"
] | Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
split : tuple of len = 2
split[0] = feature to split = j
split[1] = where to split = l
Returns
-------
tuple(gain : float, left node prediction : int) | [
"Private",
"function",
"to",
"calculate",
"the",
"gain",
"in",
"cost",
"of",
"using",
"split",
"in",
"the",
"current",
"node",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L185-L242 | train | 236,918 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._best_split | def _best_split(self, y_true, X, cost_mat):
""" Private function to calculate the split that gives the best gain.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(split : tuple(j, l), gain : float, left node prediction : int,
y_pred : int, y_prob : float)
"""
n_samples, n_features = X.shape
num_pct = self.num_pct
cost_base, y_pred, y_prob = self._node_cost(y_true, cost_mat)
# Calculate the gain of all features each split in num_pct
gains = np.zeros((n_features, num_pct))
pred = np.zeros((n_features, num_pct))
splits = np.zeros((n_features, num_pct))
# Selected features
selected_features = np.arange(0, self.n_features_)
# Add random state
np.random.shuffle(selected_features)
selected_features = selected_features[:self.max_features_]
selected_features.sort()
#TODO: # Skip the CPU intensive evaluation of the impurity criterion for
# features that were already detected as constant (hence not suitable
# for good splitting) by ancestor nodes and save the information on
# newly discovered constant features to spare computation on descendant
# nodes.
# For each feature test all possible splits
for j in selected_features:
splits[j, :] = np.percentile(X[:, j], np.arange(0, 100, 100.0 / num_pct).tolist())
for l in range(num_pct):
# Avoid repeated values, since np.percentile may return repeated values
if l == 0 or (l > 0 and splits[j, l] != splits[j, l - 1]):
split = (j, splits[j, l])
gains[j, l], pred[j, l] = self._calculate_gain(cost_base, y_true, X, cost_mat, split)
best_split = np.unravel_index(gains.argmax(), gains.shape)
return (best_split[0], splits[best_split]), gains.max(), pred[best_split], y_pred, y_prob | python | def _best_split(self, y_true, X, cost_mat):
""" Private function to calculate the split that gives the best gain.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(split : tuple(j, l), gain : float, left node prediction : int,
y_pred : int, y_prob : float)
"""
n_samples, n_features = X.shape
num_pct = self.num_pct
cost_base, y_pred, y_prob = self._node_cost(y_true, cost_mat)
# Calculate the gain of all features each split in num_pct
gains = np.zeros((n_features, num_pct))
pred = np.zeros((n_features, num_pct))
splits = np.zeros((n_features, num_pct))
# Selected features
selected_features = np.arange(0, self.n_features_)
# Add random state
np.random.shuffle(selected_features)
selected_features = selected_features[:self.max_features_]
selected_features.sort()
#TODO: # Skip the CPU intensive evaluation of the impurity criterion for
# features that were already detected as constant (hence not suitable
# for good splitting) by ancestor nodes and save the information on
# newly discovered constant features to spare computation on descendant
# nodes.
# For each feature test all possible splits
for j in selected_features:
splits[j, :] = np.percentile(X[:, j], np.arange(0, 100, 100.0 / num_pct).tolist())
for l in range(num_pct):
# Avoid repeated values, since np.percentile may return repeated values
if l == 0 or (l > 0 and splits[j, l] != splits[j, l - 1]):
split = (j, splits[j, l])
gains[j, l], pred[j, l] = self._calculate_gain(cost_base, y_true, X, cost_mat, split)
best_split = np.unravel_index(gains.argmax(), gains.shape)
return (best_split[0], splits[best_split]), gains.max(), pred[best_split], y_pred, y_prob | [
"def",
"_best_split",
"(",
"self",
",",
"y_true",
",",
"X",
",",
"cost_mat",
")",
":",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"num_pct",
"=",
"self",
".",
"num_pct",
"cost_base",
",",
"y_pred",
",",
"y_prob",
"=",
"self",
".",
"_node_cost",
"(",
"y_true",
",",
"cost_mat",
")",
"# Calculate the gain of all features each split in num_pct",
"gains",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_features",
",",
"num_pct",
")",
")",
"pred",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_features",
",",
"num_pct",
")",
")",
"splits",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_features",
",",
"num_pct",
")",
")",
"# Selected features",
"selected_features",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"self",
".",
"n_features_",
")",
"# Add random state",
"np",
".",
"random",
".",
"shuffle",
"(",
"selected_features",
")",
"selected_features",
"=",
"selected_features",
"[",
":",
"self",
".",
"max_features_",
"]",
"selected_features",
".",
"sort",
"(",
")",
"#TODO: # Skip the CPU intensive evaluation of the impurity criterion for",
"# features that were already detected as constant (hence not suitable",
"# for good splitting) by ancestor nodes and save the information on",
"# newly discovered constant features to spare computation on descendant",
"# nodes.",
"# For each feature test all possible splits",
"for",
"j",
"in",
"selected_features",
":",
"splits",
"[",
"j",
",",
":",
"]",
"=",
"np",
".",
"percentile",
"(",
"X",
"[",
":",
",",
"j",
"]",
",",
"np",
".",
"arange",
"(",
"0",
",",
"100",
",",
"100.0",
"/",
"num_pct",
")",
".",
"tolist",
"(",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_pct",
")",
":",
"# Avoid repeated values, since np.percentile may return repeated values",
"if",
"l",
"==",
"0",
"or",
"(",
"l",
">",
"0",
"and",
"splits",
"[",
"j",
",",
"l",
"]",
"!=",
"splits",
"[",
"j",
",",
"l",
"-",
"1",
"]",
")",
":",
"split",
"=",
"(",
"j",
",",
"splits",
"[",
"j",
",",
"l",
"]",
")",
"gains",
"[",
"j",
",",
"l",
"]",
",",
"pred",
"[",
"j",
",",
"l",
"]",
"=",
"self",
".",
"_calculate_gain",
"(",
"cost_base",
",",
"y_true",
",",
"X",
",",
"cost_mat",
",",
"split",
")",
"best_split",
"=",
"np",
".",
"unravel_index",
"(",
"gains",
".",
"argmax",
"(",
")",
",",
"gains",
".",
"shape",
")",
"return",
"(",
"best_split",
"[",
"0",
"]",
",",
"splits",
"[",
"best_split",
"]",
")",
",",
"gains",
".",
"max",
"(",
")",
",",
"pred",
"[",
"best_split",
"]",
",",
"y_pred",
",",
"y_prob"
] | Private function to calculate the split that gives the best gain.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
tuple(split : tuple(j, l), gain : float, left node prediction : int,
y_pred : int, y_prob : float) | [
"Private",
"function",
"to",
"calculate",
"the",
"split",
"that",
"gives",
"the",
"best",
"gain",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L244-L302 | train | 236,919 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._tree_grow | def _tree_grow(self, y_true, X, cost_mat, level=0):
""" Private recursive function to grow the decision tree.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
Tree : Object
Container of the decision tree
NOTE: it is not the same structure as the sklearn.tree.tree object
"""
#TODO: Find error, add min_samples_split
if len(X.shape) == 1:
tree = dict(y_pred=y_true, y_prob=0.5, level=level, split=-1, n_samples=1, gain=0)
return tree
# Calculate the best split of the current node
split, gain, Xl_pred, y_pred, y_prob = self._best_split(y_true, X, cost_mat)
n_samples, n_features = X.shape
# Construct the tree object as a dictionary
#TODO: Convert tree to be equal to sklearn.tree.tree object
tree = dict(y_pred=y_pred, y_prob=y_prob, level=level, split=-1, n_samples=n_samples, gain=gain)
# Check the stopping criteria
if gain < self.min_gain:
return tree
if self.max_depth is not None:
if level >= self.max_depth:
return tree
if n_samples <= self.min_samples_split:
return tree
j, l = split
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
n_samples_Xr = np.nonzero(filter_Xr)[0].shape[0]
if min(n_samples_Xl, n_samples_Xr) <= self.min_samples_leaf:
return tree
# No stooping criteria is met
tree['split'] = split
tree['node'] = self.tree_.n_nodes
self.tree_.n_nodes += 1
tree['sl'] = self._tree_grow(y_true[filter_Xl], X[filter_Xl], cost_mat[filter_Xl], level + 1)
tree['sr'] = self._tree_grow(y_true[filter_Xr], X[filter_Xr], cost_mat[filter_Xr], level + 1)
return tree | python | def _tree_grow(self, y_true, X, cost_mat, level=0):
""" Private recursive function to grow the decision tree.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
Tree : Object
Container of the decision tree
NOTE: it is not the same structure as the sklearn.tree.tree object
"""
#TODO: Find error, add min_samples_split
if len(X.shape) == 1:
tree = dict(y_pred=y_true, y_prob=0.5, level=level, split=-1, n_samples=1, gain=0)
return tree
# Calculate the best split of the current node
split, gain, Xl_pred, y_pred, y_prob = self._best_split(y_true, X, cost_mat)
n_samples, n_features = X.shape
# Construct the tree object as a dictionary
#TODO: Convert tree to be equal to sklearn.tree.tree object
tree = dict(y_pred=y_pred, y_prob=y_prob, level=level, split=-1, n_samples=n_samples, gain=gain)
# Check the stopping criteria
if gain < self.min_gain:
return tree
if self.max_depth is not None:
if level >= self.max_depth:
return tree
if n_samples <= self.min_samples_split:
return tree
j, l = split
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
n_samples_Xr = np.nonzero(filter_Xr)[0].shape[0]
if min(n_samples_Xl, n_samples_Xr) <= self.min_samples_leaf:
return tree
# No stooping criteria is met
tree['split'] = split
tree['node'] = self.tree_.n_nodes
self.tree_.n_nodes += 1
tree['sl'] = self._tree_grow(y_true[filter_Xl], X[filter_Xl], cost_mat[filter_Xl], level + 1)
tree['sr'] = self._tree_grow(y_true[filter_Xr], X[filter_Xr], cost_mat[filter_Xr], level + 1)
return tree | [
"def",
"_tree_grow",
"(",
"self",
",",
"y_true",
",",
"X",
",",
"cost_mat",
",",
"level",
"=",
"0",
")",
":",
"#TODO: Find error, add min_samples_split",
"if",
"len",
"(",
"X",
".",
"shape",
")",
"==",
"1",
":",
"tree",
"=",
"dict",
"(",
"y_pred",
"=",
"y_true",
",",
"y_prob",
"=",
"0.5",
",",
"level",
"=",
"level",
",",
"split",
"=",
"-",
"1",
",",
"n_samples",
"=",
"1",
",",
"gain",
"=",
"0",
")",
"return",
"tree",
"# Calculate the best split of the current node",
"split",
",",
"gain",
",",
"Xl_pred",
",",
"y_pred",
",",
"y_prob",
"=",
"self",
".",
"_best_split",
"(",
"y_true",
",",
"X",
",",
"cost_mat",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"# Construct the tree object as a dictionary",
"#TODO: Convert tree to be equal to sklearn.tree.tree object",
"tree",
"=",
"dict",
"(",
"y_pred",
"=",
"y_pred",
",",
"y_prob",
"=",
"y_prob",
",",
"level",
"=",
"level",
",",
"split",
"=",
"-",
"1",
",",
"n_samples",
"=",
"n_samples",
",",
"gain",
"=",
"gain",
")",
"# Check the stopping criteria",
"if",
"gain",
"<",
"self",
".",
"min_gain",
":",
"return",
"tree",
"if",
"self",
".",
"max_depth",
"is",
"not",
"None",
":",
"if",
"level",
">=",
"self",
".",
"max_depth",
":",
"return",
"tree",
"if",
"n_samples",
"<=",
"self",
".",
"min_samples_split",
":",
"return",
"tree",
"j",
",",
"l",
"=",
"split",
"filter_Xl",
"=",
"(",
"X",
"[",
":",
",",
"j",
"]",
"<=",
"l",
")",
"filter_Xr",
"=",
"~",
"filter_Xl",
"n_samples_Xl",
"=",
"np",
".",
"nonzero",
"(",
"filter_Xl",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"n_samples_Xr",
"=",
"np",
".",
"nonzero",
"(",
"filter_Xr",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"min",
"(",
"n_samples_Xl",
",",
"n_samples_Xr",
")",
"<=",
"self",
".",
"min_samples_leaf",
":",
"return",
"tree",
"# No stooping criteria is met",
"tree",
"[",
"'split'",
"]",
"=",
"split",
"tree",
"[",
"'node'",
"]",
"=",
"self",
".",
"tree_",
".",
"n_nodes",
"self",
".",
"tree_",
".",
"n_nodes",
"+=",
"1",
"tree",
"[",
"'sl'",
"]",
"=",
"self",
".",
"_tree_grow",
"(",
"y_true",
"[",
"filter_Xl",
"]",
",",
"X",
"[",
"filter_Xl",
"]",
",",
"cost_mat",
"[",
"filter_Xl",
"]",
",",
"level",
"+",
"1",
")",
"tree",
"[",
"'sr'",
"]",
"=",
"self",
".",
"_tree_grow",
"(",
"y_true",
"[",
"filter_Xr",
"]",
",",
"X",
"[",
"filter_Xr",
"]",
",",
"cost_mat",
"[",
"filter_Xr",
"]",
",",
"level",
"+",
"1",
")",
"return",
"tree"
] | Private recursive function to grow the decision tree.
Parameters
----------
y_true : array indicator matrix
Ground truth (correct) labels.
X : array-like of shape = [n_samples, n_features]
The input samples.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
Tree : Object
Container of the decision tree
NOTE: it is not the same structure as the sklearn.tree.tree object | [
"Private",
"recursive",
"function",
"to",
"grow",
"the",
"decision",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L304-L369 | train | 236,920 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._nodes | def _nodes(self, tree):
""" Private function that find the number of nodes in a tree.
Parameters
----------
tree : object
Returns
-------
nodes : array like of shape [n_nodes]
"""
def recourse(temp_tree_, nodes):
if isinstance(temp_tree_, dict):
if temp_tree_['split'] != -1:
nodes.append(temp_tree_['node'])
if temp_tree_['split'] != -1:
for k in ['sl', 'sr']:
recourse(temp_tree_[k], nodes)
return None
nodes_ = []
recourse(tree, nodes_)
return nodes_ | python | def _nodes(self, tree):
""" Private function that find the number of nodes in a tree.
Parameters
----------
tree : object
Returns
-------
nodes : array like of shape [n_nodes]
"""
def recourse(temp_tree_, nodes):
if isinstance(temp_tree_, dict):
if temp_tree_['split'] != -1:
nodes.append(temp_tree_['node'])
if temp_tree_['split'] != -1:
for k in ['sl', 'sr']:
recourse(temp_tree_[k], nodes)
return None
nodes_ = []
recourse(tree, nodes_)
return nodes_ | [
"def",
"_nodes",
"(",
"self",
",",
"tree",
")",
":",
"def",
"recourse",
"(",
"temp_tree_",
",",
"nodes",
")",
":",
"if",
"isinstance",
"(",
"temp_tree_",
",",
"dict",
")",
":",
"if",
"temp_tree_",
"[",
"'split'",
"]",
"!=",
"-",
"1",
":",
"nodes",
".",
"append",
"(",
"temp_tree_",
"[",
"'node'",
"]",
")",
"if",
"temp_tree_",
"[",
"'split'",
"]",
"!=",
"-",
"1",
":",
"for",
"k",
"in",
"[",
"'sl'",
",",
"'sr'",
"]",
":",
"recourse",
"(",
"temp_tree_",
"[",
"k",
"]",
",",
"nodes",
")",
"return",
"None",
"nodes_",
"=",
"[",
"]",
"recourse",
"(",
"tree",
",",
"nodes_",
")",
"return",
"nodes_"
] | Private function that find the number of nodes in a tree.
Parameters
----------
tree : object
Returns
-------
nodes : array like of shape [n_nodes] | [
"Private",
"function",
"that",
"find",
"the",
"number",
"of",
"nodes",
"in",
"a",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L444-L466 | train | 236,921 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._classify | def _classify(self, X, tree, proba=False):
""" Private function that classify a dataset using tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
tree : object
proba : bool, optional (default=False)
If True then return probabilities else return class
Returns
-------
prediction : array of shape = [n_samples]
If proba then return the predicted positive probabilities, else return
the predicted class for each example in X
"""
n_samples, n_features = X.shape
predicted = np.ones(n_samples)
# Check if final node
if tree['split'] == -1:
if not proba:
predicted = predicted * tree['y_pred']
else:
predicted = predicted * tree['y_prob']
else:
j, l = tree['split']
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
n_samples_Xr = np.nonzero(filter_Xr)[0].shape[0]
if n_samples_Xl == 0: # If left node is empty only continue with right
predicted[filter_Xr] = self._classify(X[filter_Xr, :], tree['sr'], proba)
elif n_samples_Xr == 0: # If right node is empty only continue with left
predicted[filter_Xl] = self._classify(X[filter_Xl, :], tree['sl'], proba)
else:
predicted[filter_Xl] = self._classify(X[filter_Xl, :], tree['sl'], proba)
predicted[filter_Xr] = self._classify(X[filter_Xr, :], tree['sr'], proba)
return predicted | python | def _classify(self, X, tree, proba=False):
""" Private function that classify a dataset using tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
tree : object
proba : bool, optional (default=False)
If True then return probabilities else return class
Returns
-------
prediction : array of shape = [n_samples]
If proba then return the predicted positive probabilities, else return
the predicted class for each example in X
"""
n_samples, n_features = X.shape
predicted = np.ones(n_samples)
# Check if final node
if tree['split'] == -1:
if not proba:
predicted = predicted * tree['y_pred']
else:
predicted = predicted * tree['y_prob']
else:
j, l = tree['split']
filter_Xl = (X[:, j] <= l)
filter_Xr = ~filter_Xl
n_samples_Xl = np.nonzero(filter_Xl)[0].shape[0]
n_samples_Xr = np.nonzero(filter_Xr)[0].shape[0]
if n_samples_Xl == 0: # If left node is empty only continue with right
predicted[filter_Xr] = self._classify(X[filter_Xr, :], tree['sr'], proba)
elif n_samples_Xr == 0: # If right node is empty only continue with left
predicted[filter_Xl] = self._classify(X[filter_Xl, :], tree['sl'], proba)
else:
predicted[filter_Xl] = self._classify(X[filter_Xl, :], tree['sl'], proba)
predicted[filter_Xr] = self._classify(X[filter_Xr, :], tree['sr'], proba)
return predicted | [
"def",
"_classify",
"(",
"self",
",",
"X",
",",
"tree",
",",
"proba",
"=",
"False",
")",
":",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"predicted",
"=",
"np",
".",
"ones",
"(",
"n_samples",
")",
"# Check if final node",
"if",
"tree",
"[",
"'split'",
"]",
"==",
"-",
"1",
":",
"if",
"not",
"proba",
":",
"predicted",
"=",
"predicted",
"*",
"tree",
"[",
"'y_pred'",
"]",
"else",
":",
"predicted",
"=",
"predicted",
"*",
"tree",
"[",
"'y_prob'",
"]",
"else",
":",
"j",
",",
"l",
"=",
"tree",
"[",
"'split'",
"]",
"filter_Xl",
"=",
"(",
"X",
"[",
":",
",",
"j",
"]",
"<=",
"l",
")",
"filter_Xr",
"=",
"~",
"filter_Xl",
"n_samples_Xl",
"=",
"np",
".",
"nonzero",
"(",
"filter_Xl",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"n_samples_Xr",
"=",
"np",
".",
"nonzero",
"(",
"filter_Xr",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"n_samples_Xl",
"==",
"0",
":",
"# If left node is empty only continue with right",
"predicted",
"[",
"filter_Xr",
"]",
"=",
"self",
".",
"_classify",
"(",
"X",
"[",
"filter_Xr",
",",
":",
"]",
",",
"tree",
"[",
"'sr'",
"]",
",",
"proba",
")",
"elif",
"n_samples_Xr",
"==",
"0",
":",
"# If right node is empty only continue with left",
"predicted",
"[",
"filter_Xl",
"]",
"=",
"self",
".",
"_classify",
"(",
"X",
"[",
"filter_Xl",
",",
":",
"]",
",",
"tree",
"[",
"'sl'",
"]",
",",
"proba",
")",
"else",
":",
"predicted",
"[",
"filter_Xl",
"]",
"=",
"self",
".",
"_classify",
"(",
"X",
"[",
"filter_Xl",
",",
":",
"]",
",",
"tree",
"[",
"'sl'",
"]",
",",
"proba",
")",
"predicted",
"[",
"filter_Xr",
"]",
"=",
"self",
".",
"_classify",
"(",
"X",
"[",
"filter_Xr",
",",
":",
"]",
",",
"tree",
"[",
"'sr'",
"]",
",",
"proba",
")",
"return",
"predicted"
] | Private function that classify a dataset using tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
tree : object
proba : bool, optional (default=False)
If True then return probabilities else return class
Returns
-------
prediction : array of shape = [n_samples]
If proba then return the predicted positive probabilities, else return
the predicted class for each example in X | [
"Private",
"function",
"that",
"classify",
"a",
"dataset",
"using",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L468-L513 | train | 236,922 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier.predict | def predict(self, X):
""" Predict class of X.
The predicted class for each sample in X is returned.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted classes,
"""
#TODO: Check consistency of X
if self.pruned:
tree_ = self.tree_.tree_pruned
else:
tree_ = self.tree_.tree
return self._classify(X, tree_, proba=False) | python | def predict(self, X):
""" Predict class of X.
The predicted class for each sample in X is returned.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted classes,
"""
#TODO: Check consistency of X
if self.pruned:
tree_ = self.tree_.tree_pruned
else:
tree_ = self.tree_.tree
return self._classify(X, tree_, proba=False) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"#TODO: Check consistency of X",
"if",
"self",
".",
"pruned",
":",
"tree_",
"=",
"self",
".",
"tree_",
".",
"tree_pruned",
"else",
":",
"tree_",
"=",
"self",
".",
"tree_",
".",
"tree",
"return",
"self",
".",
"_classify",
"(",
"X",
",",
"tree_",
",",
"proba",
"=",
"False",
")"
] | Predict class of X.
The predicted class for each sample in X is returned.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted classes, | [
"Predict",
"class",
"of",
"X",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L515-L537 | train | 236,923 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier.predict_proba | def predict_proba(self, X):
"""Predict class probabilities of the input samples X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
prob : array of shape = [n_samples, 2]
The class probabilities of the input samples.
"""
#TODO: Check consistency of X
n_samples, n_features = X.shape
prob = np.zeros((n_samples, 2))
if self.pruned:
tree_ = self.tree_.tree_pruned
else:
tree_ = self.tree_.tree
prob[:, 1] = self._classify(X, tree_, proba=True)
prob[:, 0] = 1 - prob[:, 1]
return prob | python | def predict_proba(self, X):
"""Predict class probabilities of the input samples X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
prob : array of shape = [n_samples, 2]
The class probabilities of the input samples.
"""
#TODO: Check consistency of X
n_samples, n_features = X.shape
prob = np.zeros((n_samples, 2))
if self.pruned:
tree_ = self.tree_.tree_pruned
else:
tree_ = self.tree_.tree
prob[:, 1] = self._classify(X, tree_, proba=True)
prob[:, 0] = 1 - prob[:, 1]
return prob | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"#TODO: Check consistency of X",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"prob",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"2",
")",
")",
"if",
"self",
".",
"pruned",
":",
"tree_",
"=",
"self",
".",
"tree_",
".",
"tree_pruned",
"else",
":",
"tree_",
"=",
"self",
".",
"tree_",
".",
"tree",
"prob",
"[",
":",
",",
"1",
"]",
"=",
"self",
".",
"_classify",
"(",
"X",
",",
"tree_",
",",
"proba",
"=",
"True",
")",
"prob",
"[",
":",
",",
"0",
"]",
"=",
"1",
"-",
"prob",
"[",
":",
",",
"1",
"]",
"return",
"prob"
] | Predict class probabilities of the input samples X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
prob : array of shape = [n_samples, 2]
The class probabilities of the input samples. | [
"Predict",
"class",
"probabilities",
"of",
"the",
"input",
"samples",
"X",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L539-L564 | train | 236,924 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._delete_node | def _delete_node(self, tree, node):
""" Private function that eliminate node from tree.
Parameters
----------
tree : object
node : int
node to be eliminated from tree
Returns
-------
pruned_tree : object
"""
# Calculate gains
temp_tree = copy.deepcopy(tree)
def recourse(temp_tree_, del_node):
if isinstance(temp_tree_, dict):
if temp_tree_['split'] != -1:
if temp_tree_['node'] == del_node:
del temp_tree_['sr']
del temp_tree_['sl']
del temp_tree_['node']
temp_tree_['split'] = -1
else:
for k in ['sl', 'sr']:
recourse(temp_tree_[k], del_node)
return None
recourse(temp_tree, node)
return temp_tree | python | def _delete_node(self, tree, node):
""" Private function that eliminate node from tree.
Parameters
----------
tree : object
node : int
node to be eliminated from tree
Returns
-------
pruned_tree : object
"""
# Calculate gains
temp_tree = copy.deepcopy(tree)
def recourse(temp_tree_, del_node):
if isinstance(temp_tree_, dict):
if temp_tree_['split'] != -1:
if temp_tree_['node'] == del_node:
del temp_tree_['sr']
del temp_tree_['sl']
del temp_tree_['node']
temp_tree_['split'] = -1
else:
for k in ['sl', 'sr']:
recourse(temp_tree_[k], del_node)
return None
recourse(temp_tree, node)
return temp_tree | [
"def",
"_delete_node",
"(",
"self",
",",
"tree",
",",
"node",
")",
":",
"# Calculate gains",
"temp_tree",
"=",
"copy",
".",
"deepcopy",
"(",
"tree",
")",
"def",
"recourse",
"(",
"temp_tree_",
",",
"del_node",
")",
":",
"if",
"isinstance",
"(",
"temp_tree_",
",",
"dict",
")",
":",
"if",
"temp_tree_",
"[",
"'split'",
"]",
"!=",
"-",
"1",
":",
"if",
"temp_tree_",
"[",
"'node'",
"]",
"==",
"del_node",
":",
"del",
"temp_tree_",
"[",
"'sr'",
"]",
"del",
"temp_tree_",
"[",
"'sl'",
"]",
"del",
"temp_tree_",
"[",
"'node'",
"]",
"temp_tree_",
"[",
"'split'",
"]",
"=",
"-",
"1",
"else",
":",
"for",
"k",
"in",
"[",
"'sl'",
",",
"'sr'",
"]",
":",
"recourse",
"(",
"temp_tree_",
"[",
"k",
"]",
",",
"del_node",
")",
"return",
"None",
"recourse",
"(",
"temp_tree",
",",
"node",
")",
"return",
"temp_tree"
] | Private function that eliminate node from tree.
Parameters
----------
tree : object
node : int
node to be eliminated from tree
Returns
-------
pruned_tree : object | [
"Private",
"function",
"that",
"eliminate",
"node",
"from",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L566-L599 | train | 236,925 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier._pruning | def _pruning(self, X, y_true, cost_mat):
""" Private function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
# Calculate gains
nodes = self._nodes(self.tree_.tree_pruned)
n_nodes = len(nodes)
gains = np.zeros(n_nodes)
y_pred = self._classify(X, self.tree_.tree_pruned)
cost_base = cost_loss(y_true, y_pred, cost_mat)
for m, node in enumerate(nodes):
# Create temporal tree by eliminating node from tree_pruned
temp_tree = self._delete_node(self.tree_.tree_pruned, node)
y_pred = self._classify(X, temp_tree)
nodes_pruned = self._nodes(temp_tree)
# Calculate %gain
gain = (cost_base - cost_loss(y_true, y_pred, cost_mat)) / cost_base
# Calculate %gain_size
gain_size = (len(nodes) - len(nodes_pruned)) * 1.0 / len(nodes)
# Calculate weighted gain
gains[m] = gain * gain_size
best_gain = np.max(gains)
best_node = nodes[int(np.argmax(gains))]
if best_gain > self.min_gain:
self.tree_.tree_pruned = self._delete_node(self.tree_.tree_pruned, best_node)
# If best tree is not root node, then recursively pruning the tree
if best_node != 0:
self._pruning(X, y_true, cost_mat) | python | def _pruning(self, X, y_true, cost_mat):
""" Private function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
# Calculate gains
nodes = self._nodes(self.tree_.tree_pruned)
n_nodes = len(nodes)
gains = np.zeros(n_nodes)
y_pred = self._classify(X, self.tree_.tree_pruned)
cost_base = cost_loss(y_true, y_pred, cost_mat)
for m, node in enumerate(nodes):
# Create temporal tree by eliminating node from tree_pruned
temp_tree = self._delete_node(self.tree_.tree_pruned, node)
y_pred = self._classify(X, temp_tree)
nodes_pruned = self._nodes(temp_tree)
# Calculate %gain
gain = (cost_base - cost_loss(y_true, y_pred, cost_mat)) / cost_base
# Calculate %gain_size
gain_size = (len(nodes) - len(nodes_pruned)) * 1.0 / len(nodes)
# Calculate weighted gain
gains[m] = gain * gain_size
best_gain = np.max(gains)
best_node = nodes[int(np.argmax(gains))]
if best_gain > self.min_gain:
self.tree_.tree_pruned = self._delete_node(self.tree_.tree_pruned, best_node)
# If best tree is not root node, then recursively pruning the tree
if best_node != 0:
self._pruning(X, y_true, cost_mat) | [
"def",
"_pruning",
"(",
"self",
",",
"X",
",",
"y_true",
",",
"cost_mat",
")",
":",
"# Calculate gains",
"nodes",
"=",
"self",
".",
"_nodes",
"(",
"self",
".",
"tree_",
".",
"tree_pruned",
")",
"n_nodes",
"=",
"len",
"(",
"nodes",
")",
"gains",
"=",
"np",
".",
"zeros",
"(",
"n_nodes",
")",
"y_pred",
"=",
"self",
".",
"_classify",
"(",
"X",
",",
"self",
".",
"tree_",
".",
"tree_pruned",
")",
"cost_base",
"=",
"cost_loss",
"(",
"y_true",
",",
"y_pred",
",",
"cost_mat",
")",
"for",
"m",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"# Create temporal tree by eliminating node from tree_pruned",
"temp_tree",
"=",
"self",
".",
"_delete_node",
"(",
"self",
".",
"tree_",
".",
"tree_pruned",
",",
"node",
")",
"y_pred",
"=",
"self",
".",
"_classify",
"(",
"X",
",",
"temp_tree",
")",
"nodes_pruned",
"=",
"self",
".",
"_nodes",
"(",
"temp_tree",
")",
"# Calculate %gain",
"gain",
"=",
"(",
"cost_base",
"-",
"cost_loss",
"(",
"y_true",
",",
"y_pred",
",",
"cost_mat",
")",
")",
"/",
"cost_base",
"# Calculate %gain_size",
"gain_size",
"=",
"(",
"len",
"(",
"nodes",
")",
"-",
"len",
"(",
"nodes_pruned",
")",
")",
"*",
"1.0",
"/",
"len",
"(",
"nodes",
")",
"# Calculate weighted gain",
"gains",
"[",
"m",
"]",
"=",
"gain",
"*",
"gain_size",
"best_gain",
"=",
"np",
".",
"max",
"(",
"gains",
")",
"best_node",
"=",
"nodes",
"[",
"int",
"(",
"np",
".",
"argmax",
"(",
"gains",
")",
")",
"]",
"if",
"best_gain",
">",
"self",
".",
"min_gain",
":",
"self",
".",
"tree_",
".",
"tree_pruned",
"=",
"self",
".",
"_delete_node",
"(",
"self",
".",
"tree_",
".",
"tree_pruned",
",",
"best_node",
")",
"# If best tree is not root node, then recursively pruning the tree",
"if",
"best_node",
"!=",
"0",
":",
"self",
".",
"_pruning",
"(",
"X",
",",
"y_true",
",",
"cost_mat",
")"
] | Private function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example. | [
"Private",
"function",
"that",
"prune",
"the",
"decision",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L601-L652 | train | 236,926 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | CostSensitiveDecisionTreeClassifier.pruning | def pruning(self, X, y, cost_mat):
""" Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
self.tree_.tree_pruned = copy.deepcopy(self.tree_.tree)
if self.tree_.n_nodes > 0:
self._pruning(X, y, cost_mat)
nodes_pruned = self._nodes(self.tree_.tree_pruned)
self.tree_.n_nodes_pruned = len(nodes_pruned) | python | def pruning(self, X, y, cost_mat):
""" Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
"""
self.tree_.tree_pruned = copy.deepcopy(self.tree_.tree)
if self.tree_.n_nodes > 0:
self._pruning(X, y, cost_mat)
nodes_pruned = self._nodes(self.tree_.tree_pruned)
self.tree_.n_nodes_pruned = len(nodes_pruned) | [
"def",
"pruning",
"(",
"self",
",",
"X",
",",
"y",
",",
"cost_mat",
")",
":",
"self",
".",
"tree_",
".",
"tree_pruned",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"tree_",
".",
"tree",
")",
"if",
"self",
".",
"tree_",
".",
"n_nodes",
">",
"0",
":",
"self",
".",
"_pruning",
"(",
"X",
",",
"y",
",",
"cost_mat",
")",
"nodes_pruned",
"=",
"self",
".",
"_nodes",
"(",
"self",
".",
"tree_",
".",
"tree_pruned",
")",
"self",
".",
"tree_",
".",
"n_nodes_pruned",
"=",
"len",
"(",
"nodes_pruned",
")"
] | Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example. | [
"Function",
"that",
"prune",
"the",
"decision",
"tree",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L654-L676 | train | 236,927 |
albahnsen/CostSensitiveClassification | costcla/metrics/costs.py | cost_loss | def cost_loss(y_true, y_pred, cost_mat):
#TODO: update description
"""Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to different
errors, but that is not the real case in several real-world classification
problems as they are example-dependent cost-sensitive in nature, where the
costs due to misclassification vary between examples.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
loss : float
Cost of a using y_pred on y_true with cost-matrix cost-mat
References
----------
.. [1] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
.. [2] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
savings_score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> cost_loss(y_true, y_pred, cost_mat)
3
"""
#TODO: Check consistency of cost_mat
y_true = column_or_1d(y_true)
y_true = (y_true == 1).astype(np.float)
y_pred = column_or_1d(y_pred)
y_pred = (y_pred == 1).astype(np.float)
cost = y_true * ((1 - y_pred) * cost_mat[:, 1] + y_pred * cost_mat[:, 2])
cost += (1 - y_true) * (y_pred * cost_mat[:, 0] + (1 - y_pred) * cost_mat[:, 3])
return np.sum(cost) | python | def cost_loss(y_true, y_pred, cost_mat):
#TODO: update description
"""Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to different
errors, but that is not the real case in several real-world classification
problems as they are example-dependent cost-sensitive in nature, where the
costs due to misclassification vary between examples.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
loss : float
Cost of a using y_pred on y_true with cost-matrix cost-mat
References
----------
.. [1] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
.. [2] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
savings_score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> cost_loss(y_true, y_pred, cost_mat)
3
"""
#TODO: Check consistency of cost_mat
y_true = column_or_1d(y_true)
y_true = (y_true == 1).astype(np.float)
y_pred = column_or_1d(y_pred)
y_pred = (y_pred == 1).astype(np.float)
cost = y_true * ((1 - y_pred) * cost_mat[:, 1] + y_pred * cost_mat[:, 2])
cost += (1 - y_true) * (y_pred * cost_mat[:, 0] + (1 - y_pred) * cost_mat[:, 3])
return np.sum(cost) | [
"def",
"cost_loss",
"(",
"y_true",
",",
"y_pred",
",",
"cost_mat",
")",
":",
"#TODO: update description",
"#TODO: Check consistency of cost_mat",
"y_true",
"=",
"column_or_1d",
"(",
"y_true",
")",
"y_true",
"=",
"(",
"y_true",
"==",
"1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"y_pred",
"=",
"column_or_1d",
"(",
"y_pred",
")",
"y_pred",
"=",
"(",
"y_pred",
"==",
"1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"cost",
"=",
"y_true",
"*",
"(",
"(",
"1",
"-",
"y_pred",
")",
"*",
"cost_mat",
"[",
":",
",",
"1",
"]",
"+",
"y_pred",
"*",
"cost_mat",
"[",
":",
",",
"2",
"]",
")",
"cost",
"+=",
"(",
"1",
"-",
"y_true",
")",
"*",
"(",
"y_pred",
"*",
"cost_mat",
"[",
":",
",",
"0",
"]",
"+",
"(",
"1",
"-",
"y_pred",
")",
"*",
"cost_mat",
"[",
":",
",",
"3",
"]",
")",
"return",
"np",
".",
"sum",
"(",
"cost",
")"
] | Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to different
errors, but that is not the real case in several real-world classification
problems as they are example-dependent cost-sensitive in nature, where the
costs due to misclassification vary between examples.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
loss : float
Cost of a using y_pred on y_true with cost-matrix cost-mat
References
----------
.. [1] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
.. [2] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
savings_score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> cost_loss(y_true, y_pred, cost_mat)
3 | [
"Cost",
"classification",
"loss",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L19-L81 | train | 236,928 |
albahnsen/CostSensitiveClassification | costcla/metrics/costs.py | savings_score | def savings_score(y_true, y_pred, cost_mat):
#TODO: update description
"""Savings score.
This function calculates the savings cost of using y_pred on y_true with
cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive
classification model.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
score : float
Savings of a using y_pred on y_true with cost-matrix cost-mat
The best performance is 1.
References
----------
.. [1] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
cost_loss
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import savings_score, cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> savings_score(y_true, y_pred, cost_mat)
0.5
"""
#TODO: Check consistency of cost_mat
y_true = column_or_1d(y_true)
y_pred = column_or_1d(y_pred)
n_samples = len(y_true)
# Calculate the cost of naive prediction
cost_base = min(cost_loss(y_true, np.zeros(n_samples), cost_mat),
cost_loss(y_true, np.ones(n_samples), cost_mat))
cost = cost_loss(y_true, y_pred, cost_mat)
return 1.0 - cost / cost_base | python | def savings_score(y_true, y_pred, cost_mat):
#TODO: update description
"""Savings score.
This function calculates the savings cost of using y_pred on y_true with
cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive
classification model.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
score : float
Savings of a using y_pred on y_true with cost-matrix cost-mat
The best performance is 1.
References
----------
.. [1] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
cost_loss
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import savings_score, cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> savings_score(y_true, y_pred, cost_mat)
0.5
"""
#TODO: Check consistency of cost_mat
y_true = column_or_1d(y_true)
y_pred = column_or_1d(y_pred)
n_samples = len(y_true)
# Calculate the cost of naive prediction
cost_base = min(cost_loss(y_true, np.zeros(n_samples), cost_mat),
cost_loss(y_true, np.ones(n_samples), cost_mat))
cost = cost_loss(y_true, y_pred, cost_mat)
return 1.0 - cost / cost_base | [
"def",
"savings_score",
"(",
"y_true",
",",
"y_pred",
",",
"cost_mat",
")",
":",
"#TODO: update description",
"#TODO: Check consistency of cost_mat",
"y_true",
"=",
"column_or_1d",
"(",
"y_true",
")",
"y_pred",
"=",
"column_or_1d",
"(",
"y_pred",
")",
"n_samples",
"=",
"len",
"(",
"y_true",
")",
"# Calculate the cost of naive prediction",
"cost_base",
"=",
"min",
"(",
"cost_loss",
"(",
"y_true",
",",
"np",
".",
"zeros",
"(",
"n_samples",
")",
",",
"cost_mat",
")",
",",
"cost_loss",
"(",
"y_true",
",",
"np",
".",
"ones",
"(",
"n_samples",
")",
",",
"cost_mat",
")",
")",
"cost",
"=",
"cost_loss",
"(",
"y_true",
",",
"y_pred",
",",
"cost_mat",
")",
"return",
"1.0",
"-",
"cost",
"/",
"cost_base"
] | Savings score.
This function calculates the savings cost of using y_pred on y_true with
cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive
classification model.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted labels, as returned by a classifier.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
Returns
-------
score : float
Savings of a using y_pred on y_true with cost-matrix cost-mat
The best performance is 1.
References
----------
.. [1] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,
`"Improving Credit Card Fraud Detection with Calibrated Probabilities" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,
677-685, 2014.
See also
--------
cost_loss
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import savings_score, cost_loss
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 1, 0]
>>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])
>>> savings_score(y_true, y_pred, cost_mat)
0.5 | [
"Savings",
"score",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L84-L143 | train | 236,929 |
albahnsen/CostSensitiveClassification | costcla/metrics/costs.py | brier_score_loss | def brier_score_loss(y_true, y_prob):
"""Compute the Brier score
The smaller the Brier score, the better, hence the naming with "loss".
Across all items in a set N predictions, the Brier score measures the
mean squared difference between (1) the predicted probability assigned
to the possible outcomes for item i, and (2) the actual outcome.
Therefore, the lower the Brier score is for a set of predictions, the
better the predictions are calibrated. Note that the Brier score always
takes on a value between zero and one, since this is the largest
possible difference between a predicted probability (which must be
between zero and one) and the actual outcome (which can take on values
of only 0 and 1).
The Brier score is appropriate for binary and categorical outcomes that
can be structured as true or false, but is inappropriate for ordinal
variables which can take on three or more values (this is because the
Brier score assumes that all possible outcomes are equivalently
"distant" from one another).
Parameters
----------
y_true : array, shape (n_samples,)
True targets.
y_prob : array, shape (n_samples,)
Probabilities of the positive class.
Returns
-------
score : float
Brier score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import brier_score_loss
>>> y_true = [0, 1, 1, 0]
>>> y_prob = [0.1, 0.9, 0.8, 0.3]
>>> brier_score_loss(y_true, y_prob) # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true, np.array(y_prob) > 0.5)
0.0
References
----------
http://en.wikipedia.org/wiki/Brier_score
"""
y_true = column_or_1d(y_true)
y_prob = column_or_1d(y_prob)
return np.mean((y_true - y_prob) ** 2) | python | def brier_score_loss(y_true, y_prob):
"""Compute the Brier score
The smaller the Brier score, the better, hence the naming with "loss".
Across all items in a set N predictions, the Brier score measures the
mean squared difference between (1) the predicted probability assigned
to the possible outcomes for item i, and (2) the actual outcome.
Therefore, the lower the Brier score is for a set of predictions, the
better the predictions are calibrated. Note that the Brier score always
takes on a value between zero and one, since this is the largest
possible difference between a predicted probability (which must be
between zero and one) and the actual outcome (which can take on values
of only 0 and 1).
The Brier score is appropriate for binary and categorical outcomes that
can be structured as true or false, but is inappropriate for ordinal
variables which can take on three or more values (this is because the
Brier score assumes that all possible outcomes are equivalently
"distant" from one another).
Parameters
----------
y_true : array, shape (n_samples,)
True targets.
y_prob : array, shape (n_samples,)
Probabilities of the positive class.
Returns
-------
score : float
Brier score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import brier_score_loss
>>> y_true = [0, 1, 1, 0]
>>> y_prob = [0.1, 0.9, 0.8, 0.3]
>>> brier_score_loss(y_true, y_prob) # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true, np.array(y_prob) > 0.5)
0.0
References
----------
http://en.wikipedia.org/wiki/Brier_score
"""
y_true = column_or_1d(y_true)
y_prob = column_or_1d(y_prob)
return np.mean((y_true - y_prob) ** 2) | [
"def",
"brier_score_loss",
"(",
"y_true",
",",
"y_prob",
")",
":",
"y_true",
"=",
"column_or_1d",
"(",
"y_true",
")",
"y_prob",
"=",
"column_or_1d",
"(",
"y_prob",
")",
"return",
"np",
".",
"mean",
"(",
"(",
"y_true",
"-",
"y_prob",
")",
"**",
"2",
")"
] | Compute the Brier score
The smaller the Brier score, the better, hence the naming with "loss".
Across all items in a set N predictions, the Brier score measures the
mean squared difference between (1) the predicted probability assigned
to the possible outcomes for item i, and (2) the actual outcome.
Therefore, the lower the Brier score is for a set of predictions, the
better the predictions are calibrated. Note that the Brier score always
takes on a value between zero and one, since this is the largest
possible difference between a predicted probability (which must be
between zero and one) and the actual outcome (which can take on values
of only 0 and 1).
The Brier score is appropriate for binary and categorical outcomes that
can be structured as true or false, but is inappropriate for ordinal
variables which can take on three or more values (this is because the
Brier score assumes that all possible outcomes are equivalently
"distant" from one another).
Parameters
----------
y_true : array, shape (n_samples,)
True targets.
y_prob : array, shape (n_samples,)
Probabilities of the positive class.
Returns
-------
score : float
Brier score
Examples
--------
>>> import numpy as np
>>> from costcla.metrics import brier_score_loss
>>> y_true = [0, 1, 1, 0]
>>> y_prob = [0.1, 0.9, 0.8, 0.3]
>>> brier_score_loss(y_true, y_prob) # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true, np.array(y_prob) > 0.5)
0.0
References
----------
http://en.wikipedia.org/wiki/Brier_score | [
"Compute",
"the",
"Brier",
"score"
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L149-L200 | train | 236,930 |
albahnsen/CostSensitiveClassification | costcla/models/regression.py | _logistic_cost_loss | def _logistic_cost_loss(w, X, y, cost_mat, alpha):
"""Computes the logistic loss.
Parameters
----------
w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,)
Coefficient vector or matrix of coefficient.
X : array-like, shape (n_samples, n_features)
Training data.
y : ndarray, shape (n_samples,)
Array of labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
alpha : float
Regularization parameter. alpha is equal to 1 / C.
Returns
-------
out : float
Logistic loss.
"""
if w.shape[0] == w.size:
# Only evaluating one w
return _logistic_cost_loss_i(w, X, y, cost_mat, alpha)
else:
# Evaluating a set of w
n_w = w.shape[0]
out = np.zeros(n_w)
for i in range(n_w):
out[i] = _logistic_cost_loss_i(w[i], X, y, cost_mat, alpha)
return out | python | def _logistic_cost_loss(w, X, y, cost_mat, alpha):
"""Computes the logistic loss.
Parameters
----------
w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,)
Coefficient vector or matrix of coefficient.
X : array-like, shape (n_samples, n_features)
Training data.
y : ndarray, shape (n_samples,)
Array of labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
alpha : float
Regularization parameter. alpha is equal to 1 / C.
Returns
-------
out : float
Logistic loss.
"""
if w.shape[0] == w.size:
# Only evaluating one w
return _logistic_cost_loss_i(w, X, y, cost_mat, alpha)
else:
# Evaluating a set of w
n_w = w.shape[0]
out = np.zeros(n_w)
for i in range(n_w):
out[i] = _logistic_cost_loss_i(w[i], X, y, cost_mat, alpha)
return out | [
"def",
"_logistic_cost_loss",
"(",
"w",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"alpha",
")",
":",
"if",
"w",
".",
"shape",
"[",
"0",
"]",
"==",
"w",
".",
"size",
":",
"# Only evaluating one w",
"return",
"_logistic_cost_loss_i",
"(",
"w",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"alpha",
")",
"else",
":",
"# Evaluating a set of w",
"n_w",
"=",
"w",
".",
"shape",
"[",
"0",
"]",
"out",
"=",
"np",
".",
"zeros",
"(",
"n_w",
")",
"for",
"i",
"in",
"range",
"(",
"n_w",
")",
":",
"out",
"[",
"i",
"]",
"=",
"_logistic_cost_loss_i",
"(",
"w",
"[",
"i",
"]",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"alpha",
")",
"return",
"out"
] | Computes the logistic loss.
Parameters
----------
w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,)
Coefficient vector or matrix of coefficient.
X : array-like, shape (n_samples, n_features)
Training data.
y : ndarray, shape (n_samples,)
Array of labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
alpha : float
Regularization parameter. alpha is equal to 1 / C.
Returns
-------
out : float
Logistic loss. | [
"Computes",
"the",
"logistic",
"loss",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/regression.py#L58-L98 | train | 236,931 |
albahnsen/CostSensitiveClassification | costcla/models/regression.py | CostSensitiveLogisticRegression.predict | def predict(self, X, cut_point=0.5):
"""Predicted class.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples]
Returns the prediction of the sample..
"""
return np.floor(self.predict_proba(X)[:, 1] + (1 - cut_point)) | python | def predict(self, X, cut_point=0.5):
"""Predicted class.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples]
Returns the prediction of the sample..
"""
return np.floor(self.predict_proba(X)[:, 1] + (1 - cut_point)) | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"cut_point",
"=",
"0.5",
")",
":",
"return",
"np",
".",
"floor",
"(",
"self",
".",
"predict_proba",
"(",
"X",
")",
"[",
":",
",",
"1",
"]",
"+",
"(",
"1",
"-",
"cut_point",
")",
")"
] | Predicted class.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples]
Returns the prediction of the sample.. | [
"Predicted",
"class",
"."
] | 75778ae32c70671c0cdde6c4651277b6a8b58871 | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/regression.py#L278-L290 | train | 236,932 |
MozillaSecurity/laniakea | laniakea/core/userdata.py | UserData.list_tags | def list_tags(userdata):
"""List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str
"""
macros = re.findall('@(.*?)@', userdata)
logging.info('List of available macros:')
for macro in macros:
logging.info('\t%r', macro) | python | def list_tags(userdata):
"""List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str
"""
macros = re.findall('@(.*?)@', userdata)
logging.info('List of available macros:')
for macro in macros:
logging.info('\t%r', macro) | [
"def",
"list_tags",
"(",
"userdata",
")",
":",
"macros",
"=",
"re",
".",
"findall",
"(",
"'@(.*?)@'",
",",
"userdata",
")",
"logging",
".",
"info",
"(",
"'List of available macros:'",
")",
"for",
"macro",
"in",
"macros",
":",
"logging",
".",
"info",
"(",
"'\\t%r'",
",",
"macro",
")"
] | List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str | [
"List",
"all",
"used",
"macros",
"within",
"a",
"UserData",
"script",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/userdata.py#L54-L63 | train | 236,933 |
MozillaSecurity/laniakea | laniakea/core/userdata.py | UserData.handle_tags | def handle_tags(userdata, macros):
"""Insert macro values or auto export variables in UserData scripts.
:param userdata: The UserData script.
:type userdata: str
:param macros: UserData macros as key value pair.
:type macros: dict
:return: UserData script with the macros replaced with their values.
:rtype: str
"""
macro_vars = re.findall('@(.*?)@', userdata)
for macro_var in macro_vars:
if macro_var == '!all_macros_export':
macro_var_export_list = []
for defined_macro in macros:
macro_var_export_list.append('export %s="%s"' % (defined_macro, macros[defined_macro]))
macro_var_exports = "\n".join(macro_var_export_list)
userdata = userdata.replace('@%s@' % macro_var, macro_var_exports)
elif macro_var == "!all_macros_docker":
macro_var_export_list = []
for defined_macro in macros:
macro_var_export_list.append("-e '%s=%s'" % (defined_macro, macros[defined_macro]))
macro_var_exports = " ".join(macro_var_export_list)
userdata = userdata.replace('@%s@' % macro_var, macro_var_exports)
else:
if "|" in macro_var:
macro_var, default_value = macro_var.split('|')
if macro_var not in macros:
logging.warning('Using default variable value %s for @%s@ ', default_value, macro_var)
value = default_value
else:
value = macros[macro_var]
userdata = userdata.replace('@%s|%s@' % (macro_var, default_value), value)
else:
if macro_var not in macros:
logging.error('Undefined variable @%s@ in UserData script', macro_var)
return None
userdata = userdata.replace('@%s@' % macro_var, macros[macro_var])
return userdata | python | def handle_tags(userdata, macros):
"""Insert macro values or auto export variables in UserData scripts.
:param userdata: The UserData script.
:type userdata: str
:param macros: UserData macros as key value pair.
:type macros: dict
:return: UserData script with the macros replaced with their values.
:rtype: str
"""
macro_vars = re.findall('@(.*?)@', userdata)
for macro_var in macro_vars:
if macro_var == '!all_macros_export':
macro_var_export_list = []
for defined_macro in macros:
macro_var_export_list.append('export %s="%s"' % (defined_macro, macros[defined_macro]))
macro_var_exports = "\n".join(macro_var_export_list)
userdata = userdata.replace('@%s@' % macro_var, macro_var_exports)
elif macro_var == "!all_macros_docker":
macro_var_export_list = []
for defined_macro in macros:
macro_var_export_list.append("-e '%s=%s'" % (defined_macro, macros[defined_macro]))
macro_var_exports = " ".join(macro_var_export_list)
userdata = userdata.replace('@%s@' % macro_var, macro_var_exports)
else:
if "|" in macro_var:
macro_var, default_value = macro_var.split('|')
if macro_var not in macros:
logging.warning('Using default variable value %s for @%s@ ', default_value, macro_var)
value = default_value
else:
value = macros[macro_var]
userdata = userdata.replace('@%s|%s@' % (macro_var, default_value), value)
else:
if macro_var not in macros:
logging.error('Undefined variable @%s@ in UserData script', macro_var)
return None
userdata = userdata.replace('@%s@' % macro_var, macros[macro_var])
return userdata | [
"def",
"handle_tags",
"(",
"userdata",
",",
"macros",
")",
":",
"macro_vars",
"=",
"re",
".",
"findall",
"(",
"'@(.*?)@'",
",",
"userdata",
")",
"for",
"macro_var",
"in",
"macro_vars",
":",
"if",
"macro_var",
"==",
"'!all_macros_export'",
":",
"macro_var_export_list",
"=",
"[",
"]",
"for",
"defined_macro",
"in",
"macros",
":",
"macro_var_export_list",
".",
"append",
"(",
"'export %s=\"%s\"'",
"%",
"(",
"defined_macro",
",",
"macros",
"[",
"defined_macro",
"]",
")",
")",
"macro_var_exports",
"=",
"\"\\n\"",
".",
"join",
"(",
"macro_var_export_list",
")",
"userdata",
"=",
"userdata",
".",
"replace",
"(",
"'@%s@'",
"%",
"macro_var",
",",
"macro_var_exports",
")",
"elif",
"macro_var",
"==",
"\"!all_macros_docker\"",
":",
"macro_var_export_list",
"=",
"[",
"]",
"for",
"defined_macro",
"in",
"macros",
":",
"macro_var_export_list",
".",
"append",
"(",
"\"-e '%s=%s'\"",
"%",
"(",
"defined_macro",
",",
"macros",
"[",
"defined_macro",
"]",
")",
")",
"macro_var_exports",
"=",
"\" \"",
".",
"join",
"(",
"macro_var_export_list",
")",
"userdata",
"=",
"userdata",
".",
"replace",
"(",
"'@%s@'",
"%",
"macro_var",
",",
"macro_var_exports",
")",
"else",
":",
"if",
"\"|\"",
"in",
"macro_var",
":",
"macro_var",
",",
"default_value",
"=",
"macro_var",
".",
"split",
"(",
"'|'",
")",
"if",
"macro_var",
"not",
"in",
"macros",
":",
"logging",
".",
"warning",
"(",
"'Using default variable value %s for @%s@ '",
",",
"default_value",
",",
"macro_var",
")",
"value",
"=",
"default_value",
"else",
":",
"value",
"=",
"macros",
"[",
"macro_var",
"]",
"userdata",
"=",
"userdata",
".",
"replace",
"(",
"'@%s|%s@'",
"%",
"(",
"macro_var",
",",
"default_value",
")",
",",
"value",
")",
"else",
":",
"if",
"macro_var",
"not",
"in",
"macros",
":",
"logging",
".",
"error",
"(",
"'Undefined variable @%s@ in UserData script'",
",",
"macro_var",
")",
"return",
"None",
"userdata",
"=",
"userdata",
".",
"replace",
"(",
"'@%s@'",
"%",
"macro_var",
",",
"macros",
"[",
"macro_var",
"]",
")",
"return",
"userdata"
] | Insert macro values or auto export variables in UserData scripts.
:param userdata: The UserData script.
:type userdata: str
:param macros: UserData macros as key value pair.
:type macros: dict
:return: UserData script with the macros replaced with their values.
:rtype: str | [
"Insert",
"macro",
"values",
"or",
"auto",
"export",
"variables",
"in",
"UserData",
"scripts",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/userdata.py#L66-L109 | train | 236,934 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.retry_on_ec2_error | def retry_on_ec2_error(self, func, *args, **kwargs):
"""
Call the given method with the given arguments, retrying if the call
failed due to an EC2ResponseError. This method will wait at most 30
seconds and perform up to 6 retries. If the method still fails, it will
propagate the error.
:param func: Function to call
:type func: function
"""
exception_retry_count = 6
while True:
try:
return func(*args, **kwargs)
except (boto.exception.EC2ResponseError, ssl.SSLError) as msg:
exception_retry_count -= 1
if exception_retry_count <= 0:
raise msg
time.sleep(5) | python | def retry_on_ec2_error(self, func, *args, **kwargs):
"""
Call the given method with the given arguments, retrying if the call
failed due to an EC2ResponseError. This method will wait at most 30
seconds and perform up to 6 retries. If the method still fails, it will
propagate the error.
:param func: Function to call
:type func: function
"""
exception_retry_count = 6
while True:
try:
return func(*args, **kwargs)
except (boto.exception.EC2ResponseError, ssl.SSLError) as msg:
exception_retry_count -= 1
if exception_retry_count <= 0:
raise msg
time.sleep(5) | [
"def",
"retry_on_ec2_error",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exception_retry_count",
"=",
"6",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"boto",
".",
"exception",
".",
"EC2ResponseError",
",",
"ssl",
".",
"SSLError",
")",
"as",
"msg",
":",
"exception_retry_count",
"-=",
"1",
"if",
"exception_retry_count",
"<=",
"0",
":",
"raise",
"msg",
"time",
".",
"sleep",
"(",
"5",
")"
] | Call the given method with the given arguments, retrying if the call
failed due to an EC2ResponseError. This method will wait at most 30
seconds and perform up to 6 retries. If the method still fails, it will
propagate the error.
:param func: Function to call
:type func: function | [
"Call",
"the",
"given",
"method",
"with",
"the",
"given",
"arguments",
"retrying",
"if",
"the",
"call",
"failed",
"due",
"to",
"an",
"EC2ResponseError",
".",
"This",
"method",
"will",
"wait",
"at",
"most",
"30",
"seconds",
"and",
"perform",
"up",
"to",
"6",
"retries",
".",
"If",
"the",
"method",
"still",
"fails",
"it",
"will",
"propagate",
"the",
"error",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L36-L54 | train | 236,935 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.connect | def connect(self, region, **kw_params):
"""Connect to a EC2.
:param region: The name of the region to connect to.
:type region: str
:param kw_params:
:type kw_params: dict
"""
self.ec2 = boto.ec2.connect_to_region(region, **kw_params)
if not self.ec2:
raise EC2ManagerException('Unable to connect to region "%s"' % region)
self.remote_images.clear()
if self.images and any(('image_name' in img and 'image_id' not in img) for img in self.images.values()):
for img in self.images.values():
if 'image_name' in img and 'image_id' not in img:
img['image_id'] = self.resolve_image_name(img.pop('image_name')) | python | def connect(self, region, **kw_params):
"""Connect to a EC2.
:param region: The name of the region to connect to.
:type region: str
:param kw_params:
:type kw_params: dict
"""
self.ec2 = boto.ec2.connect_to_region(region, **kw_params)
if not self.ec2:
raise EC2ManagerException('Unable to connect to region "%s"' % region)
self.remote_images.clear()
if self.images and any(('image_name' in img and 'image_id' not in img) for img in self.images.values()):
for img in self.images.values():
if 'image_name' in img and 'image_id' not in img:
img['image_id'] = self.resolve_image_name(img.pop('image_name')) | [
"def",
"connect",
"(",
"self",
",",
"region",
",",
"*",
"*",
"kw_params",
")",
":",
"self",
".",
"ec2",
"=",
"boto",
".",
"ec2",
".",
"connect_to_region",
"(",
"region",
",",
"*",
"*",
"kw_params",
")",
"if",
"not",
"self",
".",
"ec2",
":",
"raise",
"EC2ManagerException",
"(",
"'Unable to connect to region \"%s\"'",
"%",
"region",
")",
"self",
".",
"remote_images",
".",
"clear",
"(",
")",
"if",
"self",
".",
"images",
"and",
"any",
"(",
"(",
"'image_name'",
"in",
"img",
"and",
"'image_id'",
"not",
"in",
"img",
")",
"for",
"img",
"in",
"self",
".",
"images",
".",
"values",
"(",
")",
")",
":",
"for",
"img",
"in",
"self",
".",
"images",
".",
"values",
"(",
")",
":",
"if",
"'image_name'",
"in",
"img",
"and",
"'image_id'",
"not",
"in",
"img",
":",
"img",
"[",
"'image_id'",
"]",
"=",
"self",
".",
"resolve_image_name",
"(",
"img",
".",
"pop",
"(",
"'image_name'",
")",
")"
] | Connect to a EC2.
:param region: The name of the region to connect to.
:type region: str
:param kw_params:
:type kw_params: dict | [
"Connect",
"to",
"a",
"EC2",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L56-L72 | train | 236,936 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.resolve_image_name | def resolve_image_name(self, image_name):
"""Look up an AMI for the connected region based on an image name.
:param image_name: The name of the image to resolve.
:type image_name: str
:return: The AMI for the given image.
:rtype: str
"""
# look at each scope in order of size
scopes = ['self', 'amazon', 'aws-marketplace']
if image_name in self.remote_images:
return self.remote_images[image_name]
for scope in scopes:
logger.info('Retrieving available AMIs owned by %s...', scope)
remote_images = self.ec2.get_all_images(owners=[scope], filters={'name': image_name})
self.remote_images.update({ri.name: ri.id for ri in remote_images})
if image_name in self.remote_images:
return self.remote_images[image_name]
raise EC2ManagerException('Failed to resolve AMI name "%s" to an AMI' % image_name) | python | def resolve_image_name(self, image_name):
"""Look up an AMI for the connected region based on an image name.
:param image_name: The name of the image to resolve.
:type image_name: str
:return: The AMI for the given image.
:rtype: str
"""
# look at each scope in order of size
scopes = ['self', 'amazon', 'aws-marketplace']
if image_name in self.remote_images:
return self.remote_images[image_name]
for scope in scopes:
logger.info('Retrieving available AMIs owned by %s...', scope)
remote_images = self.ec2.get_all_images(owners=[scope], filters={'name': image_name})
self.remote_images.update({ri.name: ri.id for ri in remote_images})
if image_name in self.remote_images:
return self.remote_images[image_name]
raise EC2ManagerException('Failed to resolve AMI name "%s" to an AMI' % image_name) | [
"def",
"resolve_image_name",
"(",
"self",
",",
"image_name",
")",
":",
"# look at each scope in order of size",
"scopes",
"=",
"[",
"'self'",
",",
"'amazon'",
",",
"'aws-marketplace'",
"]",
"if",
"image_name",
"in",
"self",
".",
"remote_images",
":",
"return",
"self",
".",
"remote_images",
"[",
"image_name",
"]",
"for",
"scope",
"in",
"scopes",
":",
"logger",
".",
"info",
"(",
"'Retrieving available AMIs owned by %s...'",
",",
"scope",
")",
"remote_images",
"=",
"self",
".",
"ec2",
".",
"get_all_images",
"(",
"owners",
"=",
"[",
"scope",
"]",
",",
"filters",
"=",
"{",
"'name'",
":",
"image_name",
"}",
")",
"self",
".",
"remote_images",
".",
"update",
"(",
"{",
"ri",
".",
"name",
":",
"ri",
".",
"id",
"for",
"ri",
"in",
"remote_images",
"}",
")",
"if",
"image_name",
"in",
"self",
".",
"remote_images",
":",
"return",
"self",
".",
"remote_images",
"[",
"image_name",
"]",
"raise",
"EC2ManagerException",
"(",
"'Failed to resolve AMI name \"%s\" to an AMI'",
"%",
"image_name",
")"
] | Look up an AMI for the connected region based on an image name.
:param image_name: The name of the image to resolve.
:type image_name: str
:return: The AMI for the given image.
:rtype: str | [
"Look",
"up",
"an",
"AMI",
"for",
"the",
"connected",
"region",
"based",
"on",
"an",
"image",
"name",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L74-L92 | train | 236,937 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.create_on_demand | def create_on_demand(self,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False):
"""Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
:param root_device_type: The type of the root device.
:type root_device_type: str
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list
"""
name, size = self._get_default_name_size(instance_type, size)
if root_device_type == 'ebs':
self.images[instance_type]['block_device_map'] = \
self._configure_ebs_volume(vol_type, name, size, delete_on_termination)
reservation = self.ec2.run_instances(**self.images[instance_type])
logger.info('Creating requested tags...')
for i in reservation.instances:
self.retry_on_ec2_error(self.ec2.create_tags, [i.id], tags or {})
instances = []
logger.info('Waiting for instances to become ready...')
while len(reservation.instances): # pylint: disable=len-as-condition
for i in reservation.instances:
if i.state == 'running':
instances.append(i)
reservation.instances.pop(reservation.instances.index(i))
logger.info('%s is %s at %s (%s)',
i.id,
i.state,
i.public_dns_name,
i.ip_address)
else:
self.retry_on_ec2_error(i.update)
return instances | python | def create_on_demand(self,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False):
"""Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
:param root_device_type: The type of the root device.
:type root_device_type: str
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list
"""
name, size = self._get_default_name_size(instance_type, size)
if root_device_type == 'ebs':
self.images[instance_type]['block_device_map'] = \
self._configure_ebs_volume(vol_type, name, size, delete_on_termination)
reservation = self.ec2.run_instances(**self.images[instance_type])
logger.info('Creating requested tags...')
for i in reservation.instances:
self.retry_on_ec2_error(self.ec2.create_tags, [i.id], tags or {})
instances = []
logger.info('Waiting for instances to become ready...')
while len(reservation.instances): # pylint: disable=len-as-condition
for i in reservation.instances:
if i.state == 'running':
instances.append(i)
reservation.instances.pop(reservation.instances.index(i))
logger.info('%s is %s at %s (%s)',
i.id,
i.state,
i.public_dns_name,
i.ip_address)
else:
self.retry_on_ec2_error(i.update)
return instances | [
"def",
"create_on_demand",
"(",
"self",
",",
"instance_type",
"=",
"'default'",
",",
"tags",
"=",
"None",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False",
")",
":",
"name",
",",
"size",
"=",
"self",
".",
"_get_default_name_size",
"(",
"instance_type",
",",
"size",
")",
"if",
"root_device_type",
"==",
"'ebs'",
":",
"self",
".",
"images",
"[",
"instance_type",
"]",
"[",
"'block_device_map'",
"]",
"=",
"self",
".",
"_configure_ebs_volume",
"(",
"vol_type",
",",
"name",
",",
"size",
",",
"delete_on_termination",
")",
"reservation",
"=",
"self",
".",
"ec2",
".",
"run_instances",
"(",
"*",
"*",
"self",
".",
"images",
"[",
"instance_type",
"]",
")",
"logger",
".",
"info",
"(",
"'Creating requested tags...'",
")",
"for",
"i",
"in",
"reservation",
".",
"instances",
":",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"create_tags",
",",
"[",
"i",
".",
"id",
"]",
",",
"tags",
"or",
"{",
"}",
")",
"instances",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"'Waiting for instances to become ready...'",
")",
"while",
"len",
"(",
"reservation",
".",
"instances",
")",
":",
"# pylint: disable=len-as-condition",
"for",
"i",
"in",
"reservation",
".",
"instances",
":",
"if",
"i",
".",
"state",
"==",
"'running'",
":",
"instances",
".",
"append",
"(",
"i",
")",
"reservation",
".",
"instances",
".",
"pop",
"(",
"reservation",
".",
"instances",
".",
"index",
"(",
"i",
")",
")",
"logger",
".",
"info",
"(",
"'%s is %s at %s (%s)'",
",",
"i",
".",
"id",
",",
"i",
".",
"state",
",",
"i",
".",
"public_dns_name",
",",
"i",
".",
"ip_address",
")",
"else",
":",
"self",
".",
"retry_on_ec2_error",
"(",
"i",
".",
"update",
")",
"return",
"instances"
] | Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
:param root_device_type: The type of the root device.
:type root_device_type: str
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list | [
"Create",
"one",
"or",
"more",
"EC2",
"on",
"-",
"demand",
"instances",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L94-L144 | train | 236,938 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.create_spot_requests | def create_spot_requests(self,
price,
instance_type='default',
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=None):
"""Request creation of one or more EC2 spot instances.
:param size:
:param vol_type:
:param delete_on_termination:
:param root_device_type: The type of the root device.
:type root_device_type: str
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param timeout: Seconds to keep the request open (cancelled if not fulfilled).
:type timeout: int
:return: List of requests created
:rtype: list
"""
name, size = self._get_default_name_size(instance_type, size)
if root_device_type == 'ebs':
self.images[instance_type]['block_device_map'] = \
self._configure_ebs_volume(vol_type, name, size, delete_on_termination)
valid_until = None
if timeout is not None:
valid_until = (datetime.datetime.now() + datetime.timedelta(seconds=timeout)).isoformat()
requests = self.ec2.request_spot_instances(price, valid_until=valid_until, **self.images[instance_type])
return [r.id for r in requests] | python | def create_spot_requests(self,
price,
instance_type='default',
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=None):
"""Request creation of one or more EC2 spot instances.
:param size:
:param vol_type:
:param delete_on_termination:
:param root_device_type: The type of the root device.
:type root_device_type: str
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param timeout: Seconds to keep the request open (cancelled if not fulfilled).
:type timeout: int
:return: List of requests created
:rtype: list
"""
name, size = self._get_default_name_size(instance_type, size)
if root_device_type == 'ebs':
self.images[instance_type]['block_device_map'] = \
self._configure_ebs_volume(vol_type, name, size, delete_on_termination)
valid_until = None
if timeout is not None:
valid_until = (datetime.datetime.now() + datetime.timedelta(seconds=timeout)).isoformat()
requests = self.ec2.request_spot_instances(price, valid_until=valid_until, **self.images[instance_type])
return [r.id for r in requests] | [
"def",
"create_spot_requests",
"(",
"self",
",",
"price",
",",
"instance_type",
"=",
"'default'",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"name",
",",
"size",
"=",
"self",
".",
"_get_default_name_size",
"(",
"instance_type",
",",
"size",
")",
"if",
"root_device_type",
"==",
"'ebs'",
":",
"self",
".",
"images",
"[",
"instance_type",
"]",
"[",
"'block_device_map'",
"]",
"=",
"self",
".",
"_configure_ebs_volume",
"(",
"vol_type",
",",
"name",
",",
"size",
",",
"delete_on_termination",
")",
"valid_until",
"=",
"None",
"if",
"timeout",
"is",
"not",
"None",
":",
"valid_until",
"=",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"timeout",
")",
")",
".",
"isoformat",
"(",
")",
"requests",
"=",
"self",
".",
"ec2",
".",
"request_spot_instances",
"(",
"price",
",",
"valid_until",
"=",
"valid_until",
",",
"*",
"*",
"self",
".",
"images",
"[",
"instance_type",
"]",
")",
"return",
"[",
"r",
".",
"id",
"for",
"r",
"in",
"requests",
"]"
] | Request creation of one or more EC2 spot instances.
:param size:
:param vol_type:
:param delete_on_termination:
:param root_device_type: The type of the root device.
:type root_device_type: str
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param timeout: Seconds to keep the request open (cancelled if not fulfilled).
:type timeout: int
:return: List of requests created
:rtype: list | [
"Request",
"creation",
"of",
"one",
"or",
"more",
"EC2",
"spot",
"instances",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L146-L181 | train | 236,939 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.check_spot_requests | def check_spot_requests(self, requests, tags=None):
"""Check status of one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
:param tags:
:type tags: dict
:return: List of boto.ec2.instance.Instance's created, order corresponding to requests param (None if request
still open, boto.ec2.instance.Reservation if request is no longer open)
:rtype: list
"""
instances = [None] * len(requests)
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
if req.instance_id:
instance = self.retry_on_ec2_error(self.ec2.get_only_instances, req.instance_id)[0]
if not instance:
raise EC2ManagerException('Failed to get instance with id %s for %s request %s'
% (req.instance_id, req.status.code, req.id))
instances[requests.index(req.id)] = instance
self.retry_on_ec2_error(self.ec2.create_tags, [instance.id], tags or {})
logger.info('Request %s is %s and %s.',
req.id,
req.status.code,
req.state)
logger.info('%s is %s at %s (%s)',
instance.id,
instance.state,
instance.public_dns_name,
instance.ip_address)
elif req.state != "open":
# return the request so we don't try again
instances[requests.index(req.id)] = req
return instances | python | def check_spot_requests(self, requests, tags=None):
"""Check status of one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
:param tags:
:type tags: dict
:return: List of boto.ec2.instance.Instance's created, order corresponding to requests param (None if request
still open, boto.ec2.instance.Reservation if request is no longer open)
:rtype: list
"""
instances = [None] * len(requests)
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
if req.instance_id:
instance = self.retry_on_ec2_error(self.ec2.get_only_instances, req.instance_id)[0]
if not instance:
raise EC2ManagerException('Failed to get instance with id %s for %s request %s'
% (req.instance_id, req.status.code, req.id))
instances[requests.index(req.id)] = instance
self.retry_on_ec2_error(self.ec2.create_tags, [instance.id], tags or {})
logger.info('Request %s is %s and %s.',
req.id,
req.status.code,
req.state)
logger.info('%s is %s at %s (%s)',
instance.id,
instance.state,
instance.public_dns_name,
instance.ip_address)
elif req.state != "open":
# return the request so we don't try again
instances[requests.index(req.id)] = req
return instances | [
"def",
"check_spot_requests",
"(",
"self",
",",
"requests",
",",
"tags",
"=",
"None",
")",
":",
"instances",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"requests",
")",
"ec2_requests",
"=",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"get_all_spot_instance_requests",
",",
"request_ids",
"=",
"requests",
")",
"for",
"req",
"in",
"ec2_requests",
":",
"if",
"req",
".",
"instance_id",
":",
"instance",
"=",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"get_only_instances",
",",
"req",
".",
"instance_id",
")",
"[",
"0",
"]",
"if",
"not",
"instance",
":",
"raise",
"EC2ManagerException",
"(",
"'Failed to get instance with id %s for %s request %s'",
"%",
"(",
"req",
".",
"instance_id",
",",
"req",
".",
"status",
".",
"code",
",",
"req",
".",
"id",
")",
")",
"instances",
"[",
"requests",
".",
"index",
"(",
"req",
".",
"id",
")",
"]",
"=",
"instance",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"create_tags",
",",
"[",
"instance",
".",
"id",
"]",
",",
"tags",
"or",
"{",
"}",
")",
"logger",
".",
"info",
"(",
"'Request %s is %s and %s.'",
",",
"req",
".",
"id",
",",
"req",
".",
"status",
".",
"code",
",",
"req",
".",
"state",
")",
"logger",
".",
"info",
"(",
"'%s is %s at %s (%s)'",
",",
"instance",
".",
"id",
",",
"instance",
".",
"state",
",",
"instance",
".",
"public_dns_name",
",",
"instance",
".",
"ip_address",
")",
"elif",
"req",
".",
"state",
"!=",
"\"open\"",
":",
"# return the request so we don't try again",
"instances",
"[",
"requests",
".",
"index",
"(",
"req",
".",
"id",
")",
"]",
"=",
"req",
"return",
"instances"
] | Check status of one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
:param tags:
:type tags: dict
:return: List of boto.ec2.instance.Instance's created, order corresponding to requests param (None if request
still open, boto.ec2.instance.Reservation if request is no longer open)
:rtype: list | [
"Check",
"status",
"of",
"one",
"or",
"more",
"EC2",
"spot",
"instance",
"requests",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L183-L221 | train | 236,940 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.cancel_spot_requests | def cancel_spot_requests(self, requests):
"""Cancel one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
"""
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
req.cancel() | python | def cancel_spot_requests(self, requests):
"""Cancel one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
"""
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
req.cancel() | [
"def",
"cancel_spot_requests",
"(",
"self",
",",
"requests",
")",
":",
"ec2_requests",
"=",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"get_all_spot_instance_requests",
",",
"request_ids",
"=",
"requests",
")",
"for",
"req",
"in",
"ec2_requests",
":",
"req",
".",
"cancel",
"(",
")"
] | Cancel one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list | [
"Cancel",
"one",
"or",
"more",
"EC2",
"spot",
"instance",
"requests",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L223-L232 | train | 236,941 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.create_spot | def create_spot(self,
price,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=None):
"""Create one or more EC2 spot instances.
:param root_device_type:
:param size:
:param vol_type:
:param delete_on_termination:
:param timeout:
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list
"""
request_ids = self.create_spot_requests(price,
instance_type=instance_type,
root_device_type=root_device_type,
size=size,
vol_type=vol_type,
delete_on_termination=delete_on_termination)
instances = []
logger.info('Waiting on fulfillment of requested spot instances.')
poll_resolution = 5.0
time_exceeded = False
while request_ids:
time.sleep(poll_resolution)
new_instances = self.check_spot_requests(request_ids, tags=tags)
if timeout is not None:
timeout -= poll_resolution
time_exceeded = timeout <= 0
fulfilled = []
for idx, instance in enumerate(new_instances):
if instance.status.code == "bad-parameters":
logging.error('Spot request for "%s" failed due to bad parameters.', instance.id)
self.cancel_spot_requests([instance.id])
if instance is not None:
fulfilled.append(idx)
if isinstance(instance, boto.ec2.instance.Instance):
instances.append(instance)
for idx in reversed(fulfilled):
request_ids.pop(idx)
if request_ids and time_exceeded:
self.cancel_spot_requests(request_ids)
break
return instances | python | def create_spot(self,
price,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=None):
"""Create one or more EC2 spot instances.
:param root_device_type:
:param size:
:param vol_type:
:param delete_on_termination:
:param timeout:
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list
"""
request_ids = self.create_spot_requests(price,
instance_type=instance_type,
root_device_type=root_device_type,
size=size,
vol_type=vol_type,
delete_on_termination=delete_on_termination)
instances = []
logger.info('Waiting on fulfillment of requested spot instances.')
poll_resolution = 5.0
time_exceeded = False
while request_ids:
time.sleep(poll_resolution)
new_instances = self.check_spot_requests(request_ids, tags=tags)
if timeout is not None:
timeout -= poll_resolution
time_exceeded = timeout <= 0
fulfilled = []
for idx, instance in enumerate(new_instances):
if instance.status.code == "bad-parameters":
logging.error('Spot request for "%s" failed due to bad parameters.', instance.id)
self.cancel_spot_requests([instance.id])
if instance is not None:
fulfilled.append(idx)
if isinstance(instance, boto.ec2.instance.Instance):
instances.append(instance)
for idx in reversed(fulfilled):
request_ids.pop(idx)
if request_ids and time_exceeded:
self.cancel_spot_requests(request_ids)
break
return instances | [
"def",
"create_spot",
"(",
"self",
",",
"price",
",",
"instance_type",
"=",
"'default'",
",",
"tags",
"=",
"None",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"request_ids",
"=",
"self",
".",
"create_spot_requests",
"(",
"price",
",",
"instance_type",
"=",
"instance_type",
",",
"root_device_type",
"=",
"root_device_type",
",",
"size",
"=",
"size",
",",
"vol_type",
"=",
"vol_type",
",",
"delete_on_termination",
"=",
"delete_on_termination",
")",
"instances",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"'Waiting on fulfillment of requested spot instances.'",
")",
"poll_resolution",
"=",
"5.0",
"time_exceeded",
"=",
"False",
"while",
"request_ids",
":",
"time",
".",
"sleep",
"(",
"poll_resolution",
")",
"new_instances",
"=",
"self",
".",
"check_spot_requests",
"(",
"request_ids",
",",
"tags",
"=",
"tags",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"-=",
"poll_resolution",
"time_exceeded",
"=",
"timeout",
"<=",
"0",
"fulfilled",
"=",
"[",
"]",
"for",
"idx",
",",
"instance",
"in",
"enumerate",
"(",
"new_instances",
")",
":",
"if",
"instance",
".",
"status",
".",
"code",
"==",
"\"bad-parameters\"",
":",
"logging",
".",
"error",
"(",
"'Spot request for \"%s\" failed due to bad parameters.'",
",",
"instance",
".",
"id",
")",
"self",
".",
"cancel_spot_requests",
"(",
"[",
"instance",
".",
"id",
"]",
")",
"if",
"instance",
"is",
"not",
"None",
":",
"fulfilled",
".",
"append",
"(",
"idx",
")",
"if",
"isinstance",
"(",
"instance",
",",
"boto",
".",
"ec2",
".",
"instance",
".",
"Instance",
")",
":",
"instances",
".",
"append",
"(",
"instance",
")",
"for",
"idx",
"in",
"reversed",
"(",
"fulfilled",
")",
":",
"request_ids",
".",
"pop",
"(",
"idx",
")",
"if",
"request_ids",
"and",
"time_exceeded",
":",
"self",
".",
"cancel_spot_requests",
"(",
"request_ids",
")",
"break",
"return",
"instances"
] | Create one or more EC2 spot instances.
:param root_device_type:
:param size:
:param vol_type:
:param delete_on_termination:
:param timeout:
:param price: Max price to pay for spot instance per hour.
:type price: float
:param instance_type: A section name in amazon.json
:type instance_type: str
:param tags:
:type tags: dict
:return: List of instances created
:rtype: list | [
"Create",
"one",
"or",
"more",
"EC2",
"spot",
"instances",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L234-L294 | train | 236,942 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager._scale_down | def _scale_down(self, instances, count):
"""Return a list of |count| last created instances by launch time.
:param instances: A list of instances.
:type instances: list
:param count: Number of instances to scale down.
:type count: integer
:return: List of instances to be scaled down.
:rtype: list
"""
i = sorted(instances, key=lambda i: i.launch_time, reverse=True)
if not i:
return []
running = len(i)
logger.info('%d instance/s are running.', running)
logger.info('Scaling down %d instances of those.', count)
if count > running:
logger.info('Scale-down value is > than running instance/s - using maximum of %d!', running)
count = running
return i[:count] | python | def _scale_down(self, instances, count):
"""Return a list of |count| last created instances by launch time.
:param instances: A list of instances.
:type instances: list
:param count: Number of instances to scale down.
:type count: integer
:return: List of instances to be scaled down.
:rtype: list
"""
i = sorted(instances, key=lambda i: i.launch_time, reverse=True)
if not i:
return []
running = len(i)
logger.info('%d instance/s are running.', running)
logger.info('Scaling down %d instances of those.', count)
if count > running:
logger.info('Scale-down value is > than running instance/s - using maximum of %d!', running)
count = running
return i[:count] | [
"def",
"_scale_down",
"(",
"self",
",",
"instances",
",",
"count",
")",
":",
"i",
"=",
"sorted",
"(",
"instances",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
".",
"launch_time",
",",
"reverse",
"=",
"True",
")",
"if",
"not",
"i",
":",
"return",
"[",
"]",
"running",
"=",
"len",
"(",
"i",
")",
"logger",
".",
"info",
"(",
"'%d instance/s are running.'",
",",
"running",
")",
"logger",
".",
"info",
"(",
"'Scaling down %d instances of those.'",
",",
"count",
")",
"if",
"count",
">",
"running",
":",
"logger",
".",
"info",
"(",
"'Scale-down value is > than running instance/s - using maximum of %d!'",
",",
"running",
")",
"count",
"=",
"running",
"return",
"i",
"[",
":",
"count",
"]"
] | Return a list of |count| last created instances by launch time.
:param instances: A list of instances.
:type instances: list
:param count: Number of instances to scale down.
:type count: integer
:return: List of instances to be scaled down.
:rtype: list | [
"Return",
"a",
"list",
"of",
"|count|",
"last",
"created",
"instances",
"by",
"launch",
"time",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L296-L315 | train | 236,943 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager._configure_ebs_volume | def _configure_ebs_volume(self, vol_type, name, size, delete_on_termination):
"""Sets the desired root EBS size, otherwise the default EC2 value is used.
:param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic)
:type vol_type: str
:param size: Desired root EBS size.
:type size: int
:param delete_on_termination: Toggle this flag to delete EBS volume on termination.
:type delete_on_termination: bool
:return: A BlockDeviceMapping object.
:rtype: object
"""
# From GitHub boto docs: http://git.io/veyDv
root_dev = boto.ec2.blockdevicemapping.BlockDeviceType()
root_dev.delete_on_termination = delete_on_termination
root_dev.volume_type = vol_type
if size != 'default':
root_dev.size = size # change root volume to desired size
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm[name] = root_dev
return bdm | python | def _configure_ebs_volume(self, vol_type, name, size, delete_on_termination):
"""Sets the desired root EBS size, otherwise the default EC2 value is used.
:param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic)
:type vol_type: str
:param size: Desired root EBS size.
:type size: int
:param delete_on_termination: Toggle this flag to delete EBS volume on termination.
:type delete_on_termination: bool
:return: A BlockDeviceMapping object.
:rtype: object
"""
# From GitHub boto docs: http://git.io/veyDv
root_dev = boto.ec2.blockdevicemapping.BlockDeviceType()
root_dev.delete_on_termination = delete_on_termination
root_dev.volume_type = vol_type
if size != 'default':
root_dev.size = size # change root volume to desired size
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm[name] = root_dev
return bdm | [
"def",
"_configure_ebs_volume",
"(",
"self",
",",
"vol_type",
",",
"name",
",",
"size",
",",
"delete_on_termination",
")",
":",
"# From GitHub boto docs: http://git.io/veyDv",
"root_dev",
"=",
"boto",
".",
"ec2",
".",
"blockdevicemapping",
".",
"BlockDeviceType",
"(",
")",
"root_dev",
".",
"delete_on_termination",
"=",
"delete_on_termination",
"root_dev",
".",
"volume_type",
"=",
"vol_type",
"if",
"size",
"!=",
"'default'",
":",
"root_dev",
".",
"size",
"=",
"size",
"# change root volume to desired size",
"bdm",
"=",
"boto",
".",
"ec2",
".",
"blockdevicemapping",
".",
"BlockDeviceMapping",
"(",
")",
"bdm",
"[",
"name",
"]",
"=",
"root_dev",
"return",
"bdm"
] | Sets the desired root EBS size, otherwise the default EC2 value is used.
:param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic)
:type vol_type: str
:param size: Desired root EBS size.
:type size: int
:param delete_on_termination: Toggle this flag to delete EBS volume on termination.
:type delete_on_termination: bool
:return: A BlockDeviceMapping object.
:rtype: object | [
"Sets",
"the",
"desired",
"root",
"EBS",
"size",
"otherwise",
"the",
"default",
"EC2",
"value",
"is",
"used",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L337-L357 | train | 236,944 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.stop | def stop(self, instances, count=0):
"""Stop each provided running instance.
:param count:
:param instances: A list of instances.
:type instances: list
"""
if not instances:
return
if count > 0:
instances = self._scale_down(instances, count)
self.ec2.stop_instances([i.id for i in instances]) | python | def stop(self, instances, count=0):
"""Stop each provided running instance.
:param count:
:param instances: A list of instances.
:type instances: list
"""
if not instances:
return
if count > 0:
instances = self._scale_down(instances, count)
self.ec2.stop_instances([i.id for i in instances]) | [
"def",
"stop",
"(",
"self",
",",
"instances",
",",
"count",
"=",
"0",
")",
":",
"if",
"not",
"instances",
":",
"return",
"if",
"count",
">",
"0",
":",
"instances",
"=",
"self",
".",
"_scale_down",
"(",
"instances",
",",
"count",
")",
"self",
".",
"ec2",
".",
"stop_instances",
"(",
"[",
"i",
".",
"id",
"for",
"i",
"in",
"instances",
"]",
")"
] | Stop each provided running instance.
:param count:
:param instances: A list of instances.
:type instances: list | [
"Stop",
"each",
"provided",
"running",
"instance",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L359-L370 | train | 236,945 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.terminate | def terminate(self, instances, count=0):
"""Terminate each provided running or stopped instance.
:param count:
:param instances: A list of instances.
:type instances: list
"""
if not instances:
return
if count > 0:
instances = self._scale_down(instances, count)
self.ec2.terminate_instances([i.id for i in instances]) | python | def terminate(self, instances, count=0):
"""Terminate each provided running or stopped instance.
:param count:
:param instances: A list of instances.
:type instances: list
"""
if not instances:
return
if count > 0:
instances = self._scale_down(instances, count)
self.ec2.terminate_instances([i.id for i in instances]) | [
"def",
"terminate",
"(",
"self",
",",
"instances",
",",
"count",
"=",
"0",
")",
":",
"if",
"not",
"instances",
":",
"return",
"if",
"count",
">",
"0",
":",
"instances",
"=",
"self",
".",
"_scale_down",
"(",
"instances",
",",
"count",
")",
"self",
".",
"ec2",
".",
"terminate_instances",
"(",
"[",
"i",
".",
"id",
"for",
"i",
"in",
"instances",
"]",
")"
] | Terminate each provided running or stopped instance.
:param count:
:param instances: A list of instances.
:type instances: list | [
"Terminate",
"each",
"provided",
"running",
"or",
"stopped",
"instance",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L372-L383 | train | 236,946 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | EC2Manager.find | def find(self, instance_ids=None, filters=None):
"""Flatten list of reservations to a list of instances.
:param instance_ids: A list of instance ids to filter by
:type instance_ids: list
:param filters: A dict of Filter.N values defined in http://goo.gl/jYNej9
:type filters: dict
:return: A flattened list of filtered instances.
:rtype: list
"""
instances = []
reservations = self.retry_on_ec2_error(self.ec2.get_all_instances, instance_ids=instance_ids, filters=filters)
for reservation in reservations:
instances.extend(reservation.instances)
return instances | python | def find(self, instance_ids=None, filters=None):
"""Flatten list of reservations to a list of instances.
:param instance_ids: A list of instance ids to filter by
:type instance_ids: list
:param filters: A dict of Filter.N values defined in http://goo.gl/jYNej9
:type filters: dict
:return: A flattened list of filtered instances.
:rtype: list
"""
instances = []
reservations = self.retry_on_ec2_error(self.ec2.get_all_instances, instance_ids=instance_ids, filters=filters)
for reservation in reservations:
instances.extend(reservation.instances)
return instances | [
"def",
"find",
"(",
"self",
",",
"instance_ids",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"instances",
"=",
"[",
"]",
"reservations",
"=",
"self",
".",
"retry_on_ec2_error",
"(",
"self",
".",
"ec2",
".",
"get_all_instances",
",",
"instance_ids",
"=",
"instance_ids",
",",
"filters",
"=",
"filters",
")",
"for",
"reservation",
"in",
"reservations",
":",
"instances",
".",
"extend",
"(",
"reservation",
".",
"instances",
")",
"return",
"instances"
] | Flatten list of reservations to a list of instances.
:param instance_ids: A list of instance ids to filter by
:type instance_ids: list
:param filters: A dict of Filter.N values defined in http://goo.gl/jYNej9
:type filters: dict
:return: A flattened list of filtered instances.
:rtype: list | [
"Flatten",
"list",
"of",
"reservations",
"to",
"a",
"list",
"of",
"instances",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L385-L399 | train | 236,947 |
MozillaSecurity/laniakea | laniakea/core/common.py | ModuleLoader.load | def load(self, root, module_path, pkg_name):
"""Load modules dynamically.
"""
root = os.path.join(root, module_path)
import_name = os.path.join(pkg_name, module_path).replace(os.sep, '.')
for (_, name, _) in pkgutil.iter_modules([root]):
self.modules[name] = import_module('.' + name, package=import_name)
return self.modules | python | def load(self, root, module_path, pkg_name):
"""Load modules dynamically.
"""
root = os.path.join(root, module_path)
import_name = os.path.join(pkg_name, module_path).replace(os.sep, '.')
for (_, name, _) in pkgutil.iter_modules([root]):
self.modules[name] = import_module('.' + name, package=import_name)
return self.modules | [
"def",
"load",
"(",
"self",
",",
"root",
",",
"module_path",
",",
"pkg_name",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"module_path",
")",
"import_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_name",
",",
"module_path",
")",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'.'",
")",
"for",
"(",
"_",
",",
"name",
",",
"_",
")",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"[",
"root",
"]",
")",
":",
"self",
".",
"modules",
"[",
"name",
"]",
"=",
"import_module",
"(",
"'.'",
"+",
"name",
",",
"package",
"=",
"import_name",
")",
"return",
"self",
".",
"modules"
] | Load modules dynamically. | [
"Load",
"modules",
"dynamically",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/common.py#L155-L162 | train | 236,948 |
MozillaSecurity/laniakea | laniakea/core/common.py | ModuleLoader.command_line_interfaces | def command_line_interfaces(self):
"""Return the CommandLine classes from each provider.
"""
interfaces = []
for _, module in self.modules.items():
for entry in dir(module):
if entry.endswith('CommandLine'):
interfaces.append((module, entry))
return interfaces | python | def command_line_interfaces(self):
"""Return the CommandLine classes from each provider.
"""
interfaces = []
for _, module in self.modules.items():
for entry in dir(module):
if entry.endswith('CommandLine'):
interfaces.append((module, entry))
return interfaces | [
"def",
"command_line_interfaces",
"(",
"self",
")",
":",
"interfaces",
"=",
"[",
"]",
"for",
"_",
",",
"module",
"in",
"self",
".",
"modules",
".",
"items",
"(",
")",
":",
"for",
"entry",
"in",
"dir",
"(",
"module",
")",
":",
"if",
"entry",
".",
"endswith",
"(",
"'CommandLine'",
")",
":",
"interfaces",
".",
"append",
"(",
"(",
"module",
",",
"entry",
")",
")",
"return",
"interfaces"
] | Return the CommandLine classes from each provider. | [
"Return",
"the",
"CommandLine",
"classes",
"from",
"each",
"provider",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/common.py#L164-L172 | train | 236,949 |
MozillaSecurity/laniakea | laniakea/core/common.py | Common.pluralize | def pluralize(item):
"""Nothing to see here.
"""
assert isinstance(item, (int, list))
if isinstance(item, int):
return 's' if item > 1 else ''
if isinstance(item, list):
return 's' if len(item) > 1 else ''
return '' | python | def pluralize(item):
"""Nothing to see here.
"""
assert isinstance(item, (int, list))
if isinstance(item, int):
return 's' if item > 1 else ''
if isinstance(item, list):
return 's' if len(item) > 1 else ''
return '' | [
"def",
"pluralize",
"(",
"item",
")",
":",
"assert",
"isinstance",
"(",
"item",
",",
"(",
"int",
",",
"list",
")",
")",
"if",
"isinstance",
"(",
"item",
",",
"int",
")",
":",
"return",
"'s'",
"if",
"item",
">",
"1",
"else",
"''",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"return",
"'s'",
"if",
"len",
"(",
"item",
")",
">",
"1",
"else",
"''",
"return",
"''"
] | Nothing to see here. | [
"Nothing",
"to",
"see",
"here",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/common.py#L190-L198 | train | 236,950 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketConfiguration.validate | def validate(self):
"""Perform some basic configuration validation.
"""
if not self.conf.get('auth_token'):
raise PacketManagerException('The auth token for Packet is not defined but required.')
if not self.conf.get('projects'):
raise PacketManagerException('Required "projects" section is missing.')
projects = self.conf.get('projects')
if not projects.keys():
raise PacketManagerException('At least one project at Packet is required.')
failure = False
for project, identifier in projects.items():
if not identifier:
failure = True
logging.error('Project "%s" has no valid identifier.', project)
if failure:
raise PacketManagerException('One or more projects are not setup appropriately.') | python | def validate(self):
"""Perform some basic configuration validation.
"""
if not self.conf.get('auth_token'):
raise PacketManagerException('The auth token for Packet is not defined but required.')
if not self.conf.get('projects'):
raise PacketManagerException('Required "projects" section is missing.')
projects = self.conf.get('projects')
if not projects.keys():
raise PacketManagerException('At least one project at Packet is required.')
failure = False
for project, identifier in projects.items():
if not identifier:
failure = True
logging.error('Project "%s" has no valid identifier.', project)
if failure:
raise PacketManagerException('One or more projects are not setup appropriately.') | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"conf",
".",
"get",
"(",
"'auth_token'",
")",
":",
"raise",
"PacketManagerException",
"(",
"'The auth token for Packet is not defined but required.'",
")",
"if",
"not",
"self",
".",
"conf",
".",
"get",
"(",
"'projects'",
")",
":",
"raise",
"PacketManagerException",
"(",
"'Required \"projects\" section is missing.'",
")",
"projects",
"=",
"self",
".",
"conf",
".",
"get",
"(",
"'projects'",
")",
"if",
"not",
"projects",
".",
"keys",
"(",
")",
":",
"raise",
"PacketManagerException",
"(",
"'At least one project at Packet is required.'",
")",
"failure",
"=",
"False",
"for",
"project",
",",
"identifier",
"in",
"projects",
".",
"items",
"(",
")",
":",
"if",
"not",
"identifier",
":",
"failure",
"=",
"True",
"logging",
".",
"error",
"(",
"'Project \"%s\" has no valid identifier.'",
",",
"project",
")",
"if",
"failure",
":",
"raise",
"PacketManagerException",
"(",
"'One or more projects are not setup appropriately.'",
")"
] | Perform some basic configuration validation. | [
"Perform",
"some",
"basic",
"configuration",
"validation",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L31-L49 | train | 236,951 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.print_projects | def print_projects(self, projects):
"""Print method for projects.
"""
for project in projects:
print('{}: {}'.format(project.name, project.id)) | python | def print_projects(self, projects):
"""Print method for projects.
"""
for project in projects:
print('{}: {}'.format(project.name, project.id)) | [
"def",
"print_projects",
"(",
"self",
",",
"projects",
")",
":",
"for",
"project",
"in",
"projects",
":",
"print",
"(",
"'{}: {}'",
".",
"format",
"(",
"project",
".",
"name",
",",
"project",
".",
"id",
")",
")"
] | Print method for projects. | [
"Print",
"method",
"for",
"projects",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L76-L80 | train | 236,952 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.print_operating_systems | def print_operating_systems(self, operating_systems):
"""Print method for operating systems.
"""
for _os in operating_systems:
print('{}: {}'.format(_os.name, _os.slug)) | python | def print_operating_systems(self, operating_systems):
"""Print method for operating systems.
"""
for _os in operating_systems:
print('{}: {}'.format(_os.name, _os.slug)) | [
"def",
"print_operating_systems",
"(",
"self",
",",
"operating_systems",
")",
":",
"for",
"_os",
"in",
"operating_systems",
":",
"print",
"(",
"'{}: {}'",
".",
"format",
"(",
"_os",
".",
"name",
",",
"_os",
".",
"slug",
")",
")"
] | Print method for operating systems. | [
"Print",
"method",
"for",
"operating",
"systems",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L89-L93 | train | 236,953 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.print_plans | def print_plans(self, plans):
"""Print method for plans.
"""
for plan in plans:
print('Name: {} "{}" Price: {} USD'.format(plan.name, plan.slug, plan.pricing['hour']))
self.pprint(plan.specs)
print('\n') | python | def print_plans(self, plans):
"""Print method for plans.
"""
for plan in plans:
print('Name: {} "{}" Price: {} USD'.format(plan.name, plan.slug, plan.pricing['hour']))
self.pprint(plan.specs)
print('\n') | [
"def",
"print_plans",
"(",
"self",
",",
"plans",
")",
":",
"for",
"plan",
"in",
"plans",
":",
"print",
"(",
"'Name: {} \"{}\" Price: {} USD'",
".",
"format",
"(",
"plan",
".",
"name",
",",
"plan",
".",
"slug",
",",
"plan",
".",
"pricing",
"[",
"'hour'",
"]",
")",
")",
"self",
".",
"pprint",
"(",
"plan",
".",
"specs",
")",
"print",
"(",
"'\\n'",
")"
] | Print method for plans. | [
"Print",
"method",
"for",
"plans",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L102-L108 | train | 236,954 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.print_facilities | def print_facilities(self, facilities):
"""Print method for facilities.
"""
for facility in facilities:
print('{} - ({}): {}'.format(facility.code, facility.name, ",".join(facility.features))) | python | def print_facilities(self, facilities):
"""Print method for facilities.
"""
for facility in facilities:
print('{} - ({}): {}'.format(facility.code, facility.name, ",".join(facility.features))) | [
"def",
"print_facilities",
"(",
"self",
",",
"facilities",
")",
":",
"for",
"facility",
"in",
"facilities",
":",
"print",
"(",
"'{} - ({}): {}'",
".",
"format",
"(",
"facility",
".",
"code",
",",
"facility",
".",
"name",
",",
"\",\"",
".",
"join",
"(",
"facility",
".",
"features",
")",
")",
")"
] | Print method for facilities. | [
"Print",
"method",
"for",
"facilities",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L117-L121 | train | 236,955 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.list_devices | def list_devices(self, project_id, conditions=None, params=None):
"""Retrieve list of devices in a project by one of more conditions.
"""
default_params = {'per_page': 1000}
if params:
default_params.update(params)
data = self.api('projects/%s/devices' % project_id, params=default_params)
devices = []
for device in self.filter(conditions, data['devices']):
devices.append(packet.Device(device, self.manager))
return devices | python | def list_devices(self, project_id, conditions=None, params=None):
"""Retrieve list of devices in a project by one of more conditions.
"""
default_params = {'per_page': 1000}
if params:
default_params.update(params)
data = self.api('projects/%s/devices' % project_id, params=default_params)
devices = []
for device in self.filter(conditions, data['devices']):
devices.append(packet.Device(device, self.manager))
return devices | [
"def",
"list_devices",
"(",
"self",
",",
"project_id",
",",
"conditions",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"default_params",
"=",
"{",
"'per_page'",
":",
"1000",
"}",
"if",
"params",
":",
"default_params",
".",
"update",
"(",
"params",
")",
"data",
"=",
"self",
".",
"api",
"(",
"'projects/%s/devices'",
"%",
"project_id",
",",
"params",
"=",
"default_params",
")",
"devices",
"=",
"[",
"]",
"for",
"device",
"in",
"self",
".",
"filter",
"(",
"conditions",
",",
"data",
"[",
"'devices'",
"]",
")",
":",
"devices",
".",
"append",
"(",
"packet",
".",
"Device",
"(",
"device",
",",
"self",
".",
"manager",
")",
")",
"return",
"devices"
] | Retrieve list of devices in a project by one of more conditions. | [
"Retrieve",
"list",
"of",
"devices",
"in",
"a",
"project",
"by",
"one",
"of",
"more",
"conditions",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L134-L144 | train | 236,956 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.print_devices | def print_devices(self, devices):
"""Print method for devices.
"""
for device in devices:
print('ID: {} OS: {} IP: {} State: {} ({}) Tags: {}'
.format(device.id,
device.operating_system.slug,
self.get_public_ip(device.ip_addresses),
device.state,
'spot' if device.spot_instance else 'on-demand',
device.tags)) | python | def print_devices(self, devices):
"""Print method for devices.
"""
for device in devices:
print('ID: {} OS: {} IP: {} State: {} ({}) Tags: {}'
.format(device.id,
device.operating_system.slug,
self.get_public_ip(device.ip_addresses),
device.state,
'spot' if device.spot_instance else 'on-demand',
device.tags)) | [
"def",
"print_devices",
"(",
"self",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"print",
"(",
"'ID: {} OS: {} IP: {} State: {} ({}) Tags: {}'",
".",
"format",
"(",
"device",
".",
"id",
",",
"device",
".",
"operating_system",
".",
"slug",
",",
"self",
".",
"get_public_ip",
"(",
"device",
".",
"ip_addresses",
")",
",",
"device",
".",
"state",
",",
"'spot'",
"if",
"device",
".",
"spot_instance",
"else",
"'on-demand'",
",",
"device",
".",
"tags",
")",
")"
] | Print method for devices. | [
"Print",
"method",
"for",
"devices",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L146-L156 | train | 236,957 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.filter | def filter(criterias, devices): # pylint: disable=too-many-branches
"""Filter a device by criterias on the root level of the dictionary.
"""
if not criterias:
return devices
result = []
for device in devices: # pylint: disable=too-many-nested-blocks
for criteria_name, criteria_values in criterias.items():
if criteria_name in device.keys():
if isinstance(device[criteria_name], list):
for criteria_value in criteria_values:
if criteria_value in device[criteria_name]:
result.append(device)
break
elif isinstance(device[criteria_name], str):
for criteria_value in criteria_values:
if criteria_value == device[criteria_name]:
result.append(device)
elif isinstance(device[criteria_name], int):
for criteria_value in criteria_values:
if criteria_value == device[criteria_name]:
result.append(device)
else:
continue
return result | python | def filter(criterias, devices): # pylint: disable=too-many-branches
"""Filter a device by criterias on the root level of the dictionary.
"""
if not criterias:
return devices
result = []
for device in devices: # pylint: disable=too-many-nested-blocks
for criteria_name, criteria_values in criterias.items():
if criteria_name in device.keys():
if isinstance(device[criteria_name], list):
for criteria_value in criteria_values:
if criteria_value in device[criteria_name]:
result.append(device)
break
elif isinstance(device[criteria_name], str):
for criteria_value in criteria_values:
if criteria_value == device[criteria_name]:
result.append(device)
elif isinstance(device[criteria_name], int):
for criteria_value in criteria_values:
if criteria_value == device[criteria_name]:
result.append(device)
else:
continue
return result | [
"def",
"filter",
"(",
"criterias",
",",
"devices",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"criterias",
":",
"return",
"devices",
"result",
"=",
"[",
"]",
"for",
"device",
"in",
"devices",
":",
"# pylint: disable=too-many-nested-blocks",
"for",
"criteria_name",
",",
"criteria_values",
"in",
"criterias",
".",
"items",
"(",
")",
":",
"if",
"criteria_name",
"in",
"device",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"device",
"[",
"criteria_name",
"]",
",",
"list",
")",
":",
"for",
"criteria_value",
"in",
"criteria_values",
":",
"if",
"criteria_value",
"in",
"device",
"[",
"criteria_name",
"]",
":",
"result",
".",
"append",
"(",
"device",
")",
"break",
"elif",
"isinstance",
"(",
"device",
"[",
"criteria_name",
"]",
",",
"str",
")",
":",
"for",
"criteria_value",
"in",
"criteria_values",
":",
"if",
"criteria_value",
"==",
"device",
"[",
"criteria_name",
"]",
":",
"result",
".",
"append",
"(",
"device",
")",
"elif",
"isinstance",
"(",
"device",
"[",
"criteria_name",
"]",
",",
"int",
")",
":",
"for",
"criteria_value",
"in",
"criteria_values",
":",
"if",
"criteria_value",
"==",
"device",
"[",
"criteria_name",
"]",
":",
"result",
".",
"append",
"(",
"device",
")",
"else",
":",
"continue",
"return",
"result"
] | Filter a device by criterias on the root level of the dictionary. | [
"Filter",
"a",
"device",
"by",
"criterias",
"on",
"the",
"root",
"level",
"of",
"the",
"dictionary",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L159-L183 | train | 236,958 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.get_public_ip | def get_public_ip(addresses, version=4):
"""Return either the devices public IPv4 or IPv6 address.
"""
for addr in addresses:
if addr['public'] and addr['address_family'] == version:
return addr.get('address')
return None | python | def get_public_ip(addresses, version=4):
"""Return either the devices public IPv4 or IPv6 address.
"""
for addr in addresses:
if addr['public'] and addr['address_family'] == version:
return addr.get('address')
return None | [
"def",
"get_public_ip",
"(",
"addresses",
",",
"version",
"=",
"4",
")",
":",
"for",
"addr",
"in",
"addresses",
":",
"if",
"addr",
"[",
"'public'",
"]",
"and",
"addr",
"[",
"'address_family'",
"]",
"==",
"version",
":",
"return",
"addr",
".",
"get",
"(",
"'address'",
")",
"return",
"None"
] | Return either the devices public IPv4 or IPv6 address. | [
"Return",
"either",
"the",
"devices",
"public",
"IPv4",
"or",
"IPv6",
"address",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L192-L198 | train | 236,959 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.validate_capacity | def validate_capacity(self, servers):
"""Validates if a deploy can be fulfilled.
"""
try:
return self.manager.validate_capacity(servers)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | python | def validate_capacity(self, servers):
"""Validates if a deploy can be fulfilled.
"""
try:
return self.manager.validate_capacity(servers)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | [
"def",
"validate_capacity",
"(",
"self",
",",
"servers",
")",
":",
"try",
":",
"return",
"self",
".",
"manager",
".",
"validate_capacity",
"(",
"servers",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
"as",
"msg",
":",
"raise",
"PacketManagerException",
"(",
"msg",
")"
] | Validates if a deploy can be fulfilled. | [
"Validates",
"if",
"a",
"deploy",
"can",
"be",
"fulfilled",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L200-L206 | train | 236,960 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.create_volume | def create_volume(self, project_id, plan, size, facility, label=""):
"""Creates a new volume.
"""
try:
return self.manager.create_volume(project_id, label, plan, size, facility)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | python | def create_volume(self, project_id, plan, size, facility, label=""):
"""Creates a new volume.
"""
try:
return self.manager.create_volume(project_id, label, plan, size, facility)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | [
"def",
"create_volume",
"(",
"self",
",",
"project_id",
",",
"plan",
",",
"size",
",",
"facility",
",",
"label",
"=",
"\"\"",
")",
":",
"try",
":",
"return",
"self",
".",
"manager",
".",
"create_volume",
"(",
"project_id",
",",
"label",
",",
"plan",
",",
"size",
",",
"facility",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
"as",
"msg",
":",
"raise",
"PacketManagerException",
"(",
"msg",
")"
] | Creates a new volume. | [
"Creates",
"a",
"new",
"volume",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L208-L214 | train | 236,961 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.attach_volume_to_device | def attach_volume_to_device(self, volume_id, device_id):
"""Attaches the created Volume to a Device.
"""
try:
volume = self.manager.get_volume(volume_id)
volume.attach(device_id)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
return volume | python | def attach_volume_to_device(self, volume_id, device_id):
"""Attaches the created Volume to a Device.
"""
try:
volume = self.manager.get_volume(volume_id)
volume.attach(device_id)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
return volume | [
"def",
"attach_volume_to_device",
"(",
"self",
",",
"volume_id",
",",
"device_id",
")",
":",
"try",
":",
"volume",
"=",
"self",
".",
"manager",
".",
"get_volume",
"(",
"volume_id",
")",
"volume",
".",
"attach",
"(",
"device_id",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
"as",
"msg",
":",
"raise",
"PacketManagerException",
"(",
"msg",
")",
"return",
"volume"
] | Attaches the created Volume to a Device. | [
"Attaches",
"the",
"created",
"Volume",
"to",
"a",
"Device",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L216-L224 | train | 236,962 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.create_demand | def create_demand(self,
project_id,
facility,
plan,
operating_system,
tags=None,
userdata='',
hostname=None,
count=1):
"""Create a new on demand device under the given project.
"""
tags = {} if tags is None else tags
hostname = self.get_random_hostname() if hostname is None else hostname
devices = []
for i in range(1, count + 1):
new_hostname = hostname if count == 1 else hostname + '-' + str(i)
self.logger.info('Adding to project %s: %s, %s, %s, %s, %r',
project_id,
new_hostname,
facility,
plan,
operating_system,
tags)
try:
device = self.manager.create_device(project_id=project_id,
hostname=new_hostname,
facility=facility,
plan=plan,
tags=tags,
userdata=userdata,
operating_system=operating_system)
devices.append(device)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
return devices | python | def create_demand(self,
project_id,
facility,
plan,
operating_system,
tags=None,
userdata='',
hostname=None,
count=1):
"""Create a new on demand device under the given project.
"""
tags = {} if tags is None else tags
hostname = self.get_random_hostname() if hostname is None else hostname
devices = []
for i in range(1, count + 1):
new_hostname = hostname if count == 1 else hostname + '-' + str(i)
self.logger.info('Adding to project %s: %s, %s, %s, %s, %r',
project_id,
new_hostname,
facility,
plan,
operating_system,
tags)
try:
device = self.manager.create_device(project_id=project_id,
hostname=new_hostname,
facility=facility,
plan=plan,
tags=tags,
userdata=userdata,
operating_system=operating_system)
devices.append(device)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
return devices | [
"def",
"create_demand",
"(",
"self",
",",
"project_id",
",",
"facility",
",",
"plan",
",",
"operating_system",
",",
"tags",
"=",
"None",
",",
"userdata",
"=",
"''",
",",
"hostname",
"=",
"None",
",",
"count",
"=",
"1",
")",
":",
"tags",
"=",
"{",
"}",
"if",
"tags",
"is",
"None",
"else",
"tags",
"hostname",
"=",
"self",
".",
"get_random_hostname",
"(",
")",
"if",
"hostname",
"is",
"None",
"else",
"hostname",
"devices",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"count",
"+",
"1",
")",
":",
"new_hostname",
"=",
"hostname",
"if",
"count",
"==",
"1",
"else",
"hostname",
"+",
"'-'",
"+",
"str",
"(",
"i",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Adding to project %s: %s, %s, %s, %s, %r'",
",",
"project_id",
",",
"new_hostname",
",",
"facility",
",",
"plan",
",",
"operating_system",
",",
"tags",
")",
"try",
":",
"device",
"=",
"self",
".",
"manager",
".",
"create_device",
"(",
"project_id",
"=",
"project_id",
",",
"hostname",
"=",
"new_hostname",
",",
"facility",
"=",
"facility",
",",
"plan",
"=",
"plan",
",",
"tags",
"=",
"tags",
",",
"userdata",
"=",
"userdata",
",",
"operating_system",
"=",
"operating_system",
")",
"devices",
".",
"append",
"(",
"device",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
"as",
"msg",
":",
"raise",
"PacketManagerException",
"(",
"msg",
")",
"return",
"devices"
] | Create a new on demand device under the given project. | [
"Create",
"a",
"new",
"on",
"demand",
"device",
"under",
"the",
"given",
"project",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L226-L260 | train | 236,963 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.stop | def stop(self, devices):
"""Power-Off one or more running devices.
"""
for device in devices:
self.logger.info('Stopping: %s', device.id)
try:
device.power_off()
except packet.baseapi.Error:
raise PacketManagerException('Unable to stop instance "{}"'.format(device.id)) | python | def stop(self, devices):
"""Power-Off one or more running devices.
"""
for device in devices:
self.logger.info('Stopping: %s', device.id)
try:
device.power_off()
except packet.baseapi.Error:
raise PacketManagerException('Unable to stop instance "{}"'.format(device.id)) | [
"def",
"stop",
"(",
"self",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Stopping: %s'",
",",
"device",
".",
"id",
")",
"try",
":",
"device",
".",
"power_off",
"(",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
":",
"raise",
"PacketManagerException",
"(",
"'Unable to stop instance \"{}\"'",
".",
"format",
"(",
"device",
".",
"id",
")",
")"
] | Power-Off one or more running devices. | [
"Power",
"-",
"Off",
"one",
"or",
"more",
"running",
"devices",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L302-L310 | train | 236,964 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.reboot | def reboot(self, devices):
"""Reboot one or more devices.
"""
for device in devices:
self.logger.info('Rebooting: %s', device.id)
try:
device.reboot()
except packet.baseapi.Error:
raise PacketManagerException('Unable to reboot instance "{}"'.format(device.id)) | python | def reboot(self, devices):
"""Reboot one or more devices.
"""
for device in devices:
self.logger.info('Rebooting: %s', device.id)
try:
device.reboot()
except packet.baseapi.Error:
raise PacketManagerException('Unable to reboot instance "{}"'.format(device.id)) | [
"def",
"reboot",
"(",
"self",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Rebooting: %s'",
",",
"device",
".",
"id",
")",
"try",
":",
"device",
".",
"reboot",
"(",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
":",
"raise",
"PacketManagerException",
"(",
"'Unable to reboot instance \"{}\"'",
".",
"format",
"(",
"device",
".",
"id",
")",
")"
] | Reboot one or more devices. | [
"Reboot",
"one",
"or",
"more",
"devices",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L312-L320 | train | 236,965 |
MozillaSecurity/laniakea | laniakea/core/providers/packet/manager.py | PacketManager.terminate | def terminate(self, devices):
"""Terminate one or more running or stopped instances.
"""
for device in devices:
self.logger.info('Terminating: %s', device.id)
try:
device.delete()
except packet.baseapi.Error:
raise PacketManagerException('Unable to terminate instance "{}"'.format(device.id)) | python | def terminate(self, devices):
"""Terminate one or more running or stopped instances.
"""
for device in devices:
self.logger.info('Terminating: %s', device.id)
try:
device.delete()
except packet.baseapi.Error:
raise PacketManagerException('Unable to terminate instance "{}"'.format(device.id)) | [
"def",
"terminate",
"(",
"self",
",",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Terminating: %s'",
",",
"device",
".",
"id",
")",
"try",
":",
"device",
".",
"delete",
"(",
")",
"except",
"packet",
".",
"baseapi",
".",
"Error",
":",
"raise",
"PacketManagerException",
"(",
"'Unable to terminate instance \"{}\"'",
".",
"format",
"(",
"device",
".",
"id",
")",
")"
] | Terminate one or more running or stopped instances. | [
"Terminate",
"one",
"or",
"more",
"running",
"or",
"stopped",
"instances",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L322-L330 | train | 236,966 |
MozillaSecurity/laniakea | laniakea/__init__.py | LaniakeaCommandLine.parse_args | def parse_args(cls):
"""Main argument parser of Laniakea.
"""
# Initialize configuration and userdata directories.
dirs = appdirs.AppDirs(__title__, 'Mozilla Security')
if not os.path.isdir(dirs.user_config_dir):
shutil.copytree(os.path.join(cls.HOME, 'examples'), dirs.user_config_dir)
shutil.copytree(os.path.join(cls.HOME, 'userdata'), os.path.join(dirs.user_config_dir, 'userdata'))
parser = argparse.ArgumentParser(
description='Laniakea Runtime v{}'.format(cls.VERSION),
prog=__title__,
add_help=False,
formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120),
epilog='The exit status is 0 for non-failures and 1 for failures.')
subparsers = parser.add_subparsers(dest='provider',
description='Use -h to see the help menu of each provider.',
title='Laniakea Cloud Providers',
metavar='')
modules = ModuleLoader()
modules.load(cls.HOME, 'core/providers', 'laniakea')
for name, module in modules.modules.items():
globals()[name] = module
for module, cli in modules.command_line_interfaces():
getattr(module, cli).add_arguments(subparsers, dirs)
base = parser.add_argument_group('Laniakea Base Parameters')
base.add_argument('-verbosity',
default=2,
type=int,
choices=list(range(1, 6, 1)),
help='Log sensitivity.')
base.add_argument('-focus',
action='store_true',
default=True,
help=argparse.SUPPRESS)
base.add_argument('-settings',
metavar='path',
type=argparse.FileType(),
default=os.path.join(dirs.user_config_dir, 'laniakea.json'),
help='Laniakea core settings.')
base.add_argument('-h', '-help', '--help',
action='help',
help=argparse.SUPPRESS)
base.add_argument('-version',
action='version',
version='%(prog)s {}'.format(cls.VERSION),
help=argparse.SUPPRESS)
userdata = parser.add_argument_group('UserData Parameters')
userdata.add_argument('-userdata',
metavar='path',
type=argparse.FileType(),
help='UserData script for the provisioning process.')
userdata.add_argument('-list-userdata-macros',
action='store_true',
help='List available macros.')
userdata.add_argument('-print-userdata',
action='store_true',
help='Print the UserData script to stdout.')
userdata.add_argument('-userdata-macros',
metavar='k=v',
nargs='+',
type=str,
help='Custom macros for the UserData.')
return parser.parse_args() | python | def parse_args(cls):
"""Main argument parser of Laniakea.
"""
# Initialize configuration and userdata directories.
dirs = appdirs.AppDirs(__title__, 'Mozilla Security')
if not os.path.isdir(dirs.user_config_dir):
shutil.copytree(os.path.join(cls.HOME, 'examples'), dirs.user_config_dir)
shutil.copytree(os.path.join(cls.HOME, 'userdata'), os.path.join(dirs.user_config_dir, 'userdata'))
parser = argparse.ArgumentParser(
description='Laniakea Runtime v{}'.format(cls.VERSION),
prog=__title__,
add_help=False,
formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120),
epilog='The exit status is 0 for non-failures and 1 for failures.')
subparsers = parser.add_subparsers(dest='provider',
description='Use -h to see the help menu of each provider.',
title='Laniakea Cloud Providers',
metavar='')
modules = ModuleLoader()
modules.load(cls.HOME, 'core/providers', 'laniakea')
for name, module in modules.modules.items():
globals()[name] = module
for module, cli in modules.command_line_interfaces():
getattr(module, cli).add_arguments(subparsers, dirs)
base = parser.add_argument_group('Laniakea Base Parameters')
base.add_argument('-verbosity',
default=2,
type=int,
choices=list(range(1, 6, 1)),
help='Log sensitivity.')
base.add_argument('-focus',
action='store_true',
default=True,
help=argparse.SUPPRESS)
base.add_argument('-settings',
metavar='path',
type=argparse.FileType(),
default=os.path.join(dirs.user_config_dir, 'laniakea.json'),
help='Laniakea core settings.')
base.add_argument('-h', '-help', '--help',
action='help',
help=argparse.SUPPRESS)
base.add_argument('-version',
action='version',
version='%(prog)s {}'.format(cls.VERSION),
help=argparse.SUPPRESS)
userdata = parser.add_argument_group('UserData Parameters')
userdata.add_argument('-userdata',
metavar='path',
type=argparse.FileType(),
help='UserData script for the provisioning process.')
userdata.add_argument('-list-userdata-macros',
action='store_true',
help='List available macros.')
userdata.add_argument('-print-userdata',
action='store_true',
help='Print the UserData script to stdout.')
userdata.add_argument('-userdata-macros',
metavar='k=v',
nargs='+',
type=str,
help='Custom macros for the UserData.')
return parser.parse_args() | [
"def",
"parse_args",
"(",
"cls",
")",
":",
"# Initialize configuration and userdata directories.",
"dirs",
"=",
"appdirs",
".",
"AppDirs",
"(",
"__title__",
",",
"'Mozilla Security'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dirs",
".",
"user_config_dir",
")",
":",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"HOME",
",",
"'examples'",
")",
",",
"dirs",
".",
"user_config_dir",
")",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"HOME",
",",
"'userdata'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
".",
"user_config_dir",
",",
"'userdata'",
")",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Laniakea Runtime v{}'",
".",
"format",
"(",
"cls",
".",
"VERSION",
")",
",",
"prog",
"=",
"__title__",
",",
"add_help",
"=",
"False",
",",
"formatter_class",
"=",
"lambda",
"prog",
":",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
"(",
"prog",
",",
"max_help_position",
"=",
"40",
",",
"width",
"=",
"120",
")",
",",
"epilog",
"=",
"'The exit status is 0 for non-failures and 1 for failures.'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"dest",
"=",
"'provider'",
",",
"description",
"=",
"'Use -h to see the help menu of each provider.'",
",",
"title",
"=",
"'Laniakea Cloud Providers'",
",",
"metavar",
"=",
"''",
")",
"modules",
"=",
"ModuleLoader",
"(",
")",
"modules",
".",
"load",
"(",
"cls",
".",
"HOME",
",",
"'core/providers'",
",",
"'laniakea'",
")",
"for",
"name",
",",
"module",
"in",
"modules",
".",
"modules",
".",
"items",
"(",
")",
":",
"globals",
"(",
")",
"[",
"name",
"]",
"=",
"module",
"for",
"module",
",",
"cli",
"in",
"modules",
".",
"command_line_interfaces",
"(",
")",
":",
"getattr",
"(",
"module",
",",
"cli",
")",
".",
"add_arguments",
"(",
"subparsers",
",",
"dirs",
")",
"base",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Laniakea Base Parameters'",
")",
"base",
".",
"add_argument",
"(",
"'-verbosity'",
",",
"default",
"=",
"2",
",",
"type",
"=",
"int",
",",
"choices",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"6",
",",
"1",
")",
")",
",",
"help",
"=",
"'Log sensitivity.'",
")",
"base",
".",
"add_argument",
"(",
"'-focus'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"True",
",",
"help",
"=",
"argparse",
".",
"SUPPRESS",
")",
"base",
".",
"add_argument",
"(",
"'-settings'",
",",
"metavar",
"=",
"'path'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
")",
",",
"default",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
".",
"user_config_dir",
",",
"'laniakea.json'",
")",
",",
"help",
"=",
"'Laniakea core settings.'",
")",
"base",
".",
"add_argument",
"(",
"'-h'",
",",
"'-help'",
",",
"'--help'",
",",
"action",
"=",
"'help'",
",",
"help",
"=",
"argparse",
".",
"SUPPRESS",
")",
"base",
".",
"add_argument",
"(",
"'-version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s {}'",
".",
"format",
"(",
"cls",
".",
"VERSION",
")",
",",
"help",
"=",
"argparse",
".",
"SUPPRESS",
")",
"userdata",
"=",
"parser",
".",
"add_argument_group",
"(",
"'UserData Parameters'",
")",
"userdata",
".",
"add_argument",
"(",
"'-userdata'",
",",
"metavar",
"=",
"'path'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
")",
",",
"help",
"=",
"'UserData script for the provisioning process.'",
")",
"userdata",
".",
"add_argument",
"(",
"'-list-userdata-macros'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'List available macros.'",
")",
"userdata",
".",
"add_argument",
"(",
"'-print-userdata'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Print the UserData script to stdout.'",
")",
"userdata",
".",
"add_argument",
"(",
"'-userdata-macros'",
",",
"metavar",
"=",
"'k=v'",
",",
"nargs",
"=",
"'+'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'Custom macros for the UserData.'",
")",
"return",
"parser",
".",
"parse_args",
"(",
")"
] | Main argument parser of Laniakea. | [
"Main",
"argument",
"parser",
"of",
"Laniakea",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/__init__.py#L31-L108 | train | 236,967 |
MozillaSecurity/laniakea | laniakea/__init__.py | LaniakeaCommandLine.main | def main(cls):
"""Main entry point of Laniakea.
"""
args = cls.parse_args()
if args.focus:
Focus.init()
else:
Focus.disable()
logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s',
level=args.verbosity * 10,
datefmt='%Y-%m-%d %H:%M:%S')
# Laniakea base configuration
logger.info('Loading Laniakea configuration from %s', Focus.data(args.settings.name))
try:
settings = json.loads(args.settings.read())
except ValueError as msg:
logger.error('Unable to parse %s: %s', args.settings.name, msg)
return 1
# UserData
userdata = ''
if args.userdata:
logger.info('Reading user data script content from %s', Focus.info(args.userdata.name))
try:
userdata = UserData.handle_import_tags(args.userdata.read(),
os.path.dirname(args.userdata.name))
except UserDataException as msg:
logging.error(msg)
return 1
if args.list_userdata_macros:
UserData.list_tags(userdata)
return 0
if args.userdata_macros:
args.userdata_macros = UserData.convert_pair_to_dict(args.userdata_macros or '')
userdata = UserData.handle_tags(userdata, args.userdata_macros)
if args.print_userdata:
logger.info('Combined UserData script:\n%s', userdata)
return 0
if args.provider:
provider = getattr(globals()[args.provider], args.provider.title() + 'CommandLine')
provider().main(args, settings, userdata)
return 0 | python | def main(cls):
"""Main entry point of Laniakea.
"""
args = cls.parse_args()
if args.focus:
Focus.init()
else:
Focus.disable()
logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s',
level=args.verbosity * 10,
datefmt='%Y-%m-%d %H:%M:%S')
# Laniakea base configuration
logger.info('Loading Laniakea configuration from %s', Focus.data(args.settings.name))
try:
settings = json.loads(args.settings.read())
except ValueError as msg:
logger.error('Unable to parse %s: %s', args.settings.name, msg)
return 1
# UserData
userdata = ''
if args.userdata:
logger.info('Reading user data script content from %s', Focus.info(args.userdata.name))
try:
userdata = UserData.handle_import_tags(args.userdata.read(),
os.path.dirname(args.userdata.name))
except UserDataException as msg:
logging.error(msg)
return 1
if args.list_userdata_macros:
UserData.list_tags(userdata)
return 0
if args.userdata_macros:
args.userdata_macros = UserData.convert_pair_to_dict(args.userdata_macros or '')
userdata = UserData.handle_tags(userdata, args.userdata_macros)
if args.print_userdata:
logger.info('Combined UserData script:\n%s', userdata)
return 0
if args.provider:
provider = getattr(globals()[args.provider], args.provider.title() + 'CommandLine')
provider().main(args, settings, userdata)
return 0 | [
"def",
"main",
"(",
"cls",
")",
":",
"args",
"=",
"cls",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"focus",
":",
"Focus",
".",
"init",
"(",
")",
"else",
":",
"Focus",
".",
"disable",
"(",
")",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'[Laniakea] %(asctime)s %(levelname)s: %(message)s'",
",",
"level",
"=",
"args",
".",
"verbosity",
"*",
"10",
",",
"datefmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
"# Laniakea base configuration",
"logger",
".",
"info",
"(",
"'Loading Laniakea configuration from %s'",
",",
"Focus",
".",
"data",
"(",
"args",
".",
"settings",
".",
"name",
")",
")",
"try",
":",
"settings",
"=",
"json",
".",
"loads",
"(",
"args",
".",
"settings",
".",
"read",
"(",
")",
")",
"except",
"ValueError",
"as",
"msg",
":",
"logger",
".",
"error",
"(",
"'Unable to parse %s: %s'",
",",
"args",
".",
"settings",
".",
"name",
",",
"msg",
")",
"return",
"1",
"# UserData",
"userdata",
"=",
"''",
"if",
"args",
".",
"userdata",
":",
"logger",
".",
"info",
"(",
"'Reading user data script content from %s'",
",",
"Focus",
".",
"info",
"(",
"args",
".",
"userdata",
".",
"name",
")",
")",
"try",
":",
"userdata",
"=",
"UserData",
".",
"handle_import_tags",
"(",
"args",
".",
"userdata",
".",
"read",
"(",
")",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"args",
".",
"userdata",
".",
"name",
")",
")",
"except",
"UserDataException",
"as",
"msg",
":",
"logging",
".",
"error",
"(",
"msg",
")",
"return",
"1",
"if",
"args",
".",
"list_userdata_macros",
":",
"UserData",
".",
"list_tags",
"(",
"userdata",
")",
"return",
"0",
"if",
"args",
".",
"userdata_macros",
":",
"args",
".",
"userdata_macros",
"=",
"UserData",
".",
"convert_pair_to_dict",
"(",
"args",
".",
"userdata_macros",
"or",
"''",
")",
"userdata",
"=",
"UserData",
".",
"handle_tags",
"(",
"userdata",
",",
"args",
".",
"userdata_macros",
")",
"if",
"args",
".",
"print_userdata",
":",
"logger",
".",
"info",
"(",
"'Combined UserData script:\\n%s'",
",",
"userdata",
")",
"return",
"0",
"if",
"args",
".",
"provider",
":",
"provider",
"=",
"getattr",
"(",
"globals",
"(",
")",
"[",
"args",
".",
"provider",
"]",
",",
"args",
".",
"provider",
".",
"title",
"(",
")",
"+",
"'CommandLine'",
")",
"provider",
"(",
")",
".",
"main",
"(",
"args",
",",
"settings",
",",
"userdata",
")",
"return",
"0"
] | Main entry point of Laniakea. | [
"Main",
"entry",
"point",
"of",
"Laniakea",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/__init__.py#L111-L161 | train | 236,968 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | Filter.tags | def tags(self, tags=None):
"""Filter by tags.
:param tags: Tags to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if tags is None or not tags:
return self
nodes = []
for node in self.nodes:
if any(tag in node.extra['tags'] for tag in tags):
nodes.append(node)
self.nodes = nodes
return self | python | def tags(self, tags=None):
"""Filter by tags.
:param tags: Tags to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if tags is None or not tags:
return self
nodes = []
for node in self.nodes:
if any(tag in node.extra['tags'] for tag in tags):
nodes.append(node)
self.nodes = nodes
return self | [
"def",
"tags",
"(",
"self",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
"or",
"not",
"tags",
":",
"return",
"self",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"any",
"(",
"tag",
"in",
"node",
".",
"extra",
"[",
"'tags'",
"]",
"for",
"tag",
"in",
"tags",
")",
":",
"nodes",
".",
"append",
"(",
"node",
")",
"self",
".",
"nodes",
"=",
"nodes",
"return",
"self"
] | Filter by tags.
:param tags: Tags to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node` | [
"Filter",
"by",
"tags",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L31-L47 | train | 236,969 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | Filter.state | def state(self, states=None):
"""Filter by state.
:param tags: States to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if states is None or not states:
return self
nodes = []
for node in self.nodes:
if any(state.lower() == node.state.lower() for state in states):
nodes.append(node)
self.nodes = nodes
return self | python | def state(self, states=None):
"""Filter by state.
:param tags: States to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if states is None or not states:
return self
nodes = []
for node in self.nodes:
if any(state.lower() == node.state.lower() for state in states):
nodes.append(node)
self.nodes = nodes
return self | [
"def",
"state",
"(",
"self",
",",
"states",
"=",
"None",
")",
":",
"if",
"states",
"is",
"None",
"or",
"not",
"states",
":",
"return",
"self",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"any",
"(",
"state",
".",
"lower",
"(",
")",
"==",
"node",
".",
"state",
".",
"lower",
"(",
")",
"for",
"state",
"in",
"states",
")",
":",
"nodes",
".",
"append",
"(",
"node",
")",
"self",
".",
"nodes",
"=",
"nodes",
"return",
"self"
] | Filter by state.
:param tags: States to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node` | [
"Filter",
"by",
"state",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L49-L65 | train | 236,970 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | Filter.name | def name(self, names=None):
"""Filter by node name.
:param names: Node names to filter.
:type names: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if names is None or not names:
return self
nodes = []
for node in self.nodes:
if any(name == node.name for name in names):
nodes.append(node)
self.nodes = nodes
return self | python | def name(self, names=None):
"""Filter by node name.
:param names: Node names to filter.
:type names: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if names is None or not names:
return self
nodes = []
for node in self.nodes:
if any(name == node.name for name in names):
nodes.append(node)
self.nodes = nodes
return self | [
"def",
"name",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
"or",
"not",
"names",
":",
"return",
"self",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"any",
"(",
"name",
"==",
"node",
".",
"name",
"for",
"name",
"in",
"names",
")",
":",
"nodes",
".",
"append",
"(",
"node",
")",
"self",
".",
"nodes",
"=",
"nodes",
"return",
"self"
] | Filter by node name.
:param names: Node names to filter.
:type names: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node` | [
"Filter",
"by",
"node",
"name",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L67-L83 | train | 236,971 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | Filter.is_preemptible | def is_preemptible(self):
"""Filter by preemptible scheduling.
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
nodes = []
for node in self.nodes:
if Kurz.is_preemtible(node):
nodes.append(node)
return self | python | def is_preemptible(self):
"""Filter by preemptible scheduling.
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
nodes = []
for node in self.nodes:
if Kurz.is_preemtible(node):
nodes.append(node)
return self | [
"def",
"is_preemptible",
"(",
"self",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"Kurz",
".",
"is_preemtible",
"(",
"node",
")",
":",
"nodes",
".",
"append",
"(",
"node",
")",
"return",
"self"
] | Filter by preemptible scheduling.
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node` | [
"Filter",
"by",
"preemptible",
"scheduling",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L85-L95 | train | 236,972 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | Filter.expr | def expr(self, callback):
"""Filter by custom expression.
:param callback: Callback for custom expression.
:type name: ``function``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
nodes = []
for node in self.nodes:
if callback(node):
nodes.append(node)
self.nodes = nodes
return self | python | def expr(self, callback):
"""Filter by custom expression.
:param callback: Callback for custom expression.
:type name: ``function``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
nodes = []
for node in self.nodes:
if callback(node):
nodes.append(node)
self.nodes = nodes
return self | [
"def",
"expr",
"(",
"self",
",",
"callback",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"callback",
"(",
"node",
")",
":",
"nodes",
".",
"append",
"(",
"node",
")",
"self",
".",
"nodes",
"=",
"nodes",
"return",
"self"
] | Filter by custom expression.
:param callback: Callback for custom expression.
:type name: ``function``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node` | [
"Filter",
"by",
"custom",
"expression",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L97-L111 | train | 236,973 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.connect | def connect(self, **kwargs):
"""Connect to Google Compute Engine.
"""
try:
self.gce = get_driver(Provider.GCE)(
self.user_id,
self.key,
project=self.project,
**kwargs)
except:
raise ComputeEngineManagerException("Unable to connect to Google Compute Engine.") | python | def connect(self, **kwargs):
"""Connect to Google Compute Engine.
"""
try:
self.gce = get_driver(Provider.GCE)(
self.user_id,
self.key,
project=self.project,
**kwargs)
except:
raise ComputeEngineManagerException("Unable to connect to Google Compute Engine.") | [
"def",
"connect",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"gce",
"=",
"get_driver",
"(",
"Provider",
".",
"GCE",
")",
"(",
"self",
".",
"user_id",
",",
"self",
".",
"key",
",",
"project",
"=",
"self",
".",
"project",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"raise",
"ComputeEngineManagerException",
"(",
"\"Unable to connect to Google Compute Engine.\"",
")"
] | Connect to Google Compute Engine. | [
"Connect",
"to",
"Google",
"Compute",
"Engine",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L160-L170 | train | 236,974 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.is_connected | def is_connected(self, attempts=3):
"""Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int``
"""
if self.gce is None:
while attempts > 0:
self.logger.info("Attempting to connect ...")
try:
self.connect()
except ComputeEngineManagerException:
attempts -= 1
continue
self.logger.info("Connection established.")
return True
self.logger.error("Unable to connect to Google Compute Engine.")
return False
return True | python | def is_connected(self, attempts=3):
"""Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int``
"""
if self.gce is None:
while attempts > 0:
self.logger.info("Attempting to connect ...")
try:
self.connect()
except ComputeEngineManagerException:
attempts -= 1
continue
self.logger.info("Connection established.")
return True
self.logger.error("Unable to connect to Google Compute Engine.")
return False
return True | [
"def",
"is_connected",
"(",
"self",
",",
"attempts",
"=",
"3",
")",
":",
"if",
"self",
".",
"gce",
"is",
"None",
":",
"while",
"attempts",
">",
"0",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Attempting to connect ...\"",
")",
"try",
":",
"self",
".",
"connect",
"(",
")",
"except",
"ComputeEngineManagerException",
":",
"attempts",
"-=",
"1",
"continue",
"self",
".",
"logger",
".",
"info",
"(",
"\"Connection established.\"",
")",
"return",
"True",
"self",
".",
"logger",
".",
"error",
"(",
"\"Unable to connect to Google Compute Engine.\"",
")",
"return",
"False",
"return",
"True"
] | Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int`` | [
"Try",
"to",
"reconnect",
"if",
"neccessary",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L172-L191 | train | 236,975 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.create | def create(self, size, number, meta, name=None, image=None, attempts=3):
"""Create container VM nodes. Uses a container declaration which is undocumented.
:param size: The machine type to use.
:type size: ``str`` or :class:`GCENodeSize`
:param number: Amount of nodes to be spawned.
:type number: ``int``
:param meta: Metadata dictionary for the nodes.
:type meta: ``dict`` or ``None``
:param name: The name of the node to create.
:type name: ``str``
:param image: The image used to create the disk - optional for multiple nodes.
:type image: ``str`` or :class:`GCENodeImage` or ``None``
:param attempts: The amount of tries to perform in case nodes fail to create.
:type attempts: ``int``
:return: A list of newly created Node objects for the new nodes.
:rtype: ``list`` of :class:`Node`
"""
if name is None:
name = Common.get_random_hostname()
if image is None and number == 1:
raise ComputeEngineManagerException("Base image not provided.")
successful = 0
nodes = []
while number - successful > 0 and attempts > 0:
if number == 1:
# Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node.
nodes = [self.gce.create_node(name, size, image, **meta)]
else:
nodes = self.gce.ex_create_multiple_nodes(name, size, None, number - successful,
ignore_errors=False,
poll_interval=1,
**meta)
for node in nodes:
if isinstance(node, GCEFailedNode):
self.logger.error("Node failed to create, code %s error: %s", node.code, node.error)
continue
successful += 1
self.nodes.append(node)
attempts -= 1
if number != successful:
self.logger.error("We tried but %d nodes failed to create.", number - successful)
return nodes | python | def create(self, size, number, meta, name=None, image=None, attempts=3):
"""Create container VM nodes. Uses a container declaration which is undocumented.
:param size: The machine type to use.
:type size: ``str`` or :class:`GCENodeSize`
:param number: Amount of nodes to be spawned.
:type number: ``int``
:param meta: Metadata dictionary for the nodes.
:type meta: ``dict`` or ``None``
:param name: The name of the node to create.
:type name: ``str``
:param image: The image used to create the disk - optional for multiple nodes.
:type image: ``str`` or :class:`GCENodeImage` or ``None``
:param attempts: The amount of tries to perform in case nodes fail to create.
:type attempts: ``int``
:return: A list of newly created Node objects for the new nodes.
:rtype: ``list`` of :class:`Node`
"""
if name is None:
name = Common.get_random_hostname()
if image is None and number == 1:
raise ComputeEngineManagerException("Base image not provided.")
successful = 0
nodes = []
while number - successful > 0 and attempts > 0:
if number == 1:
# Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node.
nodes = [self.gce.create_node(name, size, image, **meta)]
else:
nodes = self.gce.ex_create_multiple_nodes(name, size, None, number - successful,
ignore_errors=False,
poll_interval=1,
**meta)
for node in nodes:
if isinstance(node, GCEFailedNode):
self.logger.error("Node failed to create, code %s error: %s", node.code, node.error)
continue
successful += 1
self.nodes.append(node)
attempts -= 1
if number != successful:
self.logger.error("We tried but %d nodes failed to create.", number - successful)
return nodes | [
"def",
"create",
"(",
"self",
",",
"size",
",",
"number",
",",
"meta",
",",
"name",
"=",
"None",
",",
"image",
"=",
"None",
",",
"attempts",
"=",
"3",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"Common",
".",
"get_random_hostname",
"(",
")",
"if",
"image",
"is",
"None",
"and",
"number",
"==",
"1",
":",
"raise",
"ComputeEngineManagerException",
"(",
"\"Base image not provided.\"",
")",
"successful",
"=",
"0",
"nodes",
"=",
"[",
"]",
"while",
"number",
"-",
"successful",
">",
"0",
"and",
"attempts",
">",
"0",
":",
"if",
"number",
"==",
"1",
":",
"# Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node.",
"nodes",
"=",
"[",
"self",
".",
"gce",
".",
"create_node",
"(",
"name",
",",
"size",
",",
"image",
",",
"*",
"*",
"meta",
")",
"]",
"else",
":",
"nodes",
"=",
"self",
".",
"gce",
".",
"ex_create_multiple_nodes",
"(",
"name",
",",
"size",
",",
"None",
",",
"number",
"-",
"successful",
",",
"ignore_errors",
"=",
"False",
",",
"poll_interval",
"=",
"1",
",",
"*",
"*",
"meta",
")",
"for",
"node",
"in",
"nodes",
":",
"if",
"isinstance",
"(",
"node",
",",
"GCEFailedNode",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Node failed to create, code %s error: %s\"",
",",
"node",
".",
"code",
",",
"node",
".",
"error",
")",
"continue",
"successful",
"+=",
"1",
"self",
".",
"nodes",
".",
"append",
"(",
"node",
")",
"attempts",
"-=",
"1",
"if",
"number",
"!=",
"successful",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"We tried but %d nodes failed to create.\"",
",",
"number",
"-",
"successful",
")",
"return",
"nodes"
] | Create container VM nodes. Uses a container declaration which is undocumented.
:param size: The machine type to use.
:type size: ``str`` or :class:`GCENodeSize`
:param number: Amount of nodes to be spawned.
:type number: ``int``
:param meta: Metadata dictionary for the nodes.
:type meta: ``dict`` or ``None``
:param name: The name of the node to create.
:type name: ``str``
:param image: The image used to create the disk - optional for multiple nodes.
:type image: ``str`` or :class:`GCENodeImage` or ``None``
:param attempts: The amount of tries to perform in case nodes fail to create.
:type attempts: ``int``
:return: A list of newly created Node objects for the new nodes.
:rtype: ``list`` of :class:`Node` | [
"Create",
"container",
"VM",
"nodes",
".",
"Uses",
"a",
"container",
"declaration",
"which",
"is",
"undocumented",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L193-L247 | train | 236,976 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.stop | def stop(self, nodes=None):
"""Stop one or many nodes.
:param nodes: Nodes to be stopped.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'stopped':
logging.warning('Node %s is already "stopped".', node.name)
continue
try:
status = self.gce.ex_stop_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | python | def stop(self, nodes=None):
"""Stop one or many nodes.
:param nodes: Nodes to be stopped.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'stopped':
logging.warning('Node %s is already "stopped".', node.name)
continue
try:
status = self.gce.ex_stop_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | [
"def",
"stop",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"result",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
".",
"state",
"==",
"'stopped'",
":",
"logging",
".",
"warning",
"(",
"'Node %s is already \"stopped\".'",
",",
"node",
".",
"name",
")",
"continue",
"try",
":",
"status",
"=",
"self",
".",
"gce",
".",
"ex_stop_node",
"(",
"node",
")",
"if",
"status",
":",
"result",
".",
"append",
"(",
"node",
")",
"except",
"InvalidRequestError",
"as",
"err",
":",
"raise",
"ComputeEngineManagerException",
"(",
"err",
")",
"return",
"result"
] | Stop one or many nodes.
:param nodes: Nodes to be stopped.
:type nodes: ``list`` | [
"Stop",
"one",
"or",
"many",
"nodes",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L249-L272 | train | 236,977 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.start | def start(self, nodes=None):
"""Start one or many nodes.
:param nodes: Nodes to be started.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'running':
logging.warning('Node %s is already "running".', node.name)
continue
try:
status = self.gce.ex_start_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | python | def start(self, nodes=None):
"""Start one or many nodes.
:param nodes: Nodes to be started.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'running':
logging.warning('Node %s is already "running".', node.name)
continue
try:
status = self.gce.ex_start_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | [
"def",
"start",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"result",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
".",
"state",
"==",
"'running'",
":",
"logging",
".",
"warning",
"(",
"'Node %s is already \"running\".'",
",",
"node",
".",
"name",
")",
"continue",
"try",
":",
"status",
"=",
"self",
".",
"gce",
".",
"ex_start_node",
"(",
"node",
")",
"if",
"status",
":",
"result",
".",
"append",
"(",
"node",
")",
"except",
"InvalidRequestError",
"as",
"err",
":",
"raise",
"ComputeEngineManagerException",
"(",
"err",
")",
"return",
"result"
] | Start one or many nodes.
:param nodes: Nodes to be started.
:type nodes: ``list`` | [
"Start",
"one",
"or",
"many",
"nodes",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L274-L297 | train | 236,978 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.reboot | def reboot(self, nodes=None):
"""Reboot one or many nodes.
:param nodes: Nodes to be rebooted.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'stopped':
logging.warning('Node %s is "stopped" and can not be rebooted.', node.name)
continue
try:
status = self.gce.reboot_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | python | def reboot(self, nodes=None):
"""Reboot one or many nodes.
:param nodes: Nodes to be rebooted.
:type nodes: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
result = []
for node in nodes:
if node.state == 'stopped':
logging.warning('Node %s is "stopped" and can not be rebooted.', node.name)
continue
try:
status = self.gce.reboot_node(node)
if status:
result.append(node)
except InvalidRequestError as err:
raise ComputeEngineManagerException(err)
return result | [
"def",
"reboot",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"result",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
".",
"state",
"==",
"'stopped'",
":",
"logging",
".",
"warning",
"(",
"'Node %s is \"stopped\" and can not be rebooted.'",
",",
"node",
".",
"name",
")",
"continue",
"try",
":",
"status",
"=",
"self",
".",
"gce",
".",
"reboot_node",
"(",
"node",
")",
"if",
"status",
":",
"result",
".",
"append",
"(",
"node",
")",
"except",
"InvalidRequestError",
"as",
"err",
":",
"raise",
"ComputeEngineManagerException",
"(",
"err",
")",
"return",
"result"
] | Reboot one or many nodes.
:param nodes: Nodes to be rebooted.
:type nodes: ``list`` | [
"Reboot",
"one",
"or",
"many",
"nodes",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L299-L322 | train | 236,979 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.terminate | def terminate(self, nodes=None):
"""Destroy one or many nodes.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
failed_kill = []
result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False)
# Verify whether all instances have been terminated.
for i, success in enumerate(result):
if success:
logging.info('Successfully destroyed: %s', nodes[i].name)
else:
logging.error('Failed to destroy: %s', nodes[i].name)
failed_kill.append(nodes[i])
return failed_kill | python | def terminate(self, nodes=None):
"""Destroy one or many nodes.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
failed_kill = []
result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False)
# Verify whether all instances have been terminated.
for i, success in enumerate(result):
if success:
logging.info('Successfully destroyed: %s', nodes[i].name)
else:
logging.error('Failed to destroy: %s', nodes[i].name)
failed_kill.append(nodes[i])
return failed_kill | [
"def",
"terminate",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"failed_kill",
"=",
"[",
"]",
"result",
"=",
"self",
".",
"gce",
".",
"ex_destroy_multiple_nodes",
"(",
"nodes",
",",
"poll_interval",
"=",
"1",
",",
"ignore_errors",
"=",
"False",
")",
"# Verify whether all instances have been terminated.",
"for",
"i",
",",
"success",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"success",
":",
"logging",
".",
"info",
"(",
"'Successfully destroyed: %s'",
",",
"nodes",
"[",
"i",
"]",
".",
"name",
")",
"else",
":",
"logging",
".",
"error",
"(",
"'Failed to destroy: %s'",
",",
"nodes",
"[",
"i",
"]",
".",
"name",
")",
"failed_kill",
".",
"append",
"(",
"nodes",
"[",
"i",
"]",
")",
"return",
"failed_kill"
] | Destroy one or many nodes.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list`` | [
"Destroy",
"one",
"or",
"many",
"nodes",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L324-L349 | train | 236,980 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.terminate_with_threads | def terminate_with_threads(self, nodes=None):
"""Destroy one or many nodes threaded.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
failed_kill = []
def worker(gce, node):
self.logger.info("Terminating node: %s", node.name)
terminated = gce.destroy_node(node)
if not terminated:
failed_kill.append(node)
threads = []
for node in nodes:
thread = threading.Thread(target=worker, args=(self.gce, node))
threads.append(thread)
thread.start()
self.logger.info("Waiting for nodes to shut down ...")
for thread in threads:
thread.join()
return failed_kill | python | def terminate_with_threads(self, nodes=None):
"""Destroy one or many nodes threaded.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list``
"""
if not self.is_connected():
return None
nodes = nodes or self.nodes
failed_kill = []
def worker(gce, node):
self.logger.info("Terminating node: %s", node.name)
terminated = gce.destroy_node(node)
if not terminated:
failed_kill.append(node)
threads = []
for node in nodes:
thread = threading.Thread(target=worker, args=(self.gce, node))
threads.append(thread)
thread.start()
self.logger.info("Waiting for nodes to shut down ...")
for thread in threads:
thread.join()
return failed_kill | [
"def",
"terminate_with_threads",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"failed_kill",
"=",
"[",
"]",
"def",
"worker",
"(",
"gce",
",",
"node",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Terminating node: %s\"",
",",
"node",
".",
"name",
")",
"terminated",
"=",
"gce",
".",
"destroy_node",
"(",
"node",
")",
"if",
"not",
"terminated",
":",
"failed_kill",
".",
"append",
"(",
"node",
")",
"threads",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"worker",
",",
"args",
"=",
"(",
"self",
".",
"gce",
",",
"node",
")",
")",
"threads",
".",
"append",
"(",
"thread",
")",
"thread",
".",
"start",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Waiting for nodes to shut down ...\"",
")",
"for",
"thread",
"in",
"threads",
":",
"thread",
".",
"join",
"(",
")",
"return",
"failed_kill"
] | Destroy one or many nodes threaded.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:return: List of nodes which failed to terminate.
:rtype: ``list`` | [
"Destroy",
"one",
"or",
"many",
"nodes",
"threaded",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L351-L382 | train | 236,981 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.terminate_ex | def terminate_ex(self, nodes, threads=False, attempts=3):
"""Wrapper method for terminate.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:param attempts: The amount of attempts for retrying to terminate failed instances.
:type attempts: ``int``
:param threads: Whether to use the threaded approach or not.
:type threads: ``bool``
"""
while nodes and attempts > 0:
if threads:
nodes = self.terminate_with_threads(nodes)
else:
nodes = self.terminate(nodes)
if nodes:
logger.info("Attempt to terminate the remaining instances once more.")
attempts -= 1
return nodes | python | def terminate_ex(self, nodes, threads=False, attempts=3):
"""Wrapper method for terminate.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:param attempts: The amount of attempts for retrying to terminate failed instances.
:type attempts: ``int``
:param threads: Whether to use the threaded approach or not.
:type threads: ``bool``
"""
while nodes and attempts > 0:
if threads:
nodes = self.terminate_with_threads(nodes)
else:
nodes = self.terminate(nodes)
if nodes:
logger.info("Attempt to terminate the remaining instances once more.")
attempts -= 1
return nodes | [
"def",
"terminate_ex",
"(",
"self",
",",
"nodes",
",",
"threads",
"=",
"False",
",",
"attempts",
"=",
"3",
")",
":",
"while",
"nodes",
"and",
"attempts",
">",
"0",
":",
"if",
"threads",
":",
"nodes",
"=",
"self",
".",
"terminate_with_threads",
"(",
"nodes",
")",
"else",
":",
"nodes",
"=",
"self",
".",
"terminate",
"(",
"nodes",
")",
"if",
"nodes",
":",
"logger",
".",
"info",
"(",
"\"Attempt to terminate the remaining instances once more.\"",
")",
"attempts",
"-=",
"1",
"return",
"nodes"
] | Wrapper method for terminate.
:param nodes: Nodes to be destroyed.
:type nodes: ``list``
:param attempts: The amount of attempts for retrying to terminate failed instances.
:type attempts: ``int``
:param threads: Whether to use the threaded approach or not.
:type threads: ``bool`` | [
"Wrapper",
"method",
"for",
"terminate",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L384-L405 | train | 236,982 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.build_bootdisk | def build_bootdisk(self, image, size=10, auto_delete=True):
"""Buid a disk struct.
:param image: Base image name.
:type image: ``str``
:param size: Persistent disk size.
:type size: ``int``
:param auto_delete: Wether to auto delete disk on instance termination.
:type auto_delete: ``bool``
"""
if image is None:
raise ComputeEngineManagerException("Image must not be None.")
return {
'boot': True,
'autoDelete': auto_delete,
'initializeParams': {
'sourceImage': "projects/cos-cloud/global/images/{}".format(image),
'diskSizeGb': size,
}
} | python | def build_bootdisk(self, image, size=10, auto_delete=True):
"""Buid a disk struct.
:param image: Base image name.
:type image: ``str``
:param size: Persistent disk size.
:type size: ``int``
:param auto_delete: Wether to auto delete disk on instance termination.
:type auto_delete: ``bool``
"""
if image is None:
raise ComputeEngineManagerException("Image must not be None.")
return {
'boot': True,
'autoDelete': auto_delete,
'initializeParams': {
'sourceImage': "projects/cos-cloud/global/images/{}".format(image),
'diskSizeGb': size,
}
} | [
"def",
"build_bootdisk",
"(",
"self",
",",
"image",
",",
"size",
"=",
"10",
",",
"auto_delete",
"=",
"True",
")",
":",
"if",
"image",
"is",
"None",
":",
"raise",
"ComputeEngineManagerException",
"(",
"\"Image must not be None.\"",
")",
"return",
"{",
"'boot'",
":",
"True",
",",
"'autoDelete'",
":",
"auto_delete",
",",
"'initializeParams'",
":",
"{",
"'sourceImage'",
":",
"\"projects/cos-cloud/global/images/{}\"",
".",
"format",
"(",
"image",
")",
",",
"'diskSizeGb'",
":",
"size",
",",
"}",
"}"
] | Buid a disk struct.
:param image: Base image name.
:type image: ``str``
:param size: Persistent disk size.
:type size: ``int``
:param auto_delete: Wether to auto delete disk on instance termination.
:type auto_delete: ``bool`` | [
"Buid",
"a",
"disk",
"struct",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L407-L428 | train | 236,983 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.build_container_vm | def build_container_vm(self, container, disk, zone="us-east1-b", tags=None, preemptible=True):
"""Build kwargs for a container VM.
:param container: Container declaration.
:type container: ``dict``
:param disk: Disk definition structure.
:type disk: ``dict``
:param zone: The zone in which the instance should run.
:type zone: ``str``
:param tags: Tags associated with the instance.
:type tags: ``dict``
:param preemptible: Wether the instance is a preemtible or not.
:type preemptible: ``bool``
"""
if tags is None:
tags = []
if container is None:
raise ComputeEngineManagerException("Container declaration must not be None.")
if disk is None:
raise ComputeEngineManagerException("Disk structure must not be None.")
return {
'ex_metadata': {
"gce-container-declaration": container,
"google-logging-enabled": "true"
},
'location': zone,
'ex_tags': tags,
'ex_disks_gce_struct': [disk],
'ex_preemptible': preemptible
} | python | def build_container_vm(self, container, disk, zone="us-east1-b", tags=None, preemptible=True):
"""Build kwargs for a container VM.
:param container: Container declaration.
:type container: ``dict``
:param disk: Disk definition structure.
:type disk: ``dict``
:param zone: The zone in which the instance should run.
:type zone: ``str``
:param tags: Tags associated with the instance.
:type tags: ``dict``
:param preemptible: Wether the instance is a preemtible or not.
:type preemptible: ``bool``
"""
if tags is None:
tags = []
if container is None:
raise ComputeEngineManagerException("Container declaration must not be None.")
if disk is None:
raise ComputeEngineManagerException("Disk structure must not be None.")
return {
'ex_metadata': {
"gce-container-declaration": container,
"google-logging-enabled": "true"
},
'location': zone,
'ex_tags': tags,
'ex_disks_gce_struct': [disk],
'ex_preemptible': preemptible
} | [
"def",
"build_container_vm",
"(",
"self",
",",
"container",
",",
"disk",
",",
"zone",
"=",
"\"us-east1-b\"",
",",
"tags",
"=",
"None",
",",
"preemptible",
"=",
"True",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"container",
"is",
"None",
":",
"raise",
"ComputeEngineManagerException",
"(",
"\"Container declaration must not be None.\"",
")",
"if",
"disk",
"is",
"None",
":",
"raise",
"ComputeEngineManagerException",
"(",
"\"Disk structure must not be None.\"",
")",
"return",
"{",
"'ex_metadata'",
":",
"{",
"\"gce-container-declaration\"",
":",
"container",
",",
"\"google-logging-enabled\"",
":",
"\"true\"",
"}",
",",
"'location'",
":",
"zone",
",",
"'ex_tags'",
":",
"tags",
",",
"'ex_disks_gce_struct'",
":",
"[",
"disk",
"]",
",",
"'ex_preemptible'",
":",
"preemptible",
"}"
] | Build kwargs for a container VM.
:param container: Container declaration.
:type container: ``dict``
:param disk: Disk definition structure.
:type disk: ``dict``
:param zone: The zone in which the instance should run.
:type zone: ``str``
:param tags: Tags associated with the instance.
:type tags: ``dict``
:param preemptible: Wether the instance is a preemtible or not.
:type preemptible: ``bool`` | [
"Build",
"kwargs",
"for",
"a",
"container",
"VM",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L430-L463 | train | 236,984 |
MozillaSecurity/laniakea | laniakea/core/providers/gce/manager.py | ComputeEngineManager.filter | def filter(self, zone='all'):
"""Filter nodes by their attributes.
:param zone: A zone containing nodes.
:type zone: ``str``
:return: A chainable filter object.
:rtype: ``object`` of :class:`Filter`
"""
if not self.is_connected():
return None
nodes = self.gce.list_nodes(zone)
return Filter(nodes) | python | def filter(self, zone='all'):
"""Filter nodes by their attributes.
:param zone: A zone containing nodes.
:type zone: ``str``
:return: A chainable filter object.
:rtype: ``object`` of :class:`Filter`
"""
if not self.is_connected():
return None
nodes = self.gce.list_nodes(zone)
return Filter(nodes) | [
"def",
"filter",
"(",
"self",
",",
"zone",
"=",
"'all'",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"self",
".",
"gce",
".",
"list_nodes",
"(",
"zone",
")",
"return",
"Filter",
"(",
"nodes",
")"
] | Filter nodes by their attributes.
:param zone: A zone containing nodes.
:type zone: ``str``
:return: A chainable filter object.
:rtype: ``object`` of :class:`Filter` | [
"Filter",
"nodes",
"by",
"their",
"attributes",
"."
] | 7e80adc6ae92c6c1332d4c08473bb271fb3b6833 | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/gce/manager.py#L465-L478 | train | 236,985 |
scivision/pymap3d | pymap3d/enu.py | enu2aer | def enu2aer(e: np.ndarray, n: np.ndarray, u: np.ndarray, deg: bool = True) -> Tuple[float, float, float]:
"""
ENU to Azimuth, Elevation, Range
Parameters
----------
e : float or np.ndarray of float
ENU East coordinate (meters)
n : float or np.ndarray of float
ENU North coordinate (meters)
u : float or np.ndarray of float
ENU Up coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
azimuth : float or np.ndarray of float
azimuth to rarget
elevation : float or np.ndarray of float
elevation to target
srange : float or np.ndarray of float
slant range [meters]
"""
# 1 millimeter precision for singularity
e = np.asarray(e)
n = np.asarray(n)
u = np.asarray(u)
with np.errstate(invalid='ignore'):
e[abs(e) < 1e-3] = 0.
n[abs(n) < 1e-3] = 0.
u[abs(u) < 1e-3] = 0.
r = hypot(e, n)
slantRange = hypot(r, u)
elev = arctan2(u, r)
az = arctan2(e, n) % tau
if deg:
az = degrees(az)
elev = degrees(elev)
return az, elev, slantRange | python | def enu2aer(e: np.ndarray, n: np.ndarray, u: np.ndarray, deg: bool = True) -> Tuple[float, float, float]:
"""
ENU to Azimuth, Elevation, Range
Parameters
----------
e : float or np.ndarray of float
ENU East coordinate (meters)
n : float or np.ndarray of float
ENU North coordinate (meters)
u : float or np.ndarray of float
ENU Up coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
azimuth : float or np.ndarray of float
azimuth to rarget
elevation : float or np.ndarray of float
elevation to target
srange : float or np.ndarray of float
slant range [meters]
"""
# 1 millimeter precision for singularity
e = np.asarray(e)
n = np.asarray(n)
u = np.asarray(u)
with np.errstate(invalid='ignore'):
e[abs(e) < 1e-3] = 0.
n[abs(n) < 1e-3] = 0.
u[abs(u) < 1e-3] = 0.
r = hypot(e, n)
slantRange = hypot(r, u)
elev = arctan2(u, r)
az = arctan2(e, n) % tau
if deg:
az = degrees(az)
elev = degrees(elev)
return az, elev, slantRange | [
"def",
"enu2aer",
"(",
"e",
":",
"np",
".",
"ndarray",
",",
"n",
":",
"np",
".",
"ndarray",
",",
"u",
":",
"np",
".",
"ndarray",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"# 1 millimeter precision for singularity",
"e",
"=",
"np",
".",
"asarray",
"(",
"e",
")",
"n",
"=",
"np",
".",
"asarray",
"(",
"n",
")",
"u",
"=",
"np",
".",
"asarray",
"(",
"u",
")",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"e",
"[",
"abs",
"(",
"e",
")",
"<",
"1e-3",
"]",
"=",
"0.",
"n",
"[",
"abs",
"(",
"n",
")",
"<",
"1e-3",
"]",
"=",
"0.",
"u",
"[",
"abs",
"(",
"u",
")",
"<",
"1e-3",
"]",
"=",
"0.",
"r",
"=",
"hypot",
"(",
"e",
",",
"n",
")",
"slantRange",
"=",
"hypot",
"(",
"r",
",",
"u",
")",
"elev",
"=",
"arctan2",
"(",
"u",
",",
"r",
")",
"az",
"=",
"arctan2",
"(",
"e",
",",
"n",
")",
"%",
"tau",
"if",
"deg",
":",
"az",
"=",
"degrees",
"(",
"az",
")",
"elev",
"=",
"degrees",
"(",
"elev",
")",
"return",
"az",
",",
"elev",
",",
"slantRange"
] | ENU to Azimuth, Elevation, Range
Parameters
----------
e : float or np.ndarray of float
ENU East coordinate (meters)
n : float or np.ndarray of float
ENU North coordinate (meters)
u : float or np.ndarray of float
ENU Up coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
azimuth : float or np.ndarray of float
azimuth to rarget
elevation : float or np.ndarray of float
elevation to target
srange : float or np.ndarray of float
slant range [meters] | [
"ENU",
"to",
"Azimuth",
"Elevation",
"Range"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L16-L62 | train | 236,986 |
scivision/pymap3d | pymap3d/enu.py | aer2enu | def aer2enu(az: float, el: float, srange: float, deg: bool = True) -> Tuple[float, float, float]:
"""
Azimuth, Elevation, Slant range to target to East, north, Up
Parameters
----------
azimuth : float or np.ndarray of float
azimuth clockwise from north (degrees)
elevation : float or np.ndarray of float
elevation angle above horizon, neglecting aberattions (degrees)
srange : float or np.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
--------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters)
"""
if deg:
el = radians(el)
az = radians(az)
with np.errstate(invalid='ignore'):
if (np.asarray(srange) < 0).any():
raise ValueError('Slant range [0, Infinity)')
r = srange * cos(el)
return r * sin(az), r * cos(az), srange * sin(el) | python | def aer2enu(az: float, el: float, srange: float, deg: bool = True) -> Tuple[float, float, float]:
"""
Azimuth, Elevation, Slant range to target to East, north, Up
Parameters
----------
azimuth : float or np.ndarray of float
azimuth clockwise from north (degrees)
elevation : float or np.ndarray of float
elevation angle above horizon, neglecting aberattions (degrees)
srange : float or np.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
--------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters)
"""
if deg:
el = radians(el)
az = radians(az)
with np.errstate(invalid='ignore'):
if (np.asarray(srange) < 0).any():
raise ValueError('Slant range [0, Infinity)')
r = srange * cos(el)
return r * sin(az), r * cos(az), srange * sin(el) | [
"def",
"aer2enu",
"(",
"az",
":",
"float",
",",
"el",
":",
"float",
",",
"srange",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"if",
"deg",
":",
"el",
"=",
"radians",
"(",
"el",
")",
"az",
"=",
"radians",
"(",
"az",
")",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"if",
"(",
"np",
".",
"asarray",
"(",
"srange",
")",
"<",
"0",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Slant range [0, Infinity)'",
")",
"r",
"=",
"srange",
"*",
"cos",
"(",
"el",
")",
"return",
"r",
"*",
"sin",
"(",
"az",
")",
",",
"r",
"*",
"cos",
"(",
"az",
")",
",",
"srange",
"*",
"sin",
"(",
"el",
")"
] | Azimuth, Elevation, Slant range to target to East, north, Up
Parameters
----------
azimuth : float or np.ndarray of float
azimuth clockwise from north (degrees)
elevation : float or np.ndarray of float
elevation angle above horizon, neglecting aberattions (degrees)
srange : float or np.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
--------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters) | [
"Azimuth",
"Elevation",
"Slant",
"range",
"to",
"target",
"to",
"East",
"north",
"Up"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L65-L99 | train | 236,987 |
scivision/pymap3d | pymap3d/enu.py | enu2geodetic | def enu2geodetic(e: float, n: float, u: float,
lat0: float, lon0: float, h0: float,
ell=None, deg: bool = True) -> Tuple[float, float, float]:
"""
East, North, Up to target to geodetic coordinates
Parameters
----------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lat : float or np.ndarray of float
geodetic latitude
lon : float or np.ndarray of float
geodetic longitude
alt : float or np.ndarray of float
altitude above ellipsoid (meters)
"""
x, y, z = enu2ecef(e, n, u, lat0, lon0, h0, ell, deg=deg)
return ecef2geodetic(x, y, z, ell, deg=deg) | python | def enu2geodetic(e: float, n: float, u: float,
lat0: float, lon0: float, h0: float,
ell=None, deg: bool = True) -> Tuple[float, float, float]:
"""
East, North, Up to target to geodetic coordinates
Parameters
----------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lat : float or np.ndarray of float
geodetic latitude
lon : float or np.ndarray of float
geodetic longitude
alt : float or np.ndarray of float
altitude above ellipsoid (meters)
"""
x, y, z = enu2ecef(e, n, u, lat0, lon0, h0, ell, deg=deg)
return ecef2geodetic(x, y, z, ell, deg=deg) | [
"def",
"enu2geodetic",
"(",
"e",
":",
"float",
",",
"n",
":",
"float",
",",
"u",
":",
"float",
",",
"lat0",
":",
"float",
",",
"lon0",
":",
"float",
",",
"h0",
":",
"float",
",",
"ell",
"=",
"None",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"x",
",",
"y",
",",
"z",
"=",
"enu2ecef",
"(",
"e",
",",
"n",
",",
"u",
",",
"lat0",
",",
"lon0",
",",
"h0",
",",
"ell",
",",
"deg",
"=",
"deg",
")",
"return",
"ecef2geodetic",
"(",
"x",
",",
"y",
",",
"z",
",",
"ell",
",",
"deg",
"=",
"deg",
")"
] | East, North, Up to target to geodetic coordinates
Parameters
----------
e : float or np.ndarray of float
East ENU coordinate (meters)
n : float or np.ndarray of float
North ENU coordinate (meters)
u : float or np.ndarray of float
Up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lat : float or np.ndarray of float
geodetic latitude
lon : float or np.ndarray of float
geodetic longitude
alt : float or np.ndarray of float
altitude above ellipsoid (meters) | [
"East",
"North",
"Up",
"to",
"target",
"to",
"geodetic",
"coordinates"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/enu.py#L102-L140 | train | 236,988 |
scivision/pymap3d | pymap3d/vincenty.py | track2 | def track2(lat1: float, lon1: float, lat2: float, lon2: float,
ell: Ellipsoid = None, npts: int = 100, deg: bool = True):
"""
computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2
Parameters
----------
Lat1 : float or numpy.ndarray of float
Geodetic latitude of first point (degrees)
Lon1 : float or numpy.ndarray of float
Geodetic longitude of first point (degrees)
Lat2 : float or numpy.ndarray of float
Geodetic latitude of second point (degrees)
Lon2 : float or numpy.ndarray of float
Geodetic longitude of second point (degrees)
ell : Ellipsoid, optional
reference ellipsoid
npts : int, optional
number of points (default is 100)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lats : numpy.ndarray of float
latitudes of points along track
lons : numpy.ndarray of float
longitudes of points along track
Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <jeffrey.s.whitaker@noaa.gov>
"""
if ell is None:
ell = Ellipsoid()
if npts <= 1:
raise ValueError('npts must be greater than 1')
if npts == 2:
return [lat1, lat2], [lon1, lon2]
if deg is True:
rlat1, rlon1, rlat2, rlon2 = np.radians([lat1, lon1, lat2, lon2])
else:
rlat1, rlon1, rlat2, rlon2 = lat1, lon1, lat2, lon2
gcarclen = 2. * np.arcsin(np.sqrt((np.sin((rlat1 - rlat2) / 2))**2 +
np.cos(rlat1) * np.cos(rlat2) * (np.sin((rlon1 - rlon2) / 2))**2))
# check to see if points are antipodal (if so, route is undefined).
if np.allclose(gcarclen, pi):
raise ValueError('cannot compute intermediate points on a great circle whose endpoints are antipodal')
distance, azimuth, _ = vdist(lat1, lon1, lat2, lon2)
incdist = distance / (npts - 1)
latpt = lat1
lonpt = lon1
lons = [lonpt]
lats = [latpt]
for n in range(npts - 2):
latptnew, lonptnew, _ = vreckon(latpt, lonpt, incdist, azimuth)
_, azimuth, _ = vdist(latptnew, lonptnew, lat2, lon2, ell=ell)
lats.append(latptnew)
lons.append(lonptnew)
latpt = latptnew
lonpt = lonptnew
lons.append(lon2)
lats.append(lat2)
if not deg:
lats = np.radians(lats)
lons = np.radians(lons)
return lats, lons | python | def track2(lat1: float, lon1: float, lat2: float, lon2: float,
ell: Ellipsoid = None, npts: int = 100, deg: bool = True):
"""
computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2
Parameters
----------
Lat1 : float or numpy.ndarray of float
Geodetic latitude of first point (degrees)
Lon1 : float or numpy.ndarray of float
Geodetic longitude of first point (degrees)
Lat2 : float or numpy.ndarray of float
Geodetic latitude of second point (degrees)
Lon2 : float or numpy.ndarray of float
Geodetic longitude of second point (degrees)
ell : Ellipsoid, optional
reference ellipsoid
npts : int, optional
number of points (default is 100)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lats : numpy.ndarray of float
latitudes of points along track
lons : numpy.ndarray of float
longitudes of points along track
Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <jeffrey.s.whitaker@noaa.gov>
"""
if ell is None:
ell = Ellipsoid()
if npts <= 1:
raise ValueError('npts must be greater than 1')
if npts == 2:
return [lat1, lat2], [lon1, lon2]
if deg is True:
rlat1, rlon1, rlat2, rlon2 = np.radians([lat1, lon1, lat2, lon2])
else:
rlat1, rlon1, rlat2, rlon2 = lat1, lon1, lat2, lon2
gcarclen = 2. * np.arcsin(np.sqrt((np.sin((rlat1 - rlat2) / 2))**2 +
np.cos(rlat1) * np.cos(rlat2) * (np.sin((rlon1 - rlon2) / 2))**2))
# check to see if points are antipodal (if so, route is undefined).
if np.allclose(gcarclen, pi):
raise ValueError('cannot compute intermediate points on a great circle whose endpoints are antipodal')
distance, azimuth, _ = vdist(lat1, lon1, lat2, lon2)
incdist = distance / (npts - 1)
latpt = lat1
lonpt = lon1
lons = [lonpt]
lats = [latpt]
for n in range(npts - 2):
latptnew, lonptnew, _ = vreckon(latpt, lonpt, incdist, azimuth)
_, azimuth, _ = vdist(latptnew, lonptnew, lat2, lon2, ell=ell)
lats.append(latptnew)
lons.append(lonptnew)
latpt = latptnew
lonpt = lonptnew
lons.append(lon2)
lats.append(lat2)
if not deg:
lats = np.radians(lats)
lons = np.radians(lons)
return lats, lons | [
"def",
"track2",
"(",
"lat1",
":",
"float",
",",
"lon1",
":",
"float",
",",
"lat2",
":",
"float",
",",
"lon2",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
",",
"npts",
":",
"int",
"=",
"100",
",",
"deg",
":",
"bool",
"=",
"True",
")",
":",
"if",
"ell",
"is",
"None",
":",
"ell",
"=",
"Ellipsoid",
"(",
")",
"if",
"npts",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"'npts must be greater than 1'",
")",
"if",
"npts",
"==",
"2",
":",
"return",
"[",
"lat1",
",",
"lat2",
"]",
",",
"[",
"lon1",
",",
"lon2",
"]",
"if",
"deg",
"is",
"True",
":",
"rlat1",
",",
"rlon1",
",",
"rlat2",
",",
"rlon2",
"=",
"np",
".",
"radians",
"(",
"[",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
"]",
")",
"else",
":",
"rlat1",
",",
"rlon1",
",",
"rlat2",
",",
"rlon2",
"=",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
"gcarclen",
"=",
"2.",
"*",
"np",
".",
"arcsin",
"(",
"np",
".",
"sqrt",
"(",
"(",
"np",
".",
"sin",
"(",
"(",
"rlat1",
"-",
"rlat2",
")",
"/",
"2",
")",
")",
"**",
"2",
"+",
"np",
".",
"cos",
"(",
"rlat1",
")",
"*",
"np",
".",
"cos",
"(",
"rlat2",
")",
"*",
"(",
"np",
".",
"sin",
"(",
"(",
"rlon1",
"-",
"rlon2",
")",
"/",
"2",
")",
")",
"**",
"2",
")",
")",
"# check to see if points are antipodal (if so, route is undefined).",
"if",
"np",
".",
"allclose",
"(",
"gcarclen",
",",
"pi",
")",
":",
"raise",
"ValueError",
"(",
"'cannot compute intermediate points on a great circle whose endpoints are antipodal'",
")",
"distance",
",",
"azimuth",
",",
"_",
"=",
"vdist",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
"incdist",
"=",
"distance",
"/",
"(",
"npts",
"-",
"1",
")",
"latpt",
"=",
"lat1",
"lonpt",
"=",
"lon1",
"lons",
"=",
"[",
"lonpt",
"]",
"lats",
"=",
"[",
"latpt",
"]",
"for",
"n",
"in",
"range",
"(",
"npts",
"-",
"2",
")",
":",
"latptnew",
",",
"lonptnew",
",",
"_",
"=",
"vreckon",
"(",
"latpt",
",",
"lonpt",
",",
"incdist",
",",
"azimuth",
")",
"_",
",",
"azimuth",
",",
"_",
"=",
"vdist",
"(",
"latptnew",
",",
"lonptnew",
",",
"lat2",
",",
"lon2",
",",
"ell",
"=",
"ell",
")",
"lats",
".",
"append",
"(",
"latptnew",
")",
"lons",
".",
"append",
"(",
"lonptnew",
")",
"latpt",
"=",
"latptnew",
"lonpt",
"=",
"lonptnew",
"lons",
".",
"append",
"(",
"lon2",
")",
"lats",
".",
"append",
"(",
"lat2",
")",
"if",
"not",
"deg",
":",
"lats",
"=",
"np",
".",
"radians",
"(",
"lats",
")",
"lons",
"=",
"np",
".",
"radians",
"(",
"lons",
")",
"return",
"lats",
",",
"lons"
] | computes great circle tracks starting at the point lat1, lon1 and ending at lat2, lon2
Parameters
----------
Lat1 : float or numpy.ndarray of float
Geodetic latitude of first point (degrees)
Lon1 : float or numpy.ndarray of float
Geodetic longitude of first point (degrees)
Lat2 : float or numpy.ndarray of float
Geodetic latitude of second point (degrees)
Lon2 : float or numpy.ndarray of float
Geodetic longitude of second point (degrees)
ell : Ellipsoid, optional
reference ellipsoid
npts : int, optional
number of points (default is 100)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lats : numpy.ndarray of float
latitudes of points along track
lons : numpy.ndarray of float
longitudes of points along track
Based on code posted to the GMT mailing list in Dec 1999 by Jim Levens and by Jeff Whitaker <jeffrey.s.whitaker@noaa.gov> | [
"computes",
"great",
"circle",
"tracks",
"starting",
"at",
"the",
"point",
"lat1",
"lon1",
"and",
"ending",
"at",
"lat2",
"lon2"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vincenty.py#L416-L491 | train | 236,989 |
scivision/pymap3d | pymap3d/sidereal.py | datetime2sidereal | def datetime2sidereal(time: datetime,
lon_radians: float,
usevallado: bool = True) -> float:
"""
Convert ``datetime`` to sidereal time
from D. Vallado "Fundamentals of Astrodynamics and Applications"
time : datetime.datetime
time to convert
lon_radians : float
longitude (radians)
usevallado : bool, optional
use vallado instead of AstroPy (default is Vallado)
Results
-------
tsr : float
Sidereal time
"""
usevallado = usevallado or Time is None
if usevallado:
jd = juliandate(str2dt(time))
# %% Greenwich Sidereal time RADIANS
gst = julian2sidereal(jd)
# %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME
tsr = gst + lon_radians
else:
tsr = Time(time).sidereal_time(kind='apparent',
longitude=Longitude(lon_radians, unit=u.radian)).radian
return tsr | python | def datetime2sidereal(time: datetime,
lon_radians: float,
usevallado: bool = True) -> float:
"""
Convert ``datetime`` to sidereal time
from D. Vallado "Fundamentals of Astrodynamics and Applications"
time : datetime.datetime
time to convert
lon_radians : float
longitude (radians)
usevallado : bool, optional
use vallado instead of AstroPy (default is Vallado)
Results
-------
tsr : float
Sidereal time
"""
usevallado = usevallado or Time is None
if usevallado:
jd = juliandate(str2dt(time))
# %% Greenwich Sidereal time RADIANS
gst = julian2sidereal(jd)
# %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME
tsr = gst + lon_radians
else:
tsr = Time(time).sidereal_time(kind='apparent',
longitude=Longitude(lon_radians, unit=u.radian)).radian
return tsr | [
"def",
"datetime2sidereal",
"(",
"time",
":",
"datetime",
",",
"lon_radians",
":",
"float",
",",
"usevallado",
":",
"bool",
"=",
"True",
")",
"->",
"float",
":",
"usevallado",
"=",
"usevallado",
"or",
"Time",
"is",
"None",
"if",
"usevallado",
":",
"jd",
"=",
"juliandate",
"(",
"str2dt",
"(",
"time",
")",
")",
"# %% Greenwich Sidereal time RADIANS",
"gst",
"=",
"julian2sidereal",
"(",
"jd",
")",
"# %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME",
"tsr",
"=",
"gst",
"+",
"lon_radians",
"else",
":",
"tsr",
"=",
"Time",
"(",
"time",
")",
".",
"sidereal_time",
"(",
"kind",
"=",
"'apparent'",
",",
"longitude",
"=",
"Longitude",
"(",
"lon_radians",
",",
"unit",
"=",
"u",
".",
"radian",
")",
")",
".",
"radian",
"return",
"tsr"
] | Convert ``datetime`` to sidereal time
from D. Vallado "Fundamentals of Astrodynamics and Applications"
time : datetime.datetime
time to convert
lon_radians : float
longitude (radians)
usevallado : bool, optional
use vallado instead of AstroPy (default is Vallado)
Results
-------
tsr : float
Sidereal time | [
"Convert",
"datetime",
"to",
"sidereal",
"time"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L22-L55 | train | 236,990 |
scivision/pymap3d | pymap3d/sidereal.py | juliandate | def juliandate(time: datetime) -> float:
"""
Python datetime to Julian time
from D.Vallado Fundamentals of Astrodynamics and Applications p.187
and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61
Parameters
----------
time : datetime.datetime
time to convert
Results
-------
jd : float
Julian date
"""
times = np.atleast_1d(time)
assert times.ndim == 1
jd = np.empty(times.size)
for i, t in enumerate(times):
if t.month < 3:
year = t.year - 1
month = t.month + 12
else:
year = t.year
month = t.month
A = int(year / 100.0)
B = 2 - A + int(A / 4.)
C = ((t.second / 60. + t.minute) / 60. + t.hour) / 24.
jd[i] = (int(365.25 * (year + 4716)) +
int(30.6001 * (month + 1)) + t.day + B - 1524.5 + C)
return jd.squeeze() | python | def juliandate(time: datetime) -> float:
"""
Python datetime to Julian time
from D.Vallado Fundamentals of Astrodynamics and Applications p.187
and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61
Parameters
----------
time : datetime.datetime
time to convert
Results
-------
jd : float
Julian date
"""
times = np.atleast_1d(time)
assert times.ndim == 1
jd = np.empty(times.size)
for i, t in enumerate(times):
if t.month < 3:
year = t.year - 1
month = t.month + 12
else:
year = t.year
month = t.month
A = int(year / 100.0)
B = 2 - A + int(A / 4.)
C = ((t.second / 60. + t.minute) / 60. + t.hour) / 24.
jd[i] = (int(365.25 * (year + 4716)) +
int(30.6001 * (month + 1)) + t.day + B - 1524.5 + C)
return jd.squeeze() | [
"def",
"juliandate",
"(",
"time",
":",
"datetime",
")",
"->",
"float",
":",
"times",
"=",
"np",
".",
"atleast_1d",
"(",
"time",
")",
"assert",
"times",
".",
"ndim",
"==",
"1",
"jd",
"=",
"np",
".",
"empty",
"(",
"times",
".",
"size",
")",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"times",
")",
":",
"if",
"t",
".",
"month",
"<",
"3",
":",
"year",
"=",
"t",
".",
"year",
"-",
"1",
"month",
"=",
"t",
".",
"month",
"+",
"12",
"else",
":",
"year",
"=",
"t",
".",
"year",
"month",
"=",
"t",
".",
"month",
"A",
"=",
"int",
"(",
"year",
"/",
"100.0",
")",
"B",
"=",
"2",
"-",
"A",
"+",
"int",
"(",
"A",
"/",
"4.",
")",
"C",
"=",
"(",
"(",
"t",
".",
"second",
"/",
"60.",
"+",
"t",
".",
"minute",
")",
"/",
"60.",
"+",
"t",
".",
"hour",
")",
"/",
"24.",
"jd",
"[",
"i",
"]",
"=",
"(",
"int",
"(",
"365.25",
"*",
"(",
"year",
"+",
"4716",
")",
")",
"+",
"int",
"(",
"30.6001",
"*",
"(",
"month",
"+",
"1",
")",
")",
"+",
"t",
".",
"day",
"+",
"B",
"-",
"1524.5",
"+",
"C",
")",
"return",
"jd",
".",
"squeeze",
"(",
")"
] | Python datetime to Julian time
from D.Vallado Fundamentals of Astrodynamics and Applications p.187
and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61
Parameters
----------
time : datetime.datetime
time to convert
Results
-------
jd : float
Julian date | [
"Python",
"datetime",
"to",
"Julian",
"time"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L58-L97 | train | 236,991 |
scivision/pymap3d | pymap3d/sidereal.py | julian2sidereal | def julian2sidereal(Jdate: float) -> float:
"""
Convert Julian time to sidereal time
D. Vallado Ed. 4
Parameters
----------
Jdate: float
Julian centuries from J2000.0
Results
-------
tsr : float
Sidereal time
"""
jdate = np.atleast_1d(Jdate)
assert jdate.ndim == 1
tsr = np.empty(jdate.size)
for i, jd in enumerate(jdate):
# %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1
tUT1 = (jd - 2451545.0) / 36525.
# Eqn. 3-47 p. 188
gmst_sec = (67310.54841 + (876600 * 3600 + 8640184.812866) *
tUT1 + 0.093104 * tUT1**2 - 6.2e-6 * tUT1**3)
# 1/86400 and %(2*pi) implied by units of radians
tsr[i] = gmst_sec * (2 * pi) / 86400. % (2 * pi)
return tsr.squeeze() | python | def julian2sidereal(Jdate: float) -> float:
"""
Convert Julian time to sidereal time
D. Vallado Ed. 4
Parameters
----------
Jdate: float
Julian centuries from J2000.0
Results
-------
tsr : float
Sidereal time
"""
jdate = np.atleast_1d(Jdate)
assert jdate.ndim == 1
tsr = np.empty(jdate.size)
for i, jd in enumerate(jdate):
# %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1
tUT1 = (jd - 2451545.0) / 36525.
# Eqn. 3-47 p. 188
gmst_sec = (67310.54841 + (876600 * 3600 + 8640184.812866) *
tUT1 + 0.093104 * tUT1**2 - 6.2e-6 * tUT1**3)
# 1/86400 and %(2*pi) implied by units of radians
tsr[i] = gmst_sec * (2 * pi) / 86400. % (2 * pi)
return tsr.squeeze() | [
"def",
"julian2sidereal",
"(",
"Jdate",
":",
"float",
")",
"->",
"float",
":",
"jdate",
"=",
"np",
".",
"atleast_1d",
"(",
"Jdate",
")",
"assert",
"jdate",
".",
"ndim",
"==",
"1",
"tsr",
"=",
"np",
".",
"empty",
"(",
"jdate",
".",
"size",
")",
"for",
"i",
",",
"jd",
"in",
"enumerate",
"(",
"jdate",
")",
":",
"# %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1",
"tUT1",
"=",
"(",
"jd",
"-",
"2451545.0",
")",
"/",
"36525.",
"# Eqn. 3-47 p. 188",
"gmst_sec",
"=",
"(",
"67310.54841",
"+",
"(",
"876600",
"*",
"3600",
"+",
"8640184.812866",
")",
"*",
"tUT1",
"+",
"0.093104",
"*",
"tUT1",
"**",
"2",
"-",
"6.2e-6",
"*",
"tUT1",
"**",
"3",
")",
"# 1/86400 and %(2*pi) implied by units of radians",
"tsr",
"[",
"i",
"]",
"=",
"gmst_sec",
"*",
"(",
"2",
"*",
"pi",
")",
"/",
"86400.",
"%",
"(",
"2",
"*",
"pi",
")",
"return",
"tsr",
".",
"squeeze",
"(",
")"
] | Convert Julian time to sidereal time
D. Vallado Ed. 4
Parameters
----------
Jdate: float
Julian centuries from J2000.0
Results
-------
tsr : float
Sidereal time | [
"Convert",
"Julian",
"time",
"to",
"sidereal",
"time"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/sidereal.py#L100-L135 | train | 236,992 |
scivision/pymap3d | pymap3d/ecef.py | get_radius_normal | def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float:
"""
Compute normal radius of planetary body
Parameters
----------
lat_radians : float
latitude in radians
ell : Ellipsoid, optional
reference ellipsoid
Returns
-------
radius : float
normal radius (meters)
"""
if ell is None:
ell = Ellipsoid()
a = ell.a
b = ell.b
return a**2 / sqrt(a**2 * cos(lat_radians)**2 + b**2 * sin(lat_radians)**2) | python | def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float:
"""
Compute normal radius of planetary body
Parameters
----------
lat_radians : float
latitude in radians
ell : Ellipsoid, optional
reference ellipsoid
Returns
-------
radius : float
normal radius (meters)
"""
if ell is None:
ell = Ellipsoid()
a = ell.a
b = ell.b
return a**2 / sqrt(a**2 * cos(lat_radians)**2 + b**2 * sin(lat_radians)**2) | [
"def",
"get_radius_normal",
"(",
"lat_radians",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
")",
"->",
"float",
":",
"if",
"ell",
"is",
"None",
":",
"ell",
"=",
"Ellipsoid",
"(",
")",
"a",
"=",
"ell",
".",
"a",
"b",
"=",
"ell",
".",
"b",
"return",
"a",
"**",
"2",
"/",
"sqrt",
"(",
"a",
"**",
"2",
"*",
"cos",
"(",
"lat_radians",
")",
"**",
"2",
"+",
"b",
"**",
"2",
"*",
"sin",
"(",
"lat_radians",
")",
"**",
"2",
")"
] | Compute normal radius of planetary body
Parameters
----------
lat_radians : float
latitude in radians
ell : Ellipsoid, optional
reference ellipsoid
Returns
-------
radius : float
normal radius (meters) | [
"Compute",
"normal",
"radius",
"of",
"planetary",
"body"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L70-L94 | train | 236,993 |
scivision/pymap3d | pymap3d/ecef.py | ecef2enuv | def ecef2enuv(u: float, v: float, w: float,
lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]:
"""
VECTOR from observer to target ECEF => ENU
Parameters
----------
u : float or numpy.ndarray of float
target x ECEF coordinate (meters)
v : float or numpy.ndarray of float
target y ECEF coordinate (meters)
w : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
uEast : float or numpy.ndarray of float
target east ENU coordinate (meters)
vNorth : float or numpy.ndarray of float
target north ENU coordinate (meters)
wUp : float or numpy.ndarray of float
target up ENU coordinate (meters)
"""
if deg:
lat0 = radians(lat0)
lon0 = radians(lon0)
t = cos(lon0) * u + sin(lon0) * v
uEast = -sin(lon0) * u + cos(lon0) * v
wUp = cos(lat0) * t + sin(lat0) * w
vNorth = -sin(lat0) * t + cos(lat0) * w
return uEast, vNorth, wUp | python | def ecef2enuv(u: float, v: float, w: float,
lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]:
"""
VECTOR from observer to target ECEF => ENU
Parameters
----------
u : float or numpy.ndarray of float
target x ECEF coordinate (meters)
v : float or numpy.ndarray of float
target y ECEF coordinate (meters)
w : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
uEast : float or numpy.ndarray of float
target east ENU coordinate (meters)
vNorth : float or numpy.ndarray of float
target north ENU coordinate (meters)
wUp : float or numpy.ndarray of float
target up ENU coordinate (meters)
"""
if deg:
lat0 = radians(lat0)
lon0 = radians(lon0)
t = cos(lon0) * u + sin(lon0) * v
uEast = -sin(lon0) * u + cos(lon0) * v
wUp = cos(lat0) * t + sin(lat0) * w
vNorth = -sin(lat0) * t + cos(lat0) * w
return uEast, vNorth, wUp | [
"def",
"ecef2enuv",
"(",
"u",
":",
"float",
",",
"v",
":",
"float",
",",
"w",
":",
"float",
",",
"lat0",
":",
"float",
",",
"lon0",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"if",
"deg",
":",
"lat0",
"=",
"radians",
"(",
"lat0",
")",
"lon0",
"=",
"radians",
"(",
"lon0",
")",
"t",
"=",
"cos",
"(",
"lon0",
")",
"*",
"u",
"+",
"sin",
"(",
"lon0",
")",
"*",
"v",
"uEast",
"=",
"-",
"sin",
"(",
"lon0",
")",
"*",
"u",
"+",
"cos",
"(",
"lon0",
")",
"*",
"v",
"wUp",
"=",
"cos",
"(",
"lat0",
")",
"*",
"t",
"+",
"sin",
"(",
"lat0",
")",
"*",
"w",
"vNorth",
"=",
"-",
"sin",
"(",
"lat0",
")",
"*",
"t",
"+",
"cos",
"(",
"lat0",
")",
"*",
"w",
"return",
"uEast",
",",
"vNorth",
",",
"wUp"
] | VECTOR from observer to target ECEF => ENU
Parameters
----------
u : float or numpy.ndarray of float
target x ECEF coordinate (meters)
v : float or numpy.ndarray of float
target y ECEF coordinate (meters)
w : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
uEast : float or numpy.ndarray of float
target east ENU coordinate (meters)
vNorth : float or numpy.ndarray of float
target north ENU coordinate (meters)
wUp : float or numpy.ndarray of float
target up ENU coordinate (meters) | [
"VECTOR",
"from",
"observer",
"to",
"target",
"ECEF",
"=",
">",
"ENU"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L233-L274 | train | 236,994 |
scivision/pymap3d | pymap3d/ecef.py | ecef2enu | def ecef2enu(x: float, y: float, z: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
from observer to target, ECEF => ENU
Parameters
----------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
East : float or numpy.ndarray of float
target east ENU coordinate (meters)
North : float or numpy.ndarray of float
target north ENU coordinate (meters)
Up : float or numpy.ndarray of float
target up ENU coordinate (meters)
"""
x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg)
return uvw2enu(x - x0, y - y0, z - z0, lat0, lon0, deg=deg) | python | def ecef2enu(x: float, y: float, z: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
from observer to target, ECEF => ENU
Parameters
----------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
East : float or numpy.ndarray of float
target east ENU coordinate (meters)
North : float or numpy.ndarray of float
target north ENU coordinate (meters)
Up : float or numpy.ndarray of float
target up ENU coordinate (meters)
"""
x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg)
return uvw2enu(x - x0, y - y0, z - z0, lat0, lon0, deg=deg) | [
"def",
"ecef2enu",
"(",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"z",
":",
"float",
",",
"lat0",
":",
"float",
",",
"lon0",
":",
"float",
",",
"h0",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"x0",
",",
"y0",
",",
"z0",
"=",
"geodetic2ecef",
"(",
"lat0",
",",
"lon0",
",",
"h0",
",",
"ell",
",",
"deg",
"=",
"deg",
")",
"return",
"uvw2enu",
"(",
"x",
"-",
"x0",
",",
"y",
"-",
"y0",
",",
"z",
"-",
"z0",
",",
"lat0",
",",
"lon0",
",",
"deg",
"=",
"deg",
")"
] | from observer to target, ECEF => ENU
Parameters
----------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Returns
-------
East : float or numpy.ndarray of float
target east ENU coordinate (meters)
North : float or numpy.ndarray of float
target north ENU coordinate (meters)
Up : float or numpy.ndarray of float
target up ENU coordinate (meters) | [
"from",
"observer",
"to",
"target",
"ECEF",
"=",
">",
"ENU"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L277-L314 | train | 236,995 |
scivision/pymap3d | pymap3d/ecef.py | eci2geodetic | def eci2geodetic(eci: np.ndarray, t: datetime,
useastropy: bool = True) -> Tuple[float, float, float]:
"""
convert ECI to geodetic coordinates
Parameters
----------
eci : tuple of float
[meters] Nx3 target ECI location (x,y,z)
t : datetime.datetime, float
length N vector of datetime OR greenwich sidereal time angle [radians].
Results
-------
lat : float
geodetic latitude
lon : float
geodetic longitude
alt : float
altitude above ellipsoid (meters)
Notes
-----
Conversion is idealized: doesn't consider nutations, perterbations,
etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions
from ECI to ECEF
eci2geodetic() a.k.a. eci2lla()
"""
ecef = np.atleast_2d(eci2ecef(eci, t, useastropy=useastropy))
return np.asarray(ecef2geodetic(ecef[:, 0], ecef[:, 1], ecef[:, 2])).squeeze() | python | def eci2geodetic(eci: np.ndarray, t: datetime,
useastropy: bool = True) -> Tuple[float, float, float]:
"""
convert ECI to geodetic coordinates
Parameters
----------
eci : tuple of float
[meters] Nx3 target ECI location (x,y,z)
t : datetime.datetime, float
length N vector of datetime OR greenwich sidereal time angle [radians].
Results
-------
lat : float
geodetic latitude
lon : float
geodetic longitude
alt : float
altitude above ellipsoid (meters)
Notes
-----
Conversion is idealized: doesn't consider nutations, perterbations,
etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions
from ECI to ECEF
eci2geodetic() a.k.a. eci2lla()
"""
ecef = np.atleast_2d(eci2ecef(eci, t, useastropy=useastropy))
return np.asarray(ecef2geodetic(ecef[:, 0], ecef[:, 1], ecef[:, 2])).squeeze() | [
"def",
"eci2geodetic",
"(",
"eci",
":",
"np",
".",
"ndarray",
",",
"t",
":",
"datetime",
",",
"useastropy",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"ecef",
"=",
"np",
".",
"atleast_2d",
"(",
"eci2ecef",
"(",
"eci",
",",
"t",
",",
"useastropy",
"=",
"useastropy",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"ecef2geodetic",
"(",
"ecef",
"[",
":",
",",
"0",
"]",
",",
"ecef",
"[",
":",
",",
"1",
"]",
",",
"ecef",
"[",
":",
",",
"2",
"]",
")",
")",
".",
"squeeze",
"(",
")"
] | convert ECI to geodetic coordinates
Parameters
----------
eci : tuple of float
[meters] Nx3 target ECI location (x,y,z)
t : datetime.datetime, float
length N vector of datetime OR greenwich sidereal time angle [radians].
Results
-------
lat : float
geodetic latitude
lon : float
geodetic longitude
alt : float
altitude above ellipsoid (meters)
Notes
-----
Conversion is idealized: doesn't consider nutations, perterbations,
etc. like the IAU-76/FK5 or IAU-2000/2006 model-based conversions
from ECI to ECEF
eci2geodetic() a.k.a. eci2lla() | [
"convert",
"ECI",
"to",
"geodetic",
"coordinates"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L384-L416 | train | 236,996 |
scivision/pymap3d | pymap3d/ecef.py | enu2ecef | def enu2ecef(e1: float, n1: float, u1: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
ENU to ECEF
Parameters
----------
e1 : float or numpy.ndarray of float
target east ENU coordinate (meters)
n1 : float or numpy.ndarray of float
target north ENU coordinate (meters)
u1 : float or numpy.ndarray of float
target up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters)
"""
x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg)
dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg)
return x0 + dx, y0 + dy, z0 + dz | python | def enu2ecef(e1: float, n1: float, u1: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
ENU to ECEF
Parameters
----------
e1 : float or numpy.ndarray of float
target east ENU coordinate (meters)
n1 : float or numpy.ndarray of float
target north ENU coordinate (meters)
u1 : float or numpy.ndarray of float
target up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters)
"""
x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg)
dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg)
return x0 + dx, y0 + dy, z0 + dz | [
"def",
"enu2ecef",
"(",
"e1",
":",
"float",
",",
"n1",
":",
"float",
",",
"u1",
":",
"float",
",",
"lat0",
":",
"float",
",",
"lon0",
":",
"float",
",",
"h0",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"x0",
",",
"y0",
",",
"z0",
"=",
"geodetic2ecef",
"(",
"lat0",
",",
"lon0",
",",
"h0",
",",
"ell",
",",
"deg",
"=",
"deg",
")",
"dx",
",",
"dy",
",",
"dz",
"=",
"enu2uvw",
"(",
"e1",
",",
"n1",
",",
"u1",
",",
"lat0",
",",
"lon0",
",",
"deg",
"=",
"deg",
")",
"return",
"x0",
"+",
"dx",
",",
"y0",
"+",
"dy",
",",
"z0",
"+",
"dz"
] | ENU to ECEF
Parameters
----------
e1 : float or numpy.ndarray of float
target east ENU coordinate (meters)
n1 : float or numpy.ndarray of float
target north ENU coordinate (meters)
u1 : float or numpy.ndarray of float
target up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : float or numpy.ndarray of float
target y ECEF coordinate (meters)
z : float or numpy.ndarray of float
target z ECEF coordinate (meters) | [
"ENU",
"to",
"ECEF"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ecef.py#L419-L458 | train | 236,997 |
scivision/pymap3d | pymap3d/ned.py | aer2ned | def aer2ned(az: float, elev: float, slantRange: float,
deg: bool = True) -> Tuple[float, float, float]:
"""
converts azimuth, elevation, range to target from observer to North, East, Down
Parameters
-----------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters)
"""
e, n, u = aer2enu(az, elev, slantRange, deg=deg)
return n, e, -u | python | def aer2ned(az: float, elev: float, slantRange: float,
deg: bool = True) -> Tuple[float, float, float]:
"""
converts azimuth, elevation, range to target from observer to North, East, Down
Parameters
-----------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters)
"""
e, n, u = aer2enu(az, elev, slantRange, deg=deg)
return n, e, -u | [
"def",
"aer2ned",
"(",
"az",
":",
"float",
",",
"elev",
":",
"float",
",",
"slantRange",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"e",
",",
"n",
",",
"u",
"=",
"aer2enu",
"(",
"az",
",",
"elev",
",",
"slantRange",
",",
"deg",
"=",
"deg",
")",
"return",
"n",
",",
"e",
",",
"-",
"u"
] | converts azimuth, elevation, range to target from observer to North, East, Down
Parameters
-----------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters]
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters) | [
"converts",
"azimuth",
"elevation",
"range",
"to",
"target",
"from",
"observer",
"to",
"North",
"East",
"Down"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L7-L35 | train | 236,998 |
scivision/pymap3d | pymap3d/ned.py | ned2aer | def ned2aer(n: float, e: float, d: float,
deg: bool = True) -> Tuple[float, float, float]:
"""
converts North, East, Down to azimuth, elevation, range
Parameters
----------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters]
"""
return enu2aer(e, n, -d, deg=deg) | python | def ned2aer(n: float, e: float, d: float,
deg: bool = True) -> Tuple[float, float, float]:
"""
converts North, East, Down to azimuth, elevation, range
Parameters
----------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters]
"""
return enu2aer(e, n, -d, deg=deg) | [
"def",
"ned2aer",
"(",
"n",
":",
"float",
",",
"e",
":",
"float",
",",
"d",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"return",
"enu2aer",
"(",
"e",
",",
"n",
",",
"-",
"d",
",",
"deg",
"=",
"deg",
")"
] | converts North, East, Down to azimuth, elevation, range
Parameters
----------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinate (meters)
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
az : float or numpy.ndarray of float
azimuth
elev : float or numpy.ndarray of float
elevation
slantRange : float or numpy.ndarray of float
slant range [meters] | [
"converts",
"North",
"East",
"Down",
"to",
"azimuth",
"elevation",
"range"
] | c9cf676594611cdb52ff7e0eca6388c80ed4f63f | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L38-L65 | train | 236,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.