repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
marcotcr/lime
lime/lime_base.py
LimeBase.explain_instance_with_data
def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, feature_selection='auto', model_regressor=None): """Takes perturbed data, labels and distances, returns explanation. Args: neighborhood_data: perturbed data, 2d array. first element is assumed to be the original data point. neighborhood_labels: corresponding perturbed labels. should have as many columns as the number of possible labels. distances: distances to original data point. label: label for which we want an explanation num_features: maximum number of features in explanation feature_selection: how to select num_features. options are: 'forward_selection': iteratively add features to the model. This is costly when num_features is high 'highest_weights': selects the features that have the highest product of absolute weight * original data point when learning with all the features 'lasso_path': chooses features based on the lasso regularization path 'none': uses all features, ignores num_features 'auto': uses forward_selection if num_features <= 6, and 'highest_weights' otherwise. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression if None. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: (intercept, exp, score, local_pred): intercept is a float. exp is a sorted list of tuples, where each tuple (x,y) corresponds to the feature id (x) and the local weight (y). The list is sorted by decreasing absolute value of y. score is the R^2 value of the returned explanation local_pred is the prediction of the explanation model on the original instance """ weights = self.kernel_fn(distances) labels_column = neighborhood_labels[:, label] used_features = self.feature_selection(neighborhood_data, labels_column, weights, num_features, feature_selection) if model_regressor is None: model_regressor = Ridge(alpha=1, fit_intercept=True, random_state=self.random_state) easy_model = model_regressor easy_model.fit(neighborhood_data[:, used_features], labels_column, sample_weight=weights) prediction_score = easy_model.score( neighborhood_data[:, used_features], labels_column, sample_weight=weights) local_pred = easy_model.predict(neighborhood_data[0, used_features].reshape(1, -1)) if self.verbose: print('Intercept', easy_model.intercept_) print('Prediction_local', local_pred,) print('Right:', neighborhood_labels[0, label]) return (easy_model.intercept_, sorted(zip(used_features, easy_model.coef_), key=lambda x: np.abs(x[1]), reverse=True), prediction_score, local_pred)
python
def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, feature_selection='auto', model_regressor=None): """Takes perturbed data, labels and distances, returns explanation. Args: neighborhood_data: perturbed data, 2d array. first element is assumed to be the original data point. neighborhood_labels: corresponding perturbed labels. should have as many columns as the number of possible labels. distances: distances to original data point. label: label for which we want an explanation num_features: maximum number of features in explanation feature_selection: how to select num_features. options are: 'forward_selection': iteratively add features to the model. This is costly when num_features is high 'highest_weights': selects the features that have the highest product of absolute weight * original data point when learning with all the features 'lasso_path': chooses features based on the lasso regularization path 'none': uses all features, ignores num_features 'auto': uses forward_selection if num_features <= 6, and 'highest_weights' otherwise. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression if None. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: (intercept, exp, score, local_pred): intercept is a float. exp is a sorted list of tuples, where each tuple (x,y) corresponds to the feature id (x) and the local weight (y). The list is sorted by decreasing absolute value of y. score is the R^2 value of the returned explanation local_pred is the prediction of the explanation model on the original instance """ weights = self.kernel_fn(distances) labels_column = neighborhood_labels[:, label] used_features = self.feature_selection(neighborhood_data, labels_column, weights, num_features, feature_selection) if model_regressor is None: model_regressor = Ridge(alpha=1, fit_intercept=True, random_state=self.random_state) easy_model = model_regressor easy_model.fit(neighborhood_data[:, used_features], labels_column, sample_weight=weights) prediction_score = easy_model.score( neighborhood_data[:, used_features], labels_column, sample_weight=weights) local_pred = easy_model.predict(neighborhood_data[0, used_features].reshape(1, -1)) if self.verbose: print('Intercept', easy_model.intercept_) print('Prediction_local', local_pred,) print('Right:', neighborhood_labels[0, label]) return (easy_model.intercept_, sorted(zip(used_features, easy_model.coef_), key=lambda x: np.abs(x[1]), reverse=True), prediction_score, local_pred)
[ "def", "explain_instance_with_data", "(", "self", ",", "neighborhood_data", ",", "neighborhood_labels", ",", "distances", ",", "label", ",", "num_features", ",", "feature_selection", "=", "'auto'", ",", "model_regressor", "=", "None", ")", ":", "weights", "=", "self", ".", "kernel_fn", "(", "distances", ")", "labels_column", "=", "neighborhood_labels", "[", ":", ",", "label", "]", "used_features", "=", "self", ".", "feature_selection", "(", "neighborhood_data", ",", "labels_column", ",", "weights", ",", "num_features", ",", "feature_selection", ")", "if", "model_regressor", "is", "None", ":", "model_regressor", "=", "Ridge", "(", "alpha", "=", "1", ",", "fit_intercept", "=", "True", ",", "random_state", "=", "self", ".", "random_state", ")", "easy_model", "=", "model_regressor", "easy_model", ".", "fit", "(", "neighborhood_data", "[", ":", ",", "used_features", "]", ",", "labels_column", ",", "sample_weight", "=", "weights", ")", "prediction_score", "=", "easy_model", ".", "score", "(", "neighborhood_data", "[", ":", ",", "used_features", "]", ",", "labels_column", ",", "sample_weight", "=", "weights", ")", "local_pred", "=", "easy_model", ".", "predict", "(", "neighborhood_data", "[", "0", ",", "used_features", "]", ".", "reshape", "(", "1", ",", "-", "1", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "'Intercept'", ",", "easy_model", ".", "intercept_", ")", "print", "(", "'Prediction_local'", ",", "local_pred", ",", ")", "print", "(", "'Right:'", ",", "neighborhood_labels", "[", "0", ",", "label", "]", ")", "return", "(", "easy_model", ".", "intercept_", ",", "sorted", "(", "zip", "(", "used_features", ",", "easy_model", ".", "coef_", ")", ",", "key", "=", "lambda", "x", ":", "np", ".", "abs", "(", "x", "[", "1", "]", ")", ",", "reverse", "=", "True", ")", ",", "prediction_score", ",", "local_pred", ")" ]
Takes perturbed data, labels and distances, returns explanation. Args: neighborhood_data: perturbed data, 2d array. first element is assumed to be the original data point. neighborhood_labels: corresponding perturbed labels. should have as many columns as the number of possible labels. distances: distances to original data point. label: label for which we want an explanation num_features: maximum number of features in explanation feature_selection: how to select num_features. options are: 'forward_selection': iteratively add features to the model. This is costly when num_features is high 'highest_weights': selects the features that have the highest product of absolute weight * original data point when learning with all the features 'lasso_path': chooses features based on the lasso regularization path 'none': uses all features, ignores num_features 'auto': uses forward_selection if num_features <= 6, and 'highest_weights' otherwise. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression if None. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: (intercept, exp, score, local_pred): intercept is a float. exp is a sorted list of tuples, where each tuple (x,y) corresponds to the feature id (x) and the local weight (y). The list is sorted by decreasing absolute value of y. score is the R^2 value of the returned explanation local_pred is the prediction of the explanation model on the original instance
[ "Takes", "perturbed", "data", "labels", "and", "distances", "returns", "explanation", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L108-L179
train
marcotcr/lime
lime/explanation.py
id_generator
def id_generator(size=15, random_state=None): """Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.""" chars = list(string.ascii_uppercase + string.digits) return ''.join(random_state.choice(chars, size, replace=True))
python
def id_generator(size=15, random_state=None): """Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.""" chars = list(string.ascii_uppercase + string.digits) return ''.join(random_state.choice(chars, size, replace=True))
[ "def", "id_generator", "(", "size", "=", "15", ",", "random_state", "=", "None", ")", ":", "chars", "=", "list", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "return", "''", ".", "join", "(", "random_state", ".", "choice", "(", "chars", ",", "size", ",", "replace", "=", "True", ")", ")" ]
Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.
[ "Helper", "function", "to", "generate", "random", "div", "ids", ".", "This", "is", "useful", "for", "embedding", "HTML", "into", "ipython", "notebooks", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L17-L21
train
marcotcr/lime
lime/explanation.py
Explanation.available_labels
def available_labels(self): """ Returns the list of classification labels for which we have any explanations. """ try: assert self.mode == "classification" except AssertionError: raise NotImplementedError('Not supported for regression explanations.') else: ans = self.top_labels if self.top_labels else self.local_exp.keys() return list(ans)
python
def available_labels(self): """ Returns the list of classification labels for which we have any explanations. """ try: assert self.mode == "classification" except AssertionError: raise NotImplementedError('Not supported for regression explanations.') else: ans = self.top_labels if self.top_labels else self.local_exp.keys() return list(ans)
[ "def", "available_labels", "(", "self", ")", ":", "try", ":", "assert", "self", ".", "mode", "==", "\"classification\"", "except", "AssertionError", ":", "raise", "NotImplementedError", "(", "'Not supported for regression explanations.'", ")", "else", ":", "ans", "=", "self", ".", "top_labels", "if", "self", ".", "top_labels", "else", "self", ".", "local_exp", ".", "keys", "(", ")", "return", "list", "(", "ans", ")" ]
Returns the list of classification labels for which we have any explanations.
[ "Returns", "the", "list", "of", "classification", "labels", "for", "which", "we", "have", "any", "explanations", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L117-L127
train
marcotcr/lime
lime/explanation.py
Explanation.as_list
def as_list(self, label=1, **kwargs): """Returns the explanation as a list. Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: list of tuples (representation, weight), where representation is given by domain_mapper. Weight is a float. """ label_to_use = label if self.mode == "classification" else self.dummy_label ans = self.domain_mapper.map_exp_ids(self.local_exp[label_to_use], **kwargs) ans = [(x[0], float(x[1])) for x in ans] return ans
python
def as_list(self, label=1, **kwargs): """Returns the explanation as a list. Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: list of tuples (representation, weight), where representation is given by domain_mapper. Weight is a float. """ label_to_use = label if self.mode == "classification" else self.dummy_label ans = self.domain_mapper.map_exp_ids(self.local_exp[label_to_use], **kwargs) ans = [(x[0], float(x[1])) for x in ans] return ans
[ "def", "as_list", "(", "self", ",", "label", "=", "1", ",", "*", "*", "kwargs", ")", ":", "label_to_use", "=", "label", "if", "self", ".", "mode", "==", "\"classification\"", "else", "self", ".", "dummy_label", "ans", "=", "self", ".", "domain_mapper", ".", "map_exp_ids", "(", "self", ".", "local_exp", "[", "label_to_use", "]", ",", "*", "*", "kwargs", ")", "ans", "=", "[", "(", "x", "[", "0", "]", ",", "float", "(", "x", "[", "1", "]", ")", ")", "for", "x", "in", "ans", "]", "return", "ans" ]
Returns the explanation as a list. Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: list of tuples (representation, weight), where representation is given by domain_mapper. Weight is a float.
[ "Returns", "the", "explanation", "as", "a", "list", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L129-L145
train
marcotcr/lime
lime/explanation.py
Explanation.as_pyplot_figure
def as_pyplot_figure(self, label=1, **kwargs): """Returns the explanation as a pyplot figure. Will throw an error if you don't have matplotlib installed Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: pyplot figure (barchart). """ import matplotlib.pyplot as plt exp = self.as_list(label=label, **kwargs) fig = plt.figure() vals = [x[1] for x in exp] names = [x[0] for x in exp] vals.reverse() names.reverse() colors = ['green' if x > 0 else 'red' for x in vals] pos = np.arange(len(exp)) + .5 plt.barh(pos, vals, align='center', color=colors) plt.yticks(pos, names) if self.mode == "classification": title = 'Local explanation for class %s' % self.class_names[label] else: title = 'Local explanation' plt.title(title) return fig
python
def as_pyplot_figure(self, label=1, **kwargs): """Returns the explanation as a pyplot figure. Will throw an error if you don't have matplotlib installed Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: pyplot figure (barchart). """ import matplotlib.pyplot as plt exp = self.as_list(label=label, **kwargs) fig = plt.figure() vals = [x[1] for x in exp] names = [x[0] for x in exp] vals.reverse() names.reverse() colors = ['green' if x > 0 else 'red' for x in vals] pos = np.arange(len(exp)) + .5 plt.barh(pos, vals, align='center', color=colors) plt.yticks(pos, names) if self.mode == "classification": title = 'Local explanation for class %s' % self.class_names[label] else: title = 'Local explanation' plt.title(title) return fig
[ "def", "as_pyplot_figure", "(", "self", ",", "label", "=", "1", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "exp", "=", "self", ".", "as_list", "(", "label", "=", "label", ",", "*", "*", "kwargs", ")", "fig", "=", "plt", ".", "figure", "(", ")", "vals", "=", "[", "x", "[", "1", "]", "for", "x", "in", "exp", "]", "names", "=", "[", "x", "[", "0", "]", "for", "x", "in", "exp", "]", "vals", ".", "reverse", "(", ")", "names", ".", "reverse", "(", ")", "colors", "=", "[", "'green'", "if", "x", ">", "0", "else", "'red'", "for", "x", "in", "vals", "]", "pos", "=", "np", ".", "arange", "(", "len", "(", "exp", ")", ")", "+", ".5", "plt", ".", "barh", "(", "pos", ",", "vals", ",", "align", "=", "'center'", ",", "color", "=", "colors", ")", "plt", ".", "yticks", "(", "pos", ",", "names", ")", "if", "self", ".", "mode", "==", "\"classification\"", ":", "title", "=", "'Local explanation for class %s'", "%", "self", ".", "class_names", "[", "label", "]", "else", ":", "title", "=", "'Local explanation'", "plt", ".", "title", "(", "title", ")", "return", "fig" ]
Returns the explanation as a pyplot figure. Will throw an error if you don't have matplotlib installed Args: label: desired label. If you ask for a label for which an explanation wasn't computed, will throw an exception. Will be ignored for regression explanations. kwargs: keyword arguments, passed to domain_mapper Returns: pyplot figure (barchart).
[ "Returns", "the", "explanation", "as", "a", "pyplot", "figure", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L155-L184
train
marcotcr/lime
lime/explanation.py
Explanation.show_in_notebook
def show_in_notebook(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an error if you don't have IPython installed""" from IPython.core.display import display, HTML display(HTML(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)))
python
def show_in_notebook(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an error if you don't have IPython installed""" from IPython.core.display import display, HTML display(HTML(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)))
[ "def", "show_in_notebook", "(", "self", ",", "labels", "=", "None", ",", "predict_proba", "=", "True", ",", "show_predicted_value", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "core", ".", "display", "import", "display", ",", "HTML", "display", "(", "HTML", "(", "self", ".", "as_html", "(", "labels", "=", "labels", ",", "predict_proba", "=", "predict_proba", ",", "show_predicted_value", "=", "show_predicted_value", ",", "*", "*", "kwargs", ")", ")", ")" ]
Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an error if you don't have IPython installed
[ "Shows", "html", "explanation", "in", "ipython", "notebook", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L186-L200
train
marcotcr/lime
lime/explanation.py
Explanation.save_to_file
def save_to_file(self, file_path, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters. """ file_ = open(file_path, 'w', encoding='utf8') file_.write(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)) file_.close()
python
def save_to_file(self, file_path, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters. """ file_ = open(file_path, 'w', encoding='utf8') file_.write(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)) file_.close()
[ "def", "save_to_file", "(", "self", ",", "file_path", ",", "labels", "=", "None", ",", "predict_proba", "=", "True", ",", "show_predicted_value", "=", "True", ",", "*", "*", "kwargs", ")", ":", "file_", "=", "open", "(", "file_path", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "file_", ".", "write", "(", "self", ".", "as_html", "(", "labels", "=", "labels", ",", "predict_proba", "=", "predict_proba", ",", "show_predicted_value", "=", "show_predicted_value", ",", "*", "*", "kwargs", ")", ")", "file_", ".", "close", "(", ")" ]
Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters.
[ "Saves", "html", "explanation", "to", "file", ".", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L202-L221
train
marcotcr/lime
lime/explanation.py
Explanation.as_html
def as_html(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you ask for a label for which an explanation wasn't computed, will throw an exception. If None, will show explanations for all available labels. (only used for classification) predict_proba: if true, add barchart with prediction probabilities for the top classes. (only used for classification) show_predicted_value: if true, add barchart with expected value (only used for regression) kwargs: keyword arguments, passed to domain_mapper Returns: code for an html page, including javascript includes. """ def jsonize(x): return json.dumps(x, ensure_ascii=False) if labels is None and self.mode == "classification": labels = self.available_labels() this_dir, _ = os.path.split(__file__) bundle = open(os.path.join(this_dir, 'bundle.js'), encoding="utf8").read() out = u'''<html> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head><script>%s </script></head><body>''' % bundle random_id = id_generator(size=15, random_state=check_random_state(self.random_state)) out += u''' <div class="lime top_div" id="top_div%s"></div> ''' % random_id predict_proba_js = '' if self.mode == "classification" and predict_proba: predict_proba_js = u''' var pp_div = top_div.append('div') .classed('lime predict_proba', true); var pp_svg = pp_div.append('svg').style('width', '100%%'); var pp = new lime.PredictProba(pp_svg, %s, %s); ''' % (jsonize([str(x) for x in self.class_names]), jsonize(list(self.predict_proba.astype(float)))) predict_value_js = '' if self.mode == "regression" and show_predicted_value: # reference self.predicted_value # (svg, predicted_value, min_value, max_value) predict_value_js = u''' var pp_div = top_div.append('div') .classed('lime predicted_value', true); var pp_svg = pp_div.append('svg').style('width', '100%%'); var pp = new lime.PredictedValue(pp_svg, %s, %s, %s); ''' % (jsonize(float(self.predicted_value)), jsonize(float(self.min_value)), jsonize(float(self.max_value))) exp_js = '''var exp_div; var exp = new lime.Explanation(%s); ''' % (jsonize([str(x) for x in self.class_names])) if self.mode == "classification": for label in labels: exp = jsonize(self.as_list(label)) exp_js += u''' exp_div = top_div.append('div').classed('lime explanation', true); exp.show(%s, %d, exp_div); ''' % (exp, label) else: exp = jsonize(self.as_list()) exp_js += u''' exp_div = top_div.append('div').classed('lime explanation', true); exp.show(%s, %s, exp_div); ''' % (exp, self.dummy_label) raw_js = '''var raw_div = top_div.append('div');''' if self.mode == "classification": html_data = self.local_exp[labels[0]] else: html_data = self.local_exp[self.dummy_label] raw_js += self.domain_mapper.visualize_instance_html( html_data, labels[0] if self.mode == "classification" else self.dummy_label, 'raw_div', 'exp', **kwargs) out += u''' <script> var top_div = d3.select('#top_div%s').classed('lime top_div', true); %s %s %s %s </script> ''' % (random_id, predict_proba_js, predict_value_js, exp_js, raw_js) out += u'</body></html>' return out
python
def as_html(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you ask for a label for which an explanation wasn't computed, will throw an exception. If None, will show explanations for all available labels. (only used for classification) predict_proba: if true, add barchart with prediction probabilities for the top classes. (only used for classification) show_predicted_value: if true, add barchart with expected value (only used for regression) kwargs: keyword arguments, passed to domain_mapper Returns: code for an html page, including javascript includes. """ def jsonize(x): return json.dumps(x, ensure_ascii=False) if labels is None and self.mode == "classification": labels = self.available_labels() this_dir, _ = os.path.split(__file__) bundle = open(os.path.join(this_dir, 'bundle.js'), encoding="utf8").read() out = u'''<html> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head><script>%s </script></head><body>''' % bundle random_id = id_generator(size=15, random_state=check_random_state(self.random_state)) out += u''' <div class="lime top_div" id="top_div%s"></div> ''' % random_id predict_proba_js = '' if self.mode == "classification" and predict_proba: predict_proba_js = u''' var pp_div = top_div.append('div') .classed('lime predict_proba', true); var pp_svg = pp_div.append('svg').style('width', '100%%'); var pp = new lime.PredictProba(pp_svg, %s, %s); ''' % (jsonize([str(x) for x in self.class_names]), jsonize(list(self.predict_proba.astype(float)))) predict_value_js = '' if self.mode == "regression" and show_predicted_value: # reference self.predicted_value # (svg, predicted_value, min_value, max_value) predict_value_js = u''' var pp_div = top_div.append('div') .classed('lime predicted_value', true); var pp_svg = pp_div.append('svg').style('width', '100%%'); var pp = new lime.PredictedValue(pp_svg, %s, %s, %s); ''' % (jsonize(float(self.predicted_value)), jsonize(float(self.min_value)), jsonize(float(self.max_value))) exp_js = '''var exp_div; var exp = new lime.Explanation(%s); ''' % (jsonize([str(x) for x in self.class_names])) if self.mode == "classification": for label in labels: exp = jsonize(self.as_list(label)) exp_js += u''' exp_div = top_div.append('div').classed('lime explanation', true); exp.show(%s, %d, exp_div); ''' % (exp, label) else: exp = jsonize(self.as_list()) exp_js += u''' exp_div = top_div.append('div').classed('lime explanation', true); exp.show(%s, %s, exp_div); ''' % (exp, self.dummy_label) raw_js = '''var raw_div = top_div.append('div');''' if self.mode == "classification": html_data = self.local_exp[labels[0]] else: html_data = self.local_exp[self.dummy_label] raw_js += self.domain_mapper.visualize_instance_html( html_data, labels[0] if self.mode == "classification" else self.dummy_label, 'raw_div', 'exp', **kwargs) out += u''' <script> var top_div = d3.select('#top_div%s').classed('lime top_div', true); %s %s %s %s </script> ''' % (random_id, predict_proba_js, predict_value_js, exp_js, raw_js) out += u'</body></html>' return out
[ "def", "as_html", "(", "self", ",", "labels", "=", "None", ",", "predict_proba", "=", "True", ",", "show_predicted_value", "=", "True", ",", "*", "*", "kwargs", ")", ":", "def", "jsonize", "(", "x", ")", ":", "return", "json", ".", "dumps", "(", "x", ",", "ensure_ascii", "=", "False", ")", "if", "labels", "is", "None", "and", "self", ".", "mode", "==", "\"classification\"", ":", "labels", "=", "self", ".", "available_labels", "(", ")", "this_dir", ",", "_", "=", "os", ".", "path", ".", "split", "(", "__file__", ")", "bundle", "=", "open", "(", "os", ".", "path", ".", "join", "(", "this_dir", ",", "'bundle.js'", ")", ",", "encoding", "=", "\"utf8\"", ")", ".", "read", "(", ")", "out", "=", "u'''<html>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n <head><script>%s </script></head><body>'''", "%", "bundle", "random_id", "=", "id_generator", "(", "size", "=", "15", ",", "random_state", "=", "check_random_state", "(", "self", ".", "random_state", ")", ")", "out", "+=", "u'''\n <div class=\"lime top_div\" id=\"top_div%s\"></div>\n '''", "%", "random_id", "predict_proba_js", "=", "''", "if", "self", ".", "mode", "==", "\"classification\"", "and", "predict_proba", ":", "predict_proba_js", "=", "u'''\n var pp_div = top_div.append('div')\n .classed('lime predict_proba', true);\n var pp_svg = pp_div.append('svg').style('width', '100%%');\n var pp = new lime.PredictProba(pp_svg, %s, %s);\n '''", "%", "(", "jsonize", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "class_names", "]", ")", ",", "jsonize", "(", "list", "(", "self", ".", "predict_proba", ".", "astype", "(", "float", ")", ")", ")", ")", "predict_value_js", "=", "''", "if", "self", ".", "mode", "==", "\"regression\"", "and", "show_predicted_value", ":", "# reference self.predicted_value", "# (svg, predicted_value, min_value, max_value)", "predict_value_js", "=", "u'''\n var pp_div = top_div.append('div')\n .classed('lime predicted_value', true);\n var pp_svg = pp_div.append('svg').style('width', '100%%');\n var pp = new lime.PredictedValue(pp_svg, %s, %s, %s);\n '''", "%", "(", "jsonize", "(", "float", "(", "self", ".", "predicted_value", ")", ")", ",", "jsonize", "(", "float", "(", "self", ".", "min_value", ")", ")", ",", "jsonize", "(", "float", "(", "self", ".", "max_value", ")", ")", ")", "exp_js", "=", "'''var exp_div;\n var exp = new lime.Explanation(%s);\n '''", "%", "(", "jsonize", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "class_names", "]", ")", ")", "if", "self", ".", "mode", "==", "\"classification\"", ":", "for", "label", "in", "labels", ":", "exp", "=", "jsonize", "(", "self", ".", "as_list", "(", "label", ")", ")", "exp_js", "+=", "u'''\n exp_div = top_div.append('div').classed('lime explanation', true);\n exp.show(%s, %d, exp_div);\n '''", "%", "(", "exp", ",", "label", ")", "else", ":", "exp", "=", "jsonize", "(", "self", ".", "as_list", "(", ")", ")", "exp_js", "+=", "u'''\n exp_div = top_div.append('div').classed('lime explanation', true);\n exp.show(%s, %s, exp_div);\n '''", "%", "(", "exp", ",", "self", ".", "dummy_label", ")", "raw_js", "=", "'''var raw_div = top_div.append('div');'''", "if", "self", ".", "mode", "==", "\"classification\"", ":", "html_data", "=", "self", ".", "local_exp", "[", "labels", "[", "0", "]", "]", "else", ":", "html_data", "=", "self", ".", "local_exp", "[", "self", ".", "dummy_label", "]", "raw_js", "+=", "self", ".", "domain_mapper", ".", "visualize_instance_html", "(", "html_data", ",", "labels", "[", "0", "]", "if", "self", ".", "mode", "==", "\"classification\"", "else", "self", ".", "dummy_label", ",", "'raw_div'", ",", "'exp'", ",", "*", "*", "kwargs", ")", "out", "+=", "u'''\n <script>\n var top_div = d3.select('#top_div%s').classed('lime top_div', true);\n %s\n %s\n %s\n %s\n </script>\n '''", "%", "(", "random_id", ",", "predict_proba_js", ",", "predict_value_js", ",", "exp_js", ",", "raw_js", ")", "out", "+=", "u'</body></html>'", "return", "out" ]
Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you ask for a label for which an explanation wasn't computed, will throw an exception. If None, will show explanations for all available labels. (only used for classification) predict_proba: if true, add barchart with prediction probabilities for the top classes. (only used for classification) show_predicted_value: if true, add barchart with expected value (only used for regression) kwargs: keyword arguments, passed to domain_mapper Returns: code for an html page, including javascript includes.
[ "Returns", "the", "explanation", "as", "an", "html", "page", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L223-L328
train
marcotcr/lime
lime/wrappers/scikit_image.py
BaseWrapper._check_params
def _check_params(self, parameters): """Checks for mistakes in 'parameters' Args : parameters: dict, parameters to be checked Raises : ValueError: if any parameter is not a valid argument for the target function or the target function is not defined TypeError: if argument parameters is not iterable """ a_valid_fn = [] if self.target_fn is None: if callable(self): a_valid_fn.append(self.__call__) else: raise TypeError('invalid argument: tested object is not callable,\ please provide a valid target_fn') elif isinstance(self.target_fn, types.FunctionType) \ or isinstance(self.target_fn, types.MethodType): a_valid_fn.append(self.target_fn) else: a_valid_fn.append(self.target_fn.__call__) if not isinstance(parameters, str): for p in parameters: for fn in a_valid_fn: if has_arg(fn, p): pass else: raise ValueError('{} is not a valid parameter'.format(p)) else: raise TypeError('invalid argument: list or dictionnary expected')
python
def _check_params(self, parameters): """Checks for mistakes in 'parameters' Args : parameters: dict, parameters to be checked Raises : ValueError: if any parameter is not a valid argument for the target function or the target function is not defined TypeError: if argument parameters is not iterable """ a_valid_fn = [] if self.target_fn is None: if callable(self): a_valid_fn.append(self.__call__) else: raise TypeError('invalid argument: tested object is not callable,\ please provide a valid target_fn') elif isinstance(self.target_fn, types.FunctionType) \ or isinstance(self.target_fn, types.MethodType): a_valid_fn.append(self.target_fn) else: a_valid_fn.append(self.target_fn.__call__) if not isinstance(parameters, str): for p in parameters: for fn in a_valid_fn: if has_arg(fn, p): pass else: raise ValueError('{} is not a valid parameter'.format(p)) else: raise TypeError('invalid argument: list or dictionnary expected')
[ "def", "_check_params", "(", "self", ",", "parameters", ")", ":", "a_valid_fn", "=", "[", "]", "if", "self", ".", "target_fn", "is", "None", ":", "if", "callable", "(", "self", ")", ":", "a_valid_fn", ".", "append", "(", "self", ".", "__call__", ")", "else", ":", "raise", "TypeError", "(", "'invalid argument: tested object is not callable,\\\n please provide a valid target_fn'", ")", "elif", "isinstance", "(", "self", ".", "target_fn", ",", "types", ".", "FunctionType", ")", "or", "isinstance", "(", "self", ".", "target_fn", ",", "types", ".", "MethodType", ")", ":", "a_valid_fn", ".", "append", "(", "self", ".", "target_fn", ")", "else", ":", "a_valid_fn", ".", "append", "(", "self", ".", "target_fn", ".", "__call__", ")", "if", "not", "isinstance", "(", "parameters", ",", "str", ")", ":", "for", "p", "in", "parameters", ":", "for", "fn", "in", "a_valid_fn", ":", "if", "has_arg", "(", "fn", ",", "p", ")", ":", "pass", "else", ":", "raise", "ValueError", "(", "'{} is not a valid parameter'", ".", "format", "(", "p", ")", ")", "else", ":", "raise", "TypeError", "(", "'invalid argument: list or dictionnary expected'", ")" ]
Checks for mistakes in 'parameters' Args : parameters: dict, parameters to be checked Raises : ValueError: if any parameter is not a valid argument for the target function or the target function is not defined TypeError: if argument parameters is not iterable
[ "Checks", "for", "mistakes", "in", "parameters" ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/wrappers/scikit_image.py#L26-L58
train
marcotcr/lime
lime/wrappers/scikit_image.py
BaseWrapper.filter_params
def filter_params(self, fn, override=None): """Filters `target_params` and return those in `fn`'s arguments. Args: fn : arbitrary function override: dict, values to override target_params Returns: result : dict, dictionary containing variables in both target_params and fn's arguments. """ override = override or {} result = {} for name, value in self.target_params.items(): if has_arg(fn, name): result.update({name: value}) result.update(override) return result
python
def filter_params(self, fn, override=None): """Filters `target_params` and return those in `fn`'s arguments. Args: fn : arbitrary function override: dict, values to override target_params Returns: result : dict, dictionary containing variables in both target_params and fn's arguments. """ override = override or {} result = {} for name, value in self.target_params.items(): if has_arg(fn, name): result.update({name: value}) result.update(override) return result
[ "def", "filter_params", "(", "self", ",", "fn", ",", "override", "=", "None", ")", ":", "override", "=", "override", "or", "{", "}", "result", "=", "{", "}", "for", "name", ",", "value", "in", "self", ".", "target_params", ".", "items", "(", ")", ":", "if", "has_arg", "(", "fn", ",", "name", ")", ":", "result", ".", "update", "(", "{", "name", ":", "value", "}", ")", "result", ".", "update", "(", "override", ")", "return", "result" ]
Filters `target_params` and return those in `fn`'s arguments. Args: fn : arbitrary function override: dict, values to override target_params Returns: result : dict, dictionary containing variables in both target_params and fn's arguments.
[ "Filters", "target_params", "and", "return", "those", "in", "fn", "s", "arguments", ".", "Args", ":", "fn", ":", "arbitrary", "function", "override", ":", "dict", "values", "to", "override", "target_params", "Returns", ":", "result", ":", "dict", "dictionary", "containing", "variables", "in", "both", "target_params", "and", "fn", "s", "arguments", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/wrappers/scikit_image.py#L72-L87
train
marcotcr/lime
lime/lime_text.py
TextDomainMapper.map_exp_ids
def map_exp_ids(self, exp, positions=False): """Maps ids to words or word-position strings. Args: exp: list of tuples [(id, weight), (id,weight)] positions: if True, also return word positions Returns: list of tuples (word, weight), or (word_positions, weight) if examples: ('bad', 1) or ('bad_3-6-12', 1) """ if positions: exp = [('%s_%s' % ( self.indexed_string.word(x[0]), '-'.join( map(str, self.indexed_string.string_position(x[0])))), x[1]) for x in exp] else: exp = [(self.indexed_string.word(x[0]), x[1]) for x in exp] return exp
python
def map_exp_ids(self, exp, positions=False): """Maps ids to words or word-position strings. Args: exp: list of tuples [(id, weight), (id,weight)] positions: if True, also return word positions Returns: list of tuples (word, weight), or (word_positions, weight) if examples: ('bad', 1) or ('bad_3-6-12', 1) """ if positions: exp = [('%s_%s' % ( self.indexed_string.word(x[0]), '-'.join( map(str, self.indexed_string.string_position(x[0])))), x[1]) for x in exp] else: exp = [(self.indexed_string.word(x[0]), x[1]) for x in exp] return exp
[ "def", "map_exp_ids", "(", "self", ",", "exp", ",", "positions", "=", "False", ")", ":", "if", "positions", ":", "exp", "=", "[", "(", "'%s_%s'", "%", "(", "self", ".", "indexed_string", ".", "word", "(", "x", "[", "0", "]", ")", ",", "'-'", ".", "join", "(", "map", "(", "str", ",", "self", ".", "indexed_string", ".", "string_position", "(", "x", "[", "0", "]", ")", ")", ")", ")", ",", "x", "[", "1", "]", ")", "for", "x", "in", "exp", "]", "else", ":", "exp", "=", "[", "(", "self", ".", "indexed_string", ".", "word", "(", "x", "[", "0", "]", ")", ",", "x", "[", "1", "]", ")", "for", "x", "in", "exp", "]", "return", "exp" ]
Maps ids to words or word-position strings. Args: exp: list of tuples [(id, weight), (id,weight)] positions: if True, also return word positions Returns: list of tuples (word, weight), or (word_positions, weight) if examples: ('bad', 1) or ('bad_3-6-12', 1)
[ "Maps", "ids", "to", "words", "or", "word", "-", "position", "strings", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L31-L51
train
marcotcr/lime
lime/lime_text.py
TextDomainMapper.visualize_instance_html
def visualize_instance_html(self, exp, label, div_name, exp_object_name, text=True, opacity=True): """Adds text with highlighted words to visualization. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object text: if False, return empty opacity: if True, fade colors according to weight """ if not text: return u'' text = (self.indexed_string.raw_string() .encode('utf-8', 'xmlcharrefreplace').decode('utf-8')) text = re.sub(r'[<>&]', '|', text) exp = [(self.indexed_string.word(x[0]), self.indexed_string.string_position(x[0]), x[1]) for x in exp] all_occurrences = list(itertools.chain.from_iterable( [itertools.product([x[0]], x[1], [x[2]]) for x in exp])) all_occurrences = [(x[0], int(x[1]), x[2]) for x in all_occurrences] ret = ''' %s.show_raw_text(%s, %d, %s, %s, %s); ''' % (exp_object_name, json.dumps(all_occurrences), label, json.dumps(text), div_name, json.dumps(opacity)) return ret
python
def visualize_instance_html(self, exp, label, div_name, exp_object_name, text=True, opacity=True): """Adds text with highlighted words to visualization. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object text: if False, return empty opacity: if True, fade colors according to weight """ if not text: return u'' text = (self.indexed_string.raw_string() .encode('utf-8', 'xmlcharrefreplace').decode('utf-8')) text = re.sub(r'[<>&]', '|', text) exp = [(self.indexed_string.word(x[0]), self.indexed_string.string_position(x[0]), x[1]) for x in exp] all_occurrences = list(itertools.chain.from_iterable( [itertools.product([x[0]], x[1], [x[2]]) for x in exp])) all_occurrences = [(x[0], int(x[1]), x[2]) for x in all_occurrences] ret = ''' %s.show_raw_text(%s, %d, %s, %s, %s); ''' % (exp_object_name, json.dumps(all_occurrences), label, json.dumps(text), div_name, json.dumps(opacity)) return ret
[ "def", "visualize_instance_html", "(", "self", ",", "exp", ",", "label", ",", "div_name", ",", "exp_object_name", ",", "text", "=", "True", ",", "opacity", "=", "True", ")", ":", "if", "not", "text", ":", "return", "u''", "text", "=", "(", "self", ".", "indexed_string", ".", "raw_string", "(", ")", ".", "encode", "(", "'utf-8'", ",", "'xmlcharrefreplace'", ")", ".", "decode", "(", "'utf-8'", ")", ")", "text", "=", "re", ".", "sub", "(", "r'[<>&]'", ",", "'|'", ",", "text", ")", "exp", "=", "[", "(", "self", ".", "indexed_string", ".", "word", "(", "x", "[", "0", "]", ")", ",", "self", ".", "indexed_string", ".", "string_position", "(", "x", "[", "0", "]", ")", ",", "x", "[", "1", "]", ")", "for", "x", "in", "exp", "]", "all_occurrences", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "itertools", ".", "product", "(", "[", "x", "[", "0", "]", "]", ",", "x", "[", "1", "]", ",", "[", "x", "[", "2", "]", "]", ")", "for", "x", "in", "exp", "]", ")", ")", "all_occurrences", "=", "[", "(", "x", "[", "0", "]", ",", "int", "(", "x", "[", "1", "]", ")", ",", "x", "[", "2", "]", ")", "for", "x", "in", "all_occurrences", "]", "ret", "=", "'''\n %s.show_raw_text(%s, %d, %s, %s, %s);\n '''", "%", "(", "exp_object_name", ",", "json", ".", "dumps", "(", "all_occurrences", ")", ",", "label", ",", "json", ".", "dumps", "(", "text", ")", ",", "div_name", ",", "json", ".", "dumps", "(", "opacity", ")", ")", "return", "ret" ]
Adds text with highlighted words to visualization. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object text: if False, return empty opacity: if True, fade colors according to weight
[ "Adds", "text", "with", "highlighted", "words", "to", "visualization", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L53-L80
train
marcotcr/lime
lime/lime_text.py
IndexedString.string_position
def string_position(self, id_): """Returns a np array with indices to id_ (int) occurrences""" if self.bow: return self.string_start[self.positions[id_]] else: return self.string_start[[self.positions[id_]]]
python
def string_position(self, id_): """Returns a np array with indices to id_ (int) occurrences""" if self.bow: return self.string_start[self.positions[id_]] else: return self.string_start[[self.positions[id_]]]
[ "def", "string_position", "(", "self", ",", "id_", ")", ":", "if", "self", ".", "bow", ":", "return", "self", ".", "string_start", "[", "self", ".", "positions", "[", "id_", "]", "]", "else", ":", "return", "self", ".", "string_start", "[", "[", "self", ".", "positions", "[", "id_", "]", "]", "]" ]
Returns a np array with indices to id_ (int) occurrences
[ "Returns", "a", "np", "array", "with", "indices", "to", "id_", "(", "int", ")", "occurrences" ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L155-L160
train
marcotcr/lime
lime/lime_text.py
IndexedString.inverse_removing
def inverse_removing(self, words_to_remove): """Returns a string after removing the appropriate words. If self.bow is false, replaces word with UNKWORDZ instead of removing it. Args: words_to_remove: list of ids (ints) to remove Returns: original raw string with appropriate words removed. """ mask = np.ones(self.as_np.shape[0], dtype='bool') mask[self.__get_idxs(words_to_remove)] = False if not self.bow: return ''.join([self.as_list[i] if mask[i] else 'UNKWORDZ' for i in range(mask.shape[0])]) return ''.join([self.as_list[v] for v in mask.nonzero()[0]])
python
def inverse_removing(self, words_to_remove): """Returns a string after removing the appropriate words. If self.bow is false, replaces word with UNKWORDZ instead of removing it. Args: words_to_remove: list of ids (ints) to remove Returns: original raw string with appropriate words removed. """ mask = np.ones(self.as_np.shape[0], dtype='bool') mask[self.__get_idxs(words_to_remove)] = False if not self.bow: return ''.join([self.as_list[i] if mask[i] else 'UNKWORDZ' for i in range(mask.shape[0])]) return ''.join([self.as_list[v] for v in mask.nonzero()[0]])
[ "def", "inverse_removing", "(", "self", ",", "words_to_remove", ")", ":", "mask", "=", "np", ".", "ones", "(", "self", ".", "as_np", ".", "shape", "[", "0", "]", ",", "dtype", "=", "'bool'", ")", "mask", "[", "self", ".", "__get_idxs", "(", "words_to_remove", ")", "]", "=", "False", "if", "not", "self", ".", "bow", ":", "return", "''", ".", "join", "(", "[", "self", ".", "as_list", "[", "i", "]", "if", "mask", "[", "i", "]", "else", "'UNKWORDZ'", "for", "i", "in", "range", "(", "mask", ".", "shape", "[", "0", "]", ")", "]", ")", "return", "''", ".", "join", "(", "[", "self", ".", "as_list", "[", "v", "]", "for", "v", "in", "mask", ".", "nonzero", "(", ")", "[", "0", "]", "]", ")" ]
Returns a string after removing the appropriate words. If self.bow is false, replaces word with UNKWORDZ instead of removing it. Args: words_to_remove: list of ids (ints) to remove Returns: original raw string with appropriate words removed.
[ "Returns", "a", "string", "after", "removing", "the", "appropriate", "words", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L162-L179
train
marcotcr/lime
lime/lime_text.py
IndexedString._segment_with_tokens
def _segment_with_tokens(text, tokens): """Segment a string around the tokens created by a passed-in tokenizer""" list_form = [] text_ptr = 0 for token in tokens: inter_token_string = [] while not text[text_ptr:].startswith(token): inter_token_string.append(text[text_ptr]) text_ptr += 1 if text_ptr >= len(text): raise ValueError("Tokenization produced tokens that do not belong in string!") text_ptr += len(token) if inter_token_string: list_form.append(''.join(inter_token_string)) list_form.append(token) if text_ptr < len(text): list_form.append(text[text_ptr:]) return list_form
python
def _segment_with_tokens(text, tokens): """Segment a string around the tokens created by a passed-in tokenizer""" list_form = [] text_ptr = 0 for token in tokens: inter_token_string = [] while not text[text_ptr:].startswith(token): inter_token_string.append(text[text_ptr]) text_ptr += 1 if text_ptr >= len(text): raise ValueError("Tokenization produced tokens that do not belong in string!") text_ptr += len(token) if inter_token_string: list_form.append(''.join(inter_token_string)) list_form.append(token) if text_ptr < len(text): list_form.append(text[text_ptr:]) return list_form
[ "def", "_segment_with_tokens", "(", "text", ",", "tokens", ")", ":", "list_form", "=", "[", "]", "text_ptr", "=", "0", "for", "token", "in", "tokens", ":", "inter_token_string", "=", "[", "]", "while", "not", "text", "[", "text_ptr", ":", "]", ".", "startswith", "(", "token", ")", ":", "inter_token_string", ".", "append", "(", "text", "[", "text_ptr", "]", ")", "text_ptr", "+=", "1", "if", "text_ptr", ">=", "len", "(", "text", ")", ":", "raise", "ValueError", "(", "\"Tokenization produced tokens that do not belong in string!\"", ")", "text_ptr", "+=", "len", "(", "token", ")", "if", "inter_token_string", ":", "list_form", ".", "append", "(", "''", ".", "join", "(", "inter_token_string", ")", ")", "list_form", ".", "append", "(", "token", ")", "if", "text_ptr", "<", "len", "(", "text", ")", ":", "list_form", ".", "append", "(", "text", "[", "text_ptr", ":", "]", ")", "return", "list_form" ]
Segment a string around the tokens created by a passed-in tokenizer
[ "Segment", "a", "string", "around", "the", "tokens", "created", "by", "a", "passed", "-", "in", "tokenizer" ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L182-L199
train
marcotcr/lime
lime/lime_text.py
IndexedString.__get_idxs
def __get_idxs(self, words): """Returns indexes to appropriate words.""" if self.bow: return list(itertools.chain.from_iterable( [self.positions[z] for z in words])) else: return self.positions[words]
python
def __get_idxs(self, words): """Returns indexes to appropriate words.""" if self.bow: return list(itertools.chain.from_iterable( [self.positions[z] for z in words])) else: return self.positions[words]
[ "def", "__get_idxs", "(", "self", ",", "words", ")", ":", "if", "self", ".", "bow", ":", "return", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "self", ".", "positions", "[", "z", "]", "for", "z", "in", "words", "]", ")", ")", "else", ":", "return", "self", ".", "positions", "[", "words", "]" ]
Returns indexes to appropriate words.
[ "Returns", "indexes", "to", "appropriate", "words", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L201-L207
train
marcotcr/lime
lime/lime_text.py
LimeTextExplainer.explain_instance
def explain_instance(self, text_instance, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='cosine', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: text_instance: raw text string to be explained. classifier_fn: classifier prediction probability function, which takes a list of d strings and outputs a (d, k) numpy array with prediction probabilities, where k is the number of classes. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ indexed_string = IndexedCharacters( text_instance, bow=self.bow) if self.char_level else IndexedString( text_instance, bow=self.bow, split_expression=self.split_expression) domain_mapper = TextDomainMapper(indexed_string) data, yss, distances = self.__data_labels_distances( indexed_string, classifier_fn, num_samples, distance_metric=distance_metric) if self.class_names is None: self.class_names = [str(x) for x in range(yss[0].shape[0])] ret_exp = explanation.Explanation(domain_mapper=domain_mapper, class_names=self.class_names, random_state=self.random_state) ret_exp.predict_proba = yss[0] if top_labels: labels = np.argsort(yss[0])[-top_labels:] ret_exp.top_labels = list(labels) ret_exp.top_labels.reverse() for label in labels: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( data, yss, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) return ret_exp
python
def explain_instance(self, text_instance, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='cosine', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: text_instance: raw text string to be explained. classifier_fn: classifier prediction probability function, which takes a list of d strings and outputs a (d, k) numpy array with prediction probabilities, where k is the number of classes. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ indexed_string = IndexedCharacters( text_instance, bow=self.bow) if self.char_level else IndexedString( text_instance, bow=self.bow, split_expression=self.split_expression) domain_mapper = TextDomainMapper(indexed_string) data, yss, distances = self.__data_labels_distances( indexed_string, classifier_fn, num_samples, distance_metric=distance_metric) if self.class_names is None: self.class_names = [str(x) for x in range(yss[0].shape[0])] ret_exp = explanation.Explanation(domain_mapper=domain_mapper, class_names=self.class_names, random_state=self.random_state) ret_exp.predict_proba = yss[0] if top_labels: labels = np.argsort(yss[0])[-top_labels:] ret_exp.top_labels = list(labels) ret_exp.top_labels.reverse() for label in labels: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( data, yss, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) return ret_exp
[ "def", "explain_instance", "(", "self", ",", "text_instance", ",", "classifier_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=", "'cosine'", ",", "model_regressor", "=", "None", ")", ":", "indexed_string", "=", "IndexedCharacters", "(", "text_instance", ",", "bow", "=", "self", ".", "bow", ")", "if", "self", ".", "char_level", "else", "IndexedString", "(", "text_instance", ",", "bow", "=", "self", ".", "bow", ",", "split_expression", "=", "self", ".", "split_expression", ")", "domain_mapper", "=", "TextDomainMapper", "(", "indexed_string", ")", "data", ",", "yss", ",", "distances", "=", "self", ".", "__data_labels_distances", "(", "indexed_string", ",", "classifier_fn", ",", "num_samples", ",", "distance_metric", "=", "distance_metric", ")", "if", "self", ".", "class_names", "is", "None", ":", "self", ".", "class_names", "=", "[", "str", "(", "x", ")", "for", "x", "in", "range", "(", "yss", "[", "0", "]", ".", "shape", "[", "0", "]", ")", "]", "ret_exp", "=", "explanation", ".", "Explanation", "(", "domain_mapper", "=", "domain_mapper", ",", "class_names", "=", "self", ".", "class_names", ",", "random_state", "=", "self", ".", "random_state", ")", "ret_exp", ".", "predict_proba", "=", "yss", "[", "0", "]", "if", "top_labels", ":", "labels", "=", "np", ".", "argsort", "(", "yss", "[", "0", "]", ")", "[", "-", "top_labels", ":", "]", "ret_exp", ".", "top_labels", "=", "list", "(", "labels", ")", "ret_exp", ".", "top_labels", ".", "reverse", "(", ")", "for", "label", "in", "labels", ":", "(", "ret_exp", ".", "intercept", "[", "label", "]", ",", "ret_exp", ".", "local_exp", "[", "label", "]", ",", "ret_exp", ".", "score", ",", "ret_exp", ".", "local_pred", ")", "=", "self", ".", "base", ".", "explain_instance_with_data", "(", "data", ",", "yss", ",", "distances", ",", "label", ",", "num_features", ",", "model_regressor", "=", "model_regressor", ",", "feature_selection", "=", "self", ".", "feature_selection", ")", "return", "ret_exp" ]
Generates explanations for a prediction. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: text_instance: raw text string to be explained. classifier_fn: classifier prediction probability function, which takes a list of d strings and outputs a (d, k) numpy array with prediction probabilities, where k is the number of classes. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L356-L418
train
marcotcr/lime
lime/lime_text.py
LimeTextExplainer.__data_labels_distances
def __data_labels_distances(self, indexed_string, classifier_fn, num_samples, distance_metric='cosine'): """Generates a neighborhood around a prediction. Generates neighborhood data by randomly removing words from the instance, and predicting with the classifier. Uses cosine distance to compute distances between original and perturbed instances. Args: indexed_string: document (IndexedString) to be explained, classifier_fn: classifier prediction probability function, which takes a string and outputs prediction probabilities. For ScikitClassifier, this is classifier.predict_proba. num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity. Returns: A tuple (data, labels, distances), where: data: dense num_samples * K binary matrix, where K is the number of tokens in indexed_string. The first row is the original instance, and thus a row of ones. labels: num_samples * L matrix, where L is the number of target labels distances: cosine distance between the original instance and each perturbed instance (computed in the binary 'data' matrix), times 100. """ def distance_fn(x): return sklearn.metrics.pairwise.pairwise_distances( x, x[0], metric=distance_metric).ravel() * 100 doc_size = indexed_string.num_words() sample = self.random_state.randint(1, doc_size + 1, num_samples - 1) data = np.ones((num_samples, doc_size)) data[0] = np.ones(doc_size) features_range = range(doc_size) inverse_data = [indexed_string.raw_string()] for i, size in enumerate(sample, start=1): inactive = self.random_state.choice(features_range, size, replace=False) data[i, inactive] = 0 inverse_data.append(indexed_string.inverse_removing(inactive)) labels = classifier_fn(inverse_data) distances = distance_fn(sp.sparse.csr_matrix(data)) return data, labels, distances
python
def __data_labels_distances(self, indexed_string, classifier_fn, num_samples, distance_metric='cosine'): """Generates a neighborhood around a prediction. Generates neighborhood data by randomly removing words from the instance, and predicting with the classifier. Uses cosine distance to compute distances between original and perturbed instances. Args: indexed_string: document (IndexedString) to be explained, classifier_fn: classifier prediction probability function, which takes a string and outputs prediction probabilities. For ScikitClassifier, this is classifier.predict_proba. num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity. Returns: A tuple (data, labels, distances), where: data: dense num_samples * K binary matrix, where K is the number of tokens in indexed_string. The first row is the original instance, and thus a row of ones. labels: num_samples * L matrix, where L is the number of target labels distances: cosine distance between the original instance and each perturbed instance (computed in the binary 'data' matrix), times 100. """ def distance_fn(x): return sklearn.metrics.pairwise.pairwise_distances( x, x[0], metric=distance_metric).ravel() * 100 doc_size = indexed_string.num_words() sample = self.random_state.randint(1, doc_size + 1, num_samples - 1) data = np.ones((num_samples, doc_size)) data[0] = np.ones(doc_size) features_range = range(doc_size) inverse_data = [indexed_string.raw_string()] for i, size in enumerate(sample, start=1): inactive = self.random_state.choice(features_range, size, replace=False) data[i, inactive] = 0 inverse_data.append(indexed_string.inverse_removing(inactive)) labels = classifier_fn(inverse_data) distances = distance_fn(sp.sparse.csr_matrix(data)) return data, labels, distances
[ "def", "__data_labels_distances", "(", "self", ",", "indexed_string", ",", "classifier_fn", ",", "num_samples", ",", "distance_metric", "=", "'cosine'", ")", ":", "def", "distance_fn", "(", "x", ")", ":", "return", "sklearn", ".", "metrics", ".", "pairwise", ".", "pairwise_distances", "(", "x", ",", "x", "[", "0", "]", ",", "metric", "=", "distance_metric", ")", ".", "ravel", "(", ")", "*", "100", "doc_size", "=", "indexed_string", ".", "num_words", "(", ")", "sample", "=", "self", ".", "random_state", ".", "randint", "(", "1", ",", "doc_size", "+", "1", ",", "num_samples", "-", "1", ")", "data", "=", "np", ".", "ones", "(", "(", "num_samples", ",", "doc_size", ")", ")", "data", "[", "0", "]", "=", "np", ".", "ones", "(", "doc_size", ")", "features_range", "=", "range", "(", "doc_size", ")", "inverse_data", "=", "[", "indexed_string", ".", "raw_string", "(", ")", "]", "for", "i", ",", "size", "in", "enumerate", "(", "sample", ",", "start", "=", "1", ")", ":", "inactive", "=", "self", ".", "random_state", ".", "choice", "(", "features_range", ",", "size", ",", "replace", "=", "False", ")", "data", "[", "i", ",", "inactive", "]", "=", "0", "inverse_data", ".", "append", "(", "indexed_string", ".", "inverse_removing", "(", "inactive", ")", ")", "labels", "=", "classifier_fn", "(", "inverse_data", ")", "distances", "=", "distance_fn", "(", "sp", ".", "sparse", ".", "csr_matrix", "(", "data", ")", ")", "return", "data", ",", "labels", ",", "distances" ]
Generates a neighborhood around a prediction. Generates neighborhood data by randomly removing words from the instance, and predicting with the classifier. Uses cosine distance to compute distances between original and perturbed instances. Args: indexed_string: document (IndexedString) to be explained, classifier_fn: classifier prediction probability function, which takes a string and outputs prediction probabilities. For ScikitClassifier, this is classifier.predict_proba. num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity. Returns: A tuple (data, labels, distances), where: data: dense num_samples * K binary matrix, where K is the number of tokens in indexed_string. The first row is the original instance, and thus a row of ones. labels: num_samples * L matrix, where L is the number of target labels distances: cosine distance between the original instance and each perturbed instance (computed in the binary 'data' matrix), times 100.
[ "Generates", "a", "neighborhood", "around", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L420-L469
train
marcotcr/lime
lime/lime_tabular.py
TableDomainMapper.map_exp_ids
def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) """ names = self.exp_feature_names if self.discretized_feature_names is not None: names = self.discretized_feature_names return [(names[x[0]], x[1]) for x in exp]
python
def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) """ names = self.exp_feature_names if self.discretized_feature_names is not None: names = self.discretized_feature_names return [(names[x[0]], x[1]) for x in exp]
[ "def", "map_exp_ids", "(", "self", ",", "exp", ")", ":", "names", "=", "self", ".", "exp_feature_names", "if", "self", ".", "discretized_feature_names", "is", "not", "None", ":", "names", "=", "self", ".", "discretized_feature_names", "return", "[", "(", "names", "[", "x", "[", "0", "]", "]", ",", "x", "[", "1", "]", ")", "for", "x", "in", "exp", "]" ]
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight)
[ "Maps", "ids", "to", "feature", "names", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L45-L57
train
marcotcr/lime
lime/lime_tabular.py
TableDomainMapper.visualize_instance_html
def visualize_instance_html(self, exp, label, div_name, exp_object_name, show_table=True, show_all=False): """Shows the current example in a table format. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object show_table: if False, don't show table visualization. show_all: if True, show zero-weighted features in the table. """ if not show_table: return '' weights = [0] * len(self.feature_names) for x in exp: weights[x[0]] = x[1] out_list = list(zip(self.exp_feature_names, self.feature_values, weights)) if not show_all: out_list = [out_list[x[0]] for x in exp] ret = u''' %s.show_raw_tabular(%s, %d, %s); ''' % (exp_object_name, json.dumps(out_list, ensure_ascii=False), label, div_name) return ret
python
def visualize_instance_html(self, exp, label, div_name, exp_object_name, show_table=True, show_all=False): """Shows the current example in a table format. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object show_table: if False, don't show table visualization. show_all: if True, show zero-weighted features in the table. """ if not show_table: return '' weights = [0] * len(self.feature_names) for x in exp: weights[x[0]] = x[1] out_list = list(zip(self.exp_feature_names, self.feature_values, weights)) if not show_all: out_list = [out_list[x[0]] for x in exp] ret = u''' %s.show_raw_tabular(%s, %d, %s); ''' % (exp_object_name, json.dumps(out_list, ensure_ascii=False), label, div_name) return ret
[ "def", "visualize_instance_html", "(", "self", ",", "exp", ",", "label", ",", "div_name", ",", "exp_object_name", ",", "show_table", "=", "True", ",", "show_all", "=", "False", ")", ":", "if", "not", "show_table", ":", "return", "''", "weights", "=", "[", "0", "]", "*", "len", "(", "self", ".", "feature_names", ")", "for", "x", "in", "exp", ":", "weights", "[", "x", "[", "0", "]", "]", "=", "x", "[", "1", "]", "out_list", "=", "list", "(", "zip", "(", "self", ".", "exp_feature_names", ",", "self", ".", "feature_values", ",", "weights", ")", ")", "if", "not", "show_all", ":", "out_list", "=", "[", "out_list", "[", "x", "[", "0", "]", "]", "for", "x", "in", "exp", "]", "ret", "=", "u'''\n %s.show_raw_tabular(%s, %d, %s);\n '''", "%", "(", "exp_object_name", ",", "json", ".", "dumps", "(", "out_list", ",", "ensure_ascii", "=", "False", ")", ",", "label", ",", "div_name", ")", "return", "ret" ]
Shows the current example in a table format. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object show_table: if False, don't show table visualization. show_all: if True, show zero-weighted features in the table.
[ "Shows", "the", "current", "example", "in", "a", "table", "format", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L59-L89
train
marcotcr/lime
lime/lime_tabular.py
LimeTabularExplainer.validate_training_data_stats
def validate_training_data_stats(training_data_stats): """ Method to validate the structure of training data stats """ stat_keys = list(training_data_stats.keys()) valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"] missing_keys = list(set(valid_stat_keys) - set(stat_keys)) if len(missing_keys) > 0: raise Exception("Missing keys in training_data_stats. Details:" % (missing_keys))
python
def validate_training_data_stats(training_data_stats): """ Method to validate the structure of training data stats """ stat_keys = list(training_data_stats.keys()) valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"] missing_keys = list(set(valid_stat_keys) - set(stat_keys)) if len(missing_keys) > 0: raise Exception("Missing keys in training_data_stats. Details:" % (missing_keys))
[ "def", "validate_training_data_stats", "(", "training_data_stats", ")", ":", "stat_keys", "=", "list", "(", "training_data_stats", ".", "keys", "(", ")", ")", "valid_stat_keys", "=", "[", "\"means\"", ",", "\"mins\"", ",", "\"maxs\"", ",", "\"stds\"", ",", "\"feature_values\"", ",", "\"feature_frequencies\"", "]", "missing_keys", "=", "list", "(", "set", "(", "valid_stat_keys", ")", "-", "set", "(", "stat_keys", ")", ")", "if", "len", "(", "missing_keys", ")", ">", "0", ":", "raise", "Exception", "(", "\"Missing keys in training_data_stats. Details:\"", "%", "(", "missing_keys", ")", ")" ]
Method to validate the structure of training data stats
[ "Method", "to", "validate", "the", "structure", "of", "training", "data", "stats" ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L260-L268
train
marcotcr/lime
lime/lime_tabular.py
LimeTabularExplainer.explain_instance
def explain_instance(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 1d numpy array, corresponding to a row predict_fn: prediction function. For classifiers, this should be a function that takes a numpy array and outputs prediction probabilities. For regressors, this takes a numpy array and returns the predictions. For ScikitClassifiers, this is `classifier.predict_proba()`. For ScikitRegressors, this is `regressor.predict()`. The prediction function needs to work on multiple feature vectors (the vectors randomly perturbed from the data_row). labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ data, inverse = self.__data_inverse(data_row, num_samples) scaled_data = (data - self.scaler.mean_) / self.scaler.scale_ distances = sklearn.metrics.pairwise_distances( scaled_data, scaled_data[0].reshape(1, -1), metric=distance_metric ).ravel() yss = predict_fn(inverse) # for classification, the model needs to provide a list of tuples - classes # along with prediction probabilities if self.mode == "classification": if len(yss.shape) == 1: raise NotImplementedError("LIME does not currently support " "classifier models without probability " "scores. If this conflicts with your " "use case, please let us know: " "https://github.com/datascienceinc/lime/issues/16") elif len(yss.shape) == 2: if self.class_names is None: self.class_names = [str(x) for x in range(yss[0].shape[0])] else: self.class_names = list(self.class_names) if not np.allclose(yss.sum(axis=1), 1.0): warnings.warn(""" Prediction probabilties do not sum to 1, and thus does not constitute a probability space. Check that you classifier outputs probabilities (Not log probabilities, or actual class predictions). """) else: raise ValueError("Your model outputs " "arrays with {} dimensions".format(len(yss.shape))) # for regression, the output should be a one-dimensional array of predictions else: try: assert isinstance(yss, np.ndarray) and len(yss.shape) == 1 except AssertionError: raise ValueError("Your model needs to output single-dimensional \ numpyarrays, not arrays of {} dimensions".format(yss.shape)) predicted_value = yss[0] min_y = min(yss) max_y = max(yss) # add a dimension to be compatible with downstream machinery yss = yss[:, np.newaxis] feature_names = copy.deepcopy(self.feature_names) if feature_names is None: feature_names = [str(x) for x in range(data_row.shape[0])] values = self.convert_and_round(data_row) for i in self.categorical_features: if self.discretizer is not None and i in self.discretizer.lambdas: continue name = int(data_row[i]) if i in self.categorical_names: name = self.categorical_names[i][name] feature_names[i] = '%s=%s' % (feature_names[i], name) values[i] = 'True' categorical_features = self.categorical_features discretized_feature_names = None if self.discretizer is not None: categorical_features = range(data.shape[1]) discretized_instance = self.discretizer.discretize(data_row) discretized_feature_names = copy.deepcopy(feature_names) for f in self.discretizer.names: discretized_feature_names[f] = self.discretizer.names[f][int( discretized_instance[f])] domain_mapper = TableDomainMapper(feature_names, values, scaled_data[0], categorical_features=categorical_features, discretized_feature_names=discretized_feature_names) ret_exp = explanation.Explanation(domain_mapper, mode=self.mode, class_names=self.class_names) ret_exp.scaled_data = scaled_data if self.mode == "classification": ret_exp.predict_proba = yss[0] if top_labels: labels = np.argsort(yss[0])[-top_labels:] ret_exp.top_labels = list(labels) ret_exp.top_labels.reverse() else: ret_exp.predicted_value = predicted_value ret_exp.min_value = min_y ret_exp.max_value = max_y labels = [0] for label in labels: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( scaled_data, yss, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) if self.mode == "regression": ret_exp.intercept[1] = ret_exp.intercept[0] ret_exp.local_exp[1] = [x for x in ret_exp.local_exp[0]] ret_exp.local_exp[0] = [(i, -1 * j) for i, j in ret_exp.local_exp[1]] return ret_exp
python
def explain_instance(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 1d numpy array, corresponding to a row predict_fn: prediction function. For classifiers, this should be a function that takes a numpy array and outputs prediction probabilities. For regressors, this takes a numpy array and returns the predictions. For ScikitClassifiers, this is `classifier.predict_proba()`. For ScikitRegressors, this is `regressor.predict()`. The prediction function needs to work on multiple feature vectors (the vectors randomly perturbed from the data_row). labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ data, inverse = self.__data_inverse(data_row, num_samples) scaled_data = (data - self.scaler.mean_) / self.scaler.scale_ distances = sklearn.metrics.pairwise_distances( scaled_data, scaled_data[0].reshape(1, -1), metric=distance_metric ).ravel() yss = predict_fn(inverse) # for classification, the model needs to provide a list of tuples - classes # along with prediction probabilities if self.mode == "classification": if len(yss.shape) == 1: raise NotImplementedError("LIME does not currently support " "classifier models without probability " "scores. If this conflicts with your " "use case, please let us know: " "https://github.com/datascienceinc/lime/issues/16") elif len(yss.shape) == 2: if self.class_names is None: self.class_names = [str(x) for x in range(yss[0].shape[0])] else: self.class_names = list(self.class_names) if not np.allclose(yss.sum(axis=1), 1.0): warnings.warn(""" Prediction probabilties do not sum to 1, and thus does not constitute a probability space. Check that you classifier outputs probabilities (Not log probabilities, or actual class predictions). """) else: raise ValueError("Your model outputs " "arrays with {} dimensions".format(len(yss.shape))) # for regression, the output should be a one-dimensional array of predictions else: try: assert isinstance(yss, np.ndarray) and len(yss.shape) == 1 except AssertionError: raise ValueError("Your model needs to output single-dimensional \ numpyarrays, not arrays of {} dimensions".format(yss.shape)) predicted_value = yss[0] min_y = min(yss) max_y = max(yss) # add a dimension to be compatible with downstream machinery yss = yss[:, np.newaxis] feature_names = copy.deepcopy(self.feature_names) if feature_names is None: feature_names = [str(x) for x in range(data_row.shape[0])] values = self.convert_and_round(data_row) for i in self.categorical_features: if self.discretizer is not None and i in self.discretizer.lambdas: continue name = int(data_row[i]) if i in self.categorical_names: name = self.categorical_names[i][name] feature_names[i] = '%s=%s' % (feature_names[i], name) values[i] = 'True' categorical_features = self.categorical_features discretized_feature_names = None if self.discretizer is not None: categorical_features = range(data.shape[1]) discretized_instance = self.discretizer.discretize(data_row) discretized_feature_names = copy.deepcopy(feature_names) for f in self.discretizer.names: discretized_feature_names[f] = self.discretizer.names[f][int( discretized_instance[f])] domain_mapper = TableDomainMapper(feature_names, values, scaled_data[0], categorical_features=categorical_features, discretized_feature_names=discretized_feature_names) ret_exp = explanation.Explanation(domain_mapper, mode=self.mode, class_names=self.class_names) ret_exp.scaled_data = scaled_data if self.mode == "classification": ret_exp.predict_proba = yss[0] if top_labels: labels = np.argsort(yss[0])[-top_labels:] ret_exp.top_labels = list(labels) ret_exp.top_labels.reverse() else: ret_exp.predicted_value = predicted_value ret_exp.min_value = min_y ret_exp.max_value = max_y labels = [0] for label in labels: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( scaled_data, yss, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) if self.mode == "regression": ret_exp.intercept[1] = ret_exp.intercept[0] ret_exp.local_exp[1] = [x for x in ret_exp.local_exp[0]] ret_exp.local_exp[0] = [(i, -1 * j) for i, j in ret_exp.local_exp[1]] return ret_exp
[ "def", "explain_instance", "(", "self", ",", "data_row", ",", "predict_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=", "'euclidean'", ",", "model_regressor", "=", "None", ")", ":", "data", ",", "inverse", "=", "self", ".", "__data_inverse", "(", "data_row", ",", "num_samples", ")", "scaled_data", "=", "(", "data", "-", "self", ".", "scaler", ".", "mean_", ")", "/", "self", ".", "scaler", ".", "scale_", "distances", "=", "sklearn", ".", "metrics", ".", "pairwise_distances", "(", "scaled_data", ",", "scaled_data", "[", "0", "]", ".", "reshape", "(", "1", ",", "-", "1", ")", ",", "metric", "=", "distance_metric", ")", ".", "ravel", "(", ")", "yss", "=", "predict_fn", "(", "inverse", ")", "# for classification, the model needs to provide a list of tuples - classes", "# along with prediction probabilities", "if", "self", ".", "mode", "==", "\"classification\"", ":", "if", "len", "(", "yss", ".", "shape", ")", "==", "1", ":", "raise", "NotImplementedError", "(", "\"LIME does not currently support \"", "\"classifier models without probability \"", "\"scores. If this conflicts with your \"", "\"use case, please let us know: \"", "\"https://github.com/datascienceinc/lime/issues/16\"", ")", "elif", "len", "(", "yss", ".", "shape", ")", "==", "2", ":", "if", "self", ".", "class_names", "is", "None", ":", "self", ".", "class_names", "=", "[", "str", "(", "x", ")", "for", "x", "in", "range", "(", "yss", "[", "0", "]", ".", "shape", "[", "0", "]", ")", "]", "else", ":", "self", ".", "class_names", "=", "list", "(", "self", ".", "class_names", ")", "if", "not", "np", ".", "allclose", "(", "yss", ".", "sum", "(", "axis", "=", "1", ")", ",", "1.0", ")", ":", "warnings", ".", "warn", "(", "\"\"\"\n Prediction probabilties do not sum to 1, and\n thus does not constitute a probability space.\n Check that you classifier outputs probabilities\n (Not log probabilities, or actual class predictions).\n \"\"\"", ")", "else", ":", "raise", "ValueError", "(", "\"Your model outputs \"", "\"arrays with {} dimensions\"", ".", "format", "(", "len", "(", "yss", ".", "shape", ")", ")", ")", "# for regression, the output should be a one-dimensional array of predictions", "else", ":", "try", ":", "assert", "isinstance", "(", "yss", ",", "np", ".", "ndarray", ")", "and", "len", "(", "yss", ".", "shape", ")", "==", "1", "except", "AssertionError", ":", "raise", "ValueError", "(", "\"Your model needs to output single-dimensional \\\n numpyarrays, not arrays of {} dimensions\"", ".", "format", "(", "yss", ".", "shape", ")", ")", "predicted_value", "=", "yss", "[", "0", "]", "min_y", "=", "min", "(", "yss", ")", "max_y", "=", "max", "(", "yss", ")", "# add a dimension to be compatible with downstream machinery", "yss", "=", "yss", "[", ":", ",", "np", ".", "newaxis", "]", "feature_names", "=", "copy", ".", "deepcopy", "(", "self", ".", "feature_names", ")", "if", "feature_names", "is", "None", ":", "feature_names", "=", "[", "str", "(", "x", ")", "for", "x", "in", "range", "(", "data_row", ".", "shape", "[", "0", "]", ")", "]", "values", "=", "self", ".", "convert_and_round", "(", "data_row", ")", "for", "i", "in", "self", ".", "categorical_features", ":", "if", "self", ".", "discretizer", "is", "not", "None", "and", "i", "in", "self", ".", "discretizer", ".", "lambdas", ":", "continue", "name", "=", "int", "(", "data_row", "[", "i", "]", ")", "if", "i", "in", "self", ".", "categorical_names", ":", "name", "=", "self", ".", "categorical_names", "[", "i", "]", "[", "name", "]", "feature_names", "[", "i", "]", "=", "'%s=%s'", "%", "(", "feature_names", "[", "i", "]", ",", "name", ")", "values", "[", "i", "]", "=", "'True'", "categorical_features", "=", "self", ".", "categorical_features", "discretized_feature_names", "=", "None", "if", "self", ".", "discretizer", "is", "not", "None", ":", "categorical_features", "=", "range", "(", "data", ".", "shape", "[", "1", "]", ")", "discretized_instance", "=", "self", ".", "discretizer", ".", "discretize", "(", "data_row", ")", "discretized_feature_names", "=", "copy", ".", "deepcopy", "(", "feature_names", ")", "for", "f", "in", "self", ".", "discretizer", ".", "names", ":", "discretized_feature_names", "[", "f", "]", "=", "self", ".", "discretizer", ".", "names", "[", "f", "]", "[", "int", "(", "discretized_instance", "[", "f", "]", ")", "]", "domain_mapper", "=", "TableDomainMapper", "(", "feature_names", ",", "values", ",", "scaled_data", "[", "0", "]", ",", "categorical_features", "=", "categorical_features", ",", "discretized_feature_names", "=", "discretized_feature_names", ")", "ret_exp", "=", "explanation", ".", "Explanation", "(", "domain_mapper", ",", "mode", "=", "self", ".", "mode", ",", "class_names", "=", "self", ".", "class_names", ")", "ret_exp", ".", "scaled_data", "=", "scaled_data", "if", "self", ".", "mode", "==", "\"classification\"", ":", "ret_exp", ".", "predict_proba", "=", "yss", "[", "0", "]", "if", "top_labels", ":", "labels", "=", "np", ".", "argsort", "(", "yss", "[", "0", "]", ")", "[", "-", "top_labels", ":", "]", "ret_exp", ".", "top_labels", "=", "list", "(", "labels", ")", "ret_exp", ".", "top_labels", ".", "reverse", "(", ")", "else", ":", "ret_exp", ".", "predicted_value", "=", "predicted_value", "ret_exp", ".", "min_value", "=", "min_y", "ret_exp", ".", "max_value", "=", "max_y", "labels", "=", "[", "0", "]", "for", "label", "in", "labels", ":", "(", "ret_exp", ".", "intercept", "[", "label", "]", ",", "ret_exp", ".", "local_exp", "[", "label", "]", ",", "ret_exp", ".", "score", ",", "ret_exp", ".", "local_pred", ")", "=", "self", ".", "base", ".", "explain_instance_with_data", "(", "scaled_data", ",", "yss", ",", "distances", ",", "label", ",", "num_features", ",", "model_regressor", "=", "model_regressor", ",", "feature_selection", "=", "self", ".", "feature_selection", ")", "if", "self", ".", "mode", "==", "\"regression\"", ":", "ret_exp", ".", "intercept", "[", "1", "]", "=", "ret_exp", ".", "intercept", "[", "0", "]", "ret_exp", ".", "local_exp", "[", "1", "]", "=", "[", "x", "for", "x", "in", "ret_exp", ".", "local_exp", "[", "0", "]", "]", "ret_exp", ".", "local_exp", "[", "0", "]", "=", "[", "(", "i", ",", "-", "1", "*", "j", ")", "for", "i", ",", "j", "in", "ret_exp", ".", "local_exp", "[", "1", "]", "]", "return", "ret_exp" ]
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 1d numpy array, corresponding to a row predict_fn: prediction function. For classifiers, this should be a function that takes a numpy array and outputs prediction probabilities. For regressors, this takes a numpy array and returns the predictions. For ScikitClassifiers, this is `classifier.predict_proba()`. For ScikitRegressors, this is `regressor.predict()`. The prediction function needs to work on multiple feature vectors (the vectors randomly perturbed from the data_row). labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L270-L425
train
marcotcr/lime
lime/lime_tabular.py
LimeTabularExplainer.__data_inverse
def __data_inverse(self, data_row, num_samples): """Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according to the training distribution, and making a binary feature that is 1 when the value is the same as the instance being explained. Args: data_row: 1d numpy array, corresponding to a row num_samples: size of the neighborhood to learn the linear model Returns: A tuple (data, inverse), where: data: dense num_samples * K matrix, where categorical features are encoded with either 0 (not equal to the corresponding value in data_row) or 1. The first row is the original instance. inverse: same as data, except the categorical features are not binary, but categorical (as the original data) """ data = np.zeros((num_samples, data_row.shape[0])) categorical_features = range(data_row.shape[0]) if self.discretizer is None: data = self.random_state.normal( 0, 1, num_samples * data_row.shape[0]).reshape( num_samples, data_row.shape[0]) if self.sample_around_instance: data = data * self.scaler.scale_ + data_row else: data = data * self.scaler.scale_ + self.scaler.mean_ categorical_features = self.categorical_features first_row = data_row else: first_row = self.discretizer.discretize(data_row) data[0] = data_row.copy() inverse = data.copy() for column in categorical_features: values = self.feature_values[column] freqs = self.feature_frequencies[column] inverse_column = self.random_state.choice(values, size=num_samples, replace=True, p=freqs) binary_column = np.array([1 if x == first_row[column] else 0 for x in inverse_column]) binary_column[0] = 1 inverse_column[0] = data[0, column] data[:, column] = binary_column inverse[:, column] = inverse_column if self.discretizer is not None: inverse[1:] = self.discretizer.undiscretize(inverse[1:]) inverse[0] = data_row return data, inverse
python
def __data_inverse(self, data_row, num_samples): """Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according to the training distribution, and making a binary feature that is 1 when the value is the same as the instance being explained. Args: data_row: 1d numpy array, corresponding to a row num_samples: size of the neighborhood to learn the linear model Returns: A tuple (data, inverse), where: data: dense num_samples * K matrix, where categorical features are encoded with either 0 (not equal to the corresponding value in data_row) or 1. The first row is the original instance. inverse: same as data, except the categorical features are not binary, but categorical (as the original data) """ data = np.zeros((num_samples, data_row.shape[0])) categorical_features = range(data_row.shape[0]) if self.discretizer is None: data = self.random_state.normal( 0, 1, num_samples * data_row.shape[0]).reshape( num_samples, data_row.shape[0]) if self.sample_around_instance: data = data * self.scaler.scale_ + data_row else: data = data * self.scaler.scale_ + self.scaler.mean_ categorical_features = self.categorical_features first_row = data_row else: first_row = self.discretizer.discretize(data_row) data[0] = data_row.copy() inverse = data.copy() for column in categorical_features: values = self.feature_values[column] freqs = self.feature_frequencies[column] inverse_column = self.random_state.choice(values, size=num_samples, replace=True, p=freqs) binary_column = np.array([1 if x == first_row[column] else 0 for x in inverse_column]) binary_column[0] = 1 inverse_column[0] = data[0, column] data[:, column] = binary_column inverse[:, column] = inverse_column if self.discretizer is not None: inverse[1:] = self.discretizer.undiscretize(inverse[1:]) inverse[0] = data_row return data, inverse
[ "def", "__data_inverse", "(", "self", ",", "data_row", ",", "num_samples", ")", ":", "data", "=", "np", ".", "zeros", "(", "(", "num_samples", ",", "data_row", ".", "shape", "[", "0", "]", ")", ")", "categorical_features", "=", "range", "(", "data_row", ".", "shape", "[", "0", "]", ")", "if", "self", ".", "discretizer", "is", "None", ":", "data", "=", "self", ".", "random_state", ".", "normal", "(", "0", ",", "1", ",", "num_samples", "*", "data_row", ".", "shape", "[", "0", "]", ")", ".", "reshape", "(", "num_samples", ",", "data_row", ".", "shape", "[", "0", "]", ")", "if", "self", ".", "sample_around_instance", ":", "data", "=", "data", "*", "self", ".", "scaler", ".", "scale_", "+", "data_row", "else", ":", "data", "=", "data", "*", "self", ".", "scaler", ".", "scale_", "+", "self", ".", "scaler", ".", "mean_", "categorical_features", "=", "self", ".", "categorical_features", "first_row", "=", "data_row", "else", ":", "first_row", "=", "self", ".", "discretizer", ".", "discretize", "(", "data_row", ")", "data", "[", "0", "]", "=", "data_row", ".", "copy", "(", ")", "inverse", "=", "data", ".", "copy", "(", ")", "for", "column", "in", "categorical_features", ":", "values", "=", "self", ".", "feature_values", "[", "column", "]", "freqs", "=", "self", ".", "feature_frequencies", "[", "column", "]", "inverse_column", "=", "self", ".", "random_state", ".", "choice", "(", "values", ",", "size", "=", "num_samples", ",", "replace", "=", "True", ",", "p", "=", "freqs", ")", "binary_column", "=", "np", ".", "array", "(", "[", "1", "if", "x", "==", "first_row", "[", "column", "]", "else", "0", "for", "x", "in", "inverse_column", "]", ")", "binary_column", "[", "0", "]", "=", "1", "inverse_column", "[", "0", "]", "=", "data", "[", "0", ",", "column", "]", "data", "[", ":", ",", "column", "]", "=", "binary_column", "inverse", "[", ":", ",", "column", "]", "=", "inverse_column", "if", "self", ".", "discretizer", "is", "not", "None", ":", "inverse", "[", "1", ":", "]", "=", "self", ".", "discretizer", ".", "undiscretize", "(", "inverse", "[", "1", ":", "]", ")", "inverse", "[", "0", "]", "=", "data_row", "return", "data", ",", "inverse" ]
Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according to the training distribution, and making a binary feature that is 1 when the value is the same as the instance being explained. Args: data_row: 1d numpy array, corresponding to a row num_samples: size of the neighborhood to learn the linear model Returns: A tuple (data, inverse), where: data: dense num_samples * K matrix, where categorical features are encoded with either 0 (not equal to the corresponding value in data_row) or 1. The first row is the original instance. inverse: same as data, except the categorical features are not binary, but categorical (as the original data)
[ "Generates", "a", "neighborhood", "around", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L427-L481
train
marcotcr/lime
lime/lime_tabular.py
RecurrentTabularExplainer._make_predict_proba
def _make_predict_proba(self, func): """ The predict_proba method will expect 3d arrays, but we are reshaping them to 2D so that LIME works correctly. This wraps the function you give in explain_instance to first reshape the data to have the shape the the keras-style network expects. """ def predict_proba(X): n_samples = X.shape[0] new_shape = (n_samples, self.n_features, self.n_timesteps) X = np.transpose(X.reshape(new_shape), axes=(0, 2, 1)) return func(X) return predict_proba
python
def _make_predict_proba(self, func): """ The predict_proba method will expect 3d arrays, but we are reshaping them to 2D so that LIME works correctly. This wraps the function you give in explain_instance to first reshape the data to have the shape the the keras-style network expects. """ def predict_proba(X): n_samples = X.shape[0] new_shape = (n_samples, self.n_features, self.n_timesteps) X = np.transpose(X.reshape(new_shape), axes=(0, 2, 1)) return func(X) return predict_proba
[ "def", "_make_predict_proba", "(", "self", ",", "func", ")", ":", "def", "predict_proba", "(", "X", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "new_shape", "=", "(", "n_samples", ",", "self", ".", "n_features", ",", "self", ".", "n_timesteps", ")", "X", "=", "np", ".", "transpose", "(", "X", ".", "reshape", "(", "new_shape", ")", ",", "axes", "=", "(", "0", ",", "2", ",", "1", ")", ")", "return", "func", "(", "X", ")", "return", "predict_proba" ]
The predict_proba method will expect 3d arrays, but we are reshaping them to 2D so that LIME works correctly. This wraps the function you give in explain_instance to first reshape the data to have the shape the the keras-style network expects.
[ "The", "predict_proba", "method", "will", "expect", "3d", "arrays", "but", "we", "are", "reshaping", "them", "to", "2D", "so", "that", "LIME", "works", "correctly", ".", "This", "wraps", "the", "function", "you", "give", "in", "explain_instance", "to", "first", "reshape", "the", "data", "to", "have", "the", "shape", "the", "the", "keras", "-", "style", "network", "expects", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L571-L585
train
marcotcr/lime
lime/lime_tabular.py
RecurrentTabularExplainer.explain_instance
def explain_instance(self, data_row, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 2d numpy array, corresponding to a row classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ # Flatten input so that the normal explainer can handle it data_row = data_row.T.reshape(self.n_timesteps * self.n_features) # Wrap the classifier to reshape input classifier_fn = self._make_predict_proba(classifier_fn) return super(RecurrentTabularExplainer, self).explain_instance( data_row, classifier_fn, labels=labels, top_labels=top_labels, num_features=num_features, num_samples=num_samples, distance_metric=distance_metric, model_regressor=model_regressor)
python
def explain_instance(self, data_row, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 2d numpy array, corresponding to a row classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ # Flatten input so that the normal explainer can handle it data_row = data_row.T.reshape(self.n_timesteps * self.n_features) # Wrap the classifier to reshape input classifier_fn = self._make_predict_proba(classifier_fn) return super(RecurrentTabularExplainer, self).explain_instance( data_row, classifier_fn, labels=labels, top_labels=top_labels, num_features=num_features, num_samples=num_samples, distance_metric=distance_metric, model_regressor=model_regressor)
[ "def", "explain_instance", "(", "self", ",", "data_row", ",", "classifier_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=", "'euclidean'", ",", "model_regressor", "=", "None", ")", ":", "# Flatten input so that the normal explainer can handle it", "data_row", "=", "data_row", ".", "T", ".", "reshape", "(", "self", ".", "n_timesteps", "*", "self", ".", "n_features", ")", "# Wrap the classifier to reshape input", "classifier_fn", "=", "self", ".", "_make_predict_proba", "(", "classifier_fn", ")", "return", "super", "(", "RecurrentTabularExplainer", ",", "self", ")", ".", "explain_instance", "(", "data_row", ",", "classifier_fn", ",", "labels", "=", "labels", ",", "top_labels", "=", "top_labels", ",", "num_features", "=", "num_features", ",", "num_samples", "=", "num_samples", ",", "distance_metric", "=", "distance_metric", ",", "model_regressor", "=", "model_regressor", ")" ]
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 2d numpy array, corresponding to a row classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L587-L631
train
marcotcr/lime
lime/lime_image.py
ImageExplanation.get_image_and_mask
def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min_weight=0.): """Init function. Args: label: label to explain positive_only: if True, only take superpixels that contribute to the prediction of the label. Otherwise, use the top num_features superpixels, which can be positive or negative towards the label hide_rest: if True, make the non-explanation part of the return image gray num_features: number of superpixels to include in explanation min_weight: TODO Returns: (image, mask), where image is a 3d numpy array and mask is a 2d numpy array that can be used with skimage.segmentation.mark_boundaries """ if label not in self.local_exp: raise KeyError('Label not in explanation') segments = self.segments image = self.image exp = self.local_exp[label] mask = np.zeros(segments.shape, segments.dtype) if hide_rest: temp = np.zeros(self.image.shape) else: temp = self.image.copy() if positive_only: fs = [x[0] for x in exp if x[1] > 0 and x[1] > min_weight][:num_features] for f in fs: temp[segments == f] = image[segments == f].copy() mask[segments == f] = 1 return temp, mask else: for f, w in exp[:num_features]: if np.abs(w) < min_weight: continue c = 0 if w < 0 else 1 mask[segments == f] = 1 if w < 0 else 2 temp[segments == f] = image[segments == f].copy() temp[segments == f, c] = np.max(image) for cp in [0, 1, 2]: if c == cp: continue # temp[segments == f, cp] *= 0.5 return temp, mask
python
def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min_weight=0.): """Init function. Args: label: label to explain positive_only: if True, only take superpixels that contribute to the prediction of the label. Otherwise, use the top num_features superpixels, which can be positive or negative towards the label hide_rest: if True, make the non-explanation part of the return image gray num_features: number of superpixels to include in explanation min_weight: TODO Returns: (image, mask), where image is a 3d numpy array and mask is a 2d numpy array that can be used with skimage.segmentation.mark_boundaries """ if label not in self.local_exp: raise KeyError('Label not in explanation') segments = self.segments image = self.image exp = self.local_exp[label] mask = np.zeros(segments.shape, segments.dtype) if hide_rest: temp = np.zeros(self.image.shape) else: temp = self.image.copy() if positive_only: fs = [x[0] for x in exp if x[1] > 0 and x[1] > min_weight][:num_features] for f in fs: temp[segments == f] = image[segments == f].copy() mask[segments == f] = 1 return temp, mask else: for f, w in exp[:num_features]: if np.abs(w) < min_weight: continue c = 0 if w < 0 else 1 mask[segments == f] = 1 if w < 0 else 2 temp[segments == f] = image[segments == f].copy() temp[segments == f, c] = np.max(image) for cp in [0, 1, 2]: if c == cp: continue # temp[segments == f, cp] *= 0.5 return temp, mask
[ "def", "get_image_and_mask", "(", "self", ",", "label", ",", "positive_only", "=", "True", ",", "hide_rest", "=", "False", ",", "num_features", "=", "5", ",", "min_weight", "=", "0.", ")", ":", "if", "label", "not", "in", "self", ".", "local_exp", ":", "raise", "KeyError", "(", "'Label not in explanation'", ")", "segments", "=", "self", ".", "segments", "image", "=", "self", ".", "image", "exp", "=", "self", ".", "local_exp", "[", "label", "]", "mask", "=", "np", ".", "zeros", "(", "segments", ".", "shape", ",", "segments", ".", "dtype", ")", "if", "hide_rest", ":", "temp", "=", "np", ".", "zeros", "(", "self", ".", "image", ".", "shape", ")", "else", ":", "temp", "=", "self", ".", "image", ".", "copy", "(", ")", "if", "positive_only", ":", "fs", "=", "[", "x", "[", "0", "]", "for", "x", "in", "exp", "if", "x", "[", "1", "]", ">", "0", "and", "x", "[", "1", "]", ">", "min_weight", "]", "[", ":", "num_features", "]", "for", "f", "in", "fs", ":", "temp", "[", "segments", "==", "f", "]", "=", "image", "[", "segments", "==", "f", "]", ".", "copy", "(", ")", "mask", "[", "segments", "==", "f", "]", "=", "1", "return", "temp", ",", "mask", "else", ":", "for", "f", ",", "w", "in", "exp", "[", ":", "num_features", "]", ":", "if", "np", ".", "abs", "(", "w", ")", "<", "min_weight", ":", "continue", "c", "=", "0", "if", "w", "<", "0", "else", "1", "mask", "[", "segments", "==", "f", "]", "=", "1", "if", "w", "<", "0", "else", "2", "temp", "[", "segments", "==", "f", "]", "=", "image", "[", "segments", "==", "f", "]", ".", "copy", "(", ")", "temp", "[", "segments", "==", "f", ",", "c", "]", "=", "np", ".", "max", "(", "image", ")", "for", "cp", "in", "[", "0", ",", "1", ",", "2", "]", ":", "if", "c", "==", "cp", ":", "continue", "# temp[segments == f, cp] *= 0.5", "return", "temp", ",", "mask" ]
Init function. Args: label: label to explain positive_only: if True, only take superpixels that contribute to the prediction of the label. Otherwise, use the top num_features superpixels, which can be positive or negative towards the label hide_rest: if True, make the non-explanation part of the return image gray num_features: number of superpixels to include in explanation min_weight: TODO Returns: (image, mask), where image is a 3d numpy array and mask is a 2d numpy array that can be used with skimage.segmentation.mark_boundaries
[ "Init", "function", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_image.py#L31-L80
train
marcotcr/lime
lime/lime_image.py
LimeImageExplainer.explain_instance
def explain_instance(self, image, classifier_fn, labels=(1,), hide_color=None, top_labels=5, num_features=100000, num_samples=1000, batch_size=10, segmentation_fn=None, distance_metric='cosine', model_regressor=None, random_seed=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: image: 3 dimension RGB image. If this is only two dimensional, we will assume it's a grayscale image and call gray2rgb. classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. hide_color: TODO top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model batch_size: TODO distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() segmentation_fn: SegmentationAlgorithm, wrapped skimage segmentation function random_seed: integer used as random seed for the segmentation algorithm. If None, a random integer, between 0 and 1000, will be generated using the internal random number generator. Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ if len(image.shape) == 2: image = gray2rgb(image) if random_seed is None: random_seed = self.random_state.randint(0, high=1000) if segmentation_fn is None: segmentation_fn = SegmentationAlgorithm('quickshift', kernel_size=4, max_dist=200, ratio=0.2, random_seed=random_seed) try: segments = segmentation_fn(image) except ValueError as e: raise e fudged_image = image.copy() if hide_color is None: for x in np.unique(segments): fudged_image[segments == x] = ( np.mean(image[segments == x][:, 0]), np.mean(image[segments == x][:, 1]), np.mean(image[segments == x][:, 2])) else: fudged_image[:] = hide_color top = labels data, labels = self.data_labels(image, fudged_image, segments, classifier_fn, num_samples, batch_size=batch_size) distances = sklearn.metrics.pairwise_distances( data, data[0].reshape(1, -1), metric=distance_metric ).ravel() ret_exp = ImageExplanation(image, segments) if top_labels: top = np.argsort(labels[0])[-top_labels:] ret_exp.top_labels = list(top) ret_exp.top_labels.reverse() for label in top: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( data, labels, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) return ret_exp
python
def explain_instance(self, image, classifier_fn, labels=(1,), hide_color=None, top_labels=5, num_features=100000, num_samples=1000, batch_size=10, segmentation_fn=None, distance_metric='cosine', model_regressor=None, random_seed=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: image: 3 dimension RGB image. If this is only two dimensional, we will assume it's a grayscale image and call gray2rgb. classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. hide_color: TODO top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model batch_size: TODO distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() segmentation_fn: SegmentationAlgorithm, wrapped skimage segmentation function random_seed: integer used as random seed for the segmentation algorithm. If None, a random integer, between 0 and 1000, will be generated using the internal random number generator. Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ if len(image.shape) == 2: image = gray2rgb(image) if random_seed is None: random_seed = self.random_state.randint(0, high=1000) if segmentation_fn is None: segmentation_fn = SegmentationAlgorithm('quickshift', kernel_size=4, max_dist=200, ratio=0.2, random_seed=random_seed) try: segments = segmentation_fn(image) except ValueError as e: raise e fudged_image = image.copy() if hide_color is None: for x in np.unique(segments): fudged_image[segments == x] = ( np.mean(image[segments == x][:, 0]), np.mean(image[segments == x][:, 1]), np.mean(image[segments == x][:, 2])) else: fudged_image[:] = hide_color top = labels data, labels = self.data_labels(image, fudged_image, segments, classifier_fn, num_samples, batch_size=batch_size) distances = sklearn.metrics.pairwise_distances( data, data[0].reshape(1, -1), metric=distance_metric ).ravel() ret_exp = ImageExplanation(image, segments) if top_labels: top = np.argsort(labels[0])[-top_labels:] ret_exp.top_labels = list(top) ret_exp.top_labels.reverse() for label in top: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( data, labels, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) return ret_exp
[ "def", "explain_instance", "(", "self", ",", "image", ",", "classifier_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "hide_color", "=", "None", ",", "top_labels", "=", "5", ",", "num_features", "=", "100000", ",", "num_samples", "=", "1000", ",", "batch_size", "=", "10", ",", "segmentation_fn", "=", "None", ",", "distance_metric", "=", "'cosine'", ",", "model_regressor", "=", "None", ",", "random_seed", "=", "None", ")", ":", "if", "len", "(", "image", ".", "shape", ")", "==", "2", ":", "image", "=", "gray2rgb", "(", "image", ")", "if", "random_seed", "is", "None", ":", "random_seed", "=", "self", ".", "random_state", ".", "randint", "(", "0", ",", "high", "=", "1000", ")", "if", "segmentation_fn", "is", "None", ":", "segmentation_fn", "=", "SegmentationAlgorithm", "(", "'quickshift'", ",", "kernel_size", "=", "4", ",", "max_dist", "=", "200", ",", "ratio", "=", "0.2", ",", "random_seed", "=", "random_seed", ")", "try", ":", "segments", "=", "segmentation_fn", "(", "image", ")", "except", "ValueError", "as", "e", ":", "raise", "e", "fudged_image", "=", "image", ".", "copy", "(", ")", "if", "hide_color", "is", "None", ":", "for", "x", "in", "np", ".", "unique", "(", "segments", ")", ":", "fudged_image", "[", "segments", "==", "x", "]", "=", "(", "np", ".", "mean", "(", "image", "[", "segments", "==", "x", "]", "[", ":", ",", "0", "]", ")", ",", "np", ".", "mean", "(", "image", "[", "segments", "==", "x", "]", "[", ":", ",", "1", "]", ")", ",", "np", ".", "mean", "(", "image", "[", "segments", "==", "x", "]", "[", ":", ",", "2", "]", ")", ")", "else", ":", "fudged_image", "[", ":", "]", "=", "hide_color", "top", "=", "labels", "data", ",", "labels", "=", "self", ".", "data_labels", "(", "image", ",", "fudged_image", ",", "segments", ",", "classifier_fn", ",", "num_samples", ",", "batch_size", "=", "batch_size", ")", "distances", "=", "sklearn", ".", "metrics", ".", "pairwise_distances", "(", "data", ",", "data", "[", "0", "]", ".", "reshape", "(", "1", ",", "-", "1", ")", ",", "metric", "=", "distance_metric", ")", ".", "ravel", "(", ")", "ret_exp", "=", "ImageExplanation", "(", "image", ",", "segments", ")", "if", "top_labels", ":", "top", "=", "np", ".", "argsort", "(", "labels", "[", "0", "]", ")", "[", "-", "top_labels", ":", "]", "ret_exp", ".", "top_labels", "=", "list", "(", "top", ")", "ret_exp", ".", "top_labels", ".", "reverse", "(", ")", "for", "label", "in", "top", ":", "(", "ret_exp", ".", "intercept", "[", "label", "]", ",", "ret_exp", ".", "local_exp", "[", "label", "]", ",", "ret_exp", ".", "score", ",", "ret_exp", ".", "local_pred", ")", "=", "self", ".", "base", ".", "explain_instance_with_data", "(", "data", ",", "labels", ",", "distances", ",", "label", ",", "num_features", ",", "model_regressor", "=", "model_regressor", ",", "feature_selection", "=", "self", ".", "feature_selection", ")", "return", "ret_exp" ]
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: image: 3 dimension RGB image. If this is only two dimensional, we will assume it's a grayscale image and call gray2rgb. classifier_fn: classifier prediction probability function, which takes a numpy array and outputs prediction probabilities. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. hide_color: TODO top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model batch_size: TODO distance_metric: the distance metric to use for weights. model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() segmentation_fn: SegmentationAlgorithm, wrapped skimage segmentation function random_seed: integer used as random seed for the segmentation algorithm. If None, a random integer, between 0 and 1000, will be generated using the internal random number generator. Returns: An Explanation object (see explanation.py) with the corresponding explanations.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_image.py#L123-L214
train
marcotcr/lime
lime/lime_image.py
LimeImageExplainer.data_labels
def data_labels(self, image, fudged_image, segments, classifier_fn, num_samples, batch_size=10): """Generates images and predictions in the neighborhood of this image. Args: image: 3d numpy array, the image fudged_image: 3d numpy array, image to replace original image when superpixel is turned off segments: segmentation of the image classifier_fn: function that takes a list of images and returns a matrix of prediction probabilities num_samples: size of the neighborhood to learn the linear model batch_size: classifier_fn will be called on batches of this size. Returns: A tuple (data, labels), where: data: dense num_samples * num_superpixels labels: prediction probabilities matrix """ n_features = np.unique(segments).shape[0] data = self.random_state.randint(0, 2, num_samples * n_features)\ .reshape((num_samples, n_features)) labels = [] data[0, :] = 1 imgs = [] for row in data: temp = copy.deepcopy(image) zeros = np.where(row == 0)[0] mask = np.zeros(segments.shape).astype(bool) for z in zeros: mask[segments == z] = True temp[mask] = fudged_image[mask] imgs.append(temp) if len(imgs) == batch_size: preds = classifier_fn(np.array(imgs)) labels.extend(preds) imgs = [] if len(imgs) > 0: preds = classifier_fn(np.array(imgs)) labels.extend(preds) return data, np.array(labels)
python
def data_labels(self, image, fudged_image, segments, classifier_fn, num_samples, batch_size=10): """Generates images and predictions in the neighborhood of this image. Args: image: 3d numpy array, the image fudged_image: 3d numpy array, image to replace original image when superpixel is turned off segments: segmentation of the image classifier_fn: function that takes a list of images and returns a matrix of prediction probabilities num_samples: size of the neighborhood to learn the linear model batch_size: classifier_fn will be called on batches of this size. Returns: A tuple (data, labels), where: data: dense num_samples * num_superpixels labels: prediction probabilities matrix """ n_features = np.unique(segments).shape[0] data = self.random_state.randint(0, 2, num_samples * n_features)\ .reshape((num_samples, n_features)) labels = [] data[0, :] = 1 imgs = [] for row in data: temp = copy.deepcopy(image) zeros = np.where(row == 0)[0] mask = np.zeros(segments.shape).astype(bool) for z in zeros: mask[segments == z] = True temp[mask] = fudged_image[mask] imgs.append(temp) if len(imgs) == batch_size: preds = classifier_fn(np.array(imgs)) labels.extend(preds) imgs = [] if len(imgs) > 0: preds = classifier_fn(np.array(imgs)) labels.extend(preds) return data, np.array(labels)
[ "def", "data_labels", "(", "self", ",", "image", ",", "fudged_image", ",", "segments", ",", "classifier_fn", ",", "num_samples", ",", "batch_size", "=", "10", ")", ":", "n_features", "=", "np", ".", "unique", "(", "segments", ")", ".", "shape", "[", "0", "]", "data", "=", "self", ".", "random_state", ".", "randint", "(", "0", ",", "2", ",", "num_samples", "*", "n_features", ")", ".", "reshape", "(", "(", "num_samples", ",", "n_features", ")", ")", "labels", "=", "[", "]", "data", "[", "0", ",", ":", "]", "=", "1", "imgs", "=", "[", "]", "for", "row", "in", "data", ":", "temp", "=", "copy", ".", "deepcopy", "(", "image", ")", "zeros", "=", "np", ".", "where", "(", "row", "==", "0", ")", "[", "0", "]", "mask", "=", "np", ".", "zeros", "(", "segments", ".", "shape", ")", ".", "astype", "(", "bool", ")", "for", "z", "in", "zeros", ":", "mask", "[", "segments", "==", "z", "]", "=", "True", "temp", "[", "mask", "]", "=", "fudged_image", "[", "mask", "]", "imgs", ".", "append", "(", "temp", ")", "if", "len", "(", "imgs", ")", "==", "batch_size", ":", "preds", "=", "classifier_fn", "(", "np", ".", "array", "(", "imgs", ")", ")", "labels", ".", "extend", "(", "preds", ")", "imgs", "=", "[", "]", "if", "len", "(", "imgs", ")", ">", "0", ":", "preds", "=", "classifier_fn", "(", "np", ".", "array", "(", "imgs", ")", ")", "labels", ".", "extend", "(", "preds", ")", "return", "data", ",", "np", ".", "array", "(", "labels", ")" ]
Generates images and predictions in the neighborhood of this image. Args: image: 3d numpy array, the image fudged_image: 3d numpy array, image to replace original image when superpixel is turned off segments: segmentation of the image classifier_fn: function that takes a list of images and returns a matrix of prediction probabilities num_samples: size of the neighborhood to learn the linear model batch_size: classifier_fn will be called on batches of this size. Returns: A tuple (data, labels), where: data: dense num_samples * num_superpixels labels: prediction probabilities matrix
[ "Generates", "images", "and", "predictions", "in", "the", "neighborhood", "of", "this", "image", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_image.py#L216-L261
train
marcotcr/lime
lime/utils/generic_utils.py
has_arg
def has_arg(fn, arg_name): """Checks if a callable accepts a given keyword argument. Args: fn: callable to inspect arg_name: string, keyword argument name to check Returns: bool, whether `fn` accepts a `arg_name` keyword argument. """ if sys.version_info < (3,): if isinstance(fn, types.FunctionType) or isinstance(fn, types.MethodType): arg_spec = inspect.getargspec(fn) else: try: arg_spec = inspect.getargspec(fn.__call__) except AttributeError: return False return (arg_name in arg_spec.args) elif sys.version_info < (3, 6): arg_spec = inspect.getfullargspec(fn) return (arg_name in arg_spec.args or arg_name in arg_spec.kwonlyargs) else: try: signature = inspect.signature(fn) except ValueError: # handling Cython signature = inspect.signature(fn.__call__) parameter = signature.parameters.get(arg_name) if parameter is None: return False return (parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY))
python
def has_arg(fn, arg_name): """Checks if a callable accepts a given keyword argument. Args: fn: callable to inspect arg_name: string, keyword argument name to check Returns: bool, whether `fn` accepts a `arg_name` keyword argument. """ if sys.version_info < (3,): if isinstance(fn, types.FunctionType) or isinstance(fn, types.MethodType): arg_spec = inspect.getargspec(fn) else: try: arg_spec = inspect.getargspec(fn.__call__) except AttributeError: return False return (arg_name in arg_spec.args) elif sys.version_info < (3, 6): arg_spec = inspect.getfullargspec(fn) return (arg_name in arg_spec.args or arg_name in arg_spec.kwonlyargs) else: try: signature = inspect.signature(fn) except ValueError: # handling Cython signature = inspect.signature(fn.__call__) parameter = signature.parameters.get(arg_name) if parameter is None: return False return (parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY))
[ "def", "has_arg", "(", "fn", ",", "arg_name", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", ":", "if", "isinstance", "(", "fn", ",", "types", ".", "FunctionType", ")", "or", "isinstance", "(", "fn", ",", "types", ".", "MethodType", ")", ":", "arg_spec", "=", "inspect", ".", "getargspec", "(", "fn", ")", "else", ":", "try", ":", "arg_spec", "=", "inspect", ".", "getargspec", "(", "fn", ".", "__call__", ")", "except", "AttributeError", ":", "return", "False", "return", "(", "arg_name", "in", "arg_spec", ".", "args", ")", "elif", "sys", ".", "version_info", "<", "(", "3", ",", "6", ")", ":", "arg_spec", "=", "inspect", ".", "getfullargspec", "(", "fn", ")", "return", "(", "arg_name", "in", "arg_spec", ".", "args", "or", "arg_name", "in", "arg_spec", ".", "kwonlyargs", ")", "else", ":", "try", ":", "signature", "=", "inspect", ".", "signature", "(", "fn", ")", "except", "ValueError", ":", "# handling Cython", "signature", "=", "inspect", ".", "signature", "(", "fn", ".", "__call__", ")", "parameter", "=", "signature", ".", "parameters", ".", "get", "(", "arg_name", ")", "if", "parameter", "is", "None", ":", "return", "False", "return", "(", "parameter", ".", "kind", "in", "(", "inspect", ".", "Parameter", ".", "POSITIONAL_OR_KEYWORD", ",", "inspect", ".", "Parameter", ".", "KEYWORD_ONLY", ")", ")" ]
Checks if a callable accepts a given keyword argument. Args: fn: callable to inspect arg_name: string, keyword argument name to check Returns: bool, whether `fn` accepts a `arg_name` keyword argument.
[ "Checks", "if", "a", "callable", "accepts", "a", "given", "keyword", "argument", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/utils/generic_utils.py#L6-L39
train
marcotcr/lime
lime/discretize.py
BaseDiscretizer.discretize
def discretize(self, data): """Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized. """ ret = data.copy() for feature in self.lambdas: if len(data.shape) == 1: ret[feature] = int(self.lambdas[feature](ret[feature])) else: ret[:, feature] = self.lambdas[feature]( ret[:, feature]).astype(int) return ret
python
def discretize(self, data): """Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized. """ ret = data.copy() for feature in self.lambdas: if len(data.shape) == 1: ret[feature] = int(self.lambdas[feature](ret[feature])) else: ret[:, feature] = self.lambdas[feature]( ret[:, feature]).astype(int) return ret
[ "def", "discretize", "(", "self", ",", "data", ")", ":", "ret", "=", "data", ".", "copy", "(", ")", "for", "feature", "in", "self", ".", "lambdas", ":", "if", "len", "(", "data", ".", "shape", ")", "==", "1", ":", "ret", "[", "feature", "]", "=", "int", "(", "self", ".", "lambdas", "[", "feature", "]", "(", "ret", "[", "feature", "]", ")", ")", "else", ":", "ret", "[", ":", ",", "feature", "]", "=", "self", ".", "lambdas", "[", "feature", "]", "(", "ret", "[", ":", ",", "feature", "]", ")", ".", "astype", "(", "int", ")", "return", "ret" ]
Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized.
[ "Discretizes", "the", "data", ".", "Args", ":", "data", ":", "numpy", "2d", "or", "1d", "array", "Returns", ":", "numpy", "array", "of", "same", "dimension", "discretized", "." ]
08133d47df00ed918e22005e0c98f6eefd5a1d71
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/discretize.py#L99-L113
train
iterative/dvc
dvc/cache.py
Cache._get_remote
def _get_remote(self, config, name): """ The config file is stored in a way that allows you to have a cache for each remote. This is needed when specifying external outputs (as they require you to have an external cache location). Imagine a config file like the following: ['remote "dvc-storage"'] url = ssh://localhost/tmp ask_password = true [cache] ssh = dvc-storage This method resolves the name under the cache section into the correct Remote instance. Args: config (dict): The cache section on the config file name (str): Name of the section we are interested in to retrieve Returns: remote (dvc.Remote): Remote instance that the section is referring. None when there's no remote with that name. Example: >>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh') """ from dvc.remote import Remote remote = config.get(name) if not remote: return None settings = self.repo.config.get_remote_settings(remote) return Remote(self.repo, settings)
python
def _get_remote(self, config, name): """ The config file is stored in a way that allows you to have a cache for each remote. This is needed when specifying external outputs (as they require you to have an external cache location). Imagine a config file like the following: ['remote "dvc-storage"'] url = ssh://localhost/tmp ask_password = true [cache] ssh = dvc-storage This method resolves the name under the cache section into the correct Remote instance. Args: config (dict): The cache section on the config file name (str): Name of the section we are interested in to retrieve Returns: remote (dvc.Remote): Remote instance that the section is referring. None when there's no remote with that name. Example: >>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh') """ from dvc.remote import Remote remote = config.get(name) if not remote: return None settings = self.repo.config.get_remote_settings(remote) return Remote(self.repo, settings)
[ "def", "_get_remote", "(", "self", ",", "config", ",", "name", ")", ":", "from", "dvc", ".", "remote", "import", "Remote", "remote", "=", "config", ".", "get", "(", "name", ")", "if", "not", "remote", ":", "return", "None", "settings", "=", "self", ".", "repo", ".", "config", ".", "get_remote_settings", "(", "remote", ")", "return", "Remote", "(", "self", ".", "repo", ",", "settings", ")" ]
The config file is stored in a way that allows you to have a cache for each remote. This is needed when specifying external outputs (as they require you to have an external cache location). Imagine a config file like the following: ['remote "dvc-storage"'] url = ssh://localhost/tmp ask_password = true [cache] ssh = dvc-storage This method resolves the name under the cache section into the correct Remote instance. Args: config (dict): The cache section on the config file name (str): Name of the section we are interested in to retrieve Returns: remote (dvc.Remote): Remote instance that the section is referring. None when there's no remote with that name. Example: >>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh')
[ "The", "config", "file", "is", "stored", "in", "a", "way", "that", "allows", "you", "to", "have", "a", "cache", "for", "each", "remote", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cache.py#L52-L91
train
iterative/dvc
dvc/dagascii.py
draw
def draw(vertexes, edges): """Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges. """ # pylint: disable=too-many-locals # NOTE: coordinates might me negative, so we need to shift # everything to the positive plane before we actually draw it. Xs = [] # pylint: disable=invalid-name Ys = [] # pylint: disable=invalid-name sug = _build_sugiyama_layout(vertexes, edges) for vertex in sug.g.sV: # NOTE: moving boxes w/2 to the left Xs.append(vertex.view.xy[0] - vertex.view.w / 2.0) Xs.append(vertex.view.xy[0] + vertex.view.w / 2.0) Ys.append(vertex.view.xy[1]) Ys.append(vertex.view.xy[1] + vertex.view.h) for edge in sug.g.sE: for x, y in edge.view._pts: # pylint: disable=protected-access Xs.append(x) Ys.append(y) minx = min(Xs) miny = min(Ys) maxx = max(Xs) maxy = max(Ys) canvas_cols = int(math.ceil(math.ceil(maxx) - math.floor(minx))) + 1 canvas_lines = int(round(maxy - miny)) canvas = AsciiCanvas(canvas_cols, canvas_lines) # NOTE: first draw edges so that node boxes could overwrite them for edge in sug.g.sE: # pylint: disable=protected-access assert len(edge.view._pts) > 1 for index in range(1, len(edge.view._pts)): start = edge.view._pts[index - 1] end = edge.view._pts[index] start_x = int(round(start[0] - minx)) start_y = int(round(start[1] - miny)) end_x = int(round(end[0] - minx)) end_y = int(round(end[1] - miny)) assert start_x >= 0 assert start_y >= 0 assert end_x >= 0 assert end_y >= 0 canvas.line(start_x, start_y, end_x, end_y, "*") for vertex in sug.g.sV: # NOTE: moving boxes w/2 to the left x = vertex.view.xy[0] - vertex.view.w / 2.0 y = vertex.view.xy[1] canvas.box( int(round(x - minx)), int(round(y - miny)), vertex.view.w, vertex.view.h, ) canvas.text( int(round(x - minx)) + 1, int(round(y - miny)) + 1, vertex.data ) canvas.draw()
python
def draw(vertexes, edges): """Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges. """ # pylint: disable=too-many-locals # NOTE: coordinates might me negative, so we need to shift # everything to the positive plane before we actually draw it. Xs = [] # pylint: disable=invalid-name Ys = [] # pylint: disable=invalid-name sug = _build_sugiyama_layout(vertexes, edges) for vertex in sug.g.sV: # NOTE: moving boxes w/2 to the left Xs.append(vertex.view.xy[0] - vertex.view.w / 2.0) Xs.append(vertex.view.xy[0] + vertex.view.w / 2.0) Ys.append(vertex.view.xy[1]) Ys.append(vertex.view.xy[1] + vertex.view.h) for edge in sug.g.sE: for x, y in edge.view._pts: # pylint: disable=protected-access Xs.append(x) Ys.append(y) minx = min(Xs) miny = min(Ys) maxx = max(Xs) maxy = max(Ys) canvas_cols = int(math.ceil(math.ceil(maxx) - math.floor(minx))) + 1 canvas_lines = int(round(maxy - miny)) canvas = AsciiCanvas(canvas_cols, canvas_lines) # NOTE: first draw edges so that node boxes could overwrite them for edge in sug.g.sE: # pylint: disable=protected-access assert len(edge.view._pts) > 1 for index in range(1, len(edge.view._pts)): start = edge.view._pts[index - 1] end = edge.view._pts[index] start_x = int(round(start[0] - minx)) start_y = int(round(start[1] - miny)) end_x = int(round(end[0] - minx)) end_y = int(round(end[1] - miny)) assert start_x >= 0 assert start_y >= 0 assert end_x >= 0 assert end_y >= 0 canvas.line(start_x, start_y, end_x, end_y, "*") for vertex in sug.g.sV: # NOTE: moving boxes w/2 to the left x = vertex.view.xy[0] - vertex.view.w / 2.0 y = vertex.view.xy[1] canvas.box( int(round(x - minx)), int(round(y - miny)), vertex.view.w, vertex.view.h, ) canvas.text( int(round(x - minx)) + 1, int(round(y - miny)) + 1, vertex.data ) canvas.draw()
[ "def", "draw", "(", "vertexes", ",", "edges", ")", ":", "# pylint: disable=too-many-locals", "# NOTE: coordinates might me negative, so we need to shift", "# everything to the positive plane before we actually draw it.", "Xs", "=", "[", "]", "# pylint: disable=invalid-name", "Ys", "=", "[", "]", "# pylint: disable=invalid-name", "sug", "=", "_build_sugiyama_layout", "(", "vertexes", ",", "edges", ")", "for", "vertex", "in", "sug", ".", "g", ".", "sV", ":", "# NOTE: moving boxes w/2 to the left", "Xs", ".", "append", "(", "vertex", ".", "view", ".", "xy", "[", "0", "]", "-", "vertex", ".", "view", ".", "w", "/", "2.0", ")", "Xs", ".", "append", "(", "vertex", ".", "view", ".", "xy", "[", "0", "]", "+", "vertex", ".", "view", ".", "w", "/", "2.0", ")", "Ys", ".", "append", "(", "vertex", ".", "view", ".", "xy", "[", "1", "]", ")", "Ys", ".", "append", "(", "vertex", ".", "view", ".", "xy", "[", "1", "]", "+", "vertex", ".", "view", ".", "h", ")", "for", "edge", "in", "sug", ".", "g", ".", "sE", ":", "for", "x", ",", "y", "in", "edge", ".", "view", ".", "_pts", ":", "# pylint: disable=protected-access", "Xs", ".", "append", "(", "x", ")", "Ys", ".", "append", "(", "y", ")", "minx", "=", "min", "(", "Xs", ")", "miny", "=", "min", "(", "Ys", ")", "maxx", "=", "max", "(", "Xs", ")", "maxy", "=", "max", "(", "Ys", ")", "canvas_cols", "=", "int", "(", "math", ".", "ceil", "(", "math", ".", "ceil", "(", "maxx", ")", "-", "math", ".", "floor", "(", "minx", ")", ")", ")", "+", "1", "canvas_lines", "=", "int", "(", "round", "(", "maxy", "-", "miny", ")", ")", "canvas", "=", "AsciiCanvas", "(", "canvas_cols", ",", "canvas_lines", ")", "# NOTE: first draw edges so that node boxes could overwrite them", "for", "edge", "in", "sug", ".", "g", ".", "sE", ":", "# pylint: disable=protected-access", "assert", "len", "(", "edge", ".", "view", ".", "_pts", ")", ">", "1", "for", "index", "in", "range", "(", "1", ",", "len", "(", "edge", ".", "view", ".", "_pts", ")", ")", ":", "start", "=", "edge", ".", "view", ".", "_pts", "[", "index", "-", "1", "]", "end", "=", "edge", ".", "view", ".", "_pts", "[", "index", "]", "start_x", "=", "int", "(", "round", "(", "start", "[", "0", "]", "-", "minx", ")", ")", "start_y", "=", "int", "(", "round", "(", "start", "[", "1", "]", "-", "miny", ")", ")", "end_x", "=", "int", "(", "round", "(", "end", "[", "0", "]", "-", "minx", ")", ")", "end_y", "=", "int", "(", "round", "(", "end", "[", "1", "]", "-", "miny", ")", ")", "assert", "start_x", ">=", "0", "assert", "start_y", ">=", "0", "assert", "end_x", ">=", "0", "assert", "end_y", ">=", "0", "canvas", ".", "line", "(", "start_x", ",", "start_y", ",", "end_x", ",", "end_y", ",", "\"*\"", ")", "for", "vertex", "in", "sug", ".", "g", ".", "sV", ":", "# NOTE: moving boxes w/2 to the left", "x", "=", "vertex", ".", "view", ".", "xy", "[", "0", "]", "-", "vertex", ".", "view", ".", "w", "/", "2.0", "y", "=", "vertex", ".", "view", ".", "xy", "[", "1", "]", "canvas", ".", "box", "(", "int", "(", "round", "(", "x", "-", "minx", ")", ")", ",", "int", "(", "round", "(", "y", "-", "miny", ")", ")", ",", "vertex", ".", "view", ".", "w", ",", "vertex", ".", "view", ".", "h", ",", ")", "canvas", ".", "text", "(", "int", "(", "round", "(", "x", "-", "minx", ")", ")", "+", "1", ",", "int", "(", "round", "(", "y", "-", "miny", ")", ")", "+", "1", ",", "vertex", ".", "data", ")", "canvas", ".", "draw", "(", ")" ]
Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges.
[ "Build", "a", "DAG", "and", "draw", "it", "in", "ASCII", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L297-L370
train
iterative/dvc
dvc/dagascii.py
AsciiCanvas.draw
def draw(self): """Draws ASCII canvas on the screen.""" if sys.stdout.isatty(): # pragma: no cover from asciimatics.screen import Screen Screen.wrapper(self._do_draw) else: for line in self.canvas: print("".join(line))
python
def draw(self): """Draws ASCII canvas on the screen.""" if sys.stdout.isatty(): # pragma: no cover from asciimatics.screen import Screen Screen.wrapper(self._do_draw) else: for line in self.canvas: print("".join(line))
[ "def", "draw", "(", "self", ")", ":", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "# pragma: no cover", "from", "asciimatics", ".", "screen", "import", "Screen", "Screen", ".", "wrapper", "(", "self", ".", "_do_draw", ")", "else", ":", "for", "line", "in", "self", ".", "canvas", ":", "print", "(", "\"\"", ".", "join", "(", "line", ")", ")" ]
Draws ASCII canvas on the screen.
[ "Draws", "ASCII", "canvas", "on", "the", "screen", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L59-L67
train
iterative/dvc
dvc/dagascii.py
AsciiCanvas.point
def point(self, x, y, char): """Create a point on ASCII canvas. Args: x (int): x coordinate. Should be >= 0 and < number of columns in the canvas. y (int): y coordinate. Should be >= 0 an < number of lines in the canvas. char (str): character to place in the specified point on the canvas. """ assert len(char) == 1 assert x >= 0 assert x < self.cols assert y >= 0 assert y < self.lines self.canvas[y][x] = char
python
def point(self, x, y, char): """Create a point on ASCII canvas. Args: x (int): x coordinate. Should be >= 0 and < number of columns in the canvas. y (int): y coordinate. Should be >= 0 an < number of lines in the canvas. char (str): character to place in the specified point on the canvas. """ assert len(char) == 1 assert x >= 0 assert x < self.cols assert y >= 0 assert y < self.lines self.canvas[y][x] = char
[ "def", "point", "(", "self", ",", "x", ",", "y", ",", "char", ")", ":", "assert", "len", "(", "char", ")", "==", "1", "assert", "x", ">=", "0", "assert", "x", "<", "self", ".", "cols", "assert", "y", ">=", "0", "assert", "y", "<", "self", ".", "lines", "self", ".", "canvas", "[", "y", "]", "[", "x", "]", "=", "char" ]
Create a point on ASCII canvas. Args: x (int): x coordinate. Should be >= 0 and < number of columns in the canvas. y (int): y coordinate. Should be >= 0 an < number of lines in the canvas. char (str): character to place in the specified point on the canvas.
[ "Create", "a", "point", "on", "ASCII", "canvas", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L155-L172
train
iterative/dvc
dvc/dagascii.py
AsciiCanvas.line
def line(self, x0, y0, x1, y1, char): """Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (str): character to draw the line with. """ # pylint: disable=too-many-arguments, too-many-branches if x0 > x1: x1, x0 = x0, x1 y1, y0 = y0, y1 dx = x1 - x0 dy = y1 - y0 if dx == 0 and dy == 0: self.point(x0, y0, char) elif abs(dx) >= abs(dy): for x in range(x0, x1 + 1): if dx == 0: y = y0 else: y = y0 + int(round((x - x0) * dy / float((dx)))) self.point(x, y, char) elif y0 < y1: for y in range(y0, y1 + 1): if dy == 0: x = x0 else: x = x0 + int(round((y - y0) * dx / float((dy)))) self.point(x, y, char) else: for y in range(y1, y0 + 1): if dy == 0: x = x0 else: x = x1 + int(round((y - y1) * dx / float((dy)))) self.point(x, y, char)
python
def line(self, x0, y0, x1, y1, char): """Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (str): character to draw the line with. """ # pylint: disable=too-many-arguments, too-many-branches if x0 > x1: x1, x0 = x0, x1 y1, y0 = y0, y1 dx = x1 - x0 dy = y1 - y0 if dx == 0 and dy == 0: self.point(x0, y0, char) elif abs(dx) >= abs(dy): for x in range(x0, x1 + 1): if dx == 0: y = y0 else: y = y0 + int(round((x - x0) * dy / float((dx)))) self.point(x, y, char) elif y0 < y1: for y in range(y0, y1 + 1): if dy == 0: x = x0 else: x = x0 + int(round((y - y0) * dx / float((dy)))) self.point(x, y, char) else: for y in range(y1, y0 + 1): if dy == 0: x = x0 else: x = x1 + int(round((y - y1) * dx / float((dy)))) self.point(x, y, char)
[ "def", "line", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "char", ")", ":", "# pylint: disable=too-many-arguments, too-many-branches", "if", "x0", ">", "x1", ":", "x1", ",", "x0", "=", "x0", ",", "x1", "y1", ",", "y0", "=", "y0", ",", "y1", "dx", "=", "x1", "-", "x0", "dy", "=", "y1", "-", "y0", "if", "dx", "==", "0", "and", "dy", "==", "0", ":", "self", ".", "point", "(", "x0", ",", "y0", ",", "char", ")", "elif", "abs", "(", "dx", ")", ">=", "abs", "(", "dy", ")", ":", "for", "x", "in", "range", "(", "x0", ",", "x1", "+", "1", ")", ":", "if", "dx", "==", "0", ":", "y", "=", "y0", "else", ":", "y", "=", "y0", "+", "int", "(", "round", "(", "(", "x", "-", "x0", ")", "*", "dy", "/", "float", "(", "(", "dx", ")", ")", ")", ")", "self", ".", "point", "(", "x", ",", "y", ",", "char", ")", "elif", "y0", "<", "y1", ":", "for", "y", "in", "range", "(", "y0", ",", "y1", "+", "1", ")", ":", "if", "dy", "==", "0", ":", "x", "=", "x0", "else", ":", "x", "=", "x0", "+", "int", "(", "round", "(", "(", "y", "-", "y0", ")", "*", "dx", "/", "float", "(", "(", "dy", ")", ")", ")", ")", "self", ".", "point", "(", "x", ",", "y", ",", "char", ")", "else", ":", "for", "y", "in", "range", "(", "y1", ",", "y0", "+", "1", ")", ":", "if", "dy", "==", "0", ":", "x", "=", "x0", "else", ":", "x", "=", "x1", "+", "int", "(", "round", "(", "(", "y", "-", "y1", ")", "*", "dx", "/", "float", "(", "(", "dy", ")", ")", ")", ")", "self", ".", "point", "(", "x", ",", "y", ",", "char", ")" ]
Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (str): character to draw the line with.
[ "Create", "a", "line", "on", "ASCII", "canvas", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L174-L214
train
iterative/dvc
dvc/dagascii.py
AsciiCanvas.text
def text(self, x, y, text): """Print a text on ASCII canvas. Args: x (int): x coordinate where the text should start. y (int): y coordinate where the text should start. text (str): string that should be printed. """ for i, char in enumerate(text): self.point(x + i, y, char)
python
def text(self, x, y, text): """Print a text on ASCII canvas. Args: x (int): x coordinate where the text should start. y (int): y coordinate where the text should start. text (str): string that should be printed. """ for i, char in enumerate(text): self.point(x + i, y, char)
[ "def", "text", "(", "self", ",", "x", ",", "y", ",", "text", ")", ":", "for", "i", ",", "char", "in", "enumerate", "(", "text", ")", ":", "self", ".", "point", "(", "x", "+", "i", ",", "y", ",", "char", ")" ]
Print a text on ASCII canvas. Args: x (int): x coordinate where the text should start. y (int): y coordinate where the text should start. text (str): string that should be printed.
[ "Print", "a", "text", "on", "ASCII", "canvas", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L216-L225
train
iterative/dvc
dvc/dagascii.py
AsciiCanvas.box
def box(self, x0, y0, width, height): """Create a box on ASCII canvas. Args: x0 (int): x coordinate of the box corner. y0 (int): y coordinate of the box corner. width (int): box width. height (int): box height. """ assert width > 1 assert height > 1 width -= 1 height -= 1 for x in range(x0, x0 + width): self.point(x, y0, "-") self.point(x, y0 + height, "-") for y in range(y0, y0 + height): self.point(x0, y, "|") self.point(x0 + width, y, "|") self.point(x0, y0, "+") self.point(x0 + width, y0, "+") self.point(x0, y0 + height, "+") self.point(x0 + width, y0 + height, "+")
python
def box(self, x0, y0, width, height): """Create a box on ASCII canvas. Args: x0 (int): x coordinate of the box corner. y0 (int): y coordinate of the box corner. width (int): box width. height (int): box height. """ assert width > 1 assert height > 1 width -= 1 height -= 1 for x in range(x0, x0 + width): self.point(x, y0, "-") self.point(x, y0 + height, "-") for y in range(y0, y0 + height): self.point(x0, y, "|") self.point(x0 + width, y, "|") self.point(x0, y0, "+") self.point(x0 + width, y0, "+") self.point(x0, y0 + height, "+") self.point(x0 + width, y0 + height, "+")
[ "def", "box", "(", "self", ",", "x0", ",", "y0", ",", "width", ",", "height", ")", ":", "assert", "width", ">", "1", "assert", "height", ">", "1", "width", "-=", "1", "height", "-=", "1", "for", "x", "in", "range", "(", "x0", ",", "x0", "+", "width", ")", ":", "self", ".", "point", "(", "x", ",", "y0", ",", "\"-\"", ")", "self", ".", "point", "(", "x", ",", "y0", "+", "height", ",", "\"-\"", ")", "for", "y", "in", "range", "(", "y0", ",", "y0", "+", "height", ")", ":", "self", ".", "point", "(", "x0", ",", "y", ",", "\"|\"", ")", "self", ".", "point", "(", "x0", "+", "width", ",", "y", ",", "\"|\"", ")", "self", ".", "point", "(", "x0", ",", "y0", ",", "\"+\"", ")", "self", ".", "point", "(", "x0", "+", "width", ",", "y0", ",", "\"+\"", ")", "self", ".", "point", "(", "x0", ",", "y0", "+", "height", ",", "\"+\"", ")", "self", ".", "point", "(", "x0", "+", "width", ",", "y0", "+", "height", ",", "\"+\"", ")" ]
Create a box on ASCII canvas. Args: x0 (int): x coordinate of the box corner. y0 (int): y coordinate of the box corner. width (int): box width. height (int): box height.
[ "Create", "a", "box", "on", "ASCII", "canvas", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L227-L253
train
iterative/dvc
dvc/progress.py
Progress.refresh
def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not None: self._writeln(line) self._line = line self._lock.release()
python
def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not None: self._writeln(line) self._line = line self._lock.release()
[ "def", "refresh", "(", "self", ",", "line", "=", "None", ")", ":", "# Just go away if it is locked. Will update next time", "if", "not", "self", ".", "_lock", ".", "acquire", "(", "False", ")", ":", "return", "if", "line", "is", "None", ":", "line", "=", "self", ".", "_line", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", "and", "line", "is", "not", "None", ":", "self", ".", "_writeln", "(", "line", ")", "self", ".", "_line", "=", "line", "self", ".", "_lock", ".", "release", "(", ")" ]
Refreshes progress bar.
[ "Refreshes", "progress", "bar", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L49-L62
train
iterative/dvc
dvc/progress.py
Progress.update_target
def update_target(self, name, current, total): """Updates progress bar for a specified target.""" self.refresh(self._bar(name, current, total))
python
def update_target(self, name, current, total): """Updates progress bar for a specified target.""" self.refresh(self._bar(name, current, total))
[ "def", "update_target", "(", "self", ",", "name", ",", "current", ",", "total", ")", ":", "self", ".", "refresh", "(", "self", ".", "_bar", "(", "name", ",", "current", ",", "total", ")", ")" ]
Updates progress bar for a specified target.
[ "Updates", "progress", "bar", "for", "a", "specified", "target", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L64-L66
train
iterative/dvc
dvc/progress.py
Progress.finish_target
def finish_target(self, name): """Finishes progress bar for a specified target.""" # We have to write a msg about finished target with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self.clearln() self._print(pbar) self._n_finished += 1 self._line = None
python
def finish_target(self, name): """Finishes progress bar for a specified target.""" # We have to write a msg about finished target with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self.clearln() self._print(pbar) self._n_finished += 1 self._line = None
[ "def", "finish_target", "(", "self", ",", "name", ")", ":", "# We have to write a msg about finished target", "with", "self", ".", "_lock", ":", "pbar", "=", "self", ".", "_bar", "(", "name", ",", "100", ",", "100", ")", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "self", ".", "clearln", "(", ")", "self", ".", "_print", "(", "pbar", ")", "self", ".", "_n_finished", "+=", "1", "self", ".", "_line", "=", "None" ]
Finishes progress bar for a specified target.
[ "Finishes", "progress", "bar", "for", "a", "specified", "target", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L68-L80
train
iterative/dvc
dvc/progress.py
Progress._bar
def _bar(self, target_name, current, total): """ Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip """ bar_len = 30 if total is None: state = 0 percent = "?% " else: total = int(total) state = int((100 * current) / total) if current < total else 100 percent = str(state) + "% " if self._n_total > 1: num = "({}/{}): ".format(self._n_finished + 1, self._n_total) else: num = "" n_sh = int((state * bar_len) / 100) n_sp = bar_len - n_sh pbar = "[" + "#" * n_sh + " " * n_sp + "] " return num + pbar + percent + target_name
python
def _bar(self, target_name, current, total): """ Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip """ bar_len = 30 if total is None: state = 0 percent = "?% " else: total = int(total) state = int((100 * current) / total) if current < total else 100 percent = str(state) + "% " if self._n_total > 1: num = "({}/{}): ".format(self._n_finished + 1, self._n_total) else: num = "" n_sh = int((state * bar_len) / 100) n_sp = bar_len - n_sh pbar = "[" + "#" * n_sh + " " * n_sp + "] " return num + pbar + percent + target_name
[ "def", "_bar", "(", "self", ",", "target_name", ",", "current", ",", "total", ")", ":", "bar_len", "=", "30", "if", "total", "is", "None", ":", "state", "=", "0", "percent", "=", "\"?% \"", "else", ":", "total", "=", "int", "(", "total", ")", "state", "=", "int", "(", "(", "100", "*", "current", ")", "/", "total", ")", "if", "current", "<", "total", "else", "100", "percent", "=", "str", "(", "state", ")", "+", "\"% \"", "if", "self", ".", "_n_total", ">", "1", ":", "num", "=", "\"({}/{}): \"", ".", "format", "(", "self", ".", "_n_finished", "+", "1", ",", "self", ".", "_n_total", ")", "else", ":", "num", "=", "\"\"", "n_sh", "=", "int", "(", "(", "state", "*", "bar_len", ")", "/", "100", ")", "n_sp", "=", "bar_len", "-", "n_sh", "pbar", "=", "\"[\"", "+", "\"#\"", "*", "n_sh", "+", "\" \"", "*", "n_sp", "+", "\"] \"", "return", "num", "+", "pbar", "+", "percent", "+", "target_name" ]
Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip
[ "Make", "a", "progress", "bar", "out", "of", "info", "which", "looks", "like", ":", "(", "1", "/", "2", ")", ":", "[", "########################################", "]", "100%", "master", ".", "zip" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L82-L106
train
iterative/dvc
dvc/repo/diff.py
_extract_dir
def _extract_dir(self, dir_not_exists, output): """Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to file in .dvc/cache values -checksums for that files """ if not dir_not_exists: lst = output.dir_cache return {i["relpath"]: i["md5"] for i in lst} return {}
python
def _extract_dir(self, dir_not_exists, output): """Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to file in .dvc/cache values -checksums for that files """ if not dir_not_exists: lst = output.dir_cache return {i["relpath"]: i["md5"] for i in lst} return {}
[ "def", "_extract_dir", "(", "self", ",", "dir_not_exists", ",", "output", ")", ":", "if", "not", "dir_not_exists", ":", "lst", "=", "output", ".", "dir_cache", "return", "{", "i", "[", "\"relpath\"", "]", ":", "i", "[", "\"md5\"", "]", "for", "i", "in", "lst", "}", "return", "{", "}" ]
Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to file in .dvc/cache values -checksums for that files
[ "Extract", "the", "content", "of", "dvc", "tree", "file", "Args", ":", "self", "(", "object", ")", "-", "Repo", "class", "instance", "dir_not_exists", "(", "bool", ")", "-", "flag", "for", "directory", "existence", "output", "(", "object", ")", "-", "OutputLOCAL", "class", "instance", "Returns", ":", "dict", "-", "dictionary", "with", "keys", "-", "paths", "to", "file", "in", ".", "dvc", "/", "cache", "values", "-", "checksums", "for", "that", "files" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/diff.py#L45-L58
train
iterative/dvc
dvc/repo/diff.py
diff
def diff(self, a_ref, target=None, b_ref=None): """Gerenates diff message string output Args: target(str) - file/directory to check diff of a_ref(str) - first tag (optional) b_ref(str) - second git tag Returns: string: string of output message with diff info """ result = {} diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref) result[DIFF_A_REF] = diff_dct[DIFF_A_REF] result[DIFF_B_REF] = diff_dct[DIFF_B_REF] if diff_dct[DIFF_EQUAL]: result[DIFF_EQUAL] = True return result result[DIFF_LIST] = [] diff_outs = _get_diff_outs(self, diff_dct) if target is None: result[DIFF_LIST] = [ _diff_royal(self, path, diff_outs[path]) for path in diff_outs ] elif target in diff_outs: result[DIFF_LIST] = [_diff_royal(self, target, diff_outs[target])] else: msg = "Have not found file/directory '{}' in the commits" raise FileNotInCommitError(msg.format(target)) return result
python
def diff(self, a_ref, target=None, b_ref=None): """Gerenates diff message string output Args: target(str) - file/directory to check diff of a_ref(str) - first tag (optional) b_ref(str) - second git tag Returns: string: string of output message with diff info """ result = {} diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref) result[DIFF_A_REF] = diff_dct[DIFF_A_REF] result[DIFF_B_REF] = diff_dct[DIFF_B_REF] if diff_dct[DIFF_EQUAL]: result[DIFF_EQUAL] = True return result result[DIFF_LIST] = [] diff_outs = _get_diff_outs(self, diff_dct) if target is None: result[DIFF_LIST] = [ _diff_royal(self, path, diff_outs[path]) for path in diff_outs ] elif target in diff_outs: result[DIFF_LIST] = [_diff_royal(self, target, diff_outs[target])] else: msg = "Have not found file/directory '{}' in the commits" raise FileNotInCommitError(msg.format(target)) return result
[ "def", "diff", "(", "self", ",", "a_ref", ",", "target", "=", "None", ",", "b_ref", "=", "None", ")", ":", "result", "=", "{", "}", "diff_dct", "=", "self", ".", "scm", ".", "get_diff_trees", "(", "a_ref", ",", "b_ref", "=", "b_ref", ")", "result", "[", "DIFF_A_REF", "]", "=", "diff_dct", "[", "DIFF_A_REF", "]", "result", "[", "DIFF_B_REF", "]", "=", "diff_dct", "[", "DIFF_B_REF", "]", "if", "diff_dct", "[", "DIFF_EQUAL", "]", ":", "result", "[", "DIFF_EQUAL", "]", "=", "True", "return", "result", "result", "[", "DIFF_LIST", "]", "=", "[", "]", "diff_outs", "=", "_get_diff_outs", "(", "self", ",", "diff_dct", ")", "if", "target", "is", "None", ":", "result", "[", "DIFF_LIST", "]", "=", "[", "_diff_royal", "(", "self", ",", "path", ",", "diff_outs", "[", "path", "]", ")", "for", "path", "in", "diff_outs", "]", "elif", "target", "in", "diff_outs", ":", "result", "[", "DIFF_LIST", "]", "=", "[", "_diff_royal", "(", "self", ",", "target", ",", "diff_outs", "[", "target", "]", ")", "]", "else", ":", "msg", "=", "\"Have not found file/directory '{}' in the commits\"", "raise", "FileNotInCommitError", "(", "msg", ".", "format", "(", "target", ")", ")", "return", "result" ]
Gerenates diff message string output Args: target(str) - file/directory to check diff of a_ref(str) - first tag (optional) b_ref(str) - second git tag Returns: string: string of output message with diff info
[ "Gerenates", "diff", "message", "string", "output" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/diff.py#L223-L252
train
iterative/dvc
dvc/repo/reproduce.py
_reproduce_stages
def _reproduce_stages( G, stages, node, force, dry, interactive, ignore_build_cache, no_commit, downstream, ): r"""Derive the evaluation of the given node for the given graph. When you _reproduce a stage_, you want to _evaluate the descendants_ to know if it make sense to _recompute_ it. A post-ordered search will give us an order list of the nodes we want. For example, let's say that we have the following pipeline: E / \ D F / \ \ B C G \ / A The derived evaluation of D would be: [A, B, C, D] In case that `downstream` option is specifed, the desired effect is to derive the evaluation starting from the given stage up to the ancestors. However, the `networkx.ancestors` returns a set, without any guarantee of any order, so we are going to reverse the graph and use a pre-ordered search using the given stage as a starting point. E A / \ / \ D F B C G / \ \ --- reverse --> \ / / B C G D F \ / \ / A E The derived evaluation of _downstream_ B would be: [B, D, E] """ import networkx as nx if downstream: # NOTE (py3 only): # Python's `deepcopy` defaults to pickle/unpickle the object. # Stages are complex objects (with references to `repo`, `outs`, # and `deps`) that cause struggles when you try to serialize them. # We need to create a copy of the graph itself, and then reverse it, # instead of using graph.reverse() directly because it calls # `deepcopy` underneath -- unless copy=False is specified. pipeline = nx.dfs_preorder_nodes(G.copy().reverse(copy=False), node) else: pipeline = nx.dfs_postorder_nodes(G, node) result = [] for n in pipeline: try: ret = _reproduce_stage( stages, n, force, dry, interactive, no_commit ) if len(ret) != 0 and ignore_build_cache: # NOTE: we are walking our pipeline from the top to the # bottom. If one stage is changed, it will be reproduced, # which tells us that we should force reproducing all of # the other stages down below, even if their direct # dependencies didn't change. force = True result += ret except Exception as ex: raise ReproductionError(stages[n].relpath, ex) return result
python
def _reproduce_stages( G, stages, node, force, dry, interactive, ignore_build_cache, no_commit, downstream, ): r"""Derive the evaluation of the given node for the given graph. When you _reproduce a stage_, you want to _evaluate the descendants_ to know if it make sense to _recompute_ it. A post-ordered search will give us an order list of the nodes we want. For example, let's say that we have the following pipeline: E / \ D F / \ \ B C G \ / A The derived evaluation of D would be: [A, B, C, D] In case that `downstream` option is specifed, the desired effect is to derive the evaluation starting from the given stage up to the ancestors. However, the `networkx.ancestors` returns a set, without any guarantee of any order, so we are going to reverse the graph and use a pre-ordered search using the given stage as a starting point. E A / \ / \ D F B C G / \ \ --- reverse --> \ / / B C G D F \ / \ / A E The derived evaluation of _downstream_ B would be: [B, D, E] """ import networkx as nx if downstream: # NOTE (py3 only): # Python's `deepcopy` defaults to pickle/unpickle the object. # Stages are complex objects (with references to `repo`, `outs`, # and `deps`) that cause struggles when you try to serialize them. # We need to create a copy of the graph itself, and then reverse it, # instead of using graph.reverse() directly because it calls # `deepcopy` underneath -- unless copy=False is specified. pipeline = nx.dfs_preorder_nodes(G.copy().reverse(copy=False), node) else: pipeline = nx.dfs_postorder_nodes(G, node) result = [] for n in pipeline: try: ret = _reproduce_stage( stages, n, force, dry, interactive, no_commit ) if len(ret) != 0 and ignore_build_cache: # NOTE: we are walking our pipeline from the top to the # bottom. If one stage is changed, it will be reproduced, # which tells us that we should force reproducing all of # the other stages down below, even if their direct # dependencies didn't change. force = True result += ret except Exception as ex: raise ReproductionError(stages[n].relpath, ex) return result
[ "def", "_reproduce_stages", "(", "G", ",", "stages", ",", "node", ",", "force", ",", "dry", ",", "interactive", ",", "ignore_build_cache", ",", "no_commit", ",", "downstream", ",", ")", ":", "import", "networkx", "as", "nx", "if", "downstream", ":", "# NOTE (py3 only):", "# Python's `deepcopy` defaults to pickle/unpickle the object.", "# Stages are complex objects (with references to `repo`, `outs`,", "# and `deps`) that cause struggles when you try to serialize them.", "# We need to create a copy of the graph itself, and then reverse it,", "# instead of using graph.reverse() directly because it calls", "# `deepcopy` underneath -- unless copy=False is specified.", "pipeline", "=", "nx", ".", "dfs_preorder_nodes", "(", "G", ".", "copy", "(", ")", ".", "reverse", "(", "copy", "=", "False", ")", ",", "node", ")", "else", ":", "pipeline", "=", "nx", ".", "dfs_postorder_nodes", "(", "G", ",", "node", ")", "result", "=", "[", "]", "for", "n", "in", "pipeline", ":", "try", ":", "ret", "=", "_reproduce_stage", "(", "stages", ",", "n", ",", "force", ",", "dry", ",", "interactive", ",", "no_commit", ")", "if", "len", "(", "ret", ")", "!=", "0", "and", "ignore_build_cache", ":", "# NOTE: we are walking our pipeline from the top to the", "# bottom. If one stage is changed, it will be reproduced,", "# which tells us that we should force reproducing all of", "# the other stages down below, even if their direct", "# dependencies didn't change.", "force", "=", "True", "result", "+=", "ret", "except", "Exception", "as", "ex", ":", "raise", "ReproductionError", "(", "stages", "[", "n", "]", ".", "relpath", ",", "ex", ")", "return", "result" ]
r"""Derive the evaluation of the given node for the given graph. When you _reproduce a stage_, you want to _evaluate the descendants_ to know if it make sense to _recompute_ it. A post-ordered search will give us an order list of the nodes we want. For example, let's say that we have the following pipeline: E / \ D F / \ \ B C G \ / A The derived evaluation of D would be: [A, B, C, D] In case that `downstream` option is specifed, the desired effect is to derive the evaluation starting from the given stage up to the ancestors. However, the `networkx.ancestors` returns a set, without any guarantee of any order, so we are going to reverse the graph and use a pre-ordered search using the given stage as a starting point. E A / \ / \ D F B C G / \ \ --- reverse --> \ / / B C G D F \ / \ / A E The derived evaluation of _downstream_ B would be: [B, D, E]
[ "r", "Derive", "the", "evaluation", "of", "the", "given", "node", "for", "the", "given", "graph", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/reproduce.py#L132-L210
train
iterative/dvc
dvc/istextfile.py
istextfile
def istextfile(fname, blocksize=512): """ Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. """ with open(fname, "rb") as fobj: block = fobj.read(blocksize) if not block: # An empty file is considered a valid text file return True if b"\x00" in block: # Files with null bytes are binary return False # Use translate's 'deletechars' argument to efficiently remove all # occurrences of TEXT_CHARS from the block nontext = block.translate(None, TEXT_CHARS) return float(len(nontext)) / len(block) <= 0.30
python
def istextfile(fname, blocksize=512): """ Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. """ with open(fname, "rb") as fobj: block = fobj.read(blocksize) if not block: # An empty file is considered a valid text file return True if b"\x00" in block: # Files with null bytes are binary return False # Use translate's 'deletechars' argument to efficiently remove all # occurrences of TEXT_CHARS from the block nontext = block.translate(None, TEXT_CHARS) return float(len(nontext)) / len(block) <= 0.30
[ "def", "istextfile", "(", "fname", ",", "blocksize", "=", "512", ")", ":", "with", "open", "(", "fname", ",", "\"rb\"", ")", "as", "fobj", ":", "block", "=", "fobj", ".", "read", "(", "blocksize", ")", "if", "not", "block", ":", "# An empty file is considered a valid text file", "return", "True", "if", "b\"\\x00\"", "in", "block", ":", "# Files with null bytes are binary", "return", "False", "# Use translate's 'deletechars' argument to efficiently remove all", "# occurrences of TEXT_CHARS from the block", "nontext", "=", "block", ".", "translate", "(", "None", ",", "TEXT_CHARS", ")", "return", "float", "(", "len", "(", "nontext", ")", ")", "/", "len", "(", "block", ")", "<=", "0.30" ]
Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file.
[ "Uses", "heuristics", "to", "guess", "whether", "the", "given", "file", "is", "text", "or", "binary", "by", "reading", "a", "single", "block", "of", "bytes", "from", "the", "file", ".", "If", "more", "than", "30%", "of", "the", "chars", "in", "the", "block", "are", "non", "-", "text", "or", "there", "are", "NUL", "(", "\\", "x00", ")", "bytes", "in", "the", "block", "assume", "this", "is", "a", "binary", "file", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/istextfile.py#L24-L44
train
iterative/dvc
dvc/utils/compat.py
csv_reader
def csv_reader(unicode_csv_data, dialect=None, **kwargs): """csv.reader doesn't support Unicode input, so need to use some tricks to work around this. Source: https://docs.python.org/2/library/csv.html#csv-examples """ import csv dialect = dialect or csv.excel if is_py3: # Python3 supports encoding by default, so just return the object for row in csv.reader(unicode_csv_data, dialect=dialect, **kwargs): yield [cell for cell in row] else: # csv.py doesn't do Unicode; encode temporarily as UTF-8: reader = csv.reader( utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs ) for row in reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, "utf-8") for cell in row]
python
def csv_reader(unicode_csv_data, dialect=None, **kwargs): """csv.reader doesn't support Unicode input, so need to use some tricks to work around this. Source: https://docs.python.org/2/library/csv.html#csv-examples """ import csv dialect = dialect or csv.excel if is_py3: # Python3 supports encoding by default, so just return the object for row in csv.reader(unicode_csv_data, dialect=dialect, **kwargs): yield [cell for cell in row] else: # csv.py doesn't do Unicode; encode temporarily as UTF-8: reader = csv.reader( utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs ) for row in reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, "utf-8") for cell in row]
[ "def", "csv_reader", "(", "unicode_csv_data", ",", "dialect", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "csv", "dialect", "=", "dialect", "or", "csv", ".", "excel", "if", "is_py3", ":", "# Python3 supports encoding by default, so just return the object", "for", "row", "in", "csv", ".", "reader", "(", "unicode_csv_data", ",", "dialect", "=", "dialect", ",", "*", "*", "kwargs", ")", ":", "yield", "[", "cell", "for", "cell", "in", "row", "]", "else", ":", "# csv.py doesn't do Unicode; encode temporarily as UTF-8:", "reader", "=", "csv", ".", "reader", "(", "utf_8_encoder", "(", "unicode_csv_data", ")", ",", "dialect", "=", "dialect", ",", "*", "*", "kwargs", ")", "for", "row", "in", "reader", ":", "# decode UTF-8 back to Unicode, cell by cell:", "yield", "[", "unicode", "(", "cell", ",", "\"utf-8\"", ")", "for", "cell", "in", "row", "]" ]
csv.reader doesn't support Unicode input, so need to use some tricks to work around this. Source: https://docs.python.org/2/library/csv.html#csv-examples
[ "csv", ".", "reader", "doesn", "t", "support", "Unicode", "input", "so", "need", "to", "use", "some", "tricks", "to", "work", "around", "this", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L30-L52
train
iterative/dvc
dvc/utils/compat.py
cast_bytes
def cast_bytes(s, encoding=None): """Source: https://github.com/ipython/ipython_genutils""" if not isinstance(s, bytes): return encode(s, encoding) return s
python
def cast_bytes(s, encoding=None): """Source: https://github.com/ipython/ipython_genutils""" if not isinstance(s, bytes): return encode(s, encoding) return s
[ "def", "cast_bytes", "(", "s", ",", "encoding", "=", "None", ")", ":", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "encode", "(", "s", ",", "encoding", ")", "return", "s" ]
Source: https://github.com/ipython/ipython_genutils
[ "Source", ":", "https", ":", "//", "github", ".", "com", "/", "ipython", "/", "ipython_genutils" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L61-L65
train
iterative/dvc
dvc/utils/compat.py
_makedirs
def _makedirs(name, mode=0o777, exist_ok=False): """Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 """ head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) if head and tail and not os.path.exists(head): try: _makedirs(head, exist_ok=exist_ok) except OSError as e: if e.errno != errno.EEXIST: raise cdir = os.curdir if isinstance(tail, bytes): cdir = bytes(os.curdir, "ASCII") if tail == cdir: return try: os.mkdir(name, mode) except OSError: if not exist_ok or not os.path.isdir(name): raise
python
def _makedirs(name, mode=0o777, exist_ok=False): """Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 """ head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) if head and tail and not os.path.exists(head): try: _makedirs(head, exist_ok=exist_ok) except OSError as e: if e.errno != errno.EEXIST: raise cdir = os.curdir if isinstance(tail, bytes): cdir = bytes(os.curdir, "ASCII") if tail == cdir: return try: os.mkdir(name, mode) except OSError: if not exist_ok or not os.path.isdir(name): raise
[ "def", "_makedirs", "(", "name", ",", "mode", "=", "0o777", ",", "exist_ok", "=", "False", ")", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "name", ")", "if", "not", "tail", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "head", ")", "if", "head", "and", "tail", "and", "not", "os", ".", "path", ".", "exists", "(", "head", ")", ":", "try", ":", "_makedirs", "(", "head", ",", "exist_ok", "=", "exist_ok", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "cdir", "=", "os", ".", "curdir", "if", "isinstance", "(", "tail", ",", "bytes", ")", ":", "cdir", "=", "bytes", "(", "os", ".", "curdir", ",", "\"ASCII\"", ")", "if", "tail", "==", "cdir", ":", "return", "try", ":", "os", ".", "mkdir", "(", "name", ",", "mode", ")", "except", "OSError", ":", "if", "not", "exist_ok", "or", "not", "os", ".", "path", ".", "isdir", "(", "name", ")", ":", "raise" ]
Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
[ "Source", ":", "https", ":", "//", "github", ".", "com", "/", "python", "/", "cpython", "/", "blob", "/", "3ce3dea60646d8a5a1c952469a2eb65f937875b3", "/", "Lib", "/", "os", ".", "py#L196", "-", "L226" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L68-L90
train
iterative/dvc
dvc/repo/pkg/install.py
install
def install(self, address, target_dir, select=[], fname=None): """ Install package. The command can be run only from DVC project root. E.g. Having: DVC package in https://github.com/dmpetrov/tag_classifier $ dvc pkg install https://github.com/dmpetrov/tag_classifier Result: tag_classifier package in dvc_mod/ directory """ if not os.path.isdir(target_dir): raise DvcException( "target directory '{}' does not exist".format(target_dir) ) curr_dir = os.path.realpath(os.curdir) if not os.path.realpath(target_dir).startswith(curr_dir): raise DvcException( "the current directory should be a subdirectory of the target " "dir '{}'".format(target_dir) ) addresses = [address] if address else PackageManager.read_packages() for addr in addresses: mgr = PackageManager.get_package(addr) mgr.install_or_update(self, address, target_dir, select, fname)
python
def install(self, address, target_dir, select=[], fname=None): """ Install package. The command can be run only from DVC project root. E.g. Having: DVC package in https://github.com/dmpetrov/tag_classifier $ dvc pkg install https://github.com/dmpetrov/tag_classifier Result: tag_classifier package in dvc_mod/ directory """ if not os.path.isdir(target_dir): raise DvcException( "target directory '{}' does not exist".format(target_dir) ) curr_dir = os.path.realpath(os.curdir) if not os.path.realpath(target_dir).startswith(curr_dir): raise DvcException( "the current directory should be a subdirectory of the target " "dir '{}'".format(target_dir) ) addresses = [address] if address else PackageManager.read_packages() for addr in addresses: mgr = PackageManager.get_package(addr) mgr.install_or_update(self, address, target_dir, select, fname)
[ "def", "install", "(", "self", ",", "address", ",", "target_dir", ",", "select", "=", "[", "]", ",", "fname", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "target_dir", ")", ":", "raise", "DvcException", "(", "\"target directory '{}' does not exist\"", ".", "format", "(", "target_dir", ")", ")", "curr_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "curdir", ")", "if", "not", "os", ".", "path", ".", "realpath", "(", "target_dir", ")", ".", "startswith", "(", "curr_dir", ")", ":", "raise", "DvcException", "(", "\"the current directory should be a subdirectory of the target \"", "\"dir '{}'\"", ".", "format", "(", "target_dir", ")", ")", "addresses", "=", "[", "address", "]", "if", "address", "else", "PackageManager", ".", "read_packages", "(", ")", "for", "addr", "in", "addresses", ":", "mgr", "=", "PackageManager", ".", "get_package", "(", "addr", ")", "mgr", ".", "install_or_update", "(", "self", ",", "address", ",", "target_dir", ",", "select", ",", "fname", ")" ]
Install package. The command can be run only from DVC project root. E.g. Having: DVC package in https://github.com/dmpetrov/tag_classifier $ dvc pkg install https://github.com/dmpetrov/tag_classifier Result: tag_classifier package in dvc_mod/ directory
[ "Install", "package", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/pkg/install.py#L144-L173
train
iterative/dvc
dvc/stage.py
Stage.is_import
def is_import(self): """Whether the stage file was created with `dvc import`.""" return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1
python
def is_import(self): """Whether the stage file was created with `dvc import`.""" return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1
[ "def", "is_import", "(", "self", ")", ":", "return", "not", "self", ".", "cmd", "and", "len", "(", "self", ".", "deps", ")", "==", "1", "and", "len", "(", "self", ".", "outs", ")", "==", "1" ]
Whether the stage file was created with `dvc import`.
[ "Whether", "the", "stage", "file", "was", "created", "with", "dvc", "import", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/stage.py#L211-L213
train
iterative/dvc
dvc/stage.py
Stage.remove_outs
def remove_outs(self, ignore_remove=False, force=False): """Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.""" for out in self.outs: if out.persist and not force: out.unprotect() else: logger.debug( "Removing output '{out}' of '{stage}'.".format( out=out, stage=self.relpath ) ) out.remove(ignore_remove=ignore_remove)
python
def remove_outs(self, ignore_remove=False, force=False): """Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.""" for out in self.outs: if out.persist and not force: out.unprotect() else: logger.debug( "Removing output '{out}' of '{stage}'.".format( out=out, stage=self.relpath ) ) out.remove(ignore_remove=ignore_remove)
[ "def", "remove_outs", "(", "self", ",", "ignore_remove", "=", "False", ",", "force", "=", "False", ")", ":", "for", "out", "in", "self", ".", "outs", ":", "if", "out", ".", "persist", "and", "not", "force", ":", "out", ".", "unprotect", "(", ")", "else", ":", "logger", ".", "debug", "(", "\"Removing output '{out}' of '{stage}'.\"", ".", "format", "(", "out", "=", "out", ",", "stage", "=", "self", ".", "relpath", ")", ")", "out", ".", "remove", "(", "ignore_remove", "=", "ignore_remove", ")" ]
Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.
[ "Used", "mainly", "for", "dvc", "remove", "--", "outs", "and", ":", "func", ":", "Stage", ".", "reproduce", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/stage.py#L272-L283
train
iterative/dvc
dvc/stage.py
Stage.is_cached
def is_cached(self): """ Checks if this stage has been already ran and stored """ from dvc.remote.local import RemoteLOCAL from dvc.remote.s3 import RemoteS3 old = Stage.load(self.repo, self.path) if old._changed_outs(): return False # NOTE: need to save checksums for deps in order to compare them # with what is written in the old stage. for dep in self.deps: dep.save() old_d = old.dumpd() new_d = self.dumpd() # NOTE: need to remove checksums from old dict in order to compare # it to the new one, since the new one doesn't have checksums yet. old_d.pop(self.PARAM_MD5, None) new_d.pop(self.PARAM_MD5, None) outs = old_d.get(self.PARAM_OUTS, []) for out in outs: out.pop(RemoteLOCAL.PARAM_CHECKSUM, None) out.pop(RemoteS3.PARAM_CHECKSUM, None) if old_d != new_d: return False # NOTE: committing to prevent potential data duplication. For example # # $ dvc config cache.type hardlink # $ echo foo > foo # $ dvc add foo # $ rm -f foo # $ echo foo > foo # $ dvc add foo # should replace foo with a link to cache # old.commit() return True
python
def is_cached(self): """ Checks if this stage has been already ran and stored """ from dvc.remote.local import RemoteLOCAL from dvc.remote.s3 import RemoteS3 old = Stage.load(self.repo, self.path) if old._changed_outs(): return False # NOTE: need to save checksums for deps in order to compare them # with what is written in the old stage. for dep in self.deps: dep.save() old_d = old.dumpd() new_d = self.dumpd() # NOTE: need to remove checksums from old dict in order to compare # it to the new one, since the new one doesn't have checksums yet. old_d.pop(self.PARAM_MD5, None) new_d.pop(self.PARAM_MD5, None) outs = old_d.get(self.PARAM_OUTS, []) for out in outs: out.pop(RemoteLOCAL.PARAM_CHECKSUM, None) out.pop(RemoteS3.PARAM_CHECKSUM, None) if old_d != new_d: return False # NOTE: committing to prevent potential data duplication. For example # # $ dvc config cache.type hardlink # $ echo foo > foo # $ dvc add foo # $ rm -f foo # $ echo foo > foo # $ dvc add foo # should replace foo with a link to cache # old.commit() return True
[ "def", "is_cached", "(", "self", ")", ":", "from", "dvc", ".", "remote", ".", "local", "import", "RemoteLOCAL", "from", "dvc", ".", "remote", ".", "s3", "import", "RemoteS3", "old", "=", "Stage", ".", "load", "(", "self", ".", "repo", ",", "self", ".", "path", ")", "if", "old", ".", "_changed_outs", "(", ")", ":", "return", "False", "# NOTE: need to save checksums for deps in order to compare them", "# with what is written in the old stage.", "for", "dep", "in", "self", ".", "deps", ":", "dep", ".", "save", "(", ")", "old_d", "=", "old", ".", "dumpd", "(", ")", "new_d", "=", "self", ".", "dumpd", "(", ")", "# NOTE: need to remove checksums from old dict in order to compare", "# it to the new one, since the new one doesn't have checksums yet.", "old_d", ".", "pop", "(", "self", ".", "PARAM_MD5", ",", "None", ")", "new_d", ".", "pop", "(", "self", ".", "PARAM_MD5", ",", "None", ")", "outs", "=", "old_d", ".", "get", "(", "self", ".", "PARAM_OUTS", ",", "[", "]", ")", "for", "out", "in", "outs", ":", "out", ".", "pop", "(", "RemoteLOCAL", ".", "PARAM_CHECKSUM", ",", "None", ")", "out", ".", "pop", "(", "RemoteS3", ".", "PARAM_CHECKSUM", ",", "None", ")", "if", "old_d", "!=", "new_d", ":", "return", "False", "# NOTE: committing to prevent potential data duplication. For example", "#", "# $ dvc config cache.type hardlink", "# $ echo foo > foo", "# $ dvc add foo", "# $ rm -f foo", "# $ echo foo > foo", "# $ dvc add foo # should replace foo with a link to cache", "#", "old", ".", "commit", "(", ")", "return", "True" ]
Checks if this stage has been already ran and stored
[ "Checks", "if", "this", "stage", "has", "been", "already", "ran", "and", "stored" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/stage.py#L369-L411
train
iterative/dvc
dvc/daemon.py
daemon
def daemon(args): """Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command. """ if os.environ.get(DVC_DAEMON): logger.debug("skipping launching a new daemon.") return cmd = [sys.executable] if not is_binary(): cmd += ["-m", "dvc"] cmd += ["daemon", "-q"] + args env = fix_env() file_path = os.path.abspath(inspect.stack()[0][1]) env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2( os.path.dirname(os.path.dirname(file_path)) ) env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1") _spawn(cmd, env)
python
def daemon(args): """Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command. """ if os.environ.get(DVC_DAEMON): logger.debug("skipping launching a new daemon.") return cmd = [sys.executable] if not is_binary(): cmd += ["-m", "dvc"] cmd += ["daemon", "-q"] + args env = fix_env() file_path = os.path.abspath(inspect.stack()[0][1]) env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2( os.path.dirname(os.path.dirname(file_path)) ) env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1") _spawn(cmd, env)
[ "def", "daemon", "(", "args", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "DVC_DAEMON", ")", ":", "logger", ".", "debug", "(", "\"skipping launching a new daemon.\"", ")", "return", "cmd", "=", "[", "sys", ".", "executable", "]", "if", "not", "is_binary", "(", ")", ":", "cmd", "+=", "[", "\"-m\"", ",", "\"dvc\"", "]", "cmd", "+=", "[", "\"daemon\"", ",", "\"-q\"", "]", "+", "args", "env", "=", "fix_env", "(", ")", "file_path", "=", "os", ".", "path", ".", "abspath", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "1", "]", ")", "env", "[", "cast_bytes_py2", "(", "\"PYTHONPATH\"", ")", "]", "=", "cast_bytes_py2", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "file_path", ")", ")", ")", "env", "[", "cast_bytes_py2", "(", "DVC_DAEMON", ")", "]", "=", "cast_bytes_py2", "(", "\"1\"", ")", "_spawn", "(", "cmd", ",", "env", ")" ]
Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command.
[ "Launch", "a", "dvc", "daemon", "command", "in", "a", "detached", "process", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/daemon.py#L85-L107
train
iterative/dvc
dvc/command/run.py
CmdRun._parsed_cmd
def _parsed_cmd(self): """ We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc run echo "foo bar" """ if len(self.args.command) < 2: return " ".join(self.args.command) return " ".join(self._quote_argument(arg) for arg in self.args.command)
python
def _parsed_cmd(self): """ We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc run echo "foo bar" """ if len(self.args.command) < 2: return " ".join(self.args.command) return " ".join(self._quote_argument(arg) for arg in self.args.command)
[ "def", "_parsed_cmd", "(", "self", ")", ":", "if", "len", "(", "self", ".", "args", ".", "command", ")", "<", "2", ":", "return", "\" \"", ".", "join", "(", "self", ".", "args", ".", "command", ")", "return", "\" \"", ".", "join", "(", "self", ".", "_quote_argument", "(", "arg", ")", "for", "arg", "in", "self", ".", "args", ".", "command", ")" ]
We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc run echo "foo bar"
[ "We", "need", "to", "take", "into", "account", "two", "cases", ":" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/run.py#L61-L74
train
iterative/dvc
dvc/command/init.py
add_parser
def add_parser(subparsers, parent_parser): """Setup parser for `dvc init`.""" INIT_HELP = "Initialize DVC in the current directory." INIT_DESCRIPTION = ( "Initialize DVC in the current directory. Expects directory\n" "to be a Git repository unless --no-scm option is specified." ) init_parser = subparsers.add_parser( "init", parents=[parent_parser], description=append_doc_link(INIT_DESCRIPTION, "init"), help=INIT_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) init_parser.add_argument( "--no-scm", action="store_true", default=False, help="Initiate dvc in directory that is " "not tracked by any scm tool (e.g. git).", ) init_parser.add_argument( "-f", "--force", action="store_true", default=False, help=( "Overwrite existing '.dvc' directory. " "This operation removes local cache." ), ) init_parser.set_defaults(func=CmdInit)
python
def add_parser(subparsers, parent_parser): """Setup parser for `dvc init`.""" INIT_HELP = "Initialize DVC in the current directory." INIT_DESCRIPTION = ( "Initialize DVC in the current directory. Expects directory\n" "to be a Git repository unless --no-scm option is specified." ) init_parser = subparsers.add_parser( "init", parents=[parent_parser], description=append_doc_link(INIT_DESCRIPTION, "init"), help=INIT_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) init_parser.add_argument( "--no-scm", action="store_true", default=False, help="Initiate dvc in directory that is " "not tracked by any scm tool (e.g. git).", ) init_parser.add_argument( "-f", "--force", action="store_true", default=False, help=( "Overwrite existing '.dvc' directory. " "This operation removes local cache." ), ) init_parser.set_defaults(func=CmdInit)
[ "def", "add_parser", "(", "subparsers", ",", "parent_parser", ")", ":", "INIT_HELP", "=", "\"Initialize DVC in the current directory.\"", "INIT_DESCRIPTION", "=", "(", "\"Initialize DVC in the current directory. Expects directory\\n\"", "\"to be a Git repository unless --no-scm option is specified.\"", ")", "init_parser", "=", "subparsers", ".", "add_parser", "(", "\"init\"", ",", "parents", "=", "[", "parent_parser", "]", ",", "description", "=", "append_doc_link", "(", "INIT_DESCRIPTION", ",", "\"init\"", ")", ",", "help", "=", "INIT_HELP", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", ")", "init_parser", ".", "add_argument", "(", "\"--no-scm\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Initiate dvc in directory that is \"", "\"not tracked by any scm tool (e.g. git).\"", ",", ")", "init_parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--force\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "(", "\"Overwrite existing '.dvc' directory. \"", "\"This operation removes local cache.\"", ")", ",", ")", "init_parser", ".", "set_defaults", "(", "func", "=", "CmdInit", ")" ]
Setup parser for `dvc init`.
[ "Setup", "parser", "for", "dvc", "init", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/init.py#L31-L63
train
iterative/dvc
dvc/repo/metrics/show.py
_format_csv
def _format_csv(content, delimiter): """Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value separator Returns: str: Formatted content. Example: >>> content = ( "value_mse,deviation_mse,data_set\n" "0.421601,0.173461,train\n" "0.67528,0.289545,testing\n" "0.671502,0.297848,validation\n" ) >>> _format_csv(content, ",") "value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n" """ reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter)) rows = [row for row in reader] max_widths = [max(map(len, column)) for column in zip(*rows)] lines = [ " ".join( "{entry:{width}}".format(entry=entry, width=width + 2) for entry, width in zip(row, max_widths) ) for row in rows ] return "\n".join(lines)
python
def _format_csv(content, delimiter): """Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value separator Returns: str: Formatted content. Example: >>> content = ( "value_mse,deviation_mse,data_set\n" "0.421601,0.173461,train\n" "0.67528,0.289545,testing\n" "0.671502,0.297848,validation\n" ) >>> _format_csv(content, ",") "value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n" """ reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter)) rows = [row for row in reader] max_widths = [max(map(len, column)) for column in zip(*rows)] lines = [ " ".join( "{entry:{width}}".format(entry=entry, width=width + 2) for entry, width in zip(row, max_widths) ) for row in rows ] return "\n".join(lines)
[ "def", "_format_csv", "(", "content", ",", "delimiter", ")", ":", "reader", "=", "csv_reader", "(", "StringIO", "(", "content", ")", ",", "delimiter", "=", "builtin_str", "(", "delimiter", ")", ")", "rows", "=", "[", "row", "for", "row", "in", "reader", "]", "max_widths", "=", "[", "max", "(", "map", "(", "len", ",", "column", ")", ")", "for", "column", "in", "zip", "(", "*", "rows", ")", "]", "lines", "=", "[", "\" \"", ".", "join", "(", "\"{entry:{width}}\"", ".", "format", "(", "entry", "=", "entry", ",", "width", "=", "width", "+", "2", ")", "for", "entry", ",", "width", "in", "zip", "(", "row", ",", "max_widths", ")", ")", "for", "row", "in", "rows", "]", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value separator Returns: str: Formatted content. Example: >>> content = ( "value_mse,deviation_mse,data_set\n" "0.421601,0.173461,train\n" "0.67528,0.289545,testing\n" "0.671502,0.297848,validation\n" ) >>> _format_csv(content, ",") "value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n"
[ "Format", "delimited", "text", "to", "have", "same", "column", "width", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L77-L114
train
iterative/dvc
dvc/repo/metrics/show.py
_format_output
def _format_output(content, typ): """Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format. """ if "csv" in str(typ): return _format_csv(content, delimiter=",") if "tsv" in str(typ): return _format_csv(content, delimiter="\t") return content
python
def _format_output(content, typ): """Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format. """ if "csv" in str(typ): return _format_csv(content, delimiter=",") if "tsv" in str(typ): return _format_csv(content, delimiter="\t") return content
[ "def", "_format_output", "(", "content", ",", "typ", ")", ":", "if", "\"csv\"", "in", "str", "(", "typ", ")", ":", "return", "_format_csv", "(", "content", ",", "delimiter", "=", "\",\"", ")", "if", "\"tsv\"", "in", "str", "(", "typ", ")", ":", "return", "_format_csv", "(", "content", ",", "delimiter", "=", "\"\\t\"", ")", "return", "content" ]
Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format.
[ "Tabularize", "the", "content", "according", "to", "its", "type", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L117-L134
train
iterative/dvc
dvc/repo/metrics/show.py
_collect_metrics
def _collect_metrics(repo, path, recursive, typ, xpath, branch): """Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recursive (bool): If path is a directory, do a recursive search for metrics on the given path. typ (str): The type of metric to search for, could be one of the following (raw|json|tsv|htsv|csv|hcsv). xpath (str): Path to search for. branch (str): Branch to look up for metrics. Returns: list(tuple): (output, typ, xpath) - output: - typ: - xpath: """ outs = [out for stage in repo.stages() for out in stage.outs] if path: try: outs = repo.find_outs_by_path(path, outs=outs, recursive=recursive) except OutputNotFoundError: logger.debug( "stage file not for found for '{}' in branch '{}'".format( path, branch ) ) return [] res = [] for o in outs: if not o.metric: continue if not typ and isinstance(o.metric, dict): t = o.metric.get(o.PARAM_METRIC_TYPE, typ) x = o.metric.get(o.PARAM_METRIC_XPATH, xpath) else: t = typ x = xpath res.append((o, t, x)) return res
python
def _collect_metrics(repo, path, recursive, typ, xpath, branch): """Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recursive (bool): If path is a directory, do a recursive search for metrics on the given path. typ (str): The type of metric to search for, could be one of the following (raw|json|tsv|htsv|csv|hcsv). xpath (str): Path to search for. branch (str): Branch to look up for metrics. Returns: list(tuple): (output, typ, xpath) - output: - typ: - xpath: """ outs = [out for stage in repo.stages() for out in stage.outs] if path: try: outs = repo.find_outs_by_path(path, outs=outs, recursive=recursive) except OutputNotFoundError: logger.debug( "stage file not for found for '{}' in branch '{}'".format( path, branch ) ) return [] res = [] for o in outs: if not o.metric: continue if not typ and isinstance(o.metric, dict): t = o.metric.get(o.PARAM_METRIC_TYPE, typ) x = o.metric.get(o.PARAM_METRIC_XPATH, xpath) else: t = typ x = xpath res.append((o, t, x)) return res
[ "def", "_collect_metrics", "(", "repo", ",", "path", ",", "recursive", ",", "typ", ",", "xpath", ",", "branch", ")", ":", "outs", "=", "[", "out", "for", "stage", "in", "repo", ".", "stages", "(", ")", "for", "out", "in", "stage", ".", "outs", "]", "if", "path", ":", "try", ":", "outs", "=", "repo", ".", "find_outs_by_path", "(", "path", ",", "outs", "=", "outs", ",", "recursive", "=", "recursive", ")", "except", "OutputNotFoundError", ":", "logger", ".", "debug", "(", "\"stage file not for found for '{}' in branch '{}'\"", ".", "format", "(", "path", ",", "branch", ")", ")", "return", "[", "]", "res", "=", "[", "]", "for", "o", "in", "outs", ":", "if", "not", "o", ".", "metric", ":", "continue", "if", "not", "typ", "and", "isinstance", "(", "o", ".", "metric", ",", "dict", ")", ":", "t", "=", "o", ".", "metric", ".", "get", "(", "o", ".", "PARAM_METRIC_TYPE", ",", "typ", ")", "x", "=", "o", ".", "metric", ".", "get", "(", "o", ".", "PARAM_METRIC_XPATH", ",", "xpath", ")", "else", ":", "t", "=", "typ", "x", "=", "xpath", "res", ".", "append", "(", "(", "o", ",", "t", ",", "x", ")", ")", "return", "res" ]
Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recursive (bool): If path is a directory, do a recursive search for metrics on the given path. typ (str): The type of metric to search for, could be one of the following (raw|json|tsv|htsv|csv|hcsv). xpath (str): Path to search for. branch (str): Branch to look up for metrics. Returns: list(tuple): (output, typ, xpath) - output: - typ: - xpath:
[ "Gather", "all", "the", "metric", "outputs", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L155-L200
train
iterative/dvc
dvc/repo/metrics/show.py
_read_metrics
def _read_metrics(repo, metrics, branch): """Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: {'metric.csv': ("value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n")} """ res = {} for out, typ, xpath in metrics: assert out.scheme == "local" if not typ: typ = os.path.splitext(out.path.lower())[1].replace(".", "") if out.use_cache: open_fun = open path = repo.cache.local.get(out.checksum) else: open_fun = repo.tree.open path = out.path try: with open_fun(path) as fd: metric = _read_metric( fd, typ=typ, xpath=xpath, rel_path=out.rel_path, branch=branch, ) except IOError as e: if e.errno == errno.ENOENT: logger.warning( NO_METRICS_FILE_AT_REFERENCE_WARNING.format( out.rel_path, branch ) ) metric = None else: raise if not metric: continue res[out.rel_path] = metric return res
python
def _read_metrics(repo, metrics, branch): """Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: {'metric.csv': ("value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n")} """ res = {} for out, typ, xpath in metrics: assert out.scheme == "local" if not typ: typ = os.path.splitext(out.path.lower())[1].replace(".", "") if out.use_cache: open_fun = open path = repo.cache.local.get(out.checksum) else: open_fun = repo.tree.open path = out.path try: with open_fun(path) as fd: metric = _read_metric( fd, typ=typ, xpath=xpath, rel_path=out.rel_path, branch=branch, ) except IOError as e: if e.errno == errno.ENOENT: logger.warning( NO_METRICS_FILE_AT_REFERENCE_WARNING.format( out.rel_path, branch ) ) metric = None else: raise if not metric: continue res[out.rel_path] = metric return res
[ "def", "_read_metrics", "(", "repo", ",", "metrics", ",", "branch", ")", ":", "res", "=", "{", "}", "for", "out", ",", "typ", ",", "xpath", "in", "metrics", ":", "assert", "out", ".", "scheme", "==", "\"local\"", "if", "not", "typ", ":", "typ", "=", "os", ".", "path", ".", "splitext", "(", "out", ".", "path", ".", "lower", "(", ")", ")", "[", "1", "]", ".", "replace", "(", "\".\"", ",", "\"\"", ")", "if", "out", ".", "use_cache", ":", "open_fun", "=", "open", "path", "=", "repo", ".", "cache", ".", "local", ".", "get", "(", "out", ".", "checksum", ")", "else", ":", "open_fun", "=", "repo", ".", "tree", ".", "open", "path", "=", "out", ".", "path", "try", ":", "with", "open_fun", "(", "path", ")", "as", "fd", ":", "metric", "=", "_read_metric", "(", "fd", ",", "typ", "=", "typ", ",", "xpath", "=", "xpath", ",", "rel_path", "=", "out", ".", "rel_path", ",", "branch", "=", "branch", ",", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "logger", ".", "warning", "(", "NO_METRICS_FILE_AT_REFERENCE_WARNING", ".", "format", "(", "out", ".", "rel_path", ",", "branch", ")", ")", "metric", "=", "None", "else", ":", "raise", "if", "not", "metric", ":", "continue", "res", "[", "out", ".", "rel_path", "]", "=", "metric", "return", "res" ]
Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: {'metric.csv': ("value_mse deviation_mse data_set\n" "0.421601 0.173461 train\n" "0.67528 0.289545 testing\n" "0.671502 0.297848 validation\n")}
[ "Read", "the", "content", "of", "each", "metric", "file", "and", "format", "it", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L203-L256
train
iterative/dvc
dvc/repo/__init__.py
Repo.graph
def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: For example, running the following: $ dvc run -o A "echo A > A" $ dvc run -d A -o B "echo B > B" $ dvc run -d B -o C "echo C > C" Will create the following graph: ancestors <-- | C.dvc -> B.dvc -> A.dvc | | | --> descendants | ------- pipeline ------> | v (weakly connected components) Args: stages (list): used to build a graph, if None given, use the ones on the `from_directory`. from_directory (str): directory where to look at for stages, if None is given, use the current working directory Raises: OutputDuplicationError: two outputs with the same path StagePathAsOutputError: stage inside an output directory OverlappingOutputPathsError: output inside output directory CyclicGraphError: resulting graph has cycles """ import networkx as nx from dvc.exceptions import ( OutputDuplicationError, StagePathAsOutputError, OverlappingOutputPathsError, ) G = nx.DiGraph() G_active = nx.DiGraph() stages = stages or self.stages(from_directory, check_dag=False) stages = [stage for stage in stages if stage] outs = [] for stage in stages: for out in stage.outs: existing = [] for o in outs: if o.path == out.path: existing.append(o.stage) in_o_dir = out.path.startswith(o.path + o.sep) in_out_dir = o.path.startswith(out.path + out.sep) if in_o_dir or in_out_dir: raise OverlappingOutputPathsError(o, out) if existing: stages = [stage.relpath, existing[0].relpath] raise OutputDuplicationError(out.path, stages) outs.append(out) for stage in stages: path_dir = os.path.dirname(stage.path) + os.sep for out in outs: if path_dir.startswith(out.path + os.sep): raise StagePathAsOutputError(stage.wdir, stage.relpath) for stage in stages: node = os.path.relpath(stage.path, self.root_dir) G.add_node(node, stage=stage) G_active.add_node(node, stage=stage) for dep in stage.deps: for out in outs: if ( out.path != dep.path and not dep.path.startswith(out.path + out.sep) and not out.path.startswith(dep.path + dep.sep) ): continue dep_stage = out.stage dep_node = os.path.relpath(dep_stage.path, self.root_dir) G.add_node(dep_node, stage=dep_stage) G.add_edge(node, dep_node) if not stage.locked: G_active.add_node(dep_node, stage=dep_stage) G_active.add_edge(node, dep_node) self._check_cyclic_graph(G) return G, G_active
python
def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: For example, running the following: $ dvc run -o A "echo A > A" $ dvc run -d A -o B "echo B > B" $ dvc run -d B -o C "echo C > C" Will create the following graph: ancestors <-- | C.dvc -> B.dvc -> A.dvc | | | --> descendants | ------- pipeline ------> | v (weakly connected components) Args: stages (list): used to build a graph, if None given, use the ones on the `from_directory`. from_directory (str): directory where to look at for stages, if None is given, use the current working directory Raises: OutputDuplicationError: two outputs with the same path StagePathAsOutputError: stage inside an output directory OverlappingOutputPathsError: output inside output directory CyclicGraphError: resulting graph has cycles """ import networkx as nx from dvc.exceptions import ( OutputDuplicationError, StagePathAsOutputError, OverlappingOutputPathsError, ) G = nx.DiGraph() G_active = nx.DiGraph() stages = stages or self.stages(from_directory, check_dag=False) stages = [stage for stage in stages if stage] outs = [] for stage in stages: for out in stage.outs: existing = [] for o in outs: if o.path == out.path: existing.append(o.stage) in_o_dir = out.path.startswith(o.path + o.sep) in_out_dir = o.path.startswith(out.path + out.sep) if in_o_dir or in_out_dir: raise OverlappingOutputPathsError(o, out) if existing: stages = [stage.relpath, existing[0].relpath] raise OutputDuplicationError(out.path, stages) outs.append(out) for stage in stages: path_dir = os.path.dirname(stage.path) + os.sep for out in outs: if path_dir.startswith(out.path + os.sep): raise StagePathAsOutputError(stage.wdir, stage.relpath) for stage in stages: node = os.path.relpath(stage.path, self.root_dir) G.add_node(node, stage=stage) G_active.add_node(node, stage=stage) for dep in stage.deps: for out in outs: if ( out.path != dep.path and not dep.path.startswith(out.path + out.sep) and not out.path.startswith(dep.path + dep.sep) ): continue dep_stage = out.stage dep_node = os.path.relpath(dep_stage.path, self.root_dir) G.add_node(dep_node, stage=dep_stage) G.add_edge(node, dep_node) if not stage.locked: G_active.add_node(dep_node, stage=dep_stage) G_active.add_edge(node, dep_node) self._check_cyclic_graph(G) return G, G_active
[ "def", "graph", "(", "self", ",", "stages", "=", "None", ",", "from_directory", "=", "None", ")", ":", "import", "networkx", "as", "nx", "from", "dvc", ".", "exceptions", "import", "(", "OutputDuplicationError", ",", "StagePathAsOutputError", ",", "OverlappingOutputPathsError", ",", ")", "G", "=", "nx", ".", "DiGraph", "(", ")", "G_active", "=", "nx", ".", "DiGraph", "(", ")", "stages", "=", "stages", "or", "self", ".", "stages", "(", "from_directory", ",", "check_dag", "=", "False", ")", "stages", "=", "[", "stage", "for", "stage", "in", "stages", "if", "stage", "]", "outs", "=", "[", "]", "for", "stage", "in", "stages", ":", "for", "out", "in", "stage", ".", "outs", ":", "existing", "=", "[", "]", "for", "o", "in", "outs", ":", "if", "o", ".", "path", "==", "out", ".", "path", ":", "existing", ".", "append", "(", "o", ".", "stage", ")", "in_o_dir", "=", "out", ".", "path", ".", "startswith", "(", "o", ".", "path", "+", "o", ".", "sep", ")", "in_out_dir", "=", "o", ".", "path", ".", "startswith", "(", "out", ".", "path", "+", "out", ".", "sep", ")", "if", "in_o_dir", "or", "in_out_dir", ":", "raise", "OverlappingOutputPathsError", "(", "o", ",", "out", ")", "if", "existing", ":", "stages", "=", "[", "stage", ".", "relpath", ",", "existing", "[", "0", "]", ".", "relpath", "]", "raise", "OutputDuplicationError", "(", "out", ".", "path", ",", "stages", ")", "outs", ".", "append", "(", "out", ")", "for", "stage", "in", "stages", ":", "path_dir", "=", "os", ".", "path", ".", "dirname", "(", "stage", ".", "path", ")", "+", "os", ".", "sep", "for", "out", "in", "outs", ":", "if", "path_dir", ".", "startswith", "(", "out", ".", "path", "+", "os", ".", "sep", ")", ":", "raise", "StagePathAsOutputError", "(", "stage", ".", "wdir", ",", "stage", ".", "relpath", ")", "for", "stage", "in", "stages", ":", "node", "=", "os", ".", "path", ".", "relpath", "(", "stage", ".", "path", ",", "self", ".", "root_dir", ")", "G", ".", "add_node", "(", "node", ",", "stage", "=", "stage", ")", "G_active", ".", "add_node", "(", "node", ",", "stage", "=", "stage", ")", "for", "dep", "in", "stage", ".", "deps", ":", "for", "out", "in", "outs", ":", "if", "(", "out", ".", "path", "!=", "dep", ".", "path", "and", "not", "dep", ".", "path", ".", "startswith", "(", "out", ".", "path", "+", "out", ".", "sep", ")", "and", "not", "out", ".", "path", ".", "startswith", "(", "dep", ".", "path", "+", "dep", ".", "sep", ")", ")", ":", "continue", "dep_stage", "=", "out", ".", "stage", "dep_node", "=", "os", ".", "path", ".", "relpath", "(", "dep_stage", ".", "path", ",", "self", ".", "root_dir", ")", "G", ".", "add_node", "(", "dep_node", ",", "stage", "=", "dep_stage", ")", "G", ".", "add_edge", "(", "node", ",", "dep_node", ")", "if", "not", "stage", ".", "locked", ":", "G_active", ".", "add_node", "(", "dep_node", ",", "stage", "=", "dep_stage", ")", "G_active", ".", "add_edge", "(", "node", ",", "dep_node", ")", "self", ".", "_check_cyclic_graph", "(", "G", ")", "return", "G", ",", "G_active" ]
Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: For example, running the following: $ dvc run -o A "echo A > A" $ dvc run -d A -o B "echo B > B" $ dvc run -d B -o C "echo C > C" Will create the following graph: ancestors <-- | C.dvc -> B.dvc -> A.dvc | | | --> descendants | ------- pipeline ------> | v (weakly connected components) Args: stages (list): used to build a graph, if None given, use the ones on the `from_directory`. from_directory (str): directory where to look at for stages, if None is given, use the current working directory Raises: OutputDuplicationError: two outputs with the same path StagePathAsOutputError: stage inside an output directory OverlappingOutputPathsError: output inside output directory CyclicGraphError: resulting graph has cycles
[ "Generate", "a", "graph", "by", "using", "the", "given", "stages", "on", "the", "given", "directory" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/__init__.py#L300-L404
train
iterative/dvc
dvc/repo/__init__.py
Repo.stages
def stages(self, from_directory=None, check_dag=True): """ Walks down the root directory looking for Dvcfiles, skipping the directories that are related with any SCM (e.g. `.git`), DVC itself (`.dvc`), or directories tracked by DVC (e.g. `dvc add data` would skip `data/`) NOTE: For large repos, this could be an expensive operation. Consider using some memoization. """ from dvc.stage import Stage if not from_directory: from_directory = self.root_dir elif not os.path.isdir(from_directory): raise TargetNotDirectoryError(from_directory) stages = [] outs = [] ignore_file_handler = DvcIgnoreFileHandler(self.tree) for root, dirs, files in self.tree.walk( from_directory, ignore_file_handler=ignore_file_handler ): for fname in files: path = os.path.join(root, fname) if not Stage.is_valid_filename(path): continue stage = Stage.load(self, path) for out in stage.outs: outs.append(out.path + out.sep) stages.append(stage) def filter_dirs(dname, root=root): path = os.path.join(root, dname) if path in (self.dvc_dir, self.scm.dir): return False for out in outs: if path == os.path.normpath(out) or path.startswith(out): return False return True dirs[:] = list(filter(filter_dirs, dirs)) if check_dag: self.check_dag(stages) return stages
python
def stages(self, from_directory=None, check_dag=True): """ Walks down the root directory looking for Dvcfiles, skipping the directories that are related with any SCM (e.g. `.git`), DVC itself (`.dvc`), or directories tracked by DVC (e.g. `dvc add data` would skip `data/`) NOTE: For large repos, this could be an expensive operation. Consider using some memoization. """ from dvc.stage import Stage if not from_directory: from_directory = self.root_dir elif not os.path.isdir(from_directory): raise TargetNotDirectoryError(from_directory) stages = [] outs = [] ignore_file_handler = DvcIgnoreFileHandler(self.tree) for root, dirs, files in self.tree.walk( from_directory, ignore_file_handler=ignore_file_handler ): for fname in files: path = os.path.join(root, fname) if not Stage.is_valid_filename(path): continue stage = Stage.load(self, path) for out in stage.outs: outs.append(out.path + out.sep) stages.append(stage) def filter_dirs(dname, root=root): path = os.path.join(root, dname) if path in (self.dvc_dir, self.scm.dir): return False for out in outs: if path == os.path.normpath(out) or path.startswith(out): return False return True dirs[:] = list(filter(filter_dirs, dirs)) if check_dag: self.check_dag(stages) return stages
[ "def", "stages", "(", "self", ",", "from_directory", "=", "None", ",", "check_dag", "=", "True", ")", ":", "from", "dvc", ".", "stage", "import", "Stage", "if", "not", "from_directory", ":", "from_directory", "=", "self", ".", "root_dir", "elif", "not", "os", ".", "path", ".", "isdir", "(", "from_directory", ")", ":", "raise", "TargetNotDirectoryError", "(", "from_directory", ")", "stages", "=", "[", "]", "outs", "=", "[", "]", "ignore_file_handler", "=", "DvcIgnoreFileHandler", "(", "self", ".", "tree", ")", "for", "root", ",", "dirs", ",", "files", "in", "self", ".", "tree", ".", "walk", "(", "from_directory", ",", "ignore_file_handler", "=", "ignore_file_handler", ")", ":", "for", "fname", "in", "files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "if", "not", "Stage", ".", "is_valid_filename", "(", "path", ")", ":", "continue", "stage", "=", "Stage", ".", "load", "(", "self", ",", "path", ")", "for", "out", "in", "stage", ".", "outs", ":", "outs", ".", "append", "(", "out", ".", "path", "+", "out", ".", "sep", ")", "stages", ".", "append", "(", "stage", ")", "def", "filter_dirs", "(", "dname", ",", "root", "=", "root", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "dname", ")", "if", "path", "in", "(", "self", ".", "dvc_dir", ",", "self", ".", "scm", ".", "dir", ")", ":", "return", "False", "for", "out", "in", "outs", ":", "if", "path", "==", "os", ".", "path", ".", "normpath", "(", "out", ")", "or", "path", ".", "startswith", "(", "out", ")", ":", "return", "False", "return", "True", "dirs", "[", ":", "]", "=", "list", "(", "filter", "(", "filter_dirs", ",", "dirs", ")", ")", "if", "check_dag", ":", "self", ".", "check_dag", "(", "stages", ")", "return", "stages" ]
Walks down the root directory looking for Dvcfiles, skipping the directories that are related with any SCM (e.g. `.git`), DVC itself (`.dvc`), or directories tracked by DVC (e.g. `dvc add data` would skip `data/`) NOTE: For large repos, this could be an expensive operation. Consider using some memoization.
[ "Walks", "down", "the", "root", "directory", "looking", "for", "Dvcfiles", "skipping", "the", "directories", "that", "are", "related", "with", "any", "SCM", "(", "e", ".", "g", ".", ".", "git", ")", "DVC", "itself", "(", ".", "dvc", ")", "or", "directories", "tracked", "by", "DVC", "(", "e", ".", "g", ".", "dvc", "add", "data", "would", "skip", "data", "/", ")" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/__init__.py#L415-L462
train
iterative/dvc
dvc/logger.py
ColorFormatter._progress_aware
def _progress_aware(self): """Add a new line if progress bar hasn't finished""" from dvc.progress import progress if not progress.is_finished: progress._print() progress.clearln()
python
def _progress_aware(self): """Add a new line if progress bar hasn't finished""" from dvc.progress import progress if not progress.is_finished: progress._print() progress.clearln()
[ "def", "_progress_aware", "(", "self", ")", ":", "from", "dvc", ".", "progress", "import", "progress", "if", "not", "progress", ".", "is_finished", ":", "progress", ".", "_print", "(", ")", "progress", ".", "clearln", "(", ")" ]
Add a new line if progress bar hasn't finished
[ "Add", "a", "new", "line", "if", "progress", "bar", "hasn", "t", "finished" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/logger.py#L134-L140
train
iterative/dvc
dvc/scm/tree.py
WorkingTree.open
def open(self, path, binary=False): """Open file and return a stream.""" if binary: return open(path, "rb") return open(path, encoding="utf-8")
python
def open(self, path, binary=False): """Open file and return a stream.""" if binary: return open(path, "rb") return open(path, encoding="utf-8")
[ "def", "open", "(", "self", ",", "path", ",", "binary", "=", "False", ")", ":", "if", "binary", ":", "return", "open", "(", "path", ",", "\"rb\"", ")", "return", "open", "(", "path", ",", "encoding", "=", "\"utf-8\"", ")" ]
Open file and return a stream.
[ "Open", "file", "and", "return", "a", "stream", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/tree.py#L45-L49
train
iterative/dvc
dvc/scm/tree.py
WorkingTree.walk
def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument """ def onerror(e): raise e for root, dirs, files in dvc_walk( os.path.abspath(top), topdown=topdown, onerror=onerror, ignore_file_handler=ignore_file_handler, ): yield os.path.normpath(root), dirs, files
python
def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument """ def onerror(e): raise e for root, dirs, files in dvc_walk( os.path.abspath(top), topdown=topdown, onerror=onerror, ignore_file_handler=ignore_file_handler, ): yield os.path.normpath(root), dirs, files
[ "def", "walk", "(", "self", ",", "top", ",", "topdown", "=", "True", ",", "ignore_file_handler", "=", "None", ")", ":", "def", "onerror", "(", "e", ")", ":", "raise", "e", "for", "root", ",", "dirs", ",", "files", "in", "dvc_walk", "(", "os", ".", "path", ".", "abspath", "(", "top", ")", ",", "topdown", "=", "topdown", ",", "onerror", "=", "onerror", ",", "ignore_file_handler", "=", "ignore_file_handler", ",", ")", ":", "yield", "os", ".", "path", ".", "normpath", "(", "root", ")", ",", "dirs", ",", "files" ]
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument
[ "Directory", "tree", "generator", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/tree.py#L63-L80
train
iterative/dvc
dvc/remote/s3.py
RemoteS3._list_paths
def _list_paths(self, bucket, prefix): """ Read config for list object api, paginate through list objects.""" s3 = self.s3 kwargs = {"Bucket": bucket, "Prefix": prefix} if self.list_objects: list_objects_api = "list_objects" else: list_objects_api = "list_objects_v2" paginator = s3.get_paginator(list_objects_api) for page in paginator.paginate(**kwargs): contents = page.get("Contents", None) if not contents: continue for item in contents: yield item["Key"]
python
def _list_paths(self, bucket, prefix): """ Read config for list object api, paginate through list objects.""" s3 = self.s3 kwargs = {"Bucket": bucket, "Prefix": prefix} if self.list_objects: list_objects_api = "list_objects" else: list_objects_api = "list_objects_v2" paginator = s3.get_paginator(list_objects_api) for page in paginator.paginate(**kwargs): contents = page.get("Contents", None) if not contents: continue for item in contents: yield item["Key"]
[ "def", "_list_paths", "(", "self", ",", "bucket", ",", "prefix", ")", ":", "s3", "=", "self", ".", "s3", "kwargs", "=", "{", "\"Bucket\"", ":", "bucket", ",", "\"Prefix\"", ":", "prefix", "}", "if", "self", ".", "list_objects", ":", "list_objects_api", "=", "\"list_objects\"", "else", ":", "list_objects_api", "=", "\"list_objects_v2\"", "paginator", "=", "s3", ".", "get_paginator", "(", "list_objects_api", ")", "for", "page", "in", "paginator", ".", "paginate", "(", "*", "*", "kwargs", ")", ":", "contents", "=", "page", ".", "get", "(", "\"Contents\"", ",", "None", ")", "if", "not", "contents", ":", "continue", "for", "item", "in", "contents", ":", "yield", "item", "[", "\"Key\"", "]" ]
Read config for list object api, paginate through list objects.
[ "Read", "config", "for", "list", "object", "api", "paginate", "through", "list", "objects", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/s3.py#L212-L226
train
iterative/dvc
dvc/command/remote.py
CmdRemoteAdd.resolve_path
def resolve_path(path, config_file): """Resolve path relative to config file location. Args: path: Path to be resolved. config_file: Path to config file, which `path` is specified relative to. Returns: Path relative to the `config_file` location. If `path` is an absolute path then it will be returned without change. """ if os.path.isabs(path): return path return os.path.relpath(path, os.path.dirname(config_file))
python
def resolve_path(path, config_file): """Resolve path relative to config file location. Args: path: Path to be resolved. config_file: Path to config file, which `path` is specified relative to. Returns: Path relative to the `config_file` location. If `path` is an absolute path then it will be returned without change. """ if os.path.isabs(path): return path return os.path.relpath(path, os.path.dirname(config_file))
[ "def", "resolve_path", "(", "path", ",", "config_file", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "return", "os", ".", "path", ".", "relpath", "(", "path", ",", "os", ".", "path", ".", "dirname", "(", "config_file", ")", ")" ]
Resolve path relative to config file location. Args: path: Path to be resolved. config_file: Path to config file, which `path` is specified relative to. Returns: Path relative to the `config_file` location. If `path` is an absolute path then it will be returned without change.
[ "Resolve", "path", "relative", "to", "config", "file", "location", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/remote.py#L18-L33
train
iterative/dvc
dvc/scm/git/__init__.py
Git.get_diff_trees
def get_diff_trees(self, a_ref, b_ref=None): """Method for getting two repo trees between two git tag commits returns the dvc hash names of changed file/directory Args: a_ref(str) - git reference b_ref(str) - optional second git reference, default None Returns: dict - dictionary with keys: (a_tree, b_tree, a_ref, b_ref, equal) """ diff_dct = {DIFF_EQUAL: False} trees, commit_refs = self._get_diff_trees(a_ref, b_ref) diff_dct[DIFF_A_REF] = commit_refs[0] diff_dct[DIFF_B_REF] = commit_refs[1] if commit_refs[0] == commit_refs[1]: diff_dct[DIFF_EQUAL] = True return diff_dct diff_dct[DIFF_A_TREE] = trees[DIFF_A_TREE] diff_dct[DIFF_B_TREE] = trees[DIFF_B_TREE] return diff_dct
python
def get_diff_trees(self, a_ref, b_ref=None): """Method for getting two repo trees between two git tag commits returns the dvc hash names of changed file/directory Args: a_ref(str) - git reference b_ref(str) - optional second git reference, default None Returns: dict - dictionary with keys: (a_tree, b_tree, a_ref, b_ref, equal) """ diff_dct = {DIFF_EQUAL: False} trees, commit_refs = self._get_diff_trees(a_ref, b_ref) diff_dct[DIFF_A_REF] = commit_refs[0] diff_dct[DIFF_B_REF] = commit_refs[1] if commit_refs[0] == commit_refs[1]: diff_dct[DIFF_EQUAL] = True return diff_dct diff_dct[DIFF_A_TREE] = trees[DIFF_A_TREE] diff_dct[DIFF_B_TREE] = trees[DIFF_B_TREE] return diff_dct
[ "def", "get_diff_trees", "(", "self", ",", "a_ref", ",", "b_ref", "=", "None", ")", ":", "diff_dct", "=", "{", "DIFF_EQUAL", ":", "False", "}", "trees", ",", "commit_refs", "=", "self", ".", "_get_diff_trees", "(", "a_ref", ",", "b_ref", ")", "diff_dct", "[", "DIFF_A_REF", "]", "=", "commit_refs", "[", "0", "]", "diff_dct", "[", "DIFF_B_REF", "]", "=", "commit_refs", "[", "1", "]", "if", "commit_refs", "[", "0", "]", "==", "commit_refs", "[", "1", "]", ":", "diff_dct", "[", "DIFF_EQUAL", "]", "=", "True", "return", "diff_dct", "diff_dct", "[", "DIFF_A_TREE", "]", "=", "trees", "[", "DIFF_A_TREE", "]", "diff_dct", "[", "DIFF_B_TREE", "]", "=", "trees", "[", "DIFF_B_TREE", "]", "return", "diff_dct" ]
Method for getting two repo trees between two git tag commits returns the dvc hash names of changed file/directory Args: a_ref(str) - git reference b_ref(str) - optional second git reference, default None Returns: dict - dictionary with keys: (a_tree, b_tree, a_ref, b_ref, equal)
[ "Method", "for", "getting", "two", "repo", "trees", "between", "two", "git", "tag", "commits", "returns", "the", "dvc", "hash", "names", "of", "changed", "file", "/", "directory" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/git/__init__.py#L272-L292
train
iterative/dvc
dvc/remote/base.py
RemoteBase.changed
def changed(self, path_info, checksum_info): """Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unlinked) - Checksum is not computed (saving a new file) - The checkusm stored in the State is different from the given one - There's no file in the cache Args: path_info: dict with path information. checksum: expected checksum for this data. Returns: bool: True if data has changed, False otherwise. """ logger.debug( "checking if '{}'('{}') has changed.".format( path_info, checksum_info ) ) if not self.exists(path_info): logger.debug("'{}' doesn't exist.".format(path_info)) return True checksum = checksum_info.get(self.PARAM_CHECKSUM) if checksum is None: logger.debug("checksum for '{}' is missing.".format(path_info)) return True if self.changed_cache(checksum): logger.debug( "cache for '{}'('{}') has changed.".format(path_info, checksum) ) return True actual = self.save_info(path_info)[self.PARAM_CHECKSUM] if checksum != actual: logger.debug( "checksum '{}'(actual '{}') for '{}' has changed.".format( checksum, actual, path_info ) ) return True logger.debug("'{}' hasn't changed.".format(path_info)) return False
python
def changed(self, path_info, checksum_info): """Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unlinked) - Checksum is not computed (saving a new file) - The checkusm stored in the State is different from the given one - There's no file in the cache Args: path_info: dict with path information. checksum: expected checksum for this data. Returns: bool: True if data has changed, False otherwise. """ logger.debug( "checking if '{}'('{}') has changed.".format( path_info, checksum_info ) ) if not self.exists(path_info): logger.debug("'{}' doesn't exist.".format(path_info)) return True checksum = checksum_info.get(self.PARAM_CHECKSUM) if checksum is None: logger.debug("checksum for '{}' is missing.".format(path_info)) return True if self.changed_cache(checksum): logger.debug( "cache for '{}'('{}') has changed.".format(path_info, checksum) ) return True actual = self.save_info(path_info)[self.PARAM_CHECKSUM] if checksum != actual: logger.debug( "checksum '{}'(actual '{}') for '{}' has changed.".format( checksum, actual, path_info ) ) return True logger.debug("'{}' hasn't changed.".format(path_info)) return False
[ "def", "changed", "(", "self", ",", "path_info", ",", "checksum_info", ")", ":", "logger", ".", "debug", "(", "\"checking if '{}'('{}') has changed.\"", ".", "format", "(", "path_info", ",", "checksum_info", ")", ")", "if", "not", "self", ".", "exists", "(", "path_info", ")", ":", "logger", ".", "debug", "(", "\"'{}' doesn't exist.\"", ".", "format", "(", "path_info", ")", ")", "return", "True", "checksum", "=", "checksum_info", ".", "get", "(", "self", ".", "PARAM_CHECKSUM", ")", "if", "checksum", "is", "None", ":", "logger", ".", "debug", "(", "\"checksum for '{}' is missing.\"", ".", "format", "(", "path_info", ")", ")", "return", "True", "if", "self", ".", "changed_cache", "(", "checksum", ")", ":", "logger", ".", "debug", "(", "\"cache for '{}'('{}') has changed.\"", ".", "format", "(", "path_info", ",", "checksum", ")", ")", "return", "True", "actual", "=", "self", ".", "save_info", "(", "path_info", ")", "[", "self", ".", "PARAM_CHECKSUM", "]", "if", "checksum", "!=", "actual", ":", "logger", ".", "debug", "(", "\"checksum '{}'(actual '{}') for '{}' has changed.\"", ".", "format", "(", "checksum", ",", "actual", ",", "path_info", ")", ")", "return", "True", "logger", ".", "debug", "(", "\"'{}' hasn't changed.\"", ".", "format", "(", "path_info", ")", ")", "return", "False" ]
Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unlinked) - Checksum is not computed (saving a new file) - The checkusm stored in the State is different from the given one - There's no file in the cache Args: path_info: dict with path information. checksum: expected checksum for this data. Returns: bool: True if data has changed, False otherwise.
[ "Checks", "if", "data", "has", "changed", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/base.py#L270-L318
train
iterative/dvc
dvc/prompt.py
confirm
def confirm(statement): """Ask the user for confirmation about the specified statement. Args: statement (unicode): statement to ask the user confirmation about. Returns: bool: whether or not specified statement was confirmed. """ prompt = "{statement} [y/n]".format(statement=statement) answer = _ask(prompt, limited_to=["yes", "no", "y", "n"]) return answer and answer.startswith("y")
python
def confirm(statement): """Ask the user for confirmation about the specified statement. Args: statement (unicode): statement to ask the user confirmation about. Returns: bool: whether or not specified statement was confirmed. """ prompt = "{statement} [y/n]".format(statement=statement) answer = _ask(prompt, limited_to=["yes", "no", "y", "n"]) return answer and answer.startswith("y")
[ "def", "confirm", "(", "statement", ")", ":", "prompt", "=", "\"{statement} [y/n]\"", ".", "format", "(", "statement", "=", "statement", ")", "answer", "=", "_ask", "(", "prompt", ",", "limited_to", "=", "[", "\"yes\"", ",", "\"no\"", ",", "\"y\"", ",", "\"n\"", "]", ")", "return", "answer", "and", "answer", ".", "startswith", "(", "\"y\"", ")" ]
Ask the user for confirmation about the specified statement. Args: statement (unicode): statement to ask the user confirmation about. Returns: bool: whether or not specified statement was confirmed.
[ "Ask", "the", "user", "for", "confirmation", "about", "the", "specified", "statement", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/prompt.py#L38-L49
train
iterative/dvc
dvc/main.py
main
def main(argv=None): """Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: int: command's return code. """ args = None cmd = None try: args = parse_args(argv) if args.quiet: logger.setLevel(logging.CRITICAL) elif args.verbose: logger.setLevel(logging.DEBUG) cmd = args.func(args) ret = cmd.run_cmd() except KeyboardInterrupt: logger.exception("interrupted by the user") ret = 252 except NotDvcRepoError: logger.exception("") ret = 253 except DvcParserError: ret = 254 except Exception: # pylint: disable=broad-except logger.exception("unexpected error") ret = 255 Analytics().send_cmd(cmd, args, ret) return ret
python
def main(argv=None): """Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: int: command's return code. """ args = None cmd = None try: args = parse_args(argv) if args.quiet: logger.setLevel(logging.CRITICAL) elif args.verbose: logger.setLevel(logging.DEBUG) cmd = args.func(args) ret = cmd.run_cmd() except KeyboardInterrupt: logger.exception("interrupted by the user") ret = 252 except NotDvcRepoError: logger.exception("") ret = 253 except DvcParserError: ret = 254 except Exception: # pylint: disable=broad-except logger.exception("unexpected error") ret = 255 Analytics().send_cmd(cmd, args, ret) return ret
[ "def", "main", "(", "argv", "=", "None", ")", ":", "args", "=", "None", "cmd", "=", "None", "try", ":", "args", "=", "parse_args", "(", "argv", ")", "if", "args", ".", "quiet", ":", "logger", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "elif", "args", ".", "verbose", ":", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "cmd", "=", "args", ".", "func", "(", "args", ")", "ret", "=", "cmd", ".", "run_cmd", "(", ")", "except", "KeyboardInterrupt", ":", "logger", ".", "exception", "(", "\"interrupted by the user\"", ")", "ret", "=", "252", "except", "NotDvcRepoError", ":", "logger", ".", "exception", "(", "\"\"", ")", "ret", "=", "253", "except", "DvcParserError", ":", "ret", "=", "254", "except", "Exception", ":", "# pylint: disable=broad-except", "logger", ".", "exception", "(", "\"unexpected error\"", ")", "ret", "=", "255", "Analytics", "(", ")", ".", "send_cmd", "(", "cmd", ",", "args", ",", "ret", ")", "return", "ret" ]
Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: int: command's return code.
[ "Run", "dvc", "CLI", "command", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/main.py#L15-L52
train
iterative/dvc
dvc/config.py
supported_cache_type
def supported_cache_type(types): """Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out. """ if isinstance(types, str): types = [typ.strip() for typ in types.split(",")] for typ in types: if typ not in ["reflink", "hardlink", "symlink", "copy"]: return False return True
python
def supported_cache_type(types): """Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out. """ if isinstance(types, str): types = [typ.strip() for typ in types.split(",")] for typ in types: if typ not in ["reflink", "hardlink", "symlink", "copy"]: return False return True
[ "def", "supported_cache_type", "(", "types", ")", ":", "if", "isinstance", "(", "types", ",", "str", ")", ":", "types", "=", "[", "typ", ".", "strip", "(", ")", "for", "typ", "in", "types", ".", "split", "(", "\",\"", ")", "]", "for", "typ", "in", "types", ":", "if", "typ", "not", "in", "[", "\"reflink\"", ",", "\"hardlink\"", ",", "\"symlink\"", ",", "\"copy\"", "]", ":", "return", "False", "return", "True" ]
Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out.
[ "Checks", "if", "link", "type", "config", "option", "has", "a", "valid", "value", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L32-L43
train
iterative/dvc
dvc/config.py
Config.get_global_config_dir
def get_global_config_dir(): """Returns global config location. E.g. ~/.config/dvc/config. Returns: str: path to the global config directory. """ from appdirs import user_config_dir return user_config_dir( appname=Config.APPNAME, appauthor=Config.APPAUTHOR )
python
def get_global_config_dir(): """Returns global config location. E.g. ~/.config/dvc/config. Returns: str: path to the global config directory. """ from appdirs import user_config_dir return user_config_dir( appname=Config.APPNAME, appauthor=Config.APPAUTHOR )
[ "def", "get_global_config_dir", "(", ")", ":", "from", "appdirs", "import", "user_config_dir", "return", "user_config_dir", "(", "appname", "=", "Config", ".", "APPNAME", ",", "appauthor", "=", "Config", ".", "APPAUTHOR", ")" ]
Returns global config location. E.g. ~/.config/dvc/config. Returns: str: path to the global config directory.
[ "Returns", "global", "config", "location", ".", "E", ".", "g", ".", "~", "/", ".", "config", "/", "dvc", "/", "config", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L319-L329
train
iterative/dvc
dvc/config.py
Config.get_system_config_dir
def get_system_config_dir(): """Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory. """ from appdirs import site_config_dir return site_config_dir( appname=Config.APPNAME, appauthor=Config.APPAUTHOR )
python
def get_system_config_dir(): """Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory. """ from appdirs import site_config_dir return site_config_dir( appname=Config.APPNAME, appauthor=Config.APPAUTHOR )
[ "def", "get_system_config_dir", "(", ")", ":", "from", "appdirs", "import", "site_config_dir", "return", "site_config_dir", "(", "appname", "=", "Config", ".", "APPNAME", ",", "appauthor", "=", "Config", ".", "APPAUTHOR", ")" ]
Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory.
[ "Returns", "system", "config", "location", ".", "E", ".", "g", ".", "/", "etc", "/", "dvc", ".", "conf", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L332-L342
train
iterative/dvc
dvc/config.py
Config.init
def init(dvc_dir): """Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Config: config object. """ config_file = os.path.join(dvc_dir, Config.CONFIG) open(config_file, "w+").close() return Config(dvc_dir)
python
def init(dvc_dir): """Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Config: config object. """ config_file = os.path.join(dvc_dir, Config.CONFIG) open(config_file, "w+").close() return Config(dvc_dir)
[ "def", "init", "(", "dvc_dir", ")", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "dvc_dir", ",", "Config", ".", "CONFIG", ")", "open", "(", "config_file", ",", "\"w+\"", ")", ".", "close", "(", ")", "return", "Config", "(", "dvc_dir", ")" ]
Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Config: config object.
[ "Initializes", "dvc", "config", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L345-L356
train
iterative/dvc
dvc/config.py
Config.load
def load(self, validate=True): """Loads config from all the config files. Args: validate (bool): optional flag to tell dvc if it should validate the config or just load it as is. 'True' by default. Raises: dvc.config.ConfigError: thrown if config has invalid format. """ self._load() try: self.config = self._load_config(self.system_config_file) user = self._load_config(self.global_config_file) config = self._load_config(self.config_file) local = self._load_config(self.config_local_file) # NOTE: schema doesn't support ConfigObj.Section validation, so we # need to convert our config to dict before passing it to for conf in [user, config, local]: self.config = self._merge(self.config, conf) if validate: self.config = Schema(self.SCHEMA).validate(self.config) # NOTE: now converting back to ConfigObj self.config = configobj.ConfigObj( self.config, write_empty_values=True ) self.config.filename = self.config_file self._resolve_paths(self.config, self.config_file) except Exception as ex: raise ConfigError(ex)
python
def load(self, validate=True): """Loads config from all the config files. Args: validate (bool): optional flag to tell dvc if it should validate the config or just load it as is. 'True' by default. Raises: dvc.config.ConfigError: thrown if config has invalid format. """ self._load() try: self.config = self._load_config(self.system_config_file) user = self._load_config(self.global_config_file) config = self._load_config(self.config_file) local = self._load_config(self.config_local_file) # NOTE: schema doesn't support ConfigObj.Section validation, so we # need to convert our config to dict before passing it to for conf in [user, config, local]: self.config = self._merge(self.config, conf) if validate: self.config = Schema(self.SCHEMA).validate(self.config) # NOTE: now converting back to ConfigObj self.config = configobj.ConfigObj( self.config, write_empty_values=True ) self.config.filename = self.config_file self._resolve_paths(self.config, self.config_file) except Exception as ex: raise ConfigError(ex)
[ "def", "load", "(", "self", ",", "validate", "=", "True", ")", ":", "self", ".", "_load", "(", ")", "try", ":", "self", ".", "config", "=", "self", ".", "_load_config", "(", "self", ".", "system_config_file", ")", "user", "=", "self", ".", "_load_config", "(", "self", ".", "global_config_file", ")", "config", "=", "self", ".", "_load_config", "(", "self", ".", "config_file", ")", "local", "=", "self", ".", "_load_config", "(", "self", ".", "config_local_file", ")", "# NOTE: schema doesn't support ConfigObj.Section validation, so we", "# need to convert our config to dict before passing it to", "for", "conf", "in", "[", "user", ",", "config", ",", "local", "]", ":", "self", ".", "config", "=", "self", ".", "_merge", "(", "self", ".", "config", ",", "conf", ")", "if", "validate", ":", "self", ".", "config", "=", "Schema", "(", "self", ".", "SCHEMA", ")", ".", "validate", "(", "self", ".", "config", ")", "# NOTE: now converting back to ConfigObj", "self", ".", "config", "=", "configobj", ".", "ConfigObj", "(", "self", ".", "config", ",", "write_empty_values", "=", "True", ")", "self", ".", "config", ".", "filename", "=", "self", ".", "config_file", "self", ".", "_resolve_paths", "(", "self", ".", "config", ",", "self", ".", "config_file", ")", "except", "Exception", "as", "ex", ":", "raise", "ConfigError", "(", "ex", ")" ]
Loads config from all the config files. Args: validate (bool): optional flag to tell dvc if it should validate the config or just load it as is. 'True' by default. Raises: dvc.config.ConfigError: thrown if config has invalid format.
[ "Loads", "config", "from", "all", "the", "config", "files", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L408-L441
train
iterative/dvc
dvc/config.py
Config.save
def save(self, config=None): """Saves config to config files. Args: config (configobj.ConfigObj): optional config object to save. Raises: dvc.config.ConfigError: thrown if failed to write config file. """ if config is not None: clist = [config] else: clist = [ self._system_config, self._global_config, self._repo_config, self._local_config, ] for conf in clist: if conf.filename is None: continue try: logger.debug("Writing '{}'.".format(conf.filename)) dname = os.path.dirname(os.path.abspath(conf.filename)) try: os.makedirs(dname) except OSError as exc: if exc.errno != errno.EEXIST: raise conf.write() except Exception as exc: msg = "failed to write config '{}'".format(conf.filename) raise ConfigError(msg, exc)
python
def save(self, config=None): """Saves config to config files. Args: config (configobj.ConfigObj): optional config object to save. Raises: dvc.config.ConfigError: thrown if failed to write config file. """ if config is not None: clist = [config] else: clist = [ self._system_config, self._global_config, self._repo_config, self._local_config, ] for conf in clist: if conf.filename is None: continue try: logger.debug("Writing '{}'.".format(conf.filename)) dname = os.path.dirname(os.path.abspath(conf.filename)) try: os.makedirs(dname) except OSError as exc: if exc.errno != errno.EEXIST: raise conf.write() except Exception as exc: msg = "failed to write config '{}'".format(conf.filename) raise ConfigError(msg, exc)
[ "def", "save", "(", "self", ",", "config", "=", "None", ")", ":", "if", "config", "is", "not", "None", ":", "clist", "=", "[", "config", "]", "else", ":", "clist", "=", "[", "self", ".", "_system_config", ",", "self", ".", "_global_config", ",", "self", ".", "_repo_config", ",", "self", ".", "_local_config", ",", "]", "for", "conf", "in", "clist", ":", "if", "conf", ".", "filename", "is", "None", ":", "continue", "try", ":", "logger", ".", "debug", "(", "\"Writing '{}'.\"", ".", "format", "(", "conf", ".", "filename", ")", ")", "dname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "conf", ".", "filename", ")", ")", "try", ":", "os", ".", "makedirs", "(", "dname", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "conf", ".", "write", "(", ")", "except", "Exception", "as", "exc", ":", "msg", "=", "\"failed to write config '{}'\"", ".", "format", "(", "conf", ".", "filename", ")", "raise", "ConfigError", "(", "msg", ",", "exc", ")" ]
Saves config to config files. Args: config (configobj.ConfigObj): optional config object to save. Raises: dvc.config.ConfigError: thrown if failed to write config file.
[ "Saves", "config", "to", "config", "files", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L455-L489
train
iterative/dvc
dvc/config.py
Config.get_remote_settings
def get_remote_settings(self, name): import posixpath """ Args: name (str): The name of the remote that we want to retrieve Returns: dict: The content beneath the given remote name. Example: >>> config = {'remote "server"': {'url': 'ssh://localhost/'}} >>> get_remote_settings("server") {'url': 'ssh://localhost/'} """ settings = self.config[self.SECTION_REMOTE_FMT.format(name)] parsed = urlparse(settings["url"]) # Support for cross referenced remotes. # This will merge the settings, giving priority to the outer reference. # For example, having: # # dvc remote add server ssh://localhost # dvc remote modify server user root # dvc remote modify server ask_password true # # dvc remote add images remote://server/tmp/pictures # dvc remote modify images user alice # dvc remote modify images ask_password false # dvc remote modify images password asdf1234 # # Results on a config dictionary like: # # { # "url": "ssh://localhost/tmp/pictures", # "user": "alice", # "password": "asdf1234", # "ask_password": False, # } # if parsed.scheme == "remote": reference = self.get_remote_settings(parsed.netloc) url = posixpath.join(reference["url"], parsed.path.lstrip("/")) merged = reference.copy() merged.update(settings) merged["url"] = url return merged return settings
python
def get_remote_settings(self, name): import posixpath """ Args: name (str): The name of the remote that we want to retrieve Returns: dict: The content beneath the given remote name. Example: >>> config = {'remote "server"': {'url': 'ssh://localhost/'}} >>> get_remote_settings("server") {'url': 'ssh://localhost/'} """ settings = self.config[self.SECTION_REMOTE_FMT.format(name)] parsed = urlparse(settings["url"]) # Support for cross referenced remotes. # This will merge the settings, giving priority to the outer reference. # For example, having: # # dvc remote add server ssh://localhost # dvc remote modify server user root # dvc remote modify server ask_password true # # dvc remote add images remote://server/tmp/pictures # dvc remote modify images user alice # dvc remote modify images ask_password false # dvc remote modify images password asdf1234 # # Results on a config dictionary like: # # { # "url": "ssh://localhost/tmp/pictures", # "user": "alice", # "password": "asdf1234", # "ask_password": False, # } # if parsed.scheme == "remote": reference = self.get_remote_settings(parsed.netloc) url = posixpath.join(reference["url"], parsed.path.lstrip("/")) merged = reference.copy() merged.update(settings) merged["url"] = url return merged return settings
[ "def", "get_remote_settings", "(", "self", ",", "name", ")", ":", "import", "posixpath", "settings", "=", "self", ".", "config", "[", "self", ".", "SECTION_REMOTE_FMT", ".", "format", "(", "name", ")", "]", "parsed", "=", "urlparse", "(", "settings", "[", "\"url\"", "]", ")", "# Support for cross referenced remotes.", "# This will merge the settings, giving priority to the outer reference.", "# For example, having:", "#", "# dvc remote add server ssh://localhost", "# dvc remote modify server user root", "# dvc remote modify server ask_password true", "#", "# dvc remote add images remote://server/tmp/pictures", "# dvc remote modify images user alice", "# dvc remote modify images ask_password false", "# dvc remote modify images password asdf1234", "#", "# Results on a config dictionary like:", "#", "# {", "# \"url\": \"ssh://localhost/tmp/pictures\",", "# \"user\": \"alice\",", "# \"password\": \"asdf1234\",", "# \"ask_password\": False,", "# }", "#", "if", "parsed", ".", "scheme", "==", "\"remote\"", ":", "reference", "=", "self", ".", "get_remote_settings", "(", "parsed", ".", "netloc", ")", "url", "=", "posixpath", ".", "join", "(", "reference", "[", "\"url\"", "]", ",", "parsed", ".", "path", ".", "lstrip", "(", "\"/\"", ")", ")", "merged", "=", "reference", ".", "copy", "(", ")", "merged", ".", "update", "(", "settings", ")", "merged", "[", "\"url\"", "]", "=", "url", "return", "merged", "return", "settings" ]
Args: name (str): The name of the remote that we want to retrieve Returns: dict: The content beneath the given remote name. Example: >>> config = {'remote "server"': {'url': 'ssh://localhost/'}} >>> get_remote_settings("server") {'url': 'ssh://localhost/'}
[ "Args", ":", "name", "(", "str", ")", ":", "The", "name", "of", "the", "remote", "that", "we", "want", "to", "retrieve" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L491-L539
train
iterative/dvc
dvc/config.py
Config.unset
def unset(config, section, opt=None): """Unsets specified option and/or section in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): optional option name. """ if section not in config.keys(): raise ConfigError("section '{}' doesn't exist".format(section)) if opt is None: del config[section] return if opt not in config[section].keys(): raise ConfigError( "option '{}.{}' doesn't exist".format(section, opt) ) del config[section][opt] if not config[section]: del config[section]
python
def unset(config, section, opt=None): """Unsets specified option and/or section in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): optional option name. """ if section not in config.keys(): raise ConfigError("section '{}' doesn't exist".format(section)) if opt is None: del config[section] return if opt not in config[section].keys(): raise ConfigError( "option '{}.{}' doesn't exist".format(section, opt) ) del config[section][opt] if not config[section]: del config[section]
[ "def", "unset", "(", "config", ",", "section", ",", "opt", "=", "None", ")", ":", "if", "section", "not", "in", "config", ".", "keys", "(", ")", ":", "raise", "ConfigError", "(", "\"section '{}' doesn't exist\"", ".", "format", "(", "section", ")", ")", "if", "opt", "is", "None", ":", "del", "config", "[", "section", "]", "return", "if", "opt", "not", "in", "config", "[", "section", "]", ".", "keys", "(", ")", ":", "raise", "ConfigError", "(", "\"option '{}.{}' doesn't exist\"", ".", "format", "(", "section", ",", "opt", ")", ")", "del", "config", "[", "section", "]", "[", "opt", "]", "if", "not", "config", "[", "section", "]", ":", "del", "config", "[", "section", "]" ]
Unsets specified option and/or section in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): optional option name.
[ "Unsets", "specified", "option", "and", "/", "or", "section", "in", "the", "config", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L542-L564
train
iterative/dvc
dvc/config.py
Config.set
def set(config, section, opt, value): """Sets specified option in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. value: value to set option to. """ if section not in config.keys(): config[section] = {} config[section][opt] = value
python
def set(config, section, opt, value): """Sets specified option in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. value: value to set option to. """ if section not in config.keys(): config[section] = {} config[section][opt] = value
[ "def", "set", "(", "config", ",", "section", ",", "opt", ",", "value", ")", ":", "if", "section", "not", "in", "config", ".", "keys", "(", ")", ":", "config", "[", "section", "]", "=", "{", "}", "config", "[", "section", "]", "[", "opt", "]", "=", "value" ]
Sets specified option in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. value: value to set option to.
[ "Sets", "specified", "option", "in", "the", "config", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L567-L579
train
iterative/dvc
dvc/config.py
Config.show
def show(config, section, opt): """Prints option value from the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. """ if section not in config.keys(): raise ConfigError("section '{}' doesn't exist".format(section)) if opt not in config[section].keys(): raise ConfigError( "option '{}.{}' doesn't exist".format(section, opt) ) logger.info(config[section][opt])
python
def show(config, section, opt): """Prints option value from the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. """ if section not in config.keys(): raise ConfigError("section '{}' doesn't exist".format(section)) if opt not in config[section].keys(): raise ConfigError( "option '{}.{}' doesn't exist".format(section, opt) ) logger.info(config[section][opt])
[ "def", "show", "(", "config", ",", "section", ",", "opt", ")", ":", "if", "section", "not", "in", "config", ".", "keys", "(", ")", ":", "raise", "ConfigError", "(", "\"section '{}' doesn't exist\"", ".", "format", "(", "section", ")", ")", "if", "opt", "not", "in", "config", "[", "section", "]", ".", "keys", "(", ")", ":", "raise", "ConfigError", "(", "\"option '{}.{}' doesn't exist\"", ".", "format", "(", "section", ",", "opt", ")", ")", "logger", ".", "info", "(", "config", "[", "section", "]", "[", "opt", "]", ")" ]
Prints option value from the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name.
[ "Prints", "option", "value", "from", "the", "config", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L582-L598
train
iterative/dvc
dvc/repo/move.py
move
def move(self, from_path, to_path): """ Renames an output file and modifies the stage associated to reflect the change on the pipeline. If the output has the same name as its stage, it would also rename the corresponding stage file. E.g. Having: (hello, hello.dvc) $ dvc move hello greetings Result: (greeting, greeting.dvc) It only works with outputs generated by `add` or `import`, also known as data sources. """ import dvc.output as Output from dvc.stage import Stage from_out = Output.loads_from(Stage(self), [from_path])[0] to_path = _expand_target_path(from_path, to_path) outs = self.find_outs_by_path(from_out.path) assert len(outs) == 1 out = outs[0] stage = out.stage if not stage.is_data_source: raise MoveNotDataSourceError(stage.relpath) stage_name = os.path.splitext(os.path.basename(stage.path))[0] from_name = os.path.basename(from_out.path) if stage_name == from_name: os.unlink(stage.path) stage.path = os.path.join( os.path.dirname(to_path), os.path.basename(to_path) + Stage.STAGE_FILE_SUFFIX, ) stage.wdir = os.path.abspath( os.path.join(os.curdir, os.path.dirname(to_path)) ) to_out = Output.loads_from( stage, [os.path.basename(to_path)], out.use_cache, out.metric )[0] with self.state: out.move(to_out) stage.dump()
python
def move(self, from_path, to_path): """ Renames an output file and modifies the stage associated to reflect the change on the pipeline. If the output has the same name as its stage, it would also rename the corresponding stage file. E.g. Having: (hello, hello.dvc) $ dvc move hello greetings Result: (greeting, greeting.dvc) It only works with outputs generated by `add` or `import`, also known as data sources. """ import dvc.output as Output from dvc.stage import Stage from_out = Output.loads_from(Stage(self), [from_path])[0] to_path = _expand_target_path(from_path, to_path) outs = self.find_outs_by_path(from_out.path) assert len(outs) == 1 out = outs[0] stage = out.stage if not stage.is_data_source: raise MoveNotDataSourceError(stage.relpath) stage_name = os.path.splitext(os.path.basename(stage.path))[0] from_name = os.path.basename(from_out.path) if stage_name == from_name: os.unlink(stage.path) stage.path = os.path.join( os.path.dirname(to_path), os.path.basename(to_path) + Stage.STAGE_FILE_SUFFIX, ) stage.wdir = os.path.abspath( os.path.join(os.curdir, os.path.dirname(to_path)) ) to_out = Output.loads_from( stage, [os.path.basename(to_path)], out.use_cache, out.metric )[0] with self.state: out.move(to_out) stage.dump()
[ "def", "move", "(", "self", ",", "from_path", ",", "to_path", ")", ":", "import", "dvc", ".", "output", "as", "Output", "from", "dvc", ".", "stage", "import", "Stage", "from_out", "=", "Output", ".", "loads_from", "(", "Stage", "(", "self", ")", ",", "[", "from_path", "]", ")", "[", "0", "]", "to_path", "=", "_expand_target_path", "(", "from_path", ",", "to_path", ")", "outs", "=", "self", ".", "find_outs_by_path", "(", "from_out", ".", "path", ")", "assert", "len", "(", "outs", ")", "==", "1", "out", "=", "outs", "[", "0", "]", "stage", "=", "out", ".", "stage", "if", "not", "stage", ".", "is_data_source", ":", "raise", "MoveNotDataSourceError", "(", "stage", ".", "relpath", ")", "stage_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "stage", ".", "path", ")", ")", "[", "0", "]", "from_name", "=", "os", ".", "path", ".", "basename", "(", "from_out", ".", "path", ")", "if", "stage_name", "==", "from_name", ":", "os", ".", "unlink", "(", "stage", ".", "path", ")", "stage", ".", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "to_path", ")", ",", "os", ".", "path", ".", "basename", "(", "to_path", ")", "+", "Stage", ".", "STAGE_FILE_SUFFIX", ",", ")", "stage", ".", "wdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "curdir", ",", "os", ".", "path", ".", "dirname", "(", "to_path", ")", ")", ")", "to_out", "=", "Output", ".", "loads_from", "(", "stage", ",", "[", "os", ".", "path", ".", "basename", "(", "to_path", ")", "]", ",", "out", ".", "use_cache", ",", "out", ".", "metric", ")", "[", "0", "]", "with", "self", ".", "state", ":", "out", ".", "move", "(", "to_out", ")", "stage", ".", "dump", "(", ")" ]
Renames an output file and modifies the stage associated to reflect the change on the pipeline. If the output has the same name as its stage, it would also rename the corresponding stage file. E.g. Having: (hello, hello.dvc) $ dvc move hello greetings Result: (greeting, greeting.dvc) It only works with outputs generated by `add` or `import`, also known as data sources.
[ "Renames", "an", "output", "file", "and", "modifies", "the", "stage", "associated", "to", "reflect", "the", "change", "on", "the", "pipeline", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/move.py#L14-L68
train
iterative/dvc
dvc/repo/init.py
init
def init(root_dir=os.curdir, no_scm=False, force=False): """ Creates an empty repo on the given directory -- basically a `.dvc` directory with subdirectories for configuration and cache. It should be tracked by a SCM or use the `--no-scm` flag. If the given directory is not empty, you must use the `--force` flag to override it. Args: root_dir: Path to repo's root directory. Returns: Repo instance. Raises: KeyError: Raises an exception. """ root_dir = os.path.abspath(root_dir) dvc_dir = os.path.join(root_dir, Repo.DVC_DIR) scm = SCM(root_dir) if isinstance(scm, NoSCM) and not no_scm: raise InitError( "{repo} is not tracked by any supported scm tool (e.g. git). " "Use '--no-scm' if you don't want to use any scm.".format( repo=root_dir ) ) if os.path.isdir(dvc_dir): if not force: raise InitError( "'{repo}' exists. Use '-f' to force.".format( repo=os.path.relpath(dvc_dir) ) ) shutil.rmtree(dvc_dir) os.mkdir(dvc_dir) config = Config.init(dvc_dir) proj = Repo(root_dir) scm.add([config.config_file]) if scm.ignore_file: scm.add([os.path.join(dvc_dir, scm.ignore_file)]) logger.info("\nYou can now commit the changes to git.\n") _welcome_message() return proj
python
def init(root_dir=os.curdir, no_scm=False, force=False): """ Creates an empty repo on the given directory -- basically a `.dvc` directory with subdirectories for configuration and cache. It should be tracked by a SCM or use the `--no-scm` flag. If the given directory is not empty, you must use the `--force` flag to override it. Args: root_dir: Path to repo's root directory. Returns: Repo instance. Raises: KeyError: Raises an exception. """ root_dir = os.path.abspath(root_dir) dvc_dir = os.path.join(root_dir, Repo.DVC_DIR) scm = SCM(root_dir) if isinstance(scm, NoSCM) and not no_scm: raise InitError( "{repo} is not tracked by any supported scm tool (e.g. git). " "Use '--no-scm' if you don't want to use any scm.".format( repo=root_dir ) ) if os.path.isdir(dvc_dir): if not force: raise InitError( "'{repo}' exists. Use '-f' to force.".format( repo=os.path.relpath(dvc_dir) ) ) shutil.rmtree(dvc_dir) os.mkdir(dvc_dir) config = Config.init(dvc_dir) proj = Repo(root_dir) scm.add([config.config_file]) if scm.ignore_file: scm.add([os.path.join(dvc_dir, scm.ignore_file)]) logger.info("\nYou can now commit the changes to git.\n") _welcome_message() return proj
[ "def", "init", "(", "root_dir", "=", "os", ".", "curdir", ",", "no_scm", "=", "False", ",", "force", "=", "False", ")", ":", "root_dir", "=", "os", ".", "path", ".", "abspath", "(", "root_dir", ")", "dvc_dir", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "Repo", ".", "DVC_DIR", ")", "scm", "=", "SCM", "(", "root_dir", ")", "if", "isinstance", "(", "scm", ",", "NoSCM", ")", "and", "not", "no_scm", ":", "raise", "InitError", "(", "\"{repo} is not tracked by any supported scm tool (e.g. git). \"", "\"Use '--no-scm' if you don't want to use any scm.\"", ".", "format", "(", "repo", "=", "root_dir", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "dvc_dir", ")", ":", "if", "not", "force", ":", "raise", "InitError", "(", "\"'{repo}' exists. Use '-f' to force.\"", ".", "format", "(", "repo", "=", "os", ".", "path", ".", "relpath", "(", "dvc_dir", ")", ")", ")", "shutil", ".", "rmtree", "(", "dvc_dir", ")", "os", ".", "mkdir", "(", "dvc_dir", ")", "config", "=", "Config", ".", "init", "(", "dvc_dir", ")", "proj", "=", "Repo", "(", "root_dir", ")", "scm", ".", "add", "(", "[", "config", ".", "config_file", "]", ")", "if", "scm", ".", "ignore_file", ":", "scm", ".", "add", "(", "[", "os", ".", "path", ".", "join", "(", "dvc_dir", ",", "scm", ".", "ignore_file", ")", "]", ")", "logger", ".", "info", "(", "\"\\nYou can now commit the changes to git.\\n\"", ")", "_welcome_message", "(", ")", "return", "proj" ]
Creates an empty repo on the given directory -- basically a `.dvc` directory with subdirectories for configuration and cache. It should be tracked by a SCM or use the `--no-scm` flag. If the given directory is not empty, you must use the `--force` flag to override it. Args: root_dir: Path to repo's root directory. Returns: Repo instance. Raises: KeyError: Raises an exception.
[ "Creates", "an", "empty", "repo", "on", "the", "given", "directory", "--", "basically", "a", ".", "dvc", "directory", "with", "subdirectories", "for", "configuration", "and", "cache", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/init.py#L43-L96
train
iterative/dvc
dvc/version.py
_generate_version
def _generate_version(base_version): """Generate a version with information about the git repository""" pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if not _is_git_repo(pkg_dir) or not _have_git(): return base_version if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir): return base_version return "{base_version}+{short_sha}{dirty}".format( base_version=base_version, short_sha=_git_revision(pkg_dir).decode("utf-8")[0:6], dirty=".mod" if _is_dirty(pkg_dir) else "", )
python
def _generate_version(base_version): """Generate a version with information about the git repository""" pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if not _is_git_repo(pkg_dir) or not _have_git(): return base_version if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir): return base_version return "{base_version}+{short_sha}{dirty}".format( base_version=base_version, short_sha=_git_revision(pkg_dir).decode("utf-8")[0:6], dirty=".mod" if _is_dirty(pkg_dir) else "", )
[ "def", "_generate_version", "(", "base_version", ")", ":", "pkg_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")", "if", "not", "_is_git_repo", "(", "pkg_dir", ")", "or", "not", "_have_git", "(", ")", ":", "return", "base_version", "if", "_is_release", "(", "pkg_dir", ",", "base_version", ")", "and", "not", "_is_dirty", "(", "pkg_dir", ")", ":", "return", "base_version", "return", "\"{base_version}+{short_sha}{dirty}\"", ".", "format", "(", "base_version", "=", "base_version", ",", "short_sha", "=", "_git_revision", "(", "pkg_dir", ")", ".", "decode", "(", "\"utf-8\"", ")", "[", "0", ":", "6", "]", ",", "dirty", "=", "\".mod\"", "if", "_is_dirty", "(", "pkg_dir", ")", "else", "\"\"", ",", ")" ]
Generate a version with information about the git repository
[ "Generate", "a", "version", "with", "information", "about", "the", "git", "repository" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/version.py#L13-L27
train
iterative/dvc
dvc/version.py
_is_dirty
def _is_dirty(dir_path): """Check whether a git repository has uncommitted changes.""" try: subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path) return False except subprocess.CalledProcessError: return True
python
def _is_dirty(dir_path): """Check whether a git repository has uncommitted changes.""" try: subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path) return False except subprocess.CalledProcessError: return True
[ "def", "_is_dirty", "(", "dir_path", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "\"git\"", ",", "\"diff\"", ",", "\"--quiet\"", "]", ",", "cwd", "=", "dir_path", ")", "return", "False", "except", "subprocess", ".", "CalledProcessError", ":", "return", "True" ]
Check whether a git repository has uncommitted changes.
[ "Check", "whether", "a", "git", "repository", "has", "uncommitted", "changes", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/version.py#L66-L72
train
iterative/dvc
dvc/utils/__init__.py
file_md5
def file_md5(fname): """ get the (md5 hexdigest, md5 digest) of a file """ from dvc.progress import progress from dvc.istextfile import istextfile if os.path.exists(fname): hash_md5 = hashlib.md5() binary = not istextfile(fname) size = os.path.getsize(fname) bar = False if size >= LARGE_FILE_SIZE: bar = True msg = "Computing md5 for a large file {}. This is only done once." logger.info(msg.format(os.path.relpath(fname))) name = os.path.relpath(fname) total = 0 with open(fname, "rb") as fobj: while True: data = fobj.read(LOCAL_CHUNK_SIZE) if not data: break if bar: total += len(data) progress.update_target(name, total, size) if binary: chunk = data else: chunk = dos2unix(data) hash_md5.update(chunk) if bar: progress.finish_target(name) return (hash_md5.hexdigest(), hash_md5.digest()) else: return (None, None)
python
def file_md5(fname): """ get the (md5 hexdigest, md5 digest) of a file """ from dvc.progress import progress from dvc.istextfile import istextfile if os.path.exists(fname): hash_md5 = hashlib.md5() binary = not istextfile(fname) size = os.path.getsize(fname) bar = False if size >= LARGE_FILE_SIZE: bar = True msg = "Computing md5 for a large file {}. This is only done once." logger.info(msg.format(os.path.relpath(fname))) name = os.path.relpath(fname) total = 0 with open(fname, "rb") as fobj: while True: data = fobj.read(LOCAL_CHUNK_SIZE) if not data: break if bar: total += len(data) progress.update_target(name, total, size) if binary: chunk = data else: chunk = dos2unix(data) hash_md5.update(chunk) if bar: progress.finish_target(name) return (hash_md5.hexdigest(), hash_md5.digest()) else: return (None, None)
[ "def", "file_md5", "(", "fname", ")", ":", "from", "dvc", ".", "progress", "import", "progress", "from", "dvc", ".", "istextfile", "import", "istextfile", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "hash_md5", "=", "hashlib", ".", "md5", "(", ")", "binary", "=", "not", "istextfile", "(", "fname", ")", "size", "=", "os", ".", "path", ".", "getsize", "(", "fname", ")", "bar", "=", "False", "if", "size", ">=", "LARGE_FILE_SIZE", ":", "bar", "=", "True", "msg", "=", "\"Computing md5 for a large file {}. This is only done once.\"", "logger", ".", "info", "(", "msg", ".", "format", "(", "os", ".", "path", ".", "relpath", "(", "fname", ")", ")", ")", "name", "=", "os", ".", "path", ".", "relpath", "(", "fname", ")", "total", "=", "0", "with", "open", "(", "fname", ",", "\"rb\"", ")", "as", "fobj", ":", "while", "True", ":", "data", "=", "fobj", ".", "read", "(", "LOCAL_CHUNK_SIZE", ")", "if", "not", "data", ":", "break", "if", "bar", ":", "total", "+=", "len", "(", "data", ")", "progress", ".", "update_target", "(", "name", ",", "total", ",", "size", ")", "if", "binary", ":", "chunk", "=", "data", "else", ":", "chunk", "=", "dos2unix", "(", "data", ")", "hash_md5", ".", "update", "(", "chunk", ")", "if", "bar", ":", "progress", ".", "finish_target", "(", "name", ")", "return", "(", "hash_md5", ".", "hexdigest", "(", ")", ",", "hash_md5", ".", "digest", "(", ")", ")", "else", ":", "return", "(", "None", ",", "None", ")" ]
get the (md5 hexdigest, md5 digest) of a file
[ "get", "the", "(", "md5", "hexdigest", "md5", "digest", ")", "of", "a", "file" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L35-L74
train
iterative/dvc
dvc/utils/__init__.py
dict_filter
def dict_filter(d, exclude=[]): """ Exclude specified keys from a nested dict """ if isinstance(d, list): ret = [] for e in d: ret.append(dict_filter(e, exclude)) return ret elif isinstance(d, dict): ret = {} for k, v in d.items(): if isinstance(k, builtin_str): k = str(k) assert isinstance(k, str) if k in exclude: continue ret[k] = dict_filter(v, exclude) return ret return d
python
def dict_filter(d, exclude=[]): """ Exclude specified keys from a nested dict """ if isinstance(d, list): ret = [] for e in d: ret.append(dict_filter(e, exclude)) return ret elif isinstance(d, dict): ret = {} for k, v in d.items(): if isinstance(k, builtin_str): k = str(k) assert isinstance(k, str) if k in exclude: continue ret[k] = dict_filter(v, exclude) return ret return d
[ "def", "dict_filter", "(", "d", ",", "exclude", "=", "[", "]", ")", ":", "if", "isinstance", "(", "d", ",", "list", ")", ":", "ret", "=", "[", "]", "for", "e", "in", "d", ":", "ret", ".", "append", "(", "dict_filter", "(", "e", ",", "exclude", ")", ")", "return", "ret", "elif", "isinstance", "(", "d", ",", "dict", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "k", ",", "builtin_str", ")", ":", "k", "=", "str", "(", "k", ")", "assert", "isinstance", "(", "k", ",", "str", ")", "if", "k", "in", "exclude", ":", "continue", "ret", "[", "k", "]", "=", "dict_filter", "(", "v", ",", "exclude", ")", "return", "ret", "return", "d" ]
Exclude specified keys from a nested dict
[ "Exclude", "specified", "keys", "from", "a", "nested", "dict" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L83-L105
train
iterative/dvc
dvc/utils/__init__.py
copyfile
def copyfile(src, dest, no_progress_bar=False, name=None): """Copy file with progress bar""" from dvc.progress import progress copied = 0 name = name if name else os.path.basename(dest) total = os.stat(src).st_size if os.path.isdir(dest): dest = os.path.join(dest, os.path.basename(src)) with open(src, "rb") as fsrc, open(dest, "wb+") as fdest: while True: buf = fsrc.read(LOCAL_CHUNK_SIZE) if not buf: break fdest.write(buf) copied += len(buf) if not no_progress_bar: progress.update_target(name, copied, total) if not no_progress_bar: progress.finish_target(name)
python
def copyfile(src, dest, no_progress_bar=False, name=None): """Copy file with progress bar""" from dvc.progress import progress copied = 0 name = name if name else os.path.basename(dest) total = os.stat(src).st_size if os.path.isdir(dest): dest = os.path.join(dest, os.path.basename(src)) with open(src, "rb") as fsrc, open(dest, "wb+") as fdest: while True: buf = fsrc.read(LOCAL_CHUNK_SIZE) if not buf: break fdest.write(buf) copied += len(buf) if not no_progress_bar: progress.update_target(name, copied, total) if not no_progress_bar: progress.finish_target(name)
[ "def", "copyfile", "(", "src", ",", "dest", ",", "no_progress_bar", "=", "False", ",", "name", "=", "None", ")", ":", "from", "dvc", ".", "progress", "import", "progress", "copied", "=", "0", "name", "=", "name", "if", "name", "else", "os", ".", "path", ".", "basename", "(", "dest", ")", "total", "=", "os", ".", "stat", "(", "src", ")", ".", "st_size", "if", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "with", "open", "(", "src", ",", "\"rb\"", ")", "as", "fsrc", ",", "open", "(", "dest", ",", "\"wb+\"", ")", "as", "fdest", ":", "while", "True", ":", "buf", "=", "fsrc", ".", "read", "(", "LOCAL_CHUNK_SIZE", ")", "if", "not", "buf", ":", "break", "fdest", ".", "write", "(", "buf", ")", "copied", "+=", "len", "(", "buf", ")", "if", "not", "no_progress_bar", ":", "progress", ".", "update_target", "(", "name", ",", "copied", ",", "total", ")", "if", "not", "no_progress_bar", ":", "progress", ".", "finish_target", "(", "name", ")" ]
Copy file with progress bar
[ "Copy", "file", "with", "progress", "bar" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L114-L136
train
iterative/dvc
dvc/utils/__init__.py
dvc_walk
def dvc_walk( top, topdown=True, onerror=None, followlinks=False, ignore_file_handler=None, ): """ Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality. """ ignore_filter = None if topdown: from dvc.ignore import DvcIgnoreFilter ignore_filter = DvcIgnoreFilter( top, ignore_file_handler=ignore_file_handler ) for root, dirs, files in os.walk( top, topdown=topdown, onerror=onerror, followlinks=followlinks ): if ignore_filter: dirs[:], files[:] = ignore_filter(root, dirs, files) yield root, dirs, files
python
def dvc_walk( top, topdown=True, onerror=None, followlinks=False, ignore_file_handler=None, ): """ Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality. """ ignore_filter = None if topdown: from dvc.ignore import DvcIgnoreFilter ignore_filter = DvcIgnoreFilter( top, ignore_file_handler=ignore_file_handler ) for root, dirs, files in os.walk( top, topdown=topdown, onerror=onerror, followlinks=followlinks ): if ignore_filter: dirs[:], files[:] = ignore_filter(root, dirs, files) yield root, dirs, files
[ "def", "dvc_walk", "(", "top", ",", "topdown", "=", "True", ",", "onerror", "=", "None", ",", "followlinks", "=", "False", ",", "ignore_file_handler", "=", "None", ",", ")", ":", "ignore_filter", "=", "None", "if", "topdown", ":", "from", "dvc", ".", "ignore", "import", "DvcIgnoreFilter", "ignore_filter", "=", "DvcIgnoreFilter", "(", "top", ",", "ignore_file_handler", "=", "ignore_file_handler", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "top", ",", "topdown", "=", "topdown", ",", "onerror", "=", "onerror", ",", "followlinks", "=", "followlinks", ")", ":", "if", "ignore_filter", ":", "dirs", "[", ":", "]", ",", "files", "[", ":", "]", "=", "ignore_filter", "(", "root", ",", "dirs", ",", "files", ")", "yield", "root", ",", "dirs", ",", "files" ]
Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality.
[ "Proxy", "for", "os", ".", "walk", "directory", "tree", "generator", ".", "Utilizes", "DvcIgnoreFilter", "functionality", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L251-L277
train
iterative/dvc
dvc/utils/__init__.py
colorize
def colorize(message, color=None): """Returns a message in a specified color.""" if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow": colorama.Fore.YELLOW, "blue": colorama.Fore.BLUE, "red": colorama.Fore.RED, } return "{color}{message}{nc}".format( color=colors.get(color, ""), message=message, nc=colorama.Fore.RESET )
python
def colorize(message, color=None): """Returns a message in a specified color.""" if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow": colorama.Fore.YELLOW, "blue": colorama.Fore.BLUE, "red": colorama.Fore.RED, } return "{color}{message}{nc}".format( color=colors.get(color, ""), message=message, nc=colorama.Fore.RESET )
[ "def", "colorize", "(", "message", ",", "color", "=", "None", ")", ":", "if", "not", "color", ":", "return", "message", "colors", "=", "{", "\"green\"", ":", "colorama", ".", "Fore", ".", "GREEN", ",", "\"yellow\"", ":", "colorama", ".", "Fore", ".", "YELLOW", ",", "\"blue\"", ":", "colorama", ".", "Fore", ".", "BLUE", ",", "\"red\"", ":", "colorama", ".", "Fore", ".", "RED", ",", "}", "return", "\"{color}{message}{nc}\"", ".", "format", "(", "color", "=", "colors", ".", "get", "(", "color", ",", "\"\"", ")", ",", "message", "=", "message", ",", "nc", "=", "colorama", ".", "Fore", ".", "RESET", ")" ]
Returns a message in a specified color.
[ "Returns", "a", "message", "in", "a", "specified", "color", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L288-L302
train
iterative/dvc
dvc/utils/__init__.py
boxify
def boxify(message, border_color=None): """Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with. """ lines = message.split("\n") max_width = max(_visual_width(line) for line in lines) padding_horizontal = 5 padding_vertical = 1 box_size_horizontal = max_width + (padding_horizontal * 2) chars = {"corner": "+", "horizontal": "-", "vertical": "|", "empty": " "} margin = "{corner}{line}{corner}\n".format( corner=chars["corner"], line=chars["horizontal"] * box_size_horizontal ) padding_lines = [ "{border}{space}{border}\n".format( border=colorize(chars["vertical"], color=border_color), space=chars["empty"] * box_size_horizontal, ) * padding_vertical ] content_lines = [ "{border}{space}{content}{space}{border}\n".format( border=colorize(chars["vertical"], color=border_color), space=chars["empty"] * padding_horizontal, content=_visual_center(line, max_width), ) for line in lines ] box_str = "{margin}{padding}{content}{padding}{margin}".format( margin=colorize(margin, color=border_color), padding="".join(padding_lines), content="".join(content_lines), ) return box_str
python
def boxify(message, border_color=None): """Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with. """ lines = message.split("\n") max_width = max(_visual_width(line) for line in lines) padding_horizontal = 5 padding_vertical = 1 box_size_horizontal = max_width + (padding_horizontal * 2) chars = {"corner": "+", "horizontal": "-", "vertical": "|", "empty": " "} margin = "{corner}{line}{corner}\n".format( corner=chars["corner"], line=chars["horizontal"] * box_size_horizontal ) padding_lines = [ "{border}{space}{border}\n".format( border=colorize(chars["vertical"], color=border_color), space=chars["empty"] * box_size_horizontal, ) * padding_vertical ] content_lines = [ "{border}{space}{content}{space}{border}\n".format( border=colorize(chars["vertical"], color=border_color), space=chars["empty"] * padding_horizontal, content=_visual_center(line, max_width), ) for line in lines ] box_str = "{margin}{padding}{content}{padding}{margin}".format( margin=colorize(margin, color=border_color), padding="".join(padding_lines), content="".join(content_lines), ) return box_str
[ "def", "boxify", "(", "message", ",", "border_color", "=", "None", ")", ":", "lines", "=", "message", ".", "split", "(", "\"\\n\"", ")", "max_width", "=", "max", "(", "_visual_width", "(", "line", ")", "for", "line", "in", "lines", ")", "padding_horizontal", "=", "5", "padding_vertical", "=", "1", "box_size_horizontal", "=", "max_width", "+", "(", "padding_horizontal", "*", "2", ")", "chars", "=", "{", "\"corner\"", ":", "\"+\"", ",", "\"horizontal\"", ":", "\"-\"", ",", "\"vertical\"", ":", "\"|\"", ",", "\"empty\"", ":", "\" \"", "}", "margin", "=", "\"{corner}{line}{corner}\\n\"", ".", "format", "(", "corner", "=", "chars", "[", "\"corner\"", "]", ",", "line", "=", "chars", "[", "\"horizontal\"", "]", "*", "box_size_horizontal", ")", "padding_lines", "=", "[", "\"{border}{space}{border}\\n\"", ".", "format", "(", "border", "=", "colorize", "(", "chars", "[", "\"vertical\"", "]", ",", "color", "=", "border_color", ")", ",", "space", "=", "chars", "[", "\"empty\"", "]", "*", "box_size_horizontal", ",", ")", "*", "padding_vertical", "]", "content_lines", "=", "[", "\"{border}{space}{content}{space}{border}\\n\"", ".", "format", "(", "border", "=", "colorize", "(", "chars", "[", "\"vertical\"", "]", ",", "color", "=", "border_color", ")", ",", "space", "=", "chars", "[", "\"empty\"", "]", "*", "padding_horizontal", ",", "content", "=", "_visual_center", "(", "line", ",", "max_width", ")", ",", ")", "for", "line", "in", "lines", "]", "box_str", "=", "\"{margin}{padding}{content}{padding}{margin}\"", ".", "format", "(", "margin", "=", "colorize", "(", "margin", ",", "color", "=", "border_color", ")", ",", "padding", "=", "\"\"", ".", "join", "(", "padding_lines", ")", ",", "content", "=", "\"\"", ".", "join", "(", "content_lines", ")", ",", ")", "return", "box_str" ]
Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with.
[ "Put", "a", "message", "inside", "a", "box", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L305-L349
train
iterative/dvc
dvc/utils/__init__.py
_visual_width
def _visual_width(line): """Get the the number of columns required to display a string""" return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
python
def _visual_width(line): """Get the the number of columns required to display a string""" return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
[ "def", "_visual_width", "(", "line", ")", ":", "return", "len", "(", "re", ".", "sub", "(", "colorama", ".", "ansitowin32", ".", "AnsiToWin32", ".", "ANSI_CSI_RE", ",", "\"\"", ",", "line", ")", ")" ]
Get the the number of columns required to display a string
[ "Get", "the", "the", "number", "of", "columns", "required", "to", "display", "a", "string" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L352-L355
train
iterative/dvc
dvc/utils/__init__.py
_visual_center
def _visual_center(line, width): """Center align string according to it's visual width""" spaces = max(width - _visual_width(line), 0) left_padding = int(spaces / 2) right_padding = spaces - left_padding return (left_padding * " ") + line + (right_padding * " ")
python
def _visual_center(line, width): """Center align string according to it's visual width""" spaces = max(width - _visual_width(line), 0) left_padding = int(spaces / 2) right_padding = spaces - left_padding return (left_padding * " ") + line + (right_padding * " ")
[ "def", "_visual_center", "(", "line", ",", "width", ")", ":", "spaces", "=", "max", "(", "width", "-", "_visual_width", "(", "line", ")", ",", "0", ")", "left_padding", "=", "int", "(", "spaces", "/", "2", ")", "right_padding", "=", "spaces", "-", "left_padding", "return", "(", "left_padding", "*", "\" \"", ")", "+", "line", "+", "(", "right_padding", "*", "\" \"", ")" ]
Center align string according to it's visual width
[ "Center", "align", "string", "according", "to", "it", "s", "visual", "width" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L358-L365
train
iterative/dvc
dvc/command/base.py
fix_subparsers
def fix_subparsers(subparsers): """Workaround for bug in Python 3. See more info at: https://bugs.python.org/issue16308 https://github.com/iterative/dvc/issues/769 Args: subparsers: subparsers to fix. """ from dvc.utils.compat import is_py3 if is_py3: # pragma: no cover subparsers.required = True subparsers.dest = "cmd"
python
def fix_subparsers(subparsers): """Workaround for bug in Python 3. See more info at: https://bugs.python.org/issue16308 https://github.com/iterative/dvc/issues/769 Args: subparsers: subparsers to fix. """ from dvc.utils.compat import is_py3 if is_py3: # pragma: no cover subparsers.required = True subparsers.dest = "cmd"
[ "def", "fix_subparsers", "(", "subparsers", ")", ":", "from", "dvc", ".", "utils", ".", "compat", "import", "is_py3", "if", "is_py3", ":", "# pragma: no cover", "subparsers", ".", "required", "=", "True", "subparsers", ".", "dest", "=", "\"cmd\"" ]
Workaround for bug in Python 3. See more info at: https://bugs.python.org/issue16308 https://github.com/iterative/dvc/issues/769 Args: subparsers: subparsers to fix.
[ "Workaround", "for", "bug", "in", "Python", "3", ".", "See", "more", "info", "at", ":", "https", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue16308", "https", ":", "//", "github", ".", "com", "/", "iterative", "/", "dvc", "/", "issues", "/", "769" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/base.py#L10-L22
train
iterative/dvc
dvc/command/base.py
CmdBase.default_targets
def default_targets(self): """Default targets for `dvc repro` and `dvc pipeline`.""" from dvc.stage import Stage msg = "assuming default target '{}'.".format(Stage.STAGE_FILE) logger.warning(msg) return [Stage.STAGE_FILE]
python
def default_targets(self): """Default targets for `dvc repro` and `dvc pipeline`.""" from dvc.stage import Stage msg = "assuming default target '{}'.".format(Stage.STAGE_FILE) logger.warning(msg) return [Stage.STAGE_FILE]
[ "def", "default_targets", "(", "self", ")", ":", "from", "dvc", ".", "stage", "import", "Stage", "msg", "=", "\"assuming default target '{}'.\"", ".", "format", "(", "Stage", ".", "STAGE_FILE", ")", "logger", ".", "warning", "(", "msg", ")", "return", "[", "Stage", ".", "STAGE_FILE", "]" ]
Default targets for `dvc repro` and `dvc pipeline`.
[ "Default", "targets", "for", "dvc", "repro", "and", "dvc", "pipeline", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/base.py#L47-L53
train
iterative/dvc
dvc/scm/__init__.py
SCM
def SCM(root_dir, repo=None): # pylint: disable=invalid-name """Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path to a root directory of the repo. repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to. Returns: dvc.scm.base.Base: SCM instance. """ if Git.is_repo(root_dir) or Git.is_submodule(root_dir): return Git(root_dir, repo=repo) return NoSCM(root_dir, repo=repo)
python
def SCM(root_dir, repo=None): # pylint: disable=invalid-name """Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path to a root directory of the repo. repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to. Returns: dvc.scm.base.Base: SCM instance. """ if Git.is_repo(root_dir) or Git.is_submodule(root_dir): return Git(root_dir, repo=repo) return NoSCM(root_dir, repo=repo)
[ "def", "SCM", "(", "root_dir", ",", "repo", "=", "None", ")", ":", "# pylint: disable=invalid-name", "if", "Git", ".", "is_repo", "(", "root_dir", ")", "or", "Git", ".", "is_submodule", "(", "root_dir", ")", ":", "return", "Git", "(", "root_dir", ",", "repo", "=", "repo", ")", "return", "NoSCM", "(", "root_dir", ",", "repo", "=", "repo", ")" ]
Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path to a root directory of the repo. repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to. Returns: dvc.scm.base.Base: SCM instance.
[ "Returns", "SCM", "instance", "that", "corresponds", "to", "a", "repo", "at", "the", "specified", "path", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/__init__.py#L15-L29
train
iterative/dvc
dvc/cli.py
get_parent_parser
def get_parent_parser(): """Create instances of a parser containing common arguments shared among all the commands. When overwritting `-q` or `-v`, you need to instantiate a new object in order to prevent some weird behavior. """ parent_parser = argparse.ArgumentParser(add_help=False) log_level_group = parent_parser.add_mutually_exclusive_group() log_level_group.add_argument( "-q", "--quiet", action="store_true", default=False, help="Be quiet." ) log_level_group.add_argument( "-v", "--verbose", action="store_true", default=False, help="Be verbose.", ) return parent_parser
python
def get_parent_parser(): """Create instances of a parser containing common arguments shared among all the commands. When overwritting `-q` or `-v`, you need to instantiate a new object in order to prevent some weird behavior. """ parent_parser = argparse.ArgumentParser(add_help=False) log_level_group = parent_parser.add_mutually_exclusive_group() log_level_group.add_argument( "-q", "--quiet", action="store_true", default=False, help="Be quiet." ) log_level_group.add_argument( "-v", "--verbose", action="store_true", default=False, help="Be verbose.", ) return parent_parser
[ "def", "get_parent_parser", "(", ")", ":", "parent_parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "log_level_group", "=", "parent_parser", ".", "add_mutually_exclusive_group", "(", ")", "log_level_group", ".", "add_argument", "(", "\"-q\"", ",", "\"--quiet\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Be quiet.\"", ")", "log_level_group", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Be verbose.\"", ",", ")", "return", "parent_parser" ]
Create instances of a parser containing common arguments shared among all the commands. When overwritting `-q` or `-v`, you need to instantiate a new object in order to prevent some weird behavior.
[ "Create", "instances", "of", "a", "parser", "containing", "common", "arguments", "shared", "among", "all", "the", "commands", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cli.py#L98-L119
train
iterative/dvc
dvc/cli.py
parse_args
def parse_args(argv=None): """Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors. """ parent_parser = get_parent_parser() # Main parser desc = "Data Version Control" parser = DvcParser( prog="dvc", description=desc, parents=[parent_parser], formatter_class=argparse.RawTextHelpFormatter, ) # NOTE: On some python versions action='version' prints to stderr # instead of stdout https://bugs.python.org/issue18920 parser.add_argument( "-V", "--version", action=VersionAction, nargs=0, help="Show program's version.", ) # Sub commands subparsers = parser.add_subparsers( title="Available Commands", metavar="COMMAND", dest="cmd", help="Use dvc COMMAND --help for command-specific help.", ) fix_subparsers(subparsers) for cmd in COMMANDS: cmd.add_parser(subparsers, parent_parser) args = parser.parse_args(argv) return args
python
def parse_args(argv=None): """Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors. """ parent_parser = get_parent_parser() # Main parser desc = "Data Version Control" parser = DvcParser( prog="dvc", description=desc, parents=[parent_parser], formatter_class=argparse.RawTextHelpFormatter, ) # NOTE: On some python versions action='version' prints to stderr # instead of stdout https://bugs.python.org/issue18920 parser.add_argument( "-V", "--version", action=VersionAction, nargs=0, help="Show program's version.", ) # Sub commands subparsers = parser.add_subparsers( title="Available Commands", metavar="COMMAND", dest="cmd", help="Use dvc COMMAND --help for command-specific help.", ) fix_subparsers(subparsers) for cmd in COMMANDS: cmd.add_parser(subparsers, parent_parser) args = parser.parse_args(argv) return args
[ "def", "parse_args", "(", "argv", "=", "None", ")", ":", "parent_parser", "=", "get_parent_parser", "(", ")", "# Main parser", "desc", "=", "\"Data Version Control\"", "parser", "=", "DvcParser", "(", "prog", "=", "\"dvc\"", ",", "description", "=", "desc", ",", "parents", "=", "[", "parent_parser", "]", ",", "formatter_class", "=", "argparse", ".", "RawTextHelpFormatter", ",", ")", "# NOTE: On some python versions action='version' prints to stderr", "# instead of stdout https://bugs.python.org/issue18920", "parser", ".", "add_argument", "(", "\"-V\"", ",", "\"--version\"", ",", "action", "=", "VersionAction", ",", "nargs", "=", "0", ",", "help", "=", "\"Show program's version.\"", ",", ")", "# Sub commands", "subparsers", "=", "parser", ".", "add_subparsers", "(", "title", "=", "\"Available Commands\"", ",", "metavar", "=", "\"COMMAND\"", ",", "dest", "=", "\"cmd\"", ",", "help", "=", "\"Use dvc COMMAND --help for command-specific help.\"", ",", ")", "fix_subparsers", "(", "subparsers", ")", "for", "cmd", "in", "COMMANDS", ":", "cmd", ".", "add_parser", "(", "subparsers", ",", "parent_parser", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "return", "args" ]
Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors.
[ "Parses", "CLI", "arguments", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cli.py#L122-L167
train
iterative/dvc
dvc/utils/collections.py
apply_diff
def apply_diff(src, dest): """Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when parses files. This includes comments, ordering and line foldings. Used in Stage load/dump cycle to preserve comments and custom formatting. """ Seq = (list, tuple) Container = (Mapping, list, tuple) def is_same_type(a, b): return any( isinstance(a, t) and isinstance(b, t) for t in [str, Mapping, Seq, bool] ) if isinstance(src, Mapping) and isinstance(dest, Mapping): for key, value in src.items(): if isinstance(value, Container) and is_same_type( value, dest.get(key) ): apply_diff(value, dest[key]) elif key not in dest or value != dest[key]: dest[key] = value for key in set(dest) - set(src): del dest[key] elif isinstance(src, Seq) and isinstance(dest, Seq): if len(src) != len(dest): dest[:] = src else: for i, value in enumerate(src): if isinstance(value, Container) and is_same_type( value, dest[i] ): apply_diff(value, dest[i]) elif value != dest[i]: dest[i] = value else: raise AssertionError( "Can't apply diff from {} to {}".format( src.__class__.__name__, dest.__class__.__name__ ) )
python
def apply_diff(src, dest): """Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when parses files. This includes comments, ordering and line foldings. Used in Stage load/dump cycle to preserve comments and custom formatting. """ Seq = (list, tuple) Container = (Mapping, list, tuple) def is_same_type(a, b): return any( isinstance(a, t) and isinstance(b, t) for t in [str, Mapping, Seq, bool] ) if isinstance(src, Mapping) and isinstance(dest, Mapping): for key, value in src.items(): if isinstance(value, Container) and is_same_type( value, dest.get(key) ): apply_diff(value, dest[key]) elif key not in dest or value != dest[key]: dest[key] = value for key in set(dest) - set(src): del dest[key] elif isinstance(src, Seq) and isinstance(dest, Seq): if len(src) != len(dest): dest[:] = src else: for i, value in enumerate(src): if isinstance(value, Container) and is_same_type( value, dest[i] ): apply_diff(value, dest[i]) elif value != dest[i]: dest[i] = value else: raise AssertionError( "Can't apply diff from {} to {}".format( src.__class__.__name__, dest.__class__.__name__ ) )
[ "def", "apply_diff", "(", "src", ",", "dest", ")", ":", "Seq", "=", "(", "list", ",", "tuple", ")", "Container", "=", "(", "Mapping", ",", "list", ",", "tuple", ")", "def", "is_same_type", "(", "a", ",", "b", ")", ":", "return", "any", "(", "isinstance", "(", "a", ",", "t", ")", "and", "isinstance", "(", "b", ",", "t", ")", "for", "t", "in", "[", "str", ",", "Mapping", ",", "Seq", ",", "bool", "]", ")", "if", "isinstance", "(", "src", ",", "Mapping", ")", "and", "isinstance", "(", "dest", ",", "Mapping", ")", ":", "for", "key", ",", "value", "in", "src", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "Container", ")", "and", "is_same_type", "(", "value", ",", "dest", ".", "get", "(", "key", ")", ")", ":", "apply_diff", "(", "value", ",", "dest", "[", "key", "]", ")", "elif", "key", "not", "in", "dest", "or", "value", "!=", "dest", "[", "key", "]", ":", "dest", "[", "key", "]", "=", "value", "for", "key", "in", "set", "(", "dest", ")", "-", "set", "(", "src", ")", ":", "del", "dest", "[", "key", "]", "elif", "isinstance", "(", "src", ",", "Seq", ")", "and", "isinstance", "(", "dest", ",", "Seq", ")", ":", "if", "len", "(", "src", ")", "!=", "len", "(", "dest", ")", ":", "dest", "[", ":", "]", "=", "src", "else", ":", "for", "i", ",", "value", "in", "enumerate", "(", "src", ")", ":", "if", "isinstance", "(", "value", ",", "Container", ")", "and", "is_same_type", "(", "value", ",", "dest", "[", "i", "]", ")", ":", "apply_diff", "(", "value", ",", "dest", "[", "i", "]", ")", "elif", "value", "!=", "dest", "[", "i", "]", ":", "dest", "[", "i", "]", "=", "value", "else", ":", "raise", "AssertionError", "(", "\"Can't apply diff from {} to {}\"", ".", "format", "(", "src", ".", "__class__", ".", "__name__", ",", "dest", ".", "__class__", ".", "__name__", ")", ")" ]
Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when parses files. This includes comments, ordering and line foldings. Used in Stage load/dump cycle to preserve comments and custom formatting.
[ "Recursively", "apply", "changes", "from", "src", "to", "dest", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/collections.py#L10-L54
train
iterative/dvc
dvc/remote/ssh/connection.py
percent_cb
def percent_cb(name, complete, total): """ Callback for updating target progress """ logger.debug( "{}: {} transferred out of {}".format( name, sizeof_fmt(complete), sizeof_fmt(total) ) ) progress.update_target(name, complete, total)
python
def percent_cb(name, complete, total): """ Callback for updating target progress """ logger.debug( "{}: {} transferred out of {}".format( name, sizeof_fmt(complete), sizeof_fmt(total) ) ) progress.update_target(name, complete, total)
[ "def", "percent_cb", "(", "name", ",", "complete", ",", "total", ")", ":", "logger", ".", "debug", "(", "\"{}: {} transferred out of {}\"", ".", "format", "(", "name", ",", "sizeof_fmt", "(", "complete", ")", ",", "sizeof_fmt", "(", "total", ")", ")", ")", "progress", ".", "update_target", "(", "name", ",", "complete", ",", "total", ")" ]
Callback for updating target progress
[ "Callback", "for", "updating", "target", "progress" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/ssh/connection.py#L31-L38
train
iterative/dvc
dvc/remote/ssh/connection.py
SSHConnection.md5
def md5(self, path): """ Use different md5 commands depending on the OS: - Darwin's `md5` returns BSD-style checksums by default - Linux's `md5sum` needs the `--tag` flag for a similar output Example: MD5 (foo.txt) = f3d220a856b52aabbf294351e8a24300 """ uname = self.execute("uname").strip() command = { "Darwin": "md5 {}".format(path), "Linux": "md5sum --tag {}".format(path), }.get(uname) if not command: raise DvcException( "'{uname}' is not supported as a remote".format(uname=uname) ) md5 = self.execute(command).split()[-1] assert len(md5) == 32 return md5
python
def md5(self, path): """ Use different md5 commands depending on the OS: - Darwin's `md5` returns BSD-style checksums by default - Linux's `md5sum` needs the `--tag` flag for a similar output Example: MD5 (foo.txt) = f3d220a856b52aabbf294351e8a24300 """ uname = self.execute("uname").strip() command = { "Darwin": "md5 {}".format(path), "Linux": "md5sum --tag {}".format(path), }.get(uname) if not command: raise DvcException( "'{uname}' is not supported as a remote".format(uname=uname) ) md5 = self.execute(command).split()[-1] assert len(md5) == 32 return md5
[ "def", "md5", "(", "self", ",", "path", ")", ":", "uname", "=", "self", ".", "execute", "(", "\"uname\"", ")", ".", "strip", "(", ")", "command", "=", "{", "\"Darwin\"", ":", "\"md5 {}\"", ".", "format", "(", "path", ")", ",", "\"Linux\"", ":", "\"md5sum --tag {}\"", ".", "format", "(", "path", ")", ",", "}", ".", "get", "(", "uname", ")", "if", "not", "command", ":", "raise", "DvcException", "(", "\"'{uname}' is not supported as a remote\"", ".", "format", "(", "uname", "=", "uname", ")", ")", "md5", "=", "self", ".", "execute", "(", "command", ")", ".", "split", "(", ")", "[", "-", "1", "]", "assert", "len", "(", "md5", ")", "==", "32", "return", "md5" ]
Use different md5 commands depending on the OS: - Darwin's `md5` returns BSD-style checksums by default - Linux's `md5sum` needs the `--tag` flag for a similar output Example: MD5 (foo.txt) = f3d220a856b52aabbf294351e8a24300
[ "Use", "different", "md5", "commands", "depending", "on", "the", "OS", ":" ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/ssh/connection.py#L294-L318
train