Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
open_stream_to_socket_listener
(socket_listener)
Connect to the given :class:`~trio.SocketListener`. This is particularly useful in tests when you want to let a server pick its own port, and then connect to it:: listeners = await trio.open_tcp_listeners(0) client = await trio.testing.open_stream_to_socket_listener(listeners[0]) Args: socket_listener (~trio.SocketListener): The :class:`~trio.SocketListener` to connect to. Returns: SocketStream: a stream connected to the given listener.
Connect to the given :class:`~trio.SocketListener`.
async def open_stream_to_socket_listener(socket_listener): """Connect to the given :class:`~trio.SocketListener`. This is particularly useful in tests when you want to let a server pick its own port, and then connect to it:: listeners = await trio.open_tcp_listeners(0) client = await trio.testing.open_stream_to_socket_listener(listeners[0]) Args: socket_listener (~trio.SocketListener): The :class:`~trio.SocketListener` to connect to. Returns: SocketStream: a stream connected to the given listener. """ family = socket_listener.socket.family sockaddr = socket_listener.socket.getsockname() if family in (tsocket.AF_INET, tsocket.AF_INET6): sockaddr = list(sockaddr) if sockaddr[0] == "0.0.0.0": sockaddr[0] = "127.0.0.1" if sockaddr[0] == "::": sockaddr[0] = "::1" sockaddr = tuple(sockaddr) sock = tsocket.socket(family=family) await sock.connect(sockaddr) return SocketStream(sock)
[ "async", "def", "open_stream_to_socket_listener", "(", "socket_listener", ")", ":", "family", "=", "socket_listener", ".", "socket", ".", "family", "sockaddr", "=", "socket_listener", ".", "socket", ".", "getsockname", "(", ")", "if", "family", "in", "(", "tsocket", ".", "AF_INET", ",", "tsocket", ".", "AF_INET6", ")", ":", "sockaddr", "=", "list", "(", "sockaddr", ")", "if", "sockaddr", "[", "0", "]", "==", "\"0.0.0.0\"", ":", "sockaddr", "[", "0", "]", "=", "\"127.0.0.1\"", "if", "sockaddr", "[", "0", "]", "==", "\"::\"", ":", "sockaddr", "[", "0", "]", "=", "\"::1\"", "sockaddr", "=", "tuple", "(", "sockaddr", ")", "sock", "=", "tsocket", ".", "socket", "(", "family", "=", "family", ")", "await", "sock", ".", "connect", "(", "sockaddr", ")", "return", "SocketStream", "(", "sock", ")" ]
[ 4, 0 ]
[ 33, 29 ]
python
en
['en', 'en', 'en']
True
Compile
(logger: logging.Logger, input_text: str, cache: Optional[Cache]=None, file_checker: Optional[IRFileChecker]=None, secret_handler: Optional[SecretHandler]=None, k8s=False, envoy_version="V2")
Compile is a helper function to take a bunch of YAML and compile it into an IR and, optionally, an Envoy config. The output is a dictionary: { "ir": the IR data structure } IFF v2 is True, there will be a toplevel "v2" key whose value is the Envoy V2 config. :param input_text: The input text (WATT snapshot JSON or K8s YAML per 'k8s') :param k8s: If true, input_text is K8s YAML, otherwise it's WATT snapshot JSON :param ir: Generate the IR IFF True :param v2: Generate the V2 Envoy config IFF True
Compile is a helper function to take a bunch of YAML and compile it into an IR and, optionally, an Envoy config.
def Compile(logger: logging.Logger, input_text: str, cache: Optional[Cache]=None, file_checker: Optional[IRFileChecker]=None, secret_handler: Optional[SecretHandler]=None, k8s=False, envoy_version="V2") -> Dict[str, Union[IR, EnvoyConfig]]: """ Compile is a helper function to take a bunch of YAML and compile it into an IR and, optionally, an Envoy config. The output is a dictionary: { "ir": the IR data structure } IFF v2 is True, there will be a toplevel "v2" key whose value is the Envoy V2 config. :param input_text: The input text (WATT snapshot JSON or K8s YAML per 'k8s') :param k8s: If true, input_text is K8s YAML, otherwise it's WATT snapshot JSON :param ir: Generate the IR IFF True :param v2: Generate the V2 Envoy config IFF True """ if not file_checker: file_checker = lambda path: True if not secret_handler: secret_handler = NullSecretHandler(logger, None, None, "fake") aconf = Config() fetcher = ResourceFetcher(logger, aconf) if k8s: fetcher.parse_yaml(input_text, k8s=True) else: fetcher.parse_watt(input_text) aconf.load_all(fetcher.sorted()) ir = IR(aconf, cache=cache, file_checker=file_checker, secret_handler=secret_handler) out: Dict[str, Union[IR, EnvoyConfig]] = { "ir": ir } if ir: out[envoy_version.lower()] = EnvoyConfig.generate(ir, envoy_version.upper(), cache=cache) return out
[ "def", "Compile", "(", "logger", ":", "logging", ".", "Logger", ",", "input_text", ":", "str", ",", "cache", ":", "Optional", "[", "Cache", "]", "=", "None", ",", "file_checker", ":", "Optional", "[", "IRFileChecker", "]", "=", "None", ",", "secret_handler", ":", "Optional", "[", "SecretHandler", "]", "=", "None", ",", "k8s", "=", "False", ",", "envoy_version", "=", "\"V2\"", ")", "->", "Dict", "[", "str", ",", "Union", "[", "IR", ",", "EnvoyConfig", "]", "]", ":", "if", "not", "file_checker", ":", "file_checker", "=", "lambda", "path", ":", "True", "if", "not", "secret_handler", ":", "secret_handler", "=", "NullSecretHandler", "(", "logger", ",", "None", ",", "None", ",", "\"fake\"", ")", "aconf", "=", "Config", "(", ")", "fetcher", "=", "ResourceFetcher", "(", "logger", ",", "aconf", ")", "if", "k8s", ":", "fetcher", ".", "parse_yaml", "(", "input_text", ",", "k8s", "=", "True", ")", "else", ":", "fetcher", ".", "parse_watt", "(", "input_text", ")", "aconf", ".", "load_all", "(", "fetcher", ".", "sorted", "(", ")", ")", "ir", "=", "IR", "(", "aconf", ",", "cache", "=", "cache", ",", "file_checker", "=", "file_checker", ",", "secret_handler", "=", "secret_handler", ")", "out", ":", "Dict", "[", "str", ",", "Union", "[", "IR", ",", "EnvoyConfig", "]", "]", "=", "{", "\"ir\"", ":", "ir", "}", "if", "ir", ":", "out", "[", "envoy_version", ".", "lower", "(", ")", "]", "=", "EnvoyConfig", ".", "generate", "(", "ir", ",", "envoy_version", ".", "upper", "(", ")", ",", "cache", "=", "cache", ")", "return", "out" ]
[ 26, 0 ]
[ 74, 14 ]
python
en
['en', 'error', 'th']
False
simple_tmle
(y, w, q0w, q1w, p, alpha=0.0001)
Calculate the ATE and variances with the simplified TMLE method. Args: y (numpy.array): an outcome vector w (numpy.array): a treatment vector q0w (numpy.array): an outcome prediction vector given no treatment q1w (numpy.array): an outcome prediction vector given treatment p (numpy.array): a propensity score vector alpha (float, optional): a clipping threshold for predictions Returns: (tuple) - ate (float): ATE - se (float): The standard error of ATE
Calculate the ATE and variances with the simplified TMLE method.
def simple_tmle(y, w, q0w, q1w, p, alpha=0.0001): """Calculate the ATE and variances with the simplified TMLE method. Args: y (numpy.array): an outcome vector w (numpy.array): a treatment vector q0w (numpy.array): an outcome prediction vector given no treatment q1w (numpy.array): an outcome prediction vector given treatment p (numpy.array): a propensity score vector alpha (float, optional): a clipping threshold for predictions Returns: (tuple) - ate (float): ATE - se (float): The standard error of ATE """ scaler = MinMaxScaler() ystar = scaler.fit_transform(y.reshape(-1, 1)).flatten() q0 = np.clip(scaler.transform(q0w.reshape(-1, 1)).flatten(), alpha, 1 - alpha) q1 = np.clip(scaler.transform(q1w.reshape(-1, 1)).flatten(), alpha, 1 - alpha) qaw = q0 * (1 - w) + q1 * w intercept = logit(qaw) h1 = w / p h0 = (1 - w) / (1 - p) sol = minimize(logit_tmle, np.zeros(2), args=(ystar, intercept, h0, h1), method="Newton-CG", jac=logit_tmle_grad, hess=logit_tmle_hess) qawstar = scaler.inverse_transform(expit(intercept + sol.x[0] * h0 + sol.x[1] * h1).reshape(-1, 1)).flatten() q0star = scaler.inverse_transform(expit(logit(q0) + sol.x[0] / (1 - p)).reshape(-1, 1)).flatten() q1star = scaler.inverse_transform(expit(logit(q1) + sol.x[1] / p).reshape(-1, 1)).flatten() ic = (w / p - (1 - w) / (1 - p)) * (y - qawstar) + q1star - q0star - np.mean(q1star - q0star) return np.mean(q1star - q0star), np.sqrt(np.var(ic) / np.size(y))
[ "def", "simple_tmle", "(", "y", ",", "w", ",", "q0w", ",", "q1w", ",", "p", ",", "alpha", "=", "0.0001", ")", ":", "scaler", "=", "MinMaxScaler", "(", ")", "ystar", "=", "scaler", ".", "fit_transform", "(", "y", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", "q0", "=", "np", ".", "clip", "(", "scaler", ".", "transform", "(", "q0w", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", ",", "alpha", ",", "1", "-", "alpha", ")", "q1", "=", "np", ".", "clip", "(", "scaler", ".", "transform", "(", "q1w", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", ",", "alpha", ",", "1", "-", "alpha", ")", "qaw", "=", "q0", "*", "(", "1", "-", "w", ")", "+", "q1", "*", "w", "intercept", "=", "logit", "(", "qaw", ")", "h1", "=", "w", "/", "p", "h0", "=", "(", "1", "-", "w", ")", "/", "(", "1", "-", "p", ")", "sol", "=", "minimize", "(", "logit_tmle", ",", "np", ".", "zeros", "(", "2", ")", ",", "args", "=", "(", "ystar", ",", "intercept", ",", "h0", ",", "h1", ")", ",", "method", "=", "\"Newton-CG\"", ",", "jac", "=", "logit_tmle_grad", ",", "hess", "=", "logit_tmle_hess", ")", "qawstar", "=", "scaler", ".", "inverse_transform", "(", "expit", "(", "intercept", "+", "sol", ".", "x", "[", "0", "]", "*", "h0", "+", "sol", ".", "x", "[", "1", "]", "*", "h1", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", "q0star", "=", "scaler", ".", "inverse_transform", "(", "expit", "(", "logit", "(", "q0", ")", "+", "sol", ".", "x", "[", "0", "]", "/", "(", "1", "-", "p", ")", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", "q1star", "=", "scaler", ".", "inverse_transform", "(", "expit", "(", "logit", "(", "q1", ")", "+", "sol", ".", "x", "[", "1", "]", "/", "p", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "flatten", "(", ")", "ic", "=", "(", "w", "/", "p", "-", "(", "1", "-", "w", ")", "/", "(", "1", "-", "p", ")", ")", "*", "(", "y", "-", "qawstar", ")", "+", "q1star", "-", "q0star", "-", "np", ".", "mean", "(", "q1star", "-", "q0star", ")", "return", "np", ".", "mean", "(", "q1star", "-", "q0star", ")", ",", "np", ".", "sqrt", "(", "np", ".", "var", "(", "ic", ")", "/", "np", ".", "size", "(", "y", ")", ")" ]
[ 31, 0 ]
[ 67, 69 ]
python
en
['en', 'en', 'en']
True
TMLELearner.__init__
(self, learner, ate_alpha=.05, control_name=0, cv=None, calibrate_propensity=True)
Initialize a TMLE learner. Args: learner: a model to estimate the outcome ate_alpha (float, optional): the confidence level alpha of the ATE estimate control_name (str or int, optional): the name of the control group cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
Initialize a TMLE learner.
def __init__(self, learner, ate_alpha=.05, control_name=0, cv=None, calibrate_propensity=True): """Initialize a TMLE learner. Args: learner: a model to estimate the outcome ate_alpha (float, optional): the confidence level alpha of the ATE estimate control_name (str or int, optional): the name of the control group cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object """ self.model_tau = learner self.ate_alpha = ate_alpha self.control_name = control_name self.cv = cv self.calibrate_propensity = calibrate_propensity
[ "def", "__init__", "(", "self", ",", "learner", ",", "ate_alpha", "=", ".05", ",", "control_name", "=", "0", ",", "cv", "=", "None", ",", "calibrate_propensity", "=", "True", ")", ":", "self", ".", "model_tau", "=", "learner", "self", ".", "ate_alpha", "=", "ate_alpha", "self", ".", "control_name", "=", "control_name", "self", ".", "cv", "=", "cv", "self", ".", "calibrate_propensity", "=", "calibrate_propensity" ]
[ 76, 4 ]
[ 89, 56 ]
python
en
['en', 'en', 'en']
True
TMLELearner.estimate_ate
(self, X, treatment, y, p, segment=None, return_ci=False)
Estimate the Average Treatment Effect (ATE). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Series or dict): an array of propensity scores of float (0,1) in the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of float (0,1) segment (np.array, optional): An optional segment vector of int. If given, the ATE and its CI will be estimated for each segment. return_ci (bool, optional): Whether to return confidence intervals Returns: (tuple): The ATE and its confidence interval (LB, UB) for each treatment, t and segment, s
Estimate the Average Treatment Effect (ATE).
def estimate_ate(self, X, treatment, y, p, segment=None, return_ci=False): """Estimate the Average Treatment Effect (ATE). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Series or dict): an array of propensity scores of float (0,1) in the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of float (0,1) segment (np.array, optional): An optional segment vector of int. If given, the ATE and its CI will be estimated for each segment. return_ci (bool, optional): Whether to return confidence intervals Returns: (tuple): The ATE and its confidence interval (LB, UB) for each treatment, t and segment, s """ X, treatment, y = convert_pd_to_np(X, treatment, y) check_treatment_vector(treatment, self.control_name) self.t_groups = np.unique(treatment[treatment != self.control_name]) self.t_groups.sort() check_p_conditions(p, self.t_groups) if isinstance(p, (np.ndarray, pd.Series)): treatment_name = self.t_groups[0] p = {treatment_name: convert_pd_to_np(p)} elif isinstance(p, dict): p = {treatment_name: convert_pd_to_np(_p) for treatment_name, _p in p.items()} ate = [] ate_lb = [] ate_ub = [] for i, group in enumerate(self.t_groups): logger.info('Estimating ATE for group {}.'.format(group)) w_group = (treatment == group).astype(int) p_group = p[group] if self.calibrate_propensity: logger.info('Calibrating propensity scores.') p_group = calibrate(p_group, w_group) yhat_c = np.zeros_like(y, dtype=float) yhat_t = np.zeros_like(y, dtype=float) if self.cv: for i_fold, (i_trn, i_val) in enumerate(self.cv.split(X, y), 1): logger.info('Training an outcome model for CV #{}'.format(i_fold)) self.model_tau.fit(np.hstack((X[i_trn], w_group[i_trn].reshape(-1, 1))), y[i_trn]) yhat_c[i_val] = self.model_tau.predict(np.hstack((X[i_val], np.zeros((len(i_val), 1))))) yhat_t[i_val] = self.model_tau.predict(np.hstack((X[i_val], np.ones((len(i_val), 1))))) else: self.model_tau.fit(np.hstack((X, w_group.reshape(-1, 1))), y) yhat_c = self.model_tau.predict(np.hstack((X, np.zeros((len(y), 1))))) yhat_t = self.model_tau.predict(np.hstack((X, np.ones((len(y), 1))))) if segment is None: logger.info('Training the TMLE learner.') _ate, se = simple_tmle(y, w_group, yhat_c, yhat_t, p_group) _ate_lb = _ate - se * norm.ppf(1 - self.ate_alpha / 2) _ate_ub = _ate + se * norm.ppf(1 - self.ate_alpha / 2) else: assert segment.shape[0] == X.shape[0] and segment.ndim == 1, 'Segment must be the 1-d np.array of int.' segments = np.unique(segment) _ate = [] _ate_lb = [] _ate_ub = [] for s in sorted(segments): logger.info('Training the TMLE learner for segment {}.'.format(s)) filt = (segment == s) & (yhat_c < np.quantile(yhat_c, q=.99)) _ate_s, se = simple_tmle(y[filt], w_group[filt], yhat_c[filt], yhat_t[filt], p_group[filt]) _ate_lb_s = _ate_s - se * norm.ppf(1 - self.ate_alpha / 2) _ate_ub_s = _ate_s + se * norm.ppf(1 - self.ate_alpha / 2) _ate.append(_ate_s) _ate_lb.append(_ate_lb_s) _ate_ub.append(_ate_ub_s) ate.append(_ate) ate_lb.append(_ate_lb) ate_ub.append(_ate_ub) return np.array(ate), np.array(ate_lb), np.array(ate_ub)
[ "def", "estimate_ate", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", ",", "segment", "=", "None", ",", "return_ci", "=", "False", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_to_np", "(", "X", ",", "treatment", ",", "y", ")", "check_treatment_vector", "(", "treatment", ",", "self", ".", "control_name", ")", "self", ".", "t_groups", "=", "np", ".", "unique", "(", "treatment", "[", "treatment", "!=", "self", ".", "control_name", "]", ")", "self", ".", "t_groups", ".", "sort", "(", ")", "check_p_conditions", "(", "p", ",", "self", ".", "t_groups", ")", "if", "isinstance", "(", "p", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Series", ")", ")", ":", "treatment_name", "=", "self", ".", "t_groups", "[", "0", "]", "p", "=", "{", "treatment_name", ":", "convert_pd_to_np", "(", "p", ")", "}", "elif", "isinstance", "(", "p", ",", "dict", ")", ":", "p", "=", "{", "treatment_name", ":", "convert_pd_to_np", "(", "_p", ")", "for", "treatment_name", ",", "_p", "in", "p", ".", "items", "(", ")", "}", "ate", "=", "[", "]", "ate_lb", "=", "[", "]", "ate_ub", "=", "[", "]", "for", "i", ",", "group", "in", "enumerate", "(", "self", ".", "t_groups", ")", ":", "logger", ".", "info", "(", "'Estimating ATE for group {}.'", ".", "format", "(", "group", ")", ")", "w_group", "=", "(", "treatment", "==", "group", ")", ".", "astype", "(", "int", ")", "p_group", "=", "p", "[", "group", "]", "if", "self", ".", "calibrate_propensity", ":", "logger", ".", "info", "(", "'Calibrating propensity scores.'", ")", "p_group", "=", "calibrate", "(", "p_group", ",", "w_group", ")", "yhat_c", "=", "np", ".", "zeros_like", "(", "y", ",", "dtype", "=", "float", ")", "yhat_t", "=", "np", ".", "zeros_like", "(", "y", ",", "dtype", "=", "float", ")", "if", "self", ".", "cv", ":", "for", "i_fold", ",", "(", "i_trn", ",", "i_val", ")", "in", "enumerate", "(", "self", ".", "cv", ".", "split", "(", "X", ",", "y", ")", ",", "1", ")", ":", "logger", ".", "info", "(", "'Training an outcome model for CV #{}'", ".", "format", "(", "i_fold", ")", ")", "self", ".", "model_tau", ".", "fit", "(", "np", ".", "hstack", "(", "(", "X", "[", "i_trn", "]", ",", "w_group", "[", "i_trn", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ")", ",", "y", "[", "i_trn", "]", ")", "yhat_c", "[", "i_val", "]", "=", "self", ".", "model_tau", ".", "predict", "(", "np", ".", "hstack", "(", "(", "X", "[", "i_val", "]", ",", "np", ".", "zeros", "(", "(", "len", "(", "i_val", ")", ",", "1", ")", ")", ")", ")", ")", "yhat_t", "[", "i_val", "]", "=", "self", ".", "model_tau", ".", "predict", "(", "np", ".", "hstack", "(", "(", "X", "[", "i_val", "]", ",", "np", ".", "ones", "(", "(", "len", "(", "i_val", ")", ",", "1", ")", ")", ")", ")", ")", "else", ":", "self", ".", "model_tau", ".", "fit", "(", "np", ".", "hstack", "(", "(", "X", ",", "w_group", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ")", ",", "y", ")", "yhat_c", "=", "self", ".", "model_tau", ".", "predict", "(", "np", ".", "hstack", "(", "(", "X", ",", "np", ".", "zeros", "(", "(", "len", "(", "y", ")", ",", "1", ")", ")", ")", ")", ")", "yhat_t", "=", "self", ".", "model_tau", ".", "predict", "(", "np", ".", "hstack", "(", "(", "X", ",", "np", ".", "ones", "(", "(", "len", "(", "y", ")", ",", "1", ")", ")", ")", ")", ")", "if", "segment", "is", "None", ":", "logger", ".", "info", "(", "'Training the TMLE learner.'", ")", "_ate", ",", "se", "=", "simple_tmle", "(", "y", ",", "w_group", ",", "yhat_c", ",", "yhat_t", ",", "p_group", ")", "_ate_lb", "=", "_ate", "-", "se", "*", "norm", ".", "ppf", "(", "1", "-", "self", ".", "ate_alpha", "/", "2", ")", "_ate_ub", "=", "_ate", "+", "se", "*", "norm", ".", "ppf", "(", "1", "-", "self", ".", "ate_alpha", "/", "2", ")", "else", ":", "assert", "segment", ".", "shape", "[", "0", "]", "==", "X", ".", "shape", "[", "0", "]", "and", "segment", ".", "ndim", "==", "1", ",", "'Segment must be the 1-d np.array of int.'", "segments", "=", "np", ".", "unique", "(", "segment", ")", "_ate", "=", "[", "]", "_ate_lb", "=", "[", "]", "_ate_ub", "=", "[", "]", "for", "s", "in", "sorted", "(", "segments", ")", ":", "logger", ".", "info", "(", "'Training the TMLE learner for segment {}.'", ".", "format", "(", "s", ")", ")", "filt", "=", "(", "segment", "==", "s", ")", "&", "(", "yhat_c", "<", "np", ".", "quantile", "(", "yhat_c", ",", "q", "=", ".99", ")", ")", "_ate_s", ",", "se", "=", "simple_tmle", "(", "y", "[", "filt", "]", ",", "w_group", "[", "filt", "]", ",", "yhat_c", "[", "filt", "]", ",", "yhat_t", "[", "filt", "]", ",", "p_group", "[", "filt", "]", ")", "_ate_lb_s", "=", "_ate_s", "-", "se", "*", "norm", ".", "ppf", "(", "1", "-", "self", ".", "ate_alpha", "/", "2", ")", "_ate_ub_s", "=", "_ate_s", "+", "se", "*", "norm", ".", "ppf", "(", "1", "-", "self", ".", "ate_alpha", "/", "2", ")", "_ate", ".", "append", "(", "_ate_s", ")", "_ate_lb", ".", "append", "(", "_ate_lb_s", ")", "_ate_ub", ".", "append", "(", "_ate_ub_s", ")", "ate", ".", "append", "(", "_ate", ")", "ate_lb", ".", "append", "(", "_ate_lb", ")", "ate_ub", ".", "append", "(", "_ate_ub", ")", "return", "np", ".", "array", "(", "ate", ")", ",", "np", ".", "array", "(", "ate_lb", ")", ",", "np", ".", "array", "(", "ate_ub", ")" ]
[ 94, 4 ]
[ 178, 64 ]
python
en
['en', 'it', 'en']
True
UpliftTreeClassifier.fit
(self, X, treatment, y)
Fit the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- self : object
Fit the uplift model.
def fit(self, X, treatment, y): """ Fit the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- self : object """ assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.' self.treatment_group = list(set(treatment)) self.feature_imp_dict = defaultdict(float) if self.evaluationFunction == self.evaluate_DDP and len(self.treatment_group) > 2: raise ValueError("The DDP approach can only cope with two class problems, that is two different treatment options (e.g., control vs treatment)." "Please select another approach or only use a data set which employs two treatment options.") self.fitted_uplift_tree = self.growDecisionTreeFrom( X, treatment, y, evaluationFunction=self.evaluationFunction, max_depth=self.max_depth, min_samples_leaf=self.min_samples_leaf, depth=1, min_samples_treatment=self.min_samples_treatment, n_reg=self.n_reg, parentNodeSummary=None ) self.feature_importances_ = np.zeros(X.shape[1]) for col, imp in self.feature_imp_dict.items(): self.feature_importances_[col] = imp self.feature_importances_ /= self.feature_importances_.sum()
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ")", ":", "assert", "len", "(", "X", ")", "==", "len", "(", "y", ")", "and", "len", "(", "X", ")", "==", "len", "(", "treatment", ")", ",", "'Data length must be equal for X, treatment, and y.'", "self", ".", "treatment_group", "=", "list", "(", "set", "(", "treatment", ")", ")", "self", ".", "feature_imp_dict", "=", "defaultdict", "(", "float", ")", "if", "self", ".", "evaluationFunction", "==", "self", ".", "evaluate_DDP", "and", "len", "(", "self", ".", "treatment_group", ")", ">", "2", ":", "raise", "ValueError", "(", "\"The DDP approach can only cope with two class problems, that is two different treatment options (e.g., control vs treatment).\"", "\"Please select another approach or only use a data set which employs two treatment options.\"", ")", "self", ".", "fitted_uplift_tree", "=", "self", ".", "growDecisionTreeFrom", "(", "X", ",", "treatment", ",", "y", ",", "evaluationFunction", "=", "self", ".", "evaluationFunction", ",", "max_depth", "=", "self", ".", "max_depth", ",", "min_samples_leaf", "=", "self", ".", "min_samples_leaf", ",", "depth", "=", "1", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "self", ".", "n_reg", ",", "parentNodeSummary", "=", "None", ")", "self", ".", "feature_importances_", "=", "np", ".", "zeros", "(", "X", ".", "shape", "[", "1", "]", ")", "for", "col", ",", "imp", "in", "self", ".", "feature_imp_dict", ".", "items", "(", ")", ":", "self", ".", "feature_importances_", "[", "col", "]", "=", "imp", "self", ".", "feature_importances_", "/=", "self", ".", "feature_importances_", ".", "sum", "(", ")" ]
[ 166, 4 ]
[ 203, 68 ]
python
en
['en', 'en', 'en']
True
UpliftTreeClassifier.prune
(self, X, treatment, y, minGain=0.0001, rule='maxAbsDiff')
Prune the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. minGain : float, optional (default = 0.0001) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. Returns ------- self : object
Prune the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. minGain : float, optional (default = 0.0001) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. Returns ------- self : object
def prune(self, X, treatment, y, minGain=0.0001, rule='maxAbsDiff'): """ Prune the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. minGain : float, optional (default = 0.0001) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. Returns ------- self : object """ assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.' self.pruneTree(X, treatment, y, tree=self.fitted_uplift_tree, rule=rule, minGain=minGain, evaluationFunction=self.evaluationFunction, notify=False, n_reg=self.n_reg, parentNodeSummary=None) return self
[ "def", "prune", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "minGain", "=", "0.0001", ",", "rule", "=", "'maxAbsDiff'", ")", ":", "assert", "len", "(", "X", ")", "==", "len", "(", "y", ")", "and", "len", "(", "X", ")", "==", "len", "(", "treatment", ")", ",", "'Data length must be equal for X, treatment, and y.'", "self", ".", "pruneTree", "(", "X", ",", "treatment", ",", "y", ",", "tree", "=", "self", ".", "fitted_uplift_tree", ",", "rule", "=", "rule", ",", "minGain", "=", "minGain", ",", "evaluationFunction", "=", "self", ".", "evaluationFunction", ",", "notify", "=", "False", ",", "n_reg", "=", "self", ".", "n_reg", ",", "parentNodeSummary", "=", "None", ")", "return", "self" ]
[ 206, 4 ]
[ 238, 19 ]
python
en
['en', 'no', 'en']
True
UpliftTreeClassifier.pruneTree
(self, X, treatment, y, tree, rule='maxAbsDiff', minGain=0., evaluationFunction=None, notify=False, n_reg=0, parentNodeSummary=None)
Prune one single tree node in the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. minGain : float, optional (default = 0.) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. evaluationFunction : string, optional (default = None) Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS', 'DDP'. notify: bool, optional (default = False) n_reg: int, optional (default=0) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary, optional (default = None) Node summary statistics of the parent tree node. Returns ------- self : object
Prune one single tree node in the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. minGain : float, optional (default = 0.) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. evaluationFunction : string, optional (default = None) Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS', 'DDP'. notify: bool, optional (default = False) n_reg: int, optional (default=0) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary, optional (default = None) Node summary statistics of the parent tree node. Returns ------- self : object
def pruneTree(self, X, treatment, y, tree, rule='maxAbsDiff', minGain=0., evaluationFunction=None, notify=False, n_reg=0, parentNodeSummary=None): """Prune one single tree node in the uplift model. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. rule : string, optional (default = 'maxAbsDiff') The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and 'bestUplift' for optimizing the node-size weighted treatment effect. minGain : float, optional (default = 0.) The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual split gain is less than the minimum gain. evaluationFunction : string, optional (default = None) Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS', 'DDP'. notify: bool, optional (default = False) n_reg: int, optional (default=0) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary, optional (default = None) Node summary statistics of the parent tree node. Returns ------- self : object """ # Current Node Summary for Validation Data Set currentNodeSummary = self.tree_node_summary( treatment, y, min_samples_treatment=self.min_samples_treatment, n_reg=n_reg, parentNodeSummary=parentNodeSummary ) tree.nodeSummary = currentNodeSummary # Divide sets for child nodes X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, tree.col, tree.value) # recursive call for each branch if tree.trueBranch.results is None: self.pruneTree(X_l, w_l, y_l, tree.trueBranch, rule, minGain, evaluationFunction, notify, n_reg, parentNodeSummary=currentNodeSummary) if tree.falseBranch.results is None: self.pruneTree(X_r, w_r, y_r, tree.falseBranch, rule, minGain, evaluationFunction, notify, n_reg, parentNodeSummary=currentNodeSummary) # merge leaves (potentially) if (tree.trueBranch.results is not None and tree.falseBranch.results is not None): if rule == 'maxAbsDiff': # Current D if (tree.maxDiffTreatment in currentNodeSummary and self.control_name in currentNodeSummary): currentScoreD = tree.maxDiffSign * (currentNodeSummary[tree.maxDiffTreatment][0] - currentNodeSummary[self.control_name][0]) else: currentScoreD = 0 # trueBranch D trueNodeSummary = self.tree_node_summary( w_l, y_l, min_samples_treatment=self.min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) if (tree.trueBranch.maxDiffTreatment in trueNodeSummary and self.control_name in trueNodeSummary): trueScoreD = tree.trueBranch.maxDiffSign * (trueNodeSummary[tree.trueBranch.maxDiffTreatment][0] - trueNodeSummary[self.control_name][0]) trueScoreD = ( trueScoreD * (trueNodeSummary[tree.trueBranch.maxDiffTreatment][1] + trueNodeSummary[self.control_name][1]) / (currentNodeSummary[tree.trueBranch.maxDiffTreatment][1] + currentNodeSummary[self.control_name][1]) ) else: trueScoreD = 0 # falseBranch D falseNodeSummary = self.tree_node_summary( w_r, y_r, min_samples_treatment=self.min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) if (tree.falseBranch.maxDiffTreatment in falseNodeSummary and self.control_name in falseNodeSummary): falseScoreD = ( tree.falseBranch.maxDiffSign * (falseNodeSummary[tree.falseBranch.maxDiffTreatment][0] - falseNodeSummary[self.control_name][0]) ) falseScoreD = ( falseScoreD * (falseNodeSummary[tree.falseBranch.maxDiffTreatment][1] + falseNodeSummary[self.control_name][1]) / (currentNodeSummary[tree.falseBranch.maxDiffTreatment][1] + currentNodeSummary[self.control_name][1]) ) else: falseScoreD = 0 if ((trueScoreD + falseScoreD) - currentScoreD <= minGain or (trueScoreD + falseScoreD < 0.)): tree.trueBranch, tree.falseBranch = None, None tree.results = tree.backupResults elif rule == 'bestUplift': # Current D if (tree.bestTreatment in currentNodeSummary and self.control_name in currentNodeSummary): currentScoreD = ( currentNodeSummary[tree.bestTreatment][0] - currentNodeSummary[self.control_name][0] ) else: currentScoreD = 0 # trueBranch D trueNodeSummary = self.tree_node_summary( w_l, y_l, min_samples_treatment=self.min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) if (tree.trueBranch.bestTreatment in trueNodeSummary and self.control_name in trueNodeSummary): trueScoreD = ( trueNodeSummary[tree.trueBranch.bestTreatment][0] - trueNodeSummary[self.control_name][0] ) else: trueScoreD = 0 # falseBranch D falseNodeSummary = self.tree_node_summary( w_r, y_r, min_samples_treatment=self.min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) if (tree.falseBranch.bestTreatment in falseNodeSummary and self.control_name in falseNodeSummary): falseScoreD = ( falseNodeSummary[tree.falseBranch.bestTreatment][0] - falseNodeSummary[self.control_name][0] ) else: falseScoreD = 0 gain = ((1. * len(y_l) / len(y) * trueScoreD + 1. * len(y_r) / len(y) * falseScoreD) - currentScoreD) if gain <= minGain or (trueScoreD + falseScoreD < 0.): tree.trueBranch, tree.falseBranch = None, None tree.results = tree.backupResults return self
[ "def", "pruneTree", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "tree", ",", "rule", "=", "'maxAbsDiff'", ",", "minGain", "=", "0.", ",", "evaluationFunction", "=", "None", ",", "notify", "=", "False", ",", "n_reg", "=", "0", ",", "parentNodeSummary", "=", "None", ")", ":", "# Current Node Summary for Validation Data Set", "currentNodeSummary", "=", "self", ".", "tree_node_summary", "(", "treatment", ",", "y", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "parentNodeSummary", ")", "tree", ".", "nodeSummary", "=", "currentNodeSummary", "# Divide sets for child nodes", "X_l", ",", "X_r", ",", "w_l", ",", "w_r", ",", "y_l", ",", "y_r", "=", "self", ".", "divideSet", "(", "X", ",", "treatment", ",", "y", ",", "tree", ".", "col", ",", "tree", ".", "value", ")", "# recursive call for each branch", "if", "tree", ".", "trueBranch", ".", "results", "is", "None", ":", "self", ".", "pruneTree", "(", "X_l", ",", "w_l", ",", "y_l", ",", "tree", ".", "trueBranch", ",", "rule", ",", "minGain", ",", "evaluationFunction", ",", "notify", ",", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "if", "tree", ".", "falseBranch", ".", "results", "is", "None", ":", "self", ".", "pruneTree", "(", "X_r", ",", "w_r", ",", "y_r", ",", "tree", ".", "falseBranch", ",", "rule", ",", "minGain", ",", "evaluationFunction", ",", "notify", ",", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "# merge leaves (potentially)", "if", "(", "tree", ".", "trueBranch", ".", "results", "is", "not", "None", "and", "tree", ".", "falseBranch", ".", "results", "is", "not", "None", ")", ":", "if", "rule", "==", "'maxAbsDiff'", ":", "# Current D", "if", "(", "tree", ".", "maxDiffTreatment", "in", "currentNodeSummary", "and", "self", ".", "control_name", "in", "currentNodeSummary", ")", ":", "currentScoreD", "=", "tree", ".", "maxDiffSign", "*", "(", "currentNodeSummary", "[", "tree", ".", "maxDiffTreatment", "]", "[", "0", "]", "-", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "else", ":", "currentScoreD", "=", "0", "# trueBranch D", "trueNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_l", ",", "y_l", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "if", "(", "tree", ".", "trueBranch", ".", "maxDiffTreatment", "in", "trueNodeSummary", "and", "self", ".", "control_name", "in", "trueNodeSummary", ")", ":", "trueScoreD", "=", "tree", ".", "trueBranch", ".", "maxDiffSign", "*", "(", "trueNodeSummary", "[", "tree", ".", "trueBranch", ".", "maxDiffTreatment", "]", "[", "0", "]", "-", "trueNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "trueScoreD", "=", "(", "trueScoreD", "*", "(", "trueNodeSummary", "[", "tree", ".", "trueBranch", ".", "maxDiffTreatment", "]", "[", "1", "]", "+", "trueNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", ")", "/", "(", "currentNodeSummary", "[", "tree", ".", "trueBranch", ".", "maxDiffTreatment", "]", "[", "1", "]", "+", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", ")", ")", "else", ":", "trueScoreD", "=", "0", "# falseBranch D", "falseNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_r", ",", "y_r", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "if", "(", "tree", ".", "falseBranch", ".", "maxDiffTreatment", "in", "falseNodeSummary", "and", "self", ".", "control_name", "in", "falseNodeSummary", ")", ":", "falseScoreD", "=", "(", "tree", ".", "falseBranch", ".", "maxDiffSign", "*", "(", "falseNodeSummary", "[", "tree", ".", "falseBranch", ".", "maxDiffTreatment", "]", "[", "0", "]", "-", "falseNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", ")", "falseScoreD", "=", "(", "falseScoreD", "*", "(", "falseNodeSummary", "[", "tree", ".", "falseBranch", ".", "maxDiffTreatment", "]", "[", "1", "]", "+", "falseNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", ")", "/", "(", "currentNodeSummary", "[", "tree", ".", "falseBranch", ".", "maxDiffTreatment", "]", "[", "1", "]", "+", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", ")", ")", "else", ":", "falseScoreD", "=", "0", "if", "(", "(", "trueScoreD", "+", "falseScoreD", ")", "-", "currentScoreD", "<=", "minGain", "or", "(", "trueScoreD", "+", "falseScoreD", "<", "0.", ")", ")", ":", "tree", ".", "trueBranch", ",", "tree", ".", "falseBranch", "=", "None", ",", "None", "tree", ".", "results", "=", "tree", ".", "backupResults", "elif", "rule", "==", "'bestUplift'", ":", "# Current D", "if", "(", "tree", ".", "bestTreatment", "in", "currentNodeSummary", "and", "self", ".", "control_name", "in", "currentNodeSummary", ")", ":", "currentScoreD", "=", "(", "currentNodeSummary", "[", "tree", ".", "bestTreatment", "]", "[", "0", "]", "-", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "else", ":", "currentScoreD", "=", "0", "# trueBranch D", "trueNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_l", ",", "y_l", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "if", "(", "tree", ".", "trueBranch", ".", "bestTreatment", "in", "trueNodeSummary", "and", "self", ".", "control_name", "in", "trueNodeSummary", ")", ":", "trueScoreD", "=", "(", "trueNodeSummary", "[", "tree", ".", "trueBranch", ".", "bestTreatment", "]", "[", "0", "]", "-", "trueNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "else", ":", "trueScoreD", "=", "0", "# falseBranch D", "falseNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_r", ",", "y_r", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "if", "(", "tree", ".", "falseBranch", ".", "bestTreatment", "in", "falseNodeSummary", "and", "self", ".", "control_name", "in", "falseNodeSummary", ")", ":", "falseScoreD", "=", "(", "falseNodeSummary", "[", "tree", ".", "falseBranch", ".", "bestTreatment", "]", "[", "0", "]", "-", "falseNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "else", ":", "falseScoreD", "=", "0", "gain", "=", "(", "(", "1.", "*", "len", "(", "y_l", ")", "/", "len", "(", "y", ")", "*", "trueScoreD", "+", "1.", "*", "len", "(", "y_r", ")", "/", "len", "(", "y", ")", "*", "falseScoreD", ")", "-", "currentScoreD", ")", "if", "gain", "<=", "minGain", "or", "(", "trueScoreD", "+", "falseScoreD", "<", "0.", ")", ":", "tree", ".", "trueBranch", ",", "tree", ".", "falseBranch", "=", "None", ",", "None", "tree", ".", "results", "=", "tree", ".", "backupResults", "return", "self" ]
[ 240, 4 ]
[ 392, 19 ]
python
en
['en', 'fy', 'en']
True
UpliftTreeClassifier.fill
(self, X, treatment, y)
Fill the data into an existing tree. This is a higher-level function to transform the original data inputs into lower level data inputs (list of list and tree). Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- self : object
Fill the data into an existing tree. This is a higher-level function to transform the original data inputs into lower level data inputs (list of list and tree).
def fill(self, X, treatment, y): """ Fill the data into an existing tree. This is a higher-level function to transform the original data inputs into lower level data inputs (list of list and tree). Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- self : object """ assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.' self.fillTree(X, treatment, y, tree=self.fitted_uplift_tree) return self
[ "def", "fill", "(", "self", ",", "X", ",", "treatment", ",", "y", ")", ":", "assert", "len", "(", "X", ")", "==", "len", "(", "y", ")", "and", "len", "(", "X", ")", "==", "len", "(", "treatment", ")", ",", "'Data length must be equal for X, treatment, and y.'", "self", ".", "fillTree", "(", "X", ",", "treatment", ",", "y", ",", "tree", "=", "self", ".", "fitted_uplift_tree", ")", "return", "self" ]
[ 394, 4 ]
[ 415, 19 ]
python
en
['en', 'en', 'en']
True
UpliftTreeClassifier.fillTree
(self, X, treatment, y, tree)
Fill the data into an existing tree. This is a lower-level function to execute on the tree filling task. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. tree : object object of DecisionTree class Returns ------- self : object
Fill the data into an existing tree. This is a lower-level function to execute on the tree filling task.
def fillTree(self, X, treatment, y, tree): """ Fill the data into an existing tree. This is a lower-level function to execute on the tree filling task. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. tree : object object of DecisionTree class Returns ------- self : object """ # Current Node Summary for Validation Data Set currentNodeSummary = self.tree_node_summary(treatment, y, min_samples_treatment=0, n_reg=0, parentNodeSummary=None) tree.nodeSummary = currentNodeSummary # Divide sets for child nodes X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, tree.col, tree.value) # recursive call for each branch if tree.trueBranch is not None: self.fillTree(X_l, w_l, y_l, tree.trueBranch) if tree.falseBranch is not None: self.fillTree(X_r, w_r, y_r, tree.falseBranch) # Update Information # matchScore matchScore = (currentNodeSummary[tree.bestTreatment][0] - currentNodeSummary[self.control_name][0]) tree.matchScore = round(matchScore, 4) tree.summary['matchScore'] = round(matchScore, 4) # Samples, Group_size tree.summary['samples'] = len(y) tree.summary['group_size'] = '' for treatment_group in currentNodeSummary: tree.summary['group_size'] += ' ' + treatment_group + ': ' + str(currentNodeSummary[treatment_group][1]) # classProb if tree.results is not None: tree.results = self.uplift_classification_results(treatment, y) return self
[ "def", "fillTree", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "tree", ")", ":", "# Current Node Summary for Validation Data Set", "currentNodeSummary", "=", "self", ".", "tree_node_summary", "(", "treatment", ",", "y", ",", "min_samples_treatment", "=", "0", ",", "n_reg", "=", "0", ",", "parentNodeSummary", "=", "None", ")", "tree", ".", "nodeSummary", "=", "currentNodeSummary", "# Divide sets for child nodes", "X_l", ",", "X_r", ",", "w_l", ",", "w_r", ",", "y_l", ",", "y_r", "=", "self", ".", "divideSet", "(", "X", ",", "treatment", ",", "y", ",", "tree", ".", "col", ",", "tree", ".", "value", ")", "# recursive call for each branch", "if", "tree", ".", "trueBranch", "is", "not", "None", ":", "self", ".", "fillTree", "(", "X_l", ",", "w_l", ",", "y_l", ",", "tree", ".", "trueBranch", ")", "if", "tree", ".", "falseBranch", "is", "not", "None", ":", "self", ".", "fillTree", "(", "X_r", ",", "w_r", ",", "y_r", ",", "tree", ".", "falseBranch", ")", "# Update Information", "# matchScore", "matchScore", "=", "(", "currentNodeSummary", "[", "tree", ".", "bestTreatment", "]", "[", "0", "]", "-", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "tree", ".", "matchScore", "=", "round", "(", "matchScore", ",", "4", ")", "tree", ".", "summary", "[", "'matchScore'", "]", "=", "round", "(", "matchScore", ",", "4", ")", "# Samples, Group_size", "tree", ".", "summary", "[", "'samples'", "]", "=", "len", "(", "y", ")", "tree", ".", "summary", "[", "'group_size'", "]", "=", "''", "for", "treatment_group", "in", "currentNodeSummary", ":", "tree", ".", "summary", "[", "'group_size'", "]", "+=", "' '", "+", "treatment_group", "+", "': '", "+", "str", "(", "currentNodeSummary", "[", "treatment_group", "]", "[", "1", "]", ")", "# classProb", "if", "tree", ".", "results", "is", "not", "None", ":", "tree", ".", "results", "=", "self", ".", "uplift_classification_results", "(", "treatment", ",", "y", ")", "return", "self" ]
[ 417, 4 ]
[ 466, 19 ]
python
en
['en', 'en', 'en']
True
UpliftTreeClassifier.predict
(self, X, full_output=False)
Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. full_output : bool, optional (default=False) Whether the UpliftTree algorithm returns upliftScores, pred_nodes alongside the recommended treatment group and p_hat in the treatment group. Returns ------- df_res : DataFrame, shape = [num_samples, (num_treatments + 1)] A DataFrame containing the predicted delta in each treatment group, the best treatment group and the maximum delta.
Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group.
def predict(self, X, full_output=False): ''' Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. full_output : bool, optional (default=False) Whether the UpliftTree algorithm returns upliftScores, pred_nodes alongside the recommended treatment group and p_hat in the treatment group. Returns ------- df_res : DataFrame, shape = [num_samples, (num_treatments + 1)] A DataFrame containing the predicted delta in each treatment group, the best treatment group and the maximum delta. ''' p_hat_optimal = [] treatment_optimal = [] pred_nodes = {} upliftScores = [] for xi in range(len(X)): pred_leaf, upliftScore = self.classify(X[xi], self.fitted_uplift_tree, dataMissing=False) # Predict under uplift optimal treatment opt_treat = max(pred_leaf, key=pred_leaf.get) p_hat_optimal.append(pred_leaf[opt_treat]) treatment_optimal.append(opt_treat) if full_output: if xi == 0: for key_i in pred_leaf: pred_nodes[key_i] = [pred_leaf[key_i]] else: for key_i in pred_leaf: pred_nodes[key_i].append(pred_leaf[key_i]) upliftScores.append(upliftScore) if full_output: return treatment_optimal, p_hat_optimal, upliftScores, pred_nodes else: return treatment_optimal, p_hat_optimal
[ "def", "predict", "(", "self", ",", "X", ",", "full_output", "=", "False", ")", ":", "p_hat_optimal", "=", "[", "]", "treatment_optimal", "=", "[", "]", "pred_nodes", "=", "{", "}", "upliftScores", "=", "[", "]", "for", "xi", "in", "range", "(", "len", "(", "X", ")", ")", ":", "pred_leaf", ",", "upliftScore", "=", "self", ".", "classify", "(", "X", "[", "xi", "]", ",", "self", ".", "fitted_uplift_tree", ",", "dataMissing", "=", "False", ")", "# Predict under uplift optimal treatment", "opt_treat", "=", "max", "(", "pred_leaf", ",", "key", "=", "pred_leaf", ".", "get", ")", "p_hat_optimal", ".", "append", "(", "pred_leaf", "[", "opt_treat", "]", ")", "treatment_optimal", ".", "append", "(", "opt_treat", ")", "if", "full_output", ":", "if", "xi", "==", "0", ":", "for", "key_i", "in", "pred_leaf", ":", "pred_nodes", "[", "key_i", "]", "=", "[", "pred_leaf", "[", "key_i", "]", "]", "else", ":", "for", "key_i", "in", "pred_leaf", ":", "pred_nodes", "[", "key_i", "]", ".", "append", "(", "pred_leaf", "[", "key_i", "]", ")", "upliftScores", ".", "append", "(", "upliftScore", ")", "if", "full_output", ":", "return", "treatment_optimal", ",", "p_hat_optimal", ",", "upliftScores", ",", "pred_nodes", "else", ":", "return", "treatment_optimal", ",", "p_hat_optimal" ]
[ 468, 4 ]
[ 511, 51 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.divideSet
(X, treatment, y, column, value)
Tree node split. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. column : int The column used to split the data. value : float or int The value in the column for splitting the data. Returns ------- (X_l, X_r, treatment_l, treatment_r, y_l, y_r) : list of ndarray The covariates, treatments and outcomes of left node and the right node.
Tree node split.
def divideSet(X, treatment, y, column, value): ''' Tree node split. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. column : int The column used to split the data. value : float or int The value in the column for splitting the data. Returns ------- (X_l, X_r, treatment_l, treatment_r, y_l, y_r) : list of ndarray The covariates, treatments and outcomes of left node and the right node. ''' # for int and float values if isinstance(value, int) or isinstance(value, float): filt = X[:, column] >= value else: # for strings filt = X[:, column] == value return X[filt], X[~filt], treatment[filt], treatment[~filt], y[filt], y[~filt]
[ "def", "divideSet", "(", "X", ",", "treatment", ",", "y", ",", "column", ",", "value", ")", ":", "# for int and float values", "if", "isinstance", "(", "value", ",", "int", ")", "or", "isinstance", "(", "value", ",", "float", ")", ":", "filt", "=", "X", "[", ":", ",", "column", "]", ">=", "value", "else", ":", "# for strings", "filt", "=", "X", "[", ":", ",", "column", "]", "==", "value", "return", "X", "[", "filt", "]", ",", "X", "[", "~", "filt", "]", ",", "treatment", "[", "filt", "]", ",", "treatment", "[", "~", "filt", "]", ",", "y", "[", "filt", "]", ",", "y", "[", "~", "filt", "]" ]
[ 514, 4 ]
[ 542, 86 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.group_uniqueCounts
(self, treatment, y)
Count sample size by experiment group. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- results : dictionary The control and treatment sample size.
Count sample size by experiment group.
def group_uniqueCounts(self, treatment, y): ''' Count sample size by experiment group. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- results : dictionary The control and treatment sample size. ''' results = {} for t in self.treatment_group: filt = treatment == t n_t = y[filt].sum() results[t] = (filt.sum() - n_t, n_t) return results
[ "def", "group_uniqueCounts", "(", "self", ",", "treatment", ",", "y", ")", ":", "results", "=", "{", "}", "for", "t", "in", "self", ".", "treatment_group", ":", "filt", "=", "treatment", "==", "t", "n_t", "=", "y", "[", "filt", "]", ".", "sum", "(", ")", "results", "[", "t", "]", "=", "(", "filt", ".", "sum", "(", ")", "-", "n_t", ",", "n_t", ")", "return", "results" ]
[ 544, 4 ]
[ 566, 22 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.kl_divergence
(pk, qk)
Calculate KL Divergence for binary classification. sum(np.array(pk) * np.log(np.array(pk) / np.array(qk))) Args ---- pk : float The probability of 1 in one distribution. qk : float The probability of 1 in the other distribution. Returns ------- S : float The KL divergence.
Calculate KL Divergence for binary classification.
def kl_divergence(pk, qk): ''' Calculate KL Divergence for binary classification. sum(np.array(pk) * np.log(np.array(pk) / np.array(qk))) Args ---- pk : float The probability of 1 in one distribution. qk : float The probability of 1 in the other distribution. Returns ------- S : float The KL divergence. ''' eps = 1e-6 qk = np.clip(qk, eps, 1 - eps) if pk == 0: S = -np.log(1 - qk) elif pk == 1: S = -np.log(qk) else: S = pk * np.log(pk / qk) + (1 - pk) * np.log((1 - pk) / (1 - qk)) return S
[ "def", "kl_divergence", "(", "pk", ",", "qk", ")", ":", "eps", "=", "1e-6", "qk", "=", "np", ".", "clip", "(", "qk", ",", "eps", ",", "1", "-", "eps", ")", "if", "pk", "==", "0", ":", "S", "=", "-", "np", ".", "log", "(", "1", "-", "qk", ")", "elif", "pk", "==", "1", ":", "S", "=", "-", "np", ".", "log", "(", "qk", ")", "else", ":", "S", "=", "pk", "*", "np", ".", "log", "(", "pk", "/", "qk", ")", "+", "(", "1", "-", "pk", ")", "*", "np", ".", "log", "(", "(", "1", "-", "pk", ")", "/", "(", "1", "-", "qk", ")", ")", "return", "S" ]
[ 569, 4 ]
[ 598, 16 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.evaluate_KL
(self, nodeSummary, control_name)
Calculate KL Divergence as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : KL Divergence
Calculate KL Divergence as split evaluation criterion for a given node.
def evaluate_KL(self, nodeSummary, control_name): ''' Calculate KL Divergence as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : KL Divergence ''' if control_name not in nodeSummary: return 0 pc = nodeSummary[control_name][0] d_res = 0 for treatment_group in nodeSummary: if treatment_group != control_name: d_res += self.kl_divergence(nodeSummary[treatment_group][0], pc) return d_res
[ "def", "evaluate_KL", "(", "self", ",", "nodeSummary", ",", "control_name", ")", ":", "if", "control_name", "not", "in", "nodeSummary", ":", "return", "0", "pc", "=", "nodeSummary", "[", "control_name", "]", "[", "0", "]", "d_res", "=", "0", "for", "treatment_group", "in", "nodeSummary", ":", "if", "treatment_group", "!=", "control_name", ":", "d_res", "+=", "self", ".", "kl_divergence", "(", "nodeSummary", "[", "treatment_group", "]", "[", "0", "]", ",", "pc", ")", "return", "d_res" ]
[ 600, 4 ]
[ 624, 20 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.evaluate_ED
(nodeSummary, control_name)
Calculate Euclidean Distance as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Euclidean Distance
Calculate Euclidean Distance as split evaluation criterion for a given node.
def evaluate_ED(nodeSummary, control_name): ''' Calculate Euclidean Distance as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Euclidean Distance ''' if control_name not in nodeSummary: return 0 pc = nodeSummary[control_name][0] d_res = 0 for treatment_group in nodeSummary: if treatment_group != control_name: d_res += 2*(nodeSummary[treatment_group][0] - pc)**2 return d_res
[ "def", "evaluate_ED", "(", "nodeSummary", ",", "control_name", ")", ":", "if", "control_name", "not", "in", "nodeSummary", ":", "return", "0", "pc", "=", "nodeSummary", "[", "control_name", "]", "[", "0", "]", "d_res", "=", "0", "for", "treatment_group", "in", "nodeSummary", ":", "if", "treatment_group", "!=", "control_name", ":", "d_res", "+=", "2", "*", "(", "nodeSummary", "[", "treatment_group", "]", "[", "0", "]", "-", "pc", ")", "**", "2", "return", "d_res" ]
[ 627, 4 ]
[ 651, 20 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.evaluate_Chi
(nodeSummary, control_name)
Calculate Chi-Square statistic as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Chi-Square
Calculate Chi-Square statistic as split evaluation criterion for a given node.
def evaluate_Chi(nodeSummary, control_name): ''' Calculate Chi-Square statistic as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Chi-Square ''' if control_name not in nodeSummary: return 0 pc = nodeSummary[control_name][0] d_res = 0 for treatment_group in nodeSummary: if treatment_group != control_name: d_res += ((nodeSummary[treatment_group][0] - pc) ** 2 / max(0.1 ** 6, pc) + (nodeSummary[treatment_group][0] - pc) ** 2 / max(0.1 ** 6, 1 - pc)) return d_res
[ "def", "evaluate_Chi", "(", "nodeSummary", ",", "control_name", ")", ":", "if", "control_name", "not", "in", "nodeSummary", ":", "return", "0", "pc", "=", "nodeSummary", "[", "control_name", "]", "[", "0", "]", "d_res", "=", "0", "for", "treatment_group", "in", "nodeSummary", ":", "if", "treatment_group", "!=", "control_name", ":", "d_res", "+=", "(", "(", "nodeSummary", "[", "treatment_group", "]", "[", "0", "]", "-", "pc", ")", "**", "2", "/", "max", "(", "0.1", "**", "6", ",", "pc", ")", "+", "(", "nodeSummary", "[", "treatment_group", "]", "[", "0", "]", "-", "pc", ")", "**", "2", "/", "max", "(", "0.1", "**", "6", ",", "1", "-", "pc", ")", ")", "return", "d_res" ]
[ 654, 4 ]
[ 678, 20 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.evaluate_DDP
(nodeSummary, control_name)
Calculate Delta P as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Delta P
Calculate Delta P as split evaluation criterion for a given node.
def evaluate_DDP(nodeSummary, control_name): ''' Calculate Delta P as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Delta P ''' if control_name not in nodeSummary: return 0 pc = nodeSummary[control_name][0] d_res = 0 for treatment_group in nodeSummary: if treatment_group != control_name: d_res += nodeSummary[treatment_group][0] - pc return d_res
[ "def", "evaluate_DDP", "(", "nodeSummary", ",", "control_name", ")", ":", "if", "control_name", "not", "in", "nodeSummary", ":", "return", "0", "pc", "=", "nodeSummary", "[", "control_name", "]", "[", "0", "]", "d_res", "=", "0", "for", "treatment_group", "in", "nodeSummary", ":", "if", "treatment_group", "!=", "control_name", ":", "d_res", "+=", "nodeSummary", "[", "treatment_group", "]", "[", "0", "]", "-", "pc", "return", "d_res" ]
[ 681, 4 ]
[ 704, 20 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.evaluate_CTS
(currentNodeSummary)
Calculate CTS (conditional treatment selection) as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Chi-Square
Calculate CTS (conditional treatment selection) as split evaluation criterion for a given node.
def evaluate_CTS(currentNodeSummary): ''' Calculate CTS (conditional treatment selection) as split evaluation criterion for a given node. Args ---- nodeSummary : dictionary The tree node summary statistics, produced by tree_node_summary() method. control_name : string The control group name. Returns ------- d_res : Chi-Square ''' mu = 0.0 # iterate treatment group for r in currentNodeSummary: mu = max(mu, currentNodeSummary[r][0]) return -mu
[ "def", "evaluate_CTS", "(", "currentNodeSummary", ")", ":", "mu", "=", "0.0", "# iterate treatment group", "for", "r", "in", "currentNodeSummary", ":", "mu", "=", "max", "(", "mu", ",", "currentNodeSummary", "[", "r", "]", "[", "0", "]", ")", "return", "-", "mu" ]
[ 707, 4 ]
[ 727, 18 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.entropyH
(p, q=None)
Entropy Entropy calculation for normalization. Args ---- p : float The probability used in the entropy calculation. q : float, optional, (default = None) The second probability used in the entropy calculation. Returns ------- entropy : float
Entropy
def entropyH(p, q=None): ''' Entropy Entropy calculation for normalization. Args ---- p : float The probability used in the entropy calculation. q : float, optional, (default = None) The second probability used in the entropy calculation. Returns ------- entropy : float ''' if q is None and p > 0: return -p * np.log(p) elif q > 0: return -p * np.log(q) else: return 0
[ "def", "entropyH", "(", "p", ",", "q", "=", "None", ")", ":", "if", "q", "is", "None", "and", "p", ">", "0", ":", "return", "-", "p", "*", "np", ".", "log", "(", "p", ")", "elif", "q", ">", "0", ":", "return", "-", "p", "*", "np", ".", "log", "(", "q", ")", "else", ":", "return", "0" ]
[ 730, 4 ]
[ 753, 20 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.normI
(self, currentNodeSummary, leftNodeSummary, rightNodeSummary, control_name, alpha=0.9)
Normalization factor. Args ---- currentNodeSummary : dictionary The summary statistics of the current tree node. leftNodeSummary : dictionary The summary statistics of the left tree node. rightNodeSummary : dictionary The summary statistics of the right tree node. control_name : string The control group name. alpha : float The weight used to balance different normalization parts. Returns ------- norm_res : float Normalization factor.
Normalization factor.
def normI(self, currentNodeSummary, leftNodeSummary, rightNodeSummary, control_name, alpha=0.9): ''' Normalization factor. Args ---- currentNodeSummary : dictionary The summary statistics of the current tree node. leftNodeSummary : dictionary The summary statistics of the left tree node. rightNodeSummary : dictionary The summary statistics of the right tree node. control_name : string The control group name. alpha : float The weight used to balance different normalization parts. Returns ------- norm_res : float Normalization factor. ''' norm_res = 0 # n_t, n_c: sample size for all treatment, and control # pt_a, pc_a: % of treatment is in left node, % of control is in left node n_c = currentNodeSummary[control_name][1] n_c_left = leftNodeSummary[control_name][1] n_t = [] n_t_left = [] for treatment_group in currentNodeSummary: if treatment_group != control_name: n_t.append(currentNodeSummary[treatment_group][1]) if treatment_group in leftNodeSummary: n_t_left.append(leftNodeSummary[treatment_group][1]) else: n_t_left.append(0) pt_a = 1. * np.sum(n_t_left) / (np.sum(n_t) + 0.1) pc_a = 1. * n_c_left / (n_c + 0.1) # Normalization Part 1 norm_res += ( alpha * self.entropyH(1. * np.sum(n_t) / (np.sum(n_t) + n_c), 1. * n_c / (np.sum(n_t) + n_c)) * self.kl_divergence(pt_a, pc_a) ) # Normalization Part 2 & 3 for i in range(len(n_t)): pt_a_i = 1. * n_t_left[i] / (n_t[i] + 0.1) norm_res += ( (1 - alpha) * self.entropyH(1. * n_t[i] / (n_t[i] + n_c), 1. * n_c / (n_t[i] + n_c)) * self.kl_divergence(1. * pt_a_i, pc_a) ) norm_res += (1. * n_t[i] / (np.sum(n_t) + n_c) * self.entropyH(pt_a_i)) # Normalization Part 4 norm_res += 1. * n_c/(np.sum(n_t) + n_c) * self.entropyH(pc_a) # Normalization Part 5 norm_res += 0.5 return norm_res
[ "def", "normI", "(", "self", ",", "currentNodeSummary", ",", "leftNodeSummary", ",", "rightNodeSummary", ",", "control_name", ",", "alpha", "=", "0.9", ")", ":", "norm_res", "=", "0", "# n_t, n_c: sample size for all treatment, and control", "# pt_a, pc_a: % of treatment is in left node, % of control is in left node", "n_c", "=", "currentNodeSummary", "[", "control_name", "]", "[", "1", "]", "n_c_left", "=", "leftNodeSummary", "[", "control_name", "]", "[", "1", "]", "n_t", "=", "[", "]", "n_t_left", "=", "[", "]", "for", "treatment_group", "in", "currentNodeSummary", ":", "if", "treatment_group", "!=", "control_name", ":", "n_t", ".", "append", "(", "currentNodeSummary", "[", "treatment_group", "]", "[", "1", "]", ")", "if", "treatment_group", "in", "leftNodeSummary", ":", "n_t_left", ".", "append", "(", "leftNodeSummary", "[", "treatment_group", "]", "[", "1", "]", ")", "else", ":", "n_t_left", ".", "append", "(", "0", ")", "pt_a", "=", "1.", "*", "np", ".", "sum", "(", "n_t_left", ")", "/", "(", "np", ".", "sum", "(", "n_t", ")", "+", "0.1", ")", "pc_a", "=", "1.", "*", "n_c_left", "/", "(", "n_c", "+", "0.1", ")", "# Normalization Part 1", "norm_res", "+=", "(", "alpha", "*", "self", ".", "entropyH", "(", "1.", "*", "np", ".", "sum", "(", "n_t", ")", "/", "(", "np", ".", "sum", "(", "n_t", ")", "+", "n_c", ")", ",", "1.", "*", "n_c", "/", "(", "np", ".", "sum", "(", "n_t", ")", "+", "n_c", ")", ")", "*", "self", ".", "kl_divergence", "(", "pt_a", ",", "pc_a", ")", ")", "# Normalization Part 2 & 3", "for", "i", "in", "range", "(", "len", "(", "n_t", ")", ")", ":", "pt_a_i", "=", "1.", "*", "n_t_left", "[", "i", "]", "/", "(", "n_t", "[", "i", "]", "+", "0.1", ")", "norm_res", "+=", "(", "(", "1", "-", "alpha", ")", "*", "self", ".", "entropyH", "(", "1.", "*", "n_t", "[", "i", "]", "/", "(", "n_t", "[", "i", "]", "+", "n_c", ")", ",", "1.", "*", "n_c", "/", "(", "n_t", "[", "i", "]", "+", "n_c", ")", ")", "*", "self", ".", "kl_divergence", "(", "1.", "*", "pt_a_i", ",", "pc_a", ")", ")", "norm_res", "+=", "(", "1.", "*", "n_t", "[", "i", "]", "/", "(", "np", ".", "sum", "(", "n_t", ")", "+", "n_c", ")", "*", "self", ".", "entropyH", "(", "pt_a_i", ")", ")", "# Normalization Part 4", "norm_res", "+=", "1.", "*", "n_c", "/", "(", "np", ".", "sum", "(", "n_t", ")", "+", "n_c", ")", "*", "self", ".", "entropyH", "(", "pc_a", ")", "# Normalization Part 5", "norm_res", "+=", "0.5", "return", "norm_res" ]
[ 755, 4 ]
[ 815, 23 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.tree_node_summary
(self, treatment, y, min_samples_treatment=10, n_reg=100, parentNodeSummary=None)
Tree node summary statistics. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. min_samples_treatment: int, optional (default=10) The minimum number of samples required of the experiment group t be split at a leaf node. n_reg : int, optional (default=10) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary Node summary statistics of the parent tree node. Returns ------- nodeSummary : dictionary The node summary of the current tree node.
Tree node summary statistics.
def tree_node_summary(self, treatment, y, min_samples_treatment=10, n_reg=100, parentNodeSummary=None): ''' Tree node summary statistics. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. min_samples_treatment: int, optional (default=10) The minimum number of samples required of the experiment group t be split at a leaf node. n_reg : int, optional (default=10) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary Node summary statistics of the parent tree node. Returns ------- nodeSummary : dictionary The node summary of the current tree node. ''' # returns {treatment_group: p(1)} results = self.group_uniqueCounts(treatment, y) # node Summary: {treatment_group: [p(1), size]} nodeSummary = {} # iterate treatment group for r in results: n1 = results[r][1] ntot = results[r][0] + n1 if parentNodeSummary is None: y_mean = n1 / ntot elif ntot > min_samples_treatment: y_mean = (n1 + parentNodeSummary[r][0] * n_reg) / (ntot + n_reg) else: y_mean = parentNodeSummary[r][0] nodeSummary[r] = [y_mean, ntot] return nodeSummary
[ "def", "tree_node_summary", "(", "self", ",", "treatment", ",", "y", ",", "min_samples_treatment", "=", "10", ",", "n_reg", "=", "100", ",", "parentNodeSummary", "=", "None", ")", ":", "# returns {treatment_group: p(1)}", "results", "=", "self", ".", "group_uniqueCounts", "(", "treatment", ",", "y", ")", "# node Summary: {treatment_group: [p(1), size]}", "nodeSummary", "=", "{", "}", "# iterate treatment group", "for", "r", "in", "results", ":", "n1", "=", "results", "[", "r", "]", "[", "1", "]", "ntot", "=", "results", "[", "r", "]", "[", "0", "]", "+", "n1", "if", "parentNodeSummary", "is", "None", ":", "y_mean", "=", "n1", "/", "ntot", "elif", "ntot", ">", "min_samples_treatment", ":", "y_mean", "=", "(", "n1", "+", "parentNodeSummary", "[", "r", "]", "[", "0", "]", "*", "n_reg", ")", "/", "(", "ntot", "+", "n_reg", ")", "else", ":", "y_mean", "=", "parentNodeSummary", "[", "r", "]", "[", "0", "]", "nodeSummary", "[", "r", "]", "=", "[", "y_mean", ",", "ntot", "]", "return", "nodeSummary" ]
[ 817, 4 ]
[ 858, 26 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.uplift_classification_results
(self, treatment, y)
Classification probability for each treatment in the tree node. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- res : dictionary The probability of 1 in each treatment in the tree node.
Classification probability for each treatment in the tree node.
def uplift_classification_results(self, treatment, y): ''' Classification probability for each treatment in the tree node. Args ---- treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. Returns ------- res : dictionary The probability of 1 in each treatment in the tree node. ''' results = self.group_uniqueCounts(treatment, y) res = {} for r in results: p = float(results[r][1]) / (results[r][0] + results[r][1]) res[r] = round(p, 6) return res
[ "def", "uplift_classification_results", "(", "self", ",", "treatment", ",", "y", ")", ":", "results", "=", "self", ".", "group_uniqueCounts", "(", "treatment", ",", "y", ")", "res", "=", "{", "}", "for", "r", "in", "results", ":", "p", "=", "float", "(", "results", "[", "r", "]", "[", "1", "]", ")", "/", "(", "results", "[", "r", "]", "[", "0", "]", "+", "results", "[", "r", "]", "[", "1", "]", ")", "res", "[", "r", "]", "=", "round", "(", "p", ",", "6", ")", "return", "res" ]
[ 860, 4 ]
[ 881, 18 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.growDecisionTreeFrom
(self, X, treatment, y, evaluationFunction, max_depth=10, min_samples_leaf=100, depth=1, min_samples_treatment=10, n_reg=100, parentNodeSummary=None)
Train the uplift decision tree. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. evaluationFunction : string Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS', 'DDP'. max_depth: int, optional (default=10) The maximum depth of the tree. min_samples_leaf: int, optional (default=100) The minimum number of samples required to be split at a leaf node. depth : int, optional (default = 1) The current depth. min_samples_treatment: int, optional (default=10) The minimum number of samples required of the experiment group to be split at a leaf node. n_reg: int, optional (default=10) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary, optional (default = None) Node summary statistics of the parent tree node. Returns ------- object of DecisionTree class
Train the uplift decision tree.
def growDecisionTreeFrom(self, X, treatment, y, evaluationFunction, max_depth=10, min_samples_leaf=100, depth=1, min_samples_treatment=10, n_reg=100, parentNodeSummary=None): ''' Train the uplift decision tree. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. evaluationFunction : string Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS', 'DDP'. max_depth: int, optional (default=10) The maximum depth of the tree. min_samples_leaf: int, optional (default=100) The minimum number of samples required to be split at a leaf node. depth : int, optional (default = 1) The current depth. min_samples_treatment: int, optional (default=10) The minimum number of samples required of the experiment group to be split at a leaf node. n_reg: int, optional (default=10) The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods. parentNodeSummary : dictionary, optional (default = None) Node summary statistics of the parent tree node. Returns ------- object of DecisionTree class ''' if len(X) == 0: return DecisionTree() # Current Node Info and Summary currentNodeSummary = self.tree_node_summary(treatment, y, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=parentNodeSummary) if evaluationFunction == self.evaluate_CTS: currentScore = evaluationFunction(currentNodeSummary) else: currentScore = evaluationFunction(currentNodeSummary, control_name=self.control_name) # Prune Stats maxAbsDiff = 0 maxDiff = -1. bestTreatment = self.control_name suboptTreatment = self.control_name maxDiffTreatment = self.control_name maxDiffSign = 0 for treatment_group in currentNodeSummary: if treatment_group != self.control_name: diff = (currentNodeSummary[treatment_group][0] - currentNodeSummary[self.control_name][0]) if abs(diff) >= maxAbsDiff: maxDiffTreatment = treatment_group maxDiffSign = np.sign(diff) maxAbsDiff = abs(diff) if diff >= maxDiff: maxDiff = diff suboptTreatment = treatment_group if diff > 0: bestTreatment = treatment_group if maxDiff > 0: pt = currentNodeSummary[bestTreatment][0] nt = currentNodeSummary[bestTreatment][1] pc = currentNodeSummary[self.control_name][0] nc = currentNodeSummary[self.control_name][1] p_value = (1. - stats.norm.cdf((pt - pc) / np.sqrt(pt * (1 - pt) / nt + pc * (1 - pc) / nc))) * 2 else: pt = currentNodeSummary[suboptTreatment][0] nt = currentNodeSummary[suboptTreatment][1] pc = currentNodeSummary[self.control_name][0] nc = currentNodeSummary[self.control_name][1] p_value = (1. - stats.norm.cdf((pc - pt) / np.sqrt(pt * (1 - pt) / nt + pc * (1 - pc) / nc))) * 2 upliftScore = [maxDiff, p_value] bestGain = 0.0 bestAttribute = None # last column is the result/target column, 2nd to the last is the treatment group columnCount = X.shape[1] if (self.max_features and self.max_features > 0 and self.max_features <= columnCount): max_features = self.max_features else: max_features = columnCount for col in list(np.random.choice(a=range(columnCount), size=max_features, replace=False)): columnValues = X[:, col] # unique values lsUnique = np.unique(columnValues) if (isinstance(lsUnique[0], int) or isinstance(lsUnique[0], float)): if len(lsUnique) > 10: lspercentile = np.percentile(columnValues, [3, 5, 10, 20, 30, 50, 70, 80, 90, 95, 97]) else: lspercentile = np.percentile(lsUnique, [10, 50, 90]) lsUnique = np.unique(lspercentile) for value in lsUnique: X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, col, value) # check the split validity on min_samples_leaf 372 if (len(X_l) < min_samples_leaf or len(X_r) < min_samples_leaf): continue # summarize notes # Gain -- Entropy or Gini p = float(len(X_l)) / len(X) leftNodeSummary = self.tree_node_summary(w_l, y_l, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary) rightNodeSummary = self.tree_node_summary(w_r, y_r, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary) # check the split validity on min_samples_treatment if set(leftNodeSummary.keys()) != set(rightNodeSummary.keys()): continue node_mst = 10**8 for ti in leftNodeSummary: node_mst = np.min([node_mst, leftNodeSummary[ti][1]]) node_mst = np.min([node_mst, rightNodeSummary[ti][1]]) if node_mst < min_samples_treatment: continue # evaluate the split if evaluationFunction == self.evaluate_CTS: leftScore1 = evaluationFunction(leftNodeSummary) rightScore2 = evaluationFunction(rightNodeSummary) gain = (currentScore - p * leftScore1 - (1 - p) * rightScore2) gain_for_imp = (len(X) * currentScore - len(X_l) * leftScore1 - len(X_r) * rightScore2) elif evaluationFunction == self.evaluate_DDP: if self.control_name in leftNodeSummary and self.control_name in rightNodeSummary: leftScore1 = evaluationFunction(leftNodeSummary, control_name=self.control_name) rightScore2 = evaluationFunction(rightNodeSummary, control_name=self.control_name) gain = np.abs(leftScore1 - rightScore2) gain_for_imp = np.abs(len(X_l) * leftScore1 - len(X_r) * rightScore2) else: gain = 0 else: if (self.control_name in leftNodeSummary and self.control_name in rightNodeSummary): leftScore1 = evaluationFunction(leftNodeSummary, control_name=self.control_name) rightScore2 = evaluationFunction(rightNodeSummary, control_name=self.control_name) gain = (p * leftScore1 + (1 - p) * rightScore2 - currentScore) gain_for_imp = (len(X_l) * leftScore1 + len(X_r) * rightScore2 - len(X) * currentScore) if self.normalization: norm_factor = self.normI(currentNodeSummary, leftNodeSummary, rightNodeSummary, self.control_name, alpha=0.9) else: norm_factor = 1 gain = gain / norm_factor else: gain = 0 if (gain > bestGain and len(X_l) > min_samples_leaf and len(X_r) > min_samples_leaf): bestGain = gain bestAttribute = (col, value) best_set_left = [X_l, w_l, y_l] best_set_right = [X_r, w_r, y_r] dcY = {'impurity': '%.3f' % currentScore, 'samples': '%d' % len(X)} # Add treatment size dcY['group_size'] = '' for treatment_group in currentNodeSummary: dcY['group_size'] += ' ' + treatment_group + ': ' + str(currentNodeSummary[treatment_group][1]) dcY['upliftScore'] = [round(upliftScore[0], 4), round(upliftScore[1], 4)] dcY['matchScore'] = round(upliftScore[0], 4) if bestGain > 0 and depth < max_depth: self.feature_imp_dict[bestAttribute[0]] += gain_for_imp trueBranch = self.growDecisionTreeFrom( *best_set_left, evaluationFunction, max_depth, min_samples_leaf, depth + 1, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) falseBranch = self.growDecisionTreeFrom( *best_set_right, evaluationFunction, max_depth, min_samples_leaf, depth + 1, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary ) return DecisionTree( col=bestAttribute[0], value=bestAttribute[1], trueBranch=trueBranch, falseBranch=falseBranch, summary=dcY, maxDiffTreatment=maxDiffTreatment, maxDiffSign=maxDiffSign, nodeSummary=currentNodeSummary, backupResults=self.uplift_classification_results(treatment, y), bestTreatment=bestTreatment, upliftScore=upliftScore ) else: if evaluationFunction == self.evaluate_CTS: return DecisionTree( results=self.uplift_classification_results(treatment, y), summary=dcY, nodeSummary=currentNodeSummary, bestTreatment=bestTreatment, upliftScore=upliftScore ) else: return DecisionTree( results=self.uplift_classification_results(treatment, y), summary=dcY, maxDiffTreatment=maxDiffTreatment, maxDiffSign=maxDiffSign, nodeSummary=currentNodeSummary, bestTreatment=bestTreatment, upliftScore=upliftScore )
[ "def", "growDecisionTreeFrom", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "evaluationFunction", ",", "max_depth", "=", "10", ",", "min_samples_leaf", "=", "100", ",", "depth", "=", "1", ",", "min_samples_treatment", "=", "10", ",", "n_reg", "=", "100", ",", "parentNodeSummary", "=", "None", ")", ":", "if", "len", "(", "X", ")", "==", "0", ":", "return", "DecisionTree", "(", ")", "# Current Node Info and Summary", "currentNodeSummary", "=", "self", ".", "tree_node_summary", "(", "treatment", ",", "y", ",", "min_samples_treatment", "=", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "parentNodeSummary", ")", "if", "evaluationFunction", "==", "self", ".", "evaluate_CTS", ":", "currentScore", "=", "evaluationFunction", "(", "currentNodeSummary", ")", "else", ":", "currentScore", "=", "evaluationFunction", "(", "currentNodeSummary", ",", "control_name", "=", "self", ".", "control_name", ")", "# Prune Stats", "maxAbsDiff", "=", "0", "maxDiff", "=", "-", "1.", "bestTreatment", "=", "self", ".", "control_name", "suboptTreatment", "=", "self", ".", "control_name", "maxDiffTreatment", "=", "self", ".", "control_name", "maxDiffSign", "=", "0", "for", "treatment_group", "in", "currentNodeSummary", ":", "if", "treatment_group", "!=", "self", ".", "control_name", ":", "diff", "=", "(", "currentNodeSummary", "[", "treatment_group", "]", "[", "0", "]", "-", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", ")", "if", "abs", "(", "diff", ")", ">=", "maxAbsDiff", ":", "maxDiffTreatment", "=", "treatment_group", "maxDiffSign", "=", "np", ".", "sign", "(", "diff", ")", "maxAbsDiff", "=", "abs", "(", "diff", ")", "if", "diff", ">=", "maxDiff", ":", "maxDiff", "=", "diff", "suboptTreatment", "=", "treatment_group", "if", "diff", ">", "0", ":", "bestTreatment", "=", "treatment_group", "if", "maxDiff", ">", "0", ":", "pt", "=", "currentNodeSummary", "[", "bestTreatment", "]", "[", "0", "]", "nt", "=", "currentNodeSummary", "[", "bestTreatment", "]", "[", "1", "]", "pc", "=", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", "nc", "=", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", "p_value", "=", "(", "1.", "-", "stats", ".", "norm", ".", "cdf", "(", "(", "pt", "-", "pc", ")", "/", "np", ".", "sqrt", "(", "pt", "*", "(", "1", "-", "pt", ")", "/", "nt", "+", "pc", "*", "(", "1", "-", "pc", ")", "/", "nc", ")", ")", ")", "*", "2", "else", ":", "pt", "=", "currentNodeSummary", "[", "suboptTreatment", "]", "[", "0", "]", "nt", "=", "currentNodeSummary", "[", "suboptTreatment", "]", "[", "1", "]", "pc", "=", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "0", "]", "nc", "=", "currentNodeSummary", "[", "self", ".", "control_name", "]", "[", "1", "]", "p_value", "=", "(", "1.", "-", "stats", ".", "norm", ".", "cdf", "(", "(", "pc", "-", "pt", ")", "/", "np", ".", "sqrt", "(", "pt", "*", "(", "1", "-", "pt", ")", "/", "nt", "+", "pc", "*", "(", "1", "-", "pc", ")", "/", "nc", ")", ")", ")", "*", "2", "upliftScore", "=", "[", "maxDiff", ",", "p_value", "]", "bestGain", "=", "0.0", "bestAttribute", "=", "None", "# last column is the result/target column, 2nd to the last is the treatment group", "columnCount", "=", "X", ".", "shape", "[", "1", "]", "if", "(", "self", ".", "max_features", "and", "self", ".", "max_features", ">", "0", "and", "self", ".", "max_features", "<=", "columnCount", ")", ":", "max_features", "=", "self", ".", "max_features", "else", ":", "max_features", "=", "columnCount", "for", "col", "in", "list", "(", "np", ".", "random", ".", "choice", "(", "a", "=", "range", "(", "columnCount", ")", ",", "size", "=", "max_features", ",", "replace", "=", "False", ")", ")", ":", "columnValues", "=", "X", "[", ":", ",", "col", "]", "# unique values", "lsUnique", "=", "np", ".", "unique", "(", "columnValues", ")", "if", "(", "isinstance", "(", "lsUnique", "[", "0", "]", ",", "int", ")", "or", "isinstance", "(", "lsUnique", "[", "0", "]", ",", "float", ")", ")", ":", "if", "len", "(", "lsUnique", ")", ">", "10", ":", "lspercentile", "=", "np", ".", "percentile", "(", "columnValues", ",", "[", "3", ",", "5", ",", "10", ",", "20", ",", "30", ",", "50", ",", "70", ",", "80", ",", "90", ",", "95", ",", "97", "]", ")", "else", ":", "lspercentile", "=", "np", ".", "percentile", "(", "lsUnique", ",", "[", "10", ",", "50", ",", "90", "]", ")", "lsUnique", "=", "np", ".", "unique", "(", "lspercentile", ")", "for", "value", "in", "lsUnique", ":", "X_l", ",", "X_r", ",", "w_l", ",", "w_r", ",", "y_l", ",", "y_r", "=", "self", ".", "divideSet", "(", "X", ",", "treatment", ",", "y", ",", "col", ",", "value", ")", "# check the split validity on min_samples_leaf 372", "if", "(", "len", "(", "X_l", ")", "<", "min_samples_leaf", "or", "len", "(", "X_r", ")", "<", "min_samples_leaf", ")", ":", "continue", "# summarize notes", "# Gain -- Entropy or Gini", "p", "=", "float", "(", "len", "(", "X_l", ")", ")", "/", "len", "(", "X", ")", "leftNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_l", ",", "y_l", ",", "min_samples_treatment", "=", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "rightNodeSummary", "=", "self", ".", "tree_node_summary", "(", "w_r", ",", "y_r", ",", "min_samples_treatment", "=", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "# check the split validity on min_samples_treatment", "if", "set", "(", "leftNodeSummary", ".", "keys", "(", ")", ")", "!=", "set", "(", "rightNodeSummary", ".", "keys", "(", ")", ")", ":", "continue", "node_mst", "=", "10", "**", "8", "for", "ti", "in", "leftNodeSummary", ":", "node_mst", "=", "np", ".", "min", "(", "[", "node_mst", ",", "leftNodeSummary", "[", "ti", "]", "[", "1", "]", "]", ")", "node_mst", "=", "np", ".", "min", "(", "[", "node_mst", ",", "rightNodeSummary", "[", "ti", "]", "[", "1", "]", "]", ")", "if", "node_mst", "<", "min_samples_treatment", ":", "continue", "# evaluate the split", "if", "evaluationFunction", "==", "self", ".", "evaluate_CTS", ":", "leftScore1", "=", "evaluationFunction", "(", "leftNodeSummary", ")", "rightScore2", "=", "evaluationFunction", "(", "rightNodeSummary", ")", "gain", "=", "(", "currentScore", "-", "p", "*", "leftScore1", "-", "(", "1", "-", "p", ")", "*", "rightScore2", ")", "gain_for_imp", "=", "(", "len", "(", "X", ")", "*", "currentScore", "-", "len", "(", "X_l", ")", "*", "leftScore1", "-", "len", "(", "X_r", ")", "*", "rightScore2", ")", "elif", "evaluationFunction", "==", "self", ".", "evaluate_DDP", ":", "if", "self", ".", "control_name", "in", "leftNodeSummary", "and", "self", ".", "control_name", "in", "rightNodeSummary", ":", "leftScore1", "=", "evaluationFunction", "(", "leftNodeSummary", ",", "control_name", "=", "self", ".", "control_name", ")", "rightScore2", "=", "evaluationFunction", "(", "rightNodeSummary", ",", "control_name", "=", "self", ".", "control_name", ")", "gain", "=", "np", ".", "abs", "(", "leftScore1", "-", "rightScore2", ")", "gain_for_imp", "=", "np", ".", "abs", "(", "len", "(", "X_l", ")", "*", "leftScore1", "-", "len", "(", "X_r", ")", "*", "rightScore2", ")", "else", ":", "gain", "=", "0", "else", ":", "if", "(", "self", ".", "control_name", "in", "leftNodeSummary", "and", "self", ".", "control_name", "in", "rightNodeSummary", ")", ":", "leftScore1", "=", "evaluationFunction", "(", "leftNodeSummary", ",", "control_name", "=", "self", ".", "control_name", ")", "rightScore2", "=", "evaluationFunction", "(", "rightNodeSummary", ",", "control_name", "=", "self", ".", "control_name", ")", "gain", "=", "(", "p", "*", "leftScore1", "+", "(", "1", "-", "p", ")", "*", "rightScore2", "-", "currentScore", ")", "gain_for_imp", "=", "(", "len", "(", "X_l", ")", "*", "leftScore1", "+", "len", "(", "X_r", ")", "*", "rightScore2", "-", "len", "(", "X", ")", "*", "currentScore", ")", "if", "self", ".", "normalization", ":", "norm_factor", "=", "self", ".", "normI", "(", "currentNodeSummary", ",", "leftNodeSummary", ",", "rightNodeSummary", ",", "self", ".", "control_name", ",", "alpha", "=", "0.9", ")", "else", ":", "norm_factor", "=", "1", "gain", "=", "gain", "/", "norm_factor", "else", ":", "gain", "=", "0", "if", "(", "gain", ">", "bestGain", "and", "len", "(", "X_l", ")", ">", "min_samples_leaf", "and", "len", "(", "X_r", ")", ">", "min_samples_leaf", ")", ":", "bestGain", "=", "gain", "bestAttribute", "=", "(", "col", ",", "value", ")", "best_set_left", "=", "[", "X_l", ",", "w_l", ",", "y_l", "]", "best_set_right", "=", "[", "X_r", ",", "w_r", ",", "y_r", "]", "dcY", "=", "{", "'impurity'", ":", "'%.3f'", "%", "currentScore", ",", "'samples'", ":", "'%d'", "%", "len", "(", "X", ")", "}", "# Add treatment size", "dcY", "[", "'group_size'", "]", "=", "''", "for", "treatment_group", "in", "currentNodeSummary", ":", "dcY", "[", "'group_size'", "]", "+=", "' '", "+", "treatment_group", "+", "': '", "+", "str", "(", "currentNodeSummary", "[", "treatment_group", "]", "[", "1", "]", ")", "dcY", "[", "'upliftScore'", "]", "=", "[", "round", "(", "upliftScore", "[", "0", "]", ",", "4", ")", ",", "round", "(", "upliftScore", "[", "1", "]", ",", "4", ")", "]", "dcY", "[", "'matchScore'", "]", "=", "round", "(", "upliftScore", "[", "0", "]", ",", "4", ")", "if", "bestGain", ">", "0", "and", "depth", "<", "max_depth", ":", "self", ".", "feature_imp_dict", "[", "bestAttribute", "[", "0", "]", "]", "+=", "gain_for_imp", "trueBranch", "=", "self", ".", "growDecisionTreeFrom", "(", "*", "best_set_left", ",", "evaluationFunction", ",", "max_depth", ",", "min_samples_leaf", ",", "depth", "+", "1", ",", "min_samples_treatment", "=", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "falseBranch", "=", "self", ".", "growDecisionTreeFrom", "(", "*", "best_set_right", ",", "evaluationFunction", ",", "max_depth", ",", "min_samples_leaf", ",", "depth", "+", "1", ",", "min_samples_treatment", "=", "min_samples_treatment", ",", "n_reg", "=", "n_reg", ",", "parentNodeSummary", "=", "currentNodeSummary", ")", "return", "DecisionTree", "(", "col", "=", "bestAttribute", "[", "0", "]", ",", "value", "=", "bestAttribute", "[", "1", "]", ",", "trueBranch", "=", "trueBranch", ",", "falseBranch", "=", "falseBranch", ",", "summary", "=", "dcY", ",", "maxDiffTreatment", "=", "maxDiffTreatment", ",", "maxDiffSign", "=", "maxDiffSign", ",", "nodeSummary", "=", "currentNodeSummary", ",", "backupResults", "=", "self", ".", "uplift_classification_results", "(", "treatment", ",", "y", ")", ",", "bestTreatment", "=", "bestTreatment", ",", "upliftScore", "=", "upliftScore", ")", "else", ":", "if", "evaluationFunction", "==", "self", ".", "evaluate_CTS", ":", "return", "DecisionTree", "(", "results", "=", "self", ".", "uplift_classification_results", "(", "treatment", ",", "y", ")", ",", "summary", "=", "dcY", ",", "nodeSummary", "=", "currentNodeSummary", ",", "bestTreatment", "=", "bestTreatment", ",", "upliftScore", "=", "upliftScore", ")", "else", ":", "return", "DecisionTree", "(", "results", "=", "self", ".", "uplift_classification_results", "(", "treatment", ",", "y", ")", ",", "summary", "=", "dcY", ",", "maxDiffTreatment", "=", "maxDiffTreatment", ",", "maxDiffSign", "=", "maxDiffSign", ",", "nodeSummary", "=", "currentNodeSummary", ",", "bestTreatment", "=", "bestTreatment", ",", "upliftScore", "=", "upliftScore", ")" ]
[ 883, 4 ]
[ 1098, 17 ]
python
en
['en', 'error', 'th']
False
UpliftTreeClassifier.classify
(observations, tree, dataMissing=False)
Classifies (prediction) the observations according to the tree. Args ---- observations : list of list The internal data format for the training data (combining X, Y, treatment). dataMissing: boolean, optional (default = False) An indicator for if data are missing or not. Returns ------- tree.results, tree.upliftScore : The results in the leaf node.
Classifies (prediction) the observations according to the tree.
def classify(observations, tree, dataMissing=False): ''' Classifies (prediction) the observations according to the tree. Args ---- observations : list of list The internal data format for the training data (combining X, Y, treatment). dataMissing: boolean, optional (default = False) An indicator for if data are missing or not. Returns ------- tree.results, tree.upliftScore : The results in the leaf node. ''' def classifyWithoutMissingData(observations, tree): ''' Classifies (prediction) the observations according to the tree, assuming without missing data. Args ---- observations : list of list The internal data format for the training data (combining X, Y, treatment). Returns ------- tree.results, tree.upliftScore : The results in the leaf node. ''' if tree.results is not None: # leaf return tree.results, tree.upliftScore else: v = observations[tree.col] branch = None if isinstance(v, int) or isinstance(v, float): if v >= tree.value: branch = tree.trueBranch else: branch = tree.falseBranch else: if v == tree.value: branch = tree.trueBranch else: branch = tree.falseBranch return classifyWithoutMissingData(observations, branch) def classifyWithMissingData(observations, tree): ''' Classifies (prediction) the observations according to the tree, assuming with missing data. Args ---- observations : list of list The internal data format for the training data (combining X, Y, treatment). Returns ------- tree.results, tree.upliftScore : The results in the leaf node. ''' if tree.results is not None: # leaf return tree.results else: v = observations[tree.col] if v is None: tr = classifyWithMissingData(observations, tree.trueBranch) fr = classifyWithMissingData(observations, tree.falseBranch) tcount = sum(tr.values()) fcount = sum(fr.values()) tw = float(tcount) / (tcount + fcount) fw = float(fcount) / (tcount + fcount) # Problem description: http://blog.ludovf.net/python-collections-defaultdict/ result = defaultdict(int) for k, v in tr.items(): result[k] += v * tw for k, v in fr.items(): result[k] += v * fw return dict(result) else: branch = None if isinstance(v, int) or isinstance(v, float): if v >= tree.value: branch = tree.trueBranch else: branch = tree.falseBranch else: if v == tree.value: branch = tree.trueBranch else: branch = tree.falseBranch return classifyWithMissingData(observations, branch) # function body if dataMissing: return classifyWithMissingData(observations, tree) else: return classifyWithoutMissingData(observations, tree)
[ "def", "classify", "(", "observations", ",", "tree", ",", "dataMissing", "=", "False", ")", ":", "def", "classifyWithoutMissingData", "(", "observations", ",", "tree", ")", ":", "'''\n Classifies (prediction) the observations according to the tree, assuming without missing data.\n\n Args\n ----\n observations : list of list\n The internal data format for the training data (combining X, Y, treatment).\n\n Returns\n -------\n tree.results, tree.upliftScore :\n The results in the leaf node.\n '''", "if", "tree", ".", "results", "is", "not", "None", ":", "# leaf", "return", "tree", ".", "results", ",", "tree", ".", "upliftScore", "else", ":", "v", "=", "observations", "[", "tree", ".", "col", "]", "branch", "=", "None", "if", "isinstance", "(", "v", ",", "int", ")", "or", "isinstance", "(", "v", ",", "float", ")", ":", "if", "v", ">=", "tree", ".", "value", ":", "branch", "=", "tree", ".", "trueBranch", "else", ":", "branch", "=", "tree", ".", "falseBranch", "else", ":", "if", "v", "==", "tree", ".", "value", ":", "branch", "=", "tree", ".", "trueBranch", "else", ":", "branch", "=", "tree", ".", "falseBranch", "return", "classifyWithoutMissingData", "(", "observations", ",", "branch", ")", "def", "classifyWithMissingData", "(", "observations", ",", "tree", ")", ":", "'''\n Classifies (prediction) the observations according to the tree, assuming with missing data.\n\n Args\n ----\n observations : list of list\n The internal data format for the training data (combining X, Y, treatment).\n\n Returns\n -------\n tree.results, tree.upliftScore :\n The results in the leaf node.\n '''", "if", "tree", ".", "results", "is", "not", "None", ":", "# leaf", "return", "tree", ".", "results", "else", ":", "v", "=", "observations", "[", "tree", ".", "col", "]", "if", "v", "is", "None", ":", "tr", "=", "classifyWithMissingData", "(", "observations", ",", "tree", ".", "trueBranch", ")", "fr", "=", "classifyWithMissingData", "(", "observations", ",", "tree", ".", "falseBranch", ")", "tcount", "=", "sum", "(", "tr", ".", "values", "(", ")", ")", "fcount", "=", "sum", "(", "fr", ".", "values", "(", ")", ")", "tw", "=", "float", "(", "tcount", ")", "/", "(", "tcount", "+", "fcount", ")", "fw", "=", "float", "(", "fcount", ")", "/", "(", "tcount", "+", "fcount", ")", "# Problem description: http://blog.ludovf.net/python-collections-defaultdict/", "result", "=", "defaultdict", "(", "int", ")", "for", "k", ",", "v", "in", "tr", ".", "items", "(", ")", ":", "result", "[", "k", "]", "+=", "v", "*", "tw", "for", "k", ",", "v", "in", "fr", ".", "items", "(", ")", ":", "result", "[", "k", "]", "+=", "v", "*", "fw", "return", "dict", "(", "result", ")", "else", ":", "branch", "=", "None", "if", "isinstance", "(", "v", ",", "int", ")", "or", "isinstance", "(", "v", ",", "float", ")", ":", "if", "v", ">=", "tree", ".", "value", ":", "branch", "=", "tree", ".", "trueBranch", "else", ":", "branch", "=", "tree", ".", "falseBranch", "else", ":", "if", "v", "==", "tree", ".", "value", ":", "branch", "=", "tree", ".", "trueBranch", "else", ":", "branch", "=", "tree", ".", "falseBranch", "return", "classifyWithMissingData", "(", "observations", ",", "branch", ")", "# function body", "if", "dataMissing", ":", "return", "classifyWithMissingData", "(", "observations", ",", "tree", ")", "else", ":", "return", "classifyWithoutMissingData", "(", "observations", ",", "tree", ")" ]
[ 1101, 4 ]
[ 1201, 65 ]
python
en
['en', 'error', 'th']
False
UpliftRandomForestClassifier.__init__
(self, n_estimators=10, max_features=10, random_state=2019, max_depth=5, min_samples_leaf=100, min_samples_treatment=10, n_reg=10, evaluationFunction=None, control_name=None, normalization=True, n_jobs=-1)
Initialize the UpliftRandomForestClassifier class.
Initialize the UpliftRandomForestClassifier class.
def __init__(self, n_estimators=10, max_features=10, random_state=2019, max_depth=5, min_samples_leaf=100, min_samples_treatment=10, n_reg=10, evaluationFunction=None, control_name=None, normalization=True, n_jobs=-1): """ Initialize the UpliftRandomForestClassifier class. """ self.classes_ = {} self.n_estimators = n_estimators self.max_features = max_features self.random_state = random_state self.max_depth = max_depth self.min_samples_leaf = min_samples_leaf self.min_samples_treatment = min_samples_treatment self.n_reg = n_reg self.evaluationFunction = evaluationFunction self.control_name = control_name self.n_jobs = n_jobs # Create forest self.uplift_forest = [] for _ in range(n_estimators): uplift_tree = UpliftTreeClassifier( max_features=self.max_features, max_depth=self.max_depth, min_samples_leaf=self.min_samples_leaf, min_samples_treatment=self.min_samples_treatment, n_reg=self.n_reg, evaluationFunction=self.evaluationFunction, control_name=self.control_name, normalization=normalization) self.uplift_forest.append(uplift_tree) if self.n_jobs == -1: self.n_jobs = mp.cpu_count()
[ "def", "__init__", "(", "self", ",", "n_estimators", "=", "10", ",", "max_features", "=", "10", ",", "random_state", "=", "2019", ",", "max_depth", "=", "5", ",", "min_samples_leaf", "=", "100", ",", "min_samples_treatment", "=", "10", ",", "n_reg", "=", "10", ",", "evaluationFunction", "=", "None", ",", "control_name", "=", "None", ",", "normalization", "=", "True", ",", "n_jobs", "=", "-", "1", ")", ":", "self", ".", "classes_", "=", "{", "}", "self", ".", "n_estimators", "=", "n_estimators", "self", ".", "max_features", "=", "max_features", "self", ".", "random_state", "=", "random_state", "self", ".", "max_depth", "=", "max_depth", "self", ".", "min_samples_leaf", "=", "min_samples_leaf", "self", ".", "min_samples_treatment", "=", "min_samples_treatment", "self", ".", "n_reg", "=", "n_reg", "self", ".", "evaluationFunction", "=", "evaluationFunction", "self", ".", "control_name", "=", "control_name", "self", ".", "n_jobs", "=", "n_jobs", "# Create forest", "self", ".", "uplift_forest", "=", "[", "]", "for", "_", "in", "range", "(", "n_estimators", ")", ":", "uplift_tree", "=", "UpliftTreeClassifier", "(", "max_features", "=", "self", ".", "max_features", ",", "max_depth", "=", "self", ".", "max_depth", ",", "min_samples_leaf", "=", "self", ".", "min_samples_leaf", ",", "min_samples_treatment", "=", "self", ".", "min_samples_treatment", ",", "n_reg", "=", "self", ".", "n_reg", ",", "evaluationFunction", "=", "self", ".", "evaluationFunction", ",", "control_name", "=", "self", ".", "control_name", ",", "normalization", "=", "normalization", ")", "self", ".", "uplift_forest", ".", "append", "(", "uplift_tree", ")", "if", "self", ".", "n_jobs", "==", "-", "1", ":", "self", ".", "n_jobs", "=", "mp", ".", "cpu_count", "(", ")" ]
[ 1253, 4 ]
[ 1295, 40 ]
python
en
['en', 'error', 'th']
False
UpliftRandomForestClassifier.fit
(self, X, treatment, y)
Fit the UpliftRandomForestClassifier. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit.
Fit the UpliftRandomForestClassifier.
def fit(self, X, treatment, y): """ Fit the UpliftRandomForestClassifier. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. treatment : array-like, shape = [num_samples] An array containing the treatment group for each unit. y : array-like, shape = [num_samples] An array containing the outcome of interest for each unit. """ np.random.seed(self.random_state) # Get treatment group keys treatment_group_keys = list(set(treatment)) treatment_group_keys.remove(self.control_name) treatment_group_keys.sort() self.classes_ = {} for i, treatment_group_key in enumerate(treatment_group_keys): self.classes_[treatment_group_key] = i self.uplift_forest = ( Parallel(n_jobs=self.n_jobs) (delayed(self.bootstrap)(X, treatment, y, tree) for tree in self.uplift_forest) ) all_importances = [tree.feature_importances_ for tree in self.uplift_forest] self.feature_importances_ = np.mean(all_importances, axis=0) self.feature_importances_ /= self.feature_importances_.sum()
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ")", ":", "np", ".", "random", ".", "seed", "(", "self", ".", "random_state", ")", "# Get treatment group keys", "treatment_group_keys", "=", "list", "(", "set", "(", "treatment", ")", ")", "treatment_group_keys", ".", "remove", "(", "self", ".", "control_name", ")", "treatment_group_keys", ".", "sort", "(", ")", "self", ".", "classes_", "=", "{", "}", "for", "i", ",", "treatment_group_key", "in", "enumerate", "(", "treatment_group_keys", ")", ":", "self", ".", "classes_", "[", "treatment_group_key", "]", "=", "i", "self", ".", "uplift_forest", "=", "(", "Parallel", "(", "n_jobs", "=", "self", ".", "n_jobs", ")", "(", "delayed", "(", "self", ".", "bootstrap", ")", "(", "X", ",", "treatment", ",", "y", ",", "tree", ")", "for", "tree", "in", "self", ".", "uplift_forest", ")", ")", "all_importances", "=", "[", "tree", ".", "feature_importances_", "for", "tree", "in", "self", ".", "uplift_forest", "]", "self", ".", "feature_importances_", "=", "np", ".", "mean", "(", "all_importances", ",", "axis", "=", "0", ")", "self", ".", "feature_importances_", "/=", "self", ".", "feature_importances_", ".", "sum", "(", ")" ]
[ 1297, 4 ]
[ 1329, 68 ]
python
en
['en', 'error', 'th']
False
UpliftRandomForestClassifier.predict
(self, X, full_output=False)
Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. full_output : bool, optional (default=False) Whether the UpliftTree algorithm returns upliftScores, pred_nodes alongside the recommended treatment group and p_hat in the treatment group. Returns ------- y_pred_list : ndarray, shape = (num_samples, num_treatments]) An ndarray containing the predicted delta in each treatment group, the best treatment group and the maximum delta. df_res : DataFrame, shape = [num_samples, (num_treatments + 1)] If full_output, a DataFrame containing the predicted delta in each treatment group, the best treatment group and the maximum delta.
Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group.
def predict(self, X, full_output=False): ''' Returns the recommended treatment group and predicted optimal probability conditional on using the recommended treatment group. Args ---- X : ndarray, shape = [num_samples, num_features] An ndarray of the covariates used to train the uplift model. full_output : bool, optional (default=False) Whether the UpliftTree algorithm returns upliftScores, pred_nodes alongside the recommended treatment group and p_hat in the treatment group. Returns ------- y_pred_list : ndarray, shape = (num_samples, num_treatments]) An ndarray containing the predicted delta in each treatment group, the best treatment group and the maximum delta. df_res : DataFrame, shape = [num_samples, (num_treatments + 1)] If full_output, a DataFrame containing the predicted delta in each treatment group, the best treatment group and the maximum delta. ''' df_res = pd.DataFrame() y_pred_ensemble = dict() y_pred_list = np.zeros((X.shape[0], len(self.classes_))) # Make prediction by each tree for tree_i in range(len(self.uplift_forest)): _, _, _, y_pred_full = self.uplift_forest[tree_i].predict(X=X, full_output=True) if tree_i == 0: for treatment_group in y_pred_full: y_pred_ensemble[treatment_group] = ( np.array(y_pred_full[treatment_group]) / len(self.uplift_forest) ) else: for treatment_group in y_pred_full: y_pred_ensemble[treatment_group] = ( np.array(y_pred_ensemble[treatment_group]) + np.array(y_pred_full[treatment_group]) / len(self.uplift_forest) ) # Summarize results into dataframe for treatment_group in y_pred_ensemble: df_res[treatment_group] = y_pred_ensemble[treatment_group] df_res['recommended_treatment'] = df_res.apply(np.argmax, axis=1) # Calculate delta delta_cols = [] for treatment_group in y_pred_ensemble: if treatment_group != self.control_name: delta_cols.append('delta_%s' % (treatment_group)) df_res['delta_%s' % (treatment_group)] = df_res[treatment_group] - df_res[self.control_name] # Add deltas to results list y_pred_list[:, self.classes_[treatment_group]] = df_res['delta_%s' % (treatment_group)].values df_res['max_delta'] = df_res[delta_cols].max(axis=1) if full_output: return df_res else: return y_pred_list
[ "def", "predict", "(", "self", ",", "X", ",", "full_output", "=", "False", ")", ":", "df_res", "=", "pd", ".", "DataFrame", "(", ")", "y_pred_ensemble", "=", "dict", "(", ")", "y_pred_list", "=", "np", ".", "zeros", "(", "(", "X", ".", "shape", "[", "0", "]", ",", "len", "(", "self", ".", "classes_", ")", ")", ")", "# Make prediction by each tree", "for", "tree_i", "in", "range", "(", "len", "(", "self", ".", "uplift_forest", ")", ")", ":", "_", ",", "_", ",", "_", ",", "y_pred_full", "=", "self", ".", "uplift_forest", "[", "tree_i", "]", ".", "predict", "(", "X", "=", "X", ",", "full_output", "=", "True", ")", "if", "tree_i", "==", "0", ":", "for", "treatment_group", "in", "y_pred_full", ":", "y_pred_ensemble", "[", "treatment_group", "]", "=", "(", "np", ".", "array", "(", "y_pred_full", "[", "treatment_group", "]", ")", "/", "len", "(", "self", ".", "uplift_forest", ")", ")", "else", ":", "for", "treatment_group", "in", "y_pred_full", ":", "y_pred_ensemble", "[", "treatment_group", "]", "=", "(", "np", ".", "array", "(", "y_pred_ensemble", "[", "treatment_group", "]", ")", "+", "np", ".", "array", "(", "y_pred_full", "[", "treatment_group", "]", ")", "/", "len", "(", "self", ".", "uplift_forest", ")", ")", "# Summarize results into dataframe", "for", "treatment_group", "in", "y_pred_ensemble", ":", "df_res", "[", "treatment_group", "]", "=", "y_pred_ensemble", "[", "treatment_group", "]", "df_res", "[", "'recommended_treatment'", "]", "=", "df_res", ".", "apply", "(", "np", ".", "argmax", ",", "axis", "=", "1", ")", "# Calculate delta", "delta_cols", "=", "[", "]", "for", "treatment_group", "in", "y_pred_ensemble", ":", "if", "treatment_group", "!=", "self", ".", "control_name", ":", "delta_cols", ".", "append", "(", "'delta_%s'", "%", "(", "treatment_group", ")", ")", "df_res", "[", "'delta_%s'", "%", "(", "treatment_group", ")", "]", "=", "df_res", "[", "treatment_group", "]", "-", "df_res", "[", "self", ".", "control_name", "]", "# Add deltas to results list", "y_pred_list", "[", ":", ",", "self", ".", "classes_", "[", "treatment_group", "]", "]", "=", "df_res", "[", "'delta_%s'", "%", "(", "treatment_group", ")", "]", ".", "values", "df_res", "[", "'max_delta'", "]", "=", "df_res", "[", "delta_cols", "]", ".", "max", "(", "axis", "=", "1", ")", "if", "full_output", ":", "return", "df_res", "else", ":", "return", "y_pred_list" ]
[ 1341, 4 ]
[ 1406, 30 ]
python
en
['en', 'error', 'th']
False
num_to_str
(f, precision=DEFAULT_PRECISION, use_locale=False, no_scientific=False)
Convert the given float to a string, centralizing standards for precision and decisions about scientific notation. Adds an approximately equal sign in the event precision loss (e.g. rounding) has occurred. There's a good discussion of related issues here: https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa Args: f: the number to format precision: the number of digits of precision to display use_locale: if True, use locale-specific formatting (e.g. adding thousands separators) no_scientific: if True, print all available digits of precision without scientific notation. This may insert leading zeros before very small numbers, causing the resulting string to be longer than `precision` characters Returns: A string representation of the float, according to the desired parameters
Convert the given float to a string, centralizing standards for precision and decisions about scientific notation. Adds an approximately equal sign in the event precision loss (e.g. rounding) has occurred.
def num_to_str(f, precision=DEFAULT_PRECISION, use_locale=False, no_scientific=False): """Convert the given float to a string, centralizing standards for precision and decisions about scientific notation. Adds an approximately equal sign in the event precision loss (e.g. rounding) has occurred. There's a good discussion of related issues here: https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa Args: f: the number to format precision: the number of digits of precision to display use_locale: if True, use locale-specific formatting (e.g. adding thousands separators) no_scientific: if True, print all available digits of precision without scientific notation. This may insert leading zeros before very small numbers, causing the resulting string to be longer than `precision` characters Returns: A string representation of the float, according to the desired parameters """ assert not (use_locale and no_scientific) if precision != DEFAULT_PRECISION: local_context = decimal.Context() local_context.prec = precision else: local_context = ctx # We cast to string; we want to avoid precision issues, but format everything as though it were a float. # So, if it's not already a float, we will append a decimal point to the string representation s = repr(f) if not isinstance(f, float): s += locale.localeconv().get("decimal_point") + "0" d = local_context.create_decimal(s) if no_scientific: result = format(d, "f") elif use_locale: result = format(d, "n") else: result = format(d, "g") if f != locale.atof(result): # result = '≈' + result # ≈ # \u2248 result = "≈" + result decimal_char = locale.localeconv().get("decimal_point") if "e" not in result and "E" not in result and decimal_char in result: result = result.rstrip("0").rstrip(decimal_char) return result
[ "def", "num_to_str", "(", "f", ",", "precision", "=", "DEFAULT_PRECISION", ",", "use_locale", "=", "False", ",", "no_scientific", "=", "False", ")", ":", "assert", "not", "(", "use_locale", "and", "no_scientific", ")", "if", "precision", "!=", "DEFAULT_PRECISION", ":", "local_context", "=", "decimal", ".", "Context", "(", ")", "local_context", ".", "prec", "=", "precision", "else", ":", "local_context", "=", "ctx", "# We cast to string; we want to avoid precision issues, but format everything as though it were a float.", "# So, if it's not already a float, we will append a decimal point to the string representation", "s", "=", "repr", "(", "f", ")", "if", "not", "isinstance", "(", "f", ",", "float", ")", ":", "s", "+=", "locale", ".", "localeconv", "(", ")", ".", "get", "(", "\"decimal_point\"", ")", "+", "\"0\"", "d", "=", "local_context", ".", "create_decimal", "(", "s", ")", "if", "no_scientific", ":", "result", "=", "format", "(", "d", ",", "\"f\"", ")", "elif", "use_locale", ":", "result", "=", "format", "(", "d", ",", "\"n\"", ")", "else", ":", "result", "=", "format", "(", "d", ",", "\"g\"", ")", "if", "f", "!=", "locale", ".", "atof", "(", "result", ")", ":", "# result = '≈' + result", "# ≈ # \\u2248", "result", "=", "\"≈\" +", "r", "sult", "decimal_char", "=", "locale", ".", "localeconv", "(", ")", ".", "get", "(", "\"decimal_point\"", ")", "if", "\"e\"", "not", "in", "result", "and", "\"E\"", "not", "in", "result", "and", "decimal_char", "in", "result", ":", "result", "=", "result", ".", "rstrip", "(", "\"0\"", ")", ".", "rstrip", "(", "decimal_char", ")", "return", "result" ]
[ 18, 0 ]
[ 62, 17 ]
python
en
['en', 'en', 'en']
True
ordinal
(num)
Convert a number to ordinal
Convert a number to ordinal
def ordinal(num): """Convert a number to ordinal""" # Taken from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers/41301 # Consider a library like num2word when internationalization comes if 10 <= num % 100 <= 20: suffix = "th" else: # the second parameter is a default. suffix = SUFFIXES.get(num % 10, "th") return str(num) + suffix
[ "def", "ordinal", "(", "num", ")", ":", "# Taken from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers/41301", "# Consider a library like num2word when internationalization comes", "if", "10", "<=", "num", "%", "100", "<=", "20", ":", "suffix", "=", "\"th\"", "else", ":", "# the second parameter is a default.", "suffix", "=", "SUFFIXES", ".", "get", "(", "num", "%", "10", ",", "\"th\"", ")", "return", "str", "(", "num", ")", "+", "suffix" ]
[ 68, 0 ]
[ 77, 28 ]
python
en
['en', 'su', 'en']
True
substitute_none_for_missing
(kwargs, kwarg_list)
Utility function to plug Nones in when optional parameters are not specified in expectation kwargs. Example: Input: kwargs={"a":1, "b":2}, kwarg_list=["c", "d"] Output: {"a":1, "b":2, "c": None, "d": None} This is helpful for standardizing the input objects for rendering functions. The alternative is lots of awkward `if "some_param" not in kwargs or kwargs["some_param"] == None:` clauses in renderers.
Utility function to plug Nones in when optional parameters are not specified in expectation kwargs.
def substitute_none_for_missing(kwargs, kwarg_list): """Utility function to plug Nones in when optional parameters are not specified in expectation kwargs. Example: Input: kwargs={"a":1, "b":2}, kwarg_list=["c", "d"] Output: {"a":1, "b":2, "c": None, "d": None} This is helpful for standardizing the input objects for rendering functions. The alternative is lots of awkward `if "some_param" not in kwargs or kwargs["some_param"] == None:` clauses in renderers. """ new_kwargs = copy.deepcopy(kwargs) for kwarg in kwarg_list: if kwarg not in new_kwargs: new_kwargs[kwarg] = None return new_kwargs
[ "def", "substitute_none_for_missing", "(", "kwargs", ",", "kwarg_list", ")", ":", "new_kwargs", "=", "copy", ".", "deepcopy", "(", "kwargs", ")", "for", "kwarg", "in", "kwarg_list", ":", "if", "kwarg", "not", "in", "new_kwargs", ":", "new_kwargs", "[", "kwarg", "]", "=", "None", "return", "new_kwargs" ]
[ 114, 0 ]
[ 132, 21 ]
python
en
['en', 'en', 'en']
True
handle_strict_min_max
(params: dict)
Utility function for the at least and at most conditions based on strictness. Args: params: dictionary containing "strict_min" and "strict_max" booleans. Returns: tuple of strings to use for the at least condition and the at most condition
Utility function for the at least and at most conditions based on strictness.
def handle_strict_min_max(params: dict) -> (str, str): """ Utility function for the at least and at most conditions based on strictness. Args: params: dictionary containing "strict_min" and "strict_max" booleans. Returns: tuple of strings to use for the at least condition and the at most condition """ at_least_str = ( "greater than" if params.get("strict_min") is True else "greater than or equal to" ) at_most_str = ( "less than" if params.get("strict_max") is True else "less than or equal to" ) return at_least_str, at_most_str
[ "def", "handle_strict_min_max", "(", "params", ":", "dict", ")", "->", "(", "str", ",", "str", ")", ":", "at_least_str", "=", "(", "\"greater than\"", "if", "params", ".", "get", "(", "\"strict_min\"", ")", "is", "True", "else", "\"greater than or equal to\"", ")", "at_most_str", "=", "(", "\"less than\"", "if", "params", ".", "get", "(", "\"strict_max\"", ")", "is", "True", "else", "\"less than or equal to\"", ")", "return", "at_least_str", ",", "at_most_str" ]
[ 178, 0 ]
[ 198, 36 ]
python
en
['en', 'error', 'th']
False
DataConnector.__init__
( self, name: str, datasource_name: str, execution_engine: Optional[ExecutionEngine] = None, batch_spec_passthrough: Optional[dict] = None, )
Base class for DataConnectors Args: name (str): required name for DataConnector datasource_name (str): required name for datasource execution_engine (ExecutionEngine): optional reference to ExecutionEngine batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec
Base class for DataConnectors
def __init__( self, name: str, datasource_name: str, execution_engine: Optional[ExecutionEngine] = None, batch_spec_passthrough: Optional[dict] = None, ): """ Base class for DataConnectors Args: name (str): required name for DataConnector datasource_name (str): required name for datasource execution_engine (ExecutionEngine): optional reference to ExecutionEngine batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec """ self._name = name self._datasource_name = datasource_name self._execution_engine = execution_engine # This is a dictionary which maps data_references onto batch_requests. self._data_references_cache = {} self._data_context_root_directory = None self._batch_spec_passthrough = batch_spec_passthrough or {}
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "datasource_name", ":", "str", ",", "execution_engine", ":", "Optional", "[", "ExecutionEngine", "]", "=", "None", ",", "batch_spec_passthrough", ":", "Optional", "[", "dict", "]", "=", "None", ",", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_datasource_name", "=", "datasource_name", "self", ".", "_execution_engine", "=", "execution_engine", "# This is a dictionary which maps data_references onto batch_requests.", "self", ".", "_data_references_cache", "=", "{", "}", "self", ".", "_data_context_root_directory", "=", "None", "self", ".", "_batch_spec_passthrough", "=", "batch_spec_passthrough", "or", "{", "}" ]
[ 35, 4 ]
[ 59, 67 ]
python
en
['en', 'error', 'th']
False
DataConnector.get_batch_data_and_metadata
( self, batch_definition: BatchDefinition, )
Uses batch_definition to retrieve batch_data and batch_markers by building a batch_spec from batch_definition, then using execution_engine to return batch_data and batch_markers Args: batch_definition (BatchDefinition): required batch_definition parameter for retrieval
Uses batch_definition to retrieve batch_data and batch_markers by building a batch_spec from batch_definition, then using execution_engine to return batch_data and batch_markers
def get_batch_data_and_metadata( self, batch_definition: BatchDefinition, ) -> Tuple[Any, BatchSpec, BatchMarkers,]: # batch_data """ Uses batch_definition to retrieve batch_data and batch_markers by building a batch_spec from batch_definition, then using execution_engine to return batch_data and batch_markers Args: batch_definition (BatchDefinition): required batch_definition parameter for retrieval """ batch_spec: BatchSpec = self.build_batch_spec(batch_definition=batch_definition) batch_data, batch_markers = self._execution_engine.get_batch_data_and_markers( batch_spec=batch_spec ) self._execution_engine.load_batch_data(batch_definition.id, batch_data) return ( batch_data, batch_spec, batch_markers, )
[ "def", "get_batch_data_and_metadata", "(", "self", ",", "batch_definition", ":", "BatchDefinition", ",", ")", "->", "Tuple", "[", "Any", ",", "BatchSpec", ",", "BatchMarkers", ",", "]", ":", "# batch_data", "batch_spec", ":", "BatchSpec", "=", "self", ".", "build_batch_spec", "(", "batch_definition", "=", "batch_definition", ")", "batch_data", ",", "batch_markers", "=", "self", ".", "_execution_engine", ".", "get_batch_data_and_markers", "(", "batch_spec", "=", "batch_spec", ")", "self", ".", "_execution_engine", ".", "load_batch_data", "(", "batch_definition", ".", "id", ",", "batch_data", ")", "return", "(", "batch_data", ",", "batch_spec", ",", "batch_markers", ",", ")" ]
[ 81, 4 ]
[ 102, 9 ]
python
en
['en', 'error', 'th']
False
DataConnector.build_batch_spec
(self, batch_definition: BatchDefinition)
Builds batch_spec from batch_definition by generating batch_spec params and adding any pass_through params Args: batch_definition (BatchDefinition): required batch_definition parameter for retrieval Returns: BatchSpec object built from BatchDefinition
Builds batch_spec from batch_definition by generating batch_spec params and adding any pass_through params
def build_batch_spec(self, batch_definition: BatchDefinition) -> BatchSpec: """ Builds batch_spec from batch_definition by generating batch_spec params and adding any pass_through params Args: batch_definition (BatchDefinition): required batch_definition parameter for retrieval Returns: BatchSpec object built from BatchDefinition """ batch_spec_params: dict = ( self._generate_batch_spec_parameters_from_batch_definition( batch_definition=batch_definition ) ) # batch_spec_passthrough via Data Connector config batch_spec_passthrough: dict = deepcopy(self.batch_spec_passthrough) # batch_spec_passthrough from batch_definition supersedes batch_spec_passthrough from Data Connector config if isinstance(batch_definition.batch_spec_passthrough, dict): batch_spec_passthrough.update(batch_definition.batch_spec_passthrough) batch_spec_params.update(batch_spec_passthrough) batch_spec: BatchSpec = BatchSpec(**batch_spec_params) return batch_spec
[ "def", "build_batch_spec", "(", "self", ",", "batch_definition", ":", "BatchDefinition", ")", "->", "BatchSpec", ":", "batch_spec_params", ":", "dict", "=", "(", "self", ".", "_generate_batch_spec_parameters_from_batch_definition", "(", "batch_definition", "=", "batch_definition", ")", ")", "# batch_spec_passthrough via Data Connector config", "batch_spec_passthrough", ":", "dict", "=", "deepcopy", "(", "self", ".", "batch_spec_passthrough", ")", "# batch_spec_passthrough from batch_definition supersedes batch_spec_passthrough from Data Connector config", "if", "isinstance", "(", "batch_definition", ".", "batch_spec_passthrough", ",", "dict", ")", ":", "batch_spec_passthrough", ".", "update", "(", "batch_definition", ".", "batch_spec_passthrough", ")", "batch_spec_params", ".", "update", "(", "batch_spec_passthrough", ")", "batch_spec", ":", "BatchSpec", "=", "BatchSpec", "(", "*", "*", "batch_spec_params", ")", "return", "batch_spec" ]
[ 104, 4 ]
[ 128, 25 ]
python
en
['en', 'error', 'th']
False
DataConnector._get_data_reference_list
( self, data_asset_name: Optional[str] = None )
List objects in the underlying data store to create a list of data_references. This method is used to refresh the cache by classes that extend this base DataConnector class Args: data_asset_name (str): optional data_asset_name to retrieve more specific results
List objects in the underlying data store to create a list of data_references. This method is used to refresh the cache by classes that extend this base DataConnector class
def _get_data_reference_list( self, data_asset_name: Optional[str] = None ) -> List[str]: """ List objects in the underlying data store to create a list of data_references. This method is used to refresh the cache by classes that extend this base DataConnector class Args: data_asset_name (str): optional data_asset_name to retrieve more specific results """ raise NotImplementedError
[ "def", "_get_data_reference_list", "(", "self", ",", "data_asset_name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "List", "[", "str", "]", ":", "raise", "NotImplementedError" ]
[ 135, 4 ]
[ 146, 33 ]
python
en
['en', 'error', 'th']
False
DataConnector._get_data_reference_list_from_cache_by_data_asset_name
( self, data_asset_name: str )
Fetch data_references corresponding to data_asset_name from the cache.
Fetch data_references corresponding to data_asset_name from the cache.
def _get_data_reference_list_from_cache_by_data_asset_name( self, data_asset_name: str ) -> List[Any]: """ Fetch data_references corresponding to data_asset_name from the cache. """ raise NotImplementedError
[ "def", "_get_data_reference_list_from_cache_by_data_asset_name", "(", "self", ",", "data_asset_name", ":", "str", ")", "->", "List", "[", "Any", "]", ":", "raise", "NotImplementedError" ]
[ 148, 4 ]
[ 154, 33 ]
python
en
['en', 'error', 'th']
False
DataConnector.get_available_data_asset_names
(self)
Return the list of asset names known by this data connector. Returns: A list of available names
Return the list of asset names known by this data connector.
def get_available_data_asset_names(self) -> List[str]: """Return the list of asset names known by this data connector. Returns: A list of available names """ raise NotImplementedError
[ "def", "get_available_data_asset_names", "(", "self", ")", "->", "List", "[", "str", "]", ":", "raise", "NotImplementedError" ]
[ 162, 4 ]
[ 168, 33 ]
python
en
['en', 'en', 'en']
True
DataConnector.self_check
(self, pretty_print=True, max_examples=3)
Checks the configuration of the current DataConnector by doing the following : 1. refresh or create data_reference_cache 2. print batch_definition_count and example_data_references for each data_asset_names 3. also print unmatched data_references, and allow the user to modify the regex or glob configuration if necessary 4. select a random data_reference and attempt to retrieve and print the first few rows to user When used as part of the test_yaml_config() workflow, the user will be able to know if the data_connector is properly configured, and if the associated execution_engine can properly retrieve data using the configuration. Args: pretty_print (bool): should the output be printed? max_examples (int): how many data_references should be printed?
Checks the configuration of the current DataConnector by doing the following :
def self_check(self, pretty_print=True, max_examples=3): """ Checks the configuration of the current DataConnector by doing the following : 1. refresh or create data_reference_cache 2. print batch_definition_count and example_data_references for each data_asset_names 3. also print unmatched data_references, and allow the user to modify the regex or glob configuration if necessary 4. select a random data_reference and attempt to retrieve and print the first few rows to user When used as part of the test_yaml_config() workflow, the user will be able to know if the data_connector is properly configured, and if the associated execution_engine can properly retrieve data using the configuration. Args: pretty_print (bool): should the output be printed? max_examples (int): how many data_references should be printed? """ if len(self._data_references_cache) == 0: self._refresh_data_references_cache() if pretty_print: print("\t" + self.name, ":", self.__class__.__name__) print() asset_names = self.get_available_data_asset_names() asset_names.sort() len_asset_names = len(asset_names) report_obj = { "class_name": self.__class__.__name__, "data_asset_count": len_asset_names, "example_data_asset_names": asset_names[:max_examples], "data_assets": {} # "data_reference_count": self. } if pretty_print: print( f"\tAvailable data_asset_names ({min(len_asset_names, max_examples)} of {len_asset_names}):" ) for asset_name in asset_names[:max_examples]: data_reference_list = ( self._get_data_reference_list_from_cache_by_data_asset_name( data_asset_name=asset_name ) ) len_batch_definition_list = len(data_reference_list) example_data_references = data_reference_list[:max_examples] if pretty_print: print( f"\t\t{asset_name} ({min(len_batch_definition_list, max_examples)} of {len_batch_definition_list}):", example_data_references, ) report_obj["data_assets"][asset_name] = { "batch_definition_count": len_batch_definition_list, "example_data_references": example_data_references, } unmatched_data_references = self.get_unmatched_data_references() len_unmatched_data_references = len(unmatched_data_references) if pretty_print: print( f"\n\tUnmatched data_references ({min(len_unmatched_data_references, max_examples)} of {len_unmatched_data_references}):", unmatched_data_references[:max_examples], ) report_obj["unmatched_data_reference_count"] = len_unmatched_data_references report_obj["example_unmatched_data_references"] = unmatched_data_references[ :max_examples ] # FIXME: (Sam) Removing this temporarily since it's not supported by # some backends (e.g. BigQuery) and returns empty results for some # (e.g. MSSQL) - this needs some more work to be useful for all backends # # # Choose an example data_reference # if pretty_print: # print("\n\tChoosing an example data reference...") # # example_data_reference = None # # available_references = report_obj["data_assets"].items() # if len(available_references) == 0: # if pretty_print: # print(f"\t\tNo references available.") # return report_obj # # data_asset_name: Optional[str] = None # for tmp_data_asset_name, data_asset_return_obj in available_references: # if data_asset_return_obj["batch_definition_count"] > 0: # example_data_reference = random.choice( # data_asset_return_obj["example_data_references"] # ) # data_asset_name = tmp_data_asset_name # break # # if example_data_reference is not None: # if pretty_print: # print(f"\t\tReference chosen: {example_data_reference}") # # # ...and fetch it. # if data_asset_name is None: # raise ValueError( # "The data_asset_name for the chosen example data reference cannot be null." # ) # report_obj["example_data_reference"] = self._self_check_fetch_batch( # pretty_print=pretty_print, # example_data_reference=example_data_reference, # data_asset_name=data_asset_name, # ) # else: # report_obj["example_data_reference"] = {} return report_obj
[ "def", "self_check", "(", "self", ",", "pretty_print", "=", "True", ",", "max_examples", "=", "3", ")", ":", "if", "len", "(", "self", ".", "_data_references_cache", ")", "==", "0", ":", "self", ".", "_refresh_data_references_cache", "(", ")", "if", "pretty_print", ":", "print", "(", "\"\\t\"", "+", "self", ".", "name", ",", "\":\"", ",", "self", ".", "__class__", ".", "__name__", ")", "print", "(", ")", "asset_names", "=", "self", ".", "get_available_data_asset_names", "(", ")", "asset_names", ".", "sort", "(", ")", "len_asset_names", "=", "len", "(", "asset_names", ")", "report_obj", "=", "{", "\"class_name\"", ":", "self", ".", "__class__", ".", "__name__", ",", "\"data_asset_count\"", ":", "len_asset_names", ",", "\"example_data_asset_names\"", ":", "asset_names", "[", ":", "max_examples", "]", ",", "\"data_assets\"", ":", "{", "}", "# \"data_reference_count\": self.", "}", "if", "pretty_print", ":", "print", "(", "f\"\\tAvailable data_asset_names ({min(len_asset_names, max_examples)} of {len_asset_names}):\"", ")", "for", "asset_name", "in", "asset_names", "[", ":", "max_examples", "]", ":", "data_reference_list", "=", "(", "self", ".", "_get_data_reference_list_from_cache_by_data_asset_name", "(", "data_asset_name", "=", "asset_name", ")", ")", "len_batch_definition_list", "=", "len", "(", "data_reference_list", ")", "example_data_references", "=", "data_reference_list", "[", ":", "max_examples", "]", "if", "pretty_print", ":", "print", "(", "f\"\\t\\t{asset_name} ({min(len_batch_definition_list, max_examples)} of {len_batch_definition_list}):\"", ",", "example_data_references", ",", ")", "report_obj", "[", "\"data_assets\"", "]", "[", "asset_name", "]", "=", "{", "\"batch_definition_count\"", ":", "len_batch_definition_list", ",", "\"example_data_references\"", ":", "example_data_references", ",", "}", "unmatched_data_references", "=", "self", ".", "get_unmatched_data_references", "(", ")", "len_unmatched_data_references", "=", "len", "(", "unmatched_data_references", ")", "if", "pretty_print", ":", "print", "(", "f\"\\n\\tUnmatched data_references ({min(len_unmatched_data_references, max_examples)} of {len_unmatched_data_references}):\"", ",", "unmatched_data_references", "[", ":", "max_examples", "]", ",", ")", "report_obj", "[", "\"unmatched_data_reference_count\"", "]", "=", "len_unmatched_data_references", "report_obj", "[", "\"example_unmatched_data_references\"", "]", "=", "unmatched_data_references", "[", ":", "max_examples", "]", "# FIXME: (Sam) Removing this temporarily since it's not supported by", "# some backends (e.g. BigQuery) and returns empty results for some", "# (e.g. MSSQL) - this needs some more work to be useful for all backends", "#", "# # Choose an example data_reference", "# if pretty_print:", "# print(\"\\n\\tChoosing an example data reference...\")", "#", "# example_data_reference = None", "#", "# available_references = report_obj[\"data_assets\"].items()", "# if len(available_references) == 0:", "# if pretty_print:", "# print(f\"\\t\\tNo references available.\")", "# return report_obj", "#", "# data_asset_name: Optional[str] = None", "# for tmp_data_asset_name, data_asset_return_obj in available_references:", "# if data_asset_return_obj[\"batch_definition_count\"] > 0:", "# example_data_reference = random.choice(", "# data_asset_return_obj[\"example_data_references\"]", "# )", "# data_asset_name = tmp_data_asset_name", "# break", "#", "# if example_data_reference is not None:", "# if pretty_print:", "# print(f\"\\t\\tReference chosen: {example_data_reference}\")", "#", "# # ...and fetch it.", "# if data_asset_name is None:", "# raise ValueError(", "# \"The data_asset_name for the chosen example data reference cannot be null.\"", "# )", "# report_obj[\"example_data_reference\"] = self._self_check_fetch_batch(", "# pretty_print=pretty_print,", "# example_data_reference=example_data_reference,", "# data_asset_name=data_asset_name,", "# )", "# else:", "# report_obj[\"example_data_reference\"] = {}", "return", "report_obj" ]
[ 191, 4 ]
[ 307, 25 ]
python
en
['en', 'error', 'th']
False
DataConnector._self_check_fetch_batch
( self, pretty_print: bool, example_data_reference: Any, data_asset_name: str, )
Helper function for self_check() to retrieve batch using example_data_reference and data_asset_name, all while printing helpful messages. First 5 rows of batch_data are printed by default. Args: pretty_print (bool): print to console? example_data_reference (Any): data_reference to retrieve data_asset_name (str): data_asset_name to retrieve
Helper function for self_check() to retrieve batch using example_data_reference and data_asset_name, all while printing helpful messages. First 5 rows of batch_data are printed by default.
def _self_check_fetch_batch( self, pretty_print: bool, example_data_reference: Any, data_asset_name: str, ): """ Helper function for self_check() to retrieve batch using example_data_reference and data_asset_name, all while printing helpful messages. First 5 rows of batch_data are printed by default. Args: pretty_print (bool): print to console? example_data_reference (Any): data_reference to retrieve data_asset_name (str): data_asset_name to retrieve """ if pretty_print: print(f"\n\t\tFetching batch data...") batch_definition_list: List[ BatchDefinition ] = self._map_data_reference_to_batch_definition_list( data_reference=example_data_reference, data_asset_name=data_asset_name, ) assert len(batch_definition_list) == 1 batch_definition: BatchDefinition = batch_definition_list[0] # _execution_engine might be None for some tests if batch_definition is None or self._execution_engine is None: return {} batch_data: Any batch_spec: BatchSpec batch_data, batch_spec, _ = self.get_batch_data_and_metadata( batch_definition=batch_definition ) # Note: get_batch_data_and_metadata will have loaded the data into the currently-defined execution engine. # Consequently, when we build a Validator, we do not need to specifically load the batch into it to # resolve metrics. validator: Validator = Validator(execution_engine=batch_data.execution_engine) data: Any = validator.get_metric( metric=MetricConfiguration( metric_name="table.head", metric_domain_kwargs={ "batch_id": batch_definition.id, }, metric_value_kwargs={ "n_rows": 5, }, ) ) n_rows: int = validator.get_metric( metric=MetricConfiguration( metric_name="table.row_count", metric_domain_kwargs={ "batch_id": batch_definition.id, }, ) ) if pretty_print and data is not None: print(f"\n\t\tShowing 5 rows") print(data) return { "batch_spec": batch_spec, "n_rows": n_rows, }
[ "def", "_self_check_fetch_batch", "(", "self", ",", "pretty_print", ":", "bool", ",", "example_data_reference", ":", "Any", ",", "data_asset_name", ":", "str", ",", ")", ":", "if", "pretty_print", ":", "print", "(", "f\"\\n\\t\\tFetching batch data...\"", ")", "batch_definition_list", ":", "List", "[", "BatchDefinition", "]", "=", "self", ".", "_map_data_reference_to_batch_definition_list", "(", "data_reference", "=", "example_data_reference", ",", "data_asset_name", "=", "data_asset_name", ",", ")", "assert", "len", "(", "batch_definition_list", ")", "==", "1", "batch_definition", ":", "BatchDefinition", "=", "batch_definition_list", "[", "0", "]", "# _execution_engine might be None for some tests", "if", "batch_definition", "is", "None", "or", "self", ".", "_execution_engine", "is", "None", ":", "return", "{", "}", "batch_data", ":", "Any", "batch_spec", ":", "BatchSpec", "batch_data", ",", "batch_spec", ",", "_", "=", "self", ".", "get_batch_data_and_metadata", "(", "batch_definition", "=", "batch_definition", ")", "# Note: get_batch_data_and_metadata will have loaded the data into the currently-defined execution engine.", "# Consequently, when we build a Validator, we do not need to specifically load the batch into it to", "# resolve metrics.", "validator", ":", "Validator", "=", "Validator", "(", "execution_engine", "=", "batch_data", ".", "execution_engine", ")", "data", ":", "Any", "=", "validator", ".", "get_metric", "(", "metric", "=", "MetricConfiguration", "(", "metric_name", "=", "\"table.head\"", ",", "metric_domain_kwargs", "=", "{", "\"batch_id\"", ":", "batch_definition", ".", "id", ",", "}", ",", "metric_value_kwargs", "=", "{", "\"n_rows\"", ":", "5", ",", "}", ",", ")", ")", "n_rows", ":", "int", "=", "validator", ".", "get_metric", "(", "metric", "=", "MetricConfiguration", "(", "metric_name", "=", "\"table.row_count\"", ",", "metric_domain_kwargs", "=", "{", "\"batch_id\"", ":", "batch_definition", ".", "id", ",", "}", ",", ")", ")", "if", "pretty_print", "and", "data", "is", "not", "None", ":", "print", "(", "f\"\\n\\t\\tShowing 5 rows\"", ")", "print", "(", "data", ")", "return", "{", "\"batch_spec\"", ":", "batch_spec", ",", "\"n_rows\"", ":", "n_rows", ",", "}" ]
[ 309, 4 ]
[ 378, 9 ]
python
en
['en', 'error', 'th']
False
DataConnector._validate_batch_request
(self, batch_request: BatchRequest)
Validate batch_request by checking: 1. if configured datasource_name matches batch_request's datasource_name 2. if current data_connector_name matches batch_request's data_connector_name Args: batch_request (BatchRequest): batch_request to validate
Validate batch_request by checking: 1. if configured datasource_name matches batch_request's datasource_name 2. if current data_connector_name matches batch_request's data_connector_name Args: batch_request (BatchRequest): batch_request to validate
def _validate_batch_request(self, batch_request: BatchRequest): """ Validate batch_request by checking: 1. if configured datasource_name matches batch_request's datasource_name 2. if current data_connector_name matches batch_request's data_connector_name Args: batch_request (BatchRequest): batch_request to validate """ if batch_request.datasource_name != self.datasource_name: raise ValueError( f"""datasource_name in BatchRequest: "{batch_request.datasource_name}" does not match DataConnector datasource_name: "{self.datasource_name}".""" ) if batch_request.data_connector_name != self.name: raise ValueError( f"""data_connector_name in BatchRequest: "{batch_request.data_connector_name}" does not match DataConnector name: "{self.name}".""" )
[ "def", "_validate_batch_request", "(", "self", ",", "batch_request", ":", "BatchRequest", ")", ":", "if", "batch_request", ".", "datasource_name", "!=", "self", ".", "datasource_name", ":", "raise", "ValueError", "(", "f\"\"\"datasource_name in BatchRequest: \"{batch_request.datasource_name}\" does not match DataConnector datasource_name: \"{self.datasource_name}\".\"\"\"", ")", "if", "batch_request", ".", "data_connector_name", "!=", "self", ".", "name", ":", "raise", "ValueError", "(", "f\"\"\"data_connector_name in BatchRequest: \"{batch_request.data_connector_name}\" does not match DataConnector name: \"{self.name}\".\"\"\"", ")" ]
[ 380, 4 ]
[ 396, 13 ]
python
en
['en', 'error', 'th']
False
set_data_source
(context, data_source_type=None)
TODO: Needs a docstring and tests.
TODO: Needs a docstring and tests.
def set_data_source(context, data_source_type=None): """ TODO: Needs a docstring and tests. """ data_source_name = None if not data_source_type: configured_datasources = [ datasource for datasource in context.list_datasources() ] if len(configured_datasources) == 0: display( HTML( """ <p> No data sources found in the great_expectations.yml of your project. </p> <p> If you did not create the data source during init, here is how to add it now: <a href="https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html">How To Add a Data Source</a> </p> """ ) ) elif len(configured_datasources) > 1: display( HTML( """ <p> Found more than one data source in the great_expectations.yml of your project: <b>{1:s}</b> </p> <p> Uncomment the next cell and set data_source_name to one of these names. </p> """.format( data_source_type, ",".join( [ datasource["name"] for datasource in configured_datasources ] ), ) ) ) else: data_source_name = configured_datasources[0]["name"] display( HTML( "Will be using this data source from your project's great_expectations.yml: <b>{:s}</b>".format( data_source_name ) ) ) else: configured_datasources = [ datasource["name"] for datasource in context.list_datasources() if datasource["type"] == data_source_type ] if len(configured_datasources) == 0: display( HTML( """ <p> No {:s} data sources found in the great_expectations.yml of your project. </p> <p> If you did not create the data source during init, here is how to add it now: <a href="https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html">How To Add a Data Source</a> </p> """.format( data_source_type ) ) ) elif len(configured_datasources) > 1: display( HTML( """ <p> Found more than one {:s} data source in the great_expectations.yml of your project: <b>{:s}</b> </p> <p> Uncomment the next cell and set data_source_name to one of these names. </p> """.format( data_source_type, ",".join(configured_datasources) ) ) ) else: data_source_name = configured_datasources[0] display( HTML( "Will be using this {:s} data source from your project's great_expectations.yml: <b>{:s}</b>".format( data_source_type, data_source_name ) ) ) return data_source_name
[ "def", "set_data_source", "(", "context", ",", "data_source_type", "=", "None", ")", ":", "data_source_name", "=", "None", "if", "not", "data_source_type", ":", "configured_datasources", "=", "[", "datasource", "for", "datasource", "in", "context", ".", "list_datasources", "(", ")", "]", "if", "len", "(", "configured_datasources", ")", "==", "0", ":", "display", "(", "HTML", "(", "\"\"\"\n<p>\nNo data sources found in the great_expectations.yml of your project.\n</p>\n\n<p>\nIf you did not create the data source during init, here is how to add it now: <a href=\"https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html\">How To Add a Data Source</a>\n</p>\n\"\"\"", ")", ")", "elif", "len", "(", "configured_datasources", ")", ">", "1", ":", "display", "(", "HTML", "(", "\"\"\"\n<p>\nFound more than one data source in the great_expectations.yml of your project:\n<b>{1:s}</b>\n</p>\n<p>\nUncomment the next cell and set data_source_name to one of these names.\n</p>\n\"\"\"", ".", "format", "(", "data_source_type", ",", "\",\"", ".", "join", "(", "[", "datasource", "[", "\"name\"", "]", "for", "datasource", "in", "configured_datasources", "]", ")", ",", ")", ")", ")", "else", ":", "data_source_name", "=", "configured_datasources", "[", "0", "]", "[", "\"name\"", "]", "display", "(", "HTML", "(", "\"Will be using this data source from your project's great_expectations.yml: <b>{:s}</b>\"", ".", "format", "(", "data_source_name", ")", ")", ")", "else", ":", "configured_datasources", "=", "[", "datasource", "[", "\"name\"", "]", "for", "datasource", "in", "context", ".", "list_datasources", "(", ")", "if", "datasource", "[", "\"type\"", "]", "==", "data_source_type", "]", "if", "len", "(", "configured_datasources", ")", "==", "0", ":", "display", "(", "HTML", "(", "\"\"\"\n<p>\nNo {:s} data sources found in the great_expectations.yml of your project.\n</p>\n\n<p>\nIf you did not create the data source during init, here is how to add it now: <a href=\"https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html\">How To Add a Data Source</a>\n</p>\n\"\"\"", ".", "format", "(", "data_source_type", ")", ")", ")", "elif", "len", "(", "configured_datasources", ")", ">", "1", ":", "display", "(", "HTML", "(", "\"\"\"\n<p>\nFound more than one {:s} data source in the great_expectations.yml of your project:\n<b>{:s}</b>\n</p>\n<p>\nUncomment the next cell and set data_source_name to one of these names.\n</p>\n\"\"\"", ".", "format", "(", "data_source_type", ",", "\",\"", ".", "join", "(", "configured_datasources", ")", ")", ")", ")", "else", ":", "data_source_name", "=", "configured_datasources", "[", "0", "]", "display", "(", "HTML", "(", "\"Will be using this {:s} data source from your project's great_expectations.yml: <b>{:s}</b>\"", ".", "format", "(", "data_source_type", ",", "data_source_name", ")", ")", ")", "return", "data_source_name" ]
[ 24, 0 ]
[ 130, 27 ]
python
en
['en', 'error', 'th']
False
setup_notebook_logging
(logger=None, log_level=logging.INFO)
Set up the provided logger for the GE default logging configuration. Args: logger - the logger to configure
Set up the provided logger for the GE default logging configuration.
def setup_notebook_logging(logger=None, log_level=logging.INFO): """Set up the provided logger for the GE default logging configuration. Args: logger - the logger to configure """ def posix2local(timestamp, tz=tzlocal.get_localzone()): """Seconds since the epoch -> local time as an aware datetime object.""" return datetime.fromtimestamp(timestamp, tz) class Formatter(logging.Formatter): def converter(self, timestamp): return posix2local(timestamp) def formatTime(self, record, datefmt=None): dt = self.converter(record.created) if datefmt: s = dt.strftime(datefmt) else: t = dt.strftime(self.default_time_format) s = self.default_msec_format % (t, record.msecs) return s if not logger: logger = logging.getLogger("great_expectations") chandler = logging.StreamHandler(stream=sys.stdout) chandler.setLevel(logging.DEBUG) # chandler.setFormatter(Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", "%Y-%m-%dT%H:%M:%S%z")) chandler.setFormatter( Formatter("%(asctime)s - %(levelname)s - %(message)s", "%Y-%m-%dT%H:%M:%S%z") ) logger.addHandler(chandler) logger.setLevel(log_level) logger.info( "Great Expectations logging enabled at %s level by JupyterUX module." % (log_level,) )
[ "def", "setup_notebook_logging", "(", "logger", "=", "None", ",", "log_level", "=", "logging", ".", "INFO", ")", ":", "def", "posix2local", "(", "timestamp", ",", "tz", "=", "tzlocal", ".", "get_localzone", "(", ")", ")", ":", "\"\"\"Seconds since the epoch -> local time as an aware datetime object.\"\"\"", "return", "datetime", ".", "fromtimestamp", "(", "timestamp", ",", "tz", ")", "class", "Formatter", "(", "logging", ".", "Formatter", ")", ":", "def", "converter", "(", "self", ",", "timestamp", ")", ":", "return", "posix2local", "(", "timestamp", ")", "def", "formatTime", "(", "self", ",", "record", ",", "datefmt", "=", "None", ")", ":", "dt", "=", "self", ".", "converter", "(", "record", ".", "created", ")", "if", "datefmt", ":", "s", "=", "dt", ".", "strftime", "(", "datefmt", ")", "else", ":", "t", "=", "dt", ".", "strftime", "(", "self", ".", "default_time_format", ")", "s", "=", "self", ".", "default_msec_format", "%", "(", "t", ",", "record", ".", "msecs", ")", "return", "s", "if", "not", "logger", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"great_expectations\"", ")", "chandler", "=", "logging", ".", "StreamHandler", "(", "stream", "=", "sys", ".", "stdout", ")", "chandler", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "# chandler.setFormatter(Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", \"%Y-%m-%dT%H:%M:%S%z\"))", "chandler", ".", "setFormatter", "(", "Formatter", "(", "\"%(asctime)s - %(levelname)s - %(message)s\"", ",", "\"%Y-%m-%dT%H:%M:%S%z\"", ")", ")", "logger", ".", "addHandler", "(", "chandler", ")", "logger", ".", "setLevel", "(", "log_level", ")", "logger", ".", "info", "(", "\"Great Expectations logging enabled at %s level by JupyterUX module.\"", "%", "(", "log_level", ",", ")", ")" ]
[ 133, 0 ]
[ 171, 5 ]
python
en
['en', 'en', 'en']
True
show_available_data_asset_names
(context, data_source_name=None)
List asset names found in the current context.
List asset names found in the current context.
def show_available_data_asset_names(context, data_source_name=None): """List asset names found in the current context.""" # TODO: Needs tests. styles = """ <style type='text/css'> ul.data-assets { margin-top: 0px; } ul.data-assets li { line-height: 1.2em; list-style-type: circle; } ul.data-assets li span.expectation-suite { background: #ddd; } </style> """ print("Inspecting your data sources. This may take a moment...") expectation_suite_keys = context.list_expectation_suites() datasources = context.list_datasources() html = "" for datasource in datasources: if data_source_name and datasource["name"] != data_source_name: continue html += "<h2 style='margin: 0'>Datasource: {:s} ({:s})</h2>".format( datasource["name"], datasource["class_name"] ) ds = context.get_datasource(datasource["name"]) generators = ds.list_batch_kwargs_generators() for generator_info in generators: html += "batch_kwargs_generator: {:s} ({:s})".format( generator_info["name"], generator_info["class_name"] ) generator = ds.get_batch_kwargs_generator(generator_info["name"]) # TODO hacks to deal w/ inconsistent return types. Remove urgently mystery_object = generator.get_available_data_asset_names() if isinstance(mystery_object, dict) and "names" in mystery_object.keys(): data_asset_names = sorted([name[0] for name in mystery_object["names"]]) elif isinstance(mystery_object, list): data_asset_names = sorted(mystery_object) else: data_asset_names = [] if len(data_asset_names) > 0: html += "<h3 style='margin: 0.2em 0'>Data Assets Found:</h3>" html += styles html += "<ul class='data-assets'>" for data_asset_name in data_asset_names: html += "<li>{:s}</li>".format(data_asset_name) data_asset_expectation_suite_keys = [ es_key for es_key in expectation_suite_keys if es_key.data_asset_name.datasource == datasource["name"] and es_key.data_asset_name.generator == generator_info["name"] and es_key.data_asset_name.generator_asset == data_asset_name ] if len(data_asset_expectation_suite_keys) > 0: html += "<ul>" for es_key in data_asset_expectation_suite_keys: html += "<li><span class='expectation-suite'>Expectation Suite</span>: {:s}</li>".format( es_key.expectation_suite_name ) html += "</ul>" html += "</ul>" else: display( HTML( """<p>No data assets found in this data source.</p> <p>Read about how batch kwargs generators derive data assets from data sources: <a href="https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html">Data assets</a> </p>""" ) ) display(HTML(html))
[ "def", "show_available_data_asset_names", "(", "context", ",", "data_source_name", "=", "None", ")", ":", "# TODO: Needs tests.", "styles", "=", "\"\"\"\n <style type='text/css'>\n ul.data-assets {\n margin-top: 0px;\n }\n ul.data-assets li {\n line-height: 1.2em;\n list-style-type: circle;\n }\n ul.data-assets li span.expectation-suite {\n background: #ddd;\n }\n </style>\n \"\"\"", "print", "(", "\"Inspecting your data sources. This may take a moment...\"", ")", "expectation_suite_keys", "=", "context", ".", "list_expectation_suites", "(", ")", "datasources", "=", "context", ".", "list_datasources", "(", ")", "html", "=", "\"\"", "for", "datasource", "in", "datasources", ":", "if", "data_source_name", "and", "datasource", "[", "\"name\"", "]", "!=", "data_source_name", ":", "continue", "html", "+=", "\"<h2 style='margin: 0'>Datasource: {:s} ({:s})</h2>\"", ".", "format", "(", "datasource", "[", "\"name\"", "]", ",", "datasource", "[", "\"class_name\"", "]", ")", "ds", "=", "context", ".", "get_datasource", "(", "datasource", "[", "\"name\"", "]", ")", "generators", "=", "ds", ".", "list_batch_kwargs_generators", "(", ")", "for", "generator_info", "in", "generators", ":", "html", "+=", "\"batch_kwargs_generator: {:s} ({:s})\"", ".", "format", "(", "generator_info", "[", "\"name\"", "]", ",", "generator_info", "[", "\"class_name\"", "]", ")", "generator", "=", "ds", ".", "get_batch_kwargs_generator", "(", "generator_info", "[", "\"name\"", "]", ")", "# TODO hacks to deal w/ inconsistent return types. Remove urgently", "mystery_object", "=", "generator", ".", "get_available_data_asset_names", "(", ")", "if", "isinstance", "(", "mystery_object", ",", "dict", ")", "and", "\"names\"", "in", "mystery_object", ".", "keys", "(", ")", ":", "data_asset_names", "=", "sorted", "(", "[", "name", "[", "0", "]", "for", "name", "in", "mystery_object", "[", "\"names\"", "]", "]", ")", "elif", "isinstance", "(", "mystery_object", ",", "list", ")", ":", "data_asset_names", "=", "sorted", "(", "mystery_object", ")", "else", ":", "data_asset_names", "=", "[", "]", "if", "len", "(", "data_asset_names", ")", ">", "0", ":", "html", "+=", "\"<h3 style='margin: 0.2em 0'>Data Assets Found:</h3>\"", "html", "+=", "styles", "html", "+=", "\"<ul class='data-assets'>\"", "for", "data_asset_name", "in", "data_asset_names", ":", "html", "+=", "\"<li>{:s}</li>\"", ".", "format", "(", "data_asset_name", ")", "data_asset_expectation_suite_keys", "=", "[", "es_key", "for", "es_key", "in", "expectation_suite_keys", "if", "es_key", ".", "data_asset_name", ".", "datasource", "==", "datasource", "[", "\"name\"", "]", "and", "es_key", ".", "data_asset_name", ".", "generator", "==", "generator_info", "[", "\"name\"", "]", "and", "es_key", ".", "data_asset_name", ".", "generator_asset", "==", "data_asset_name", "]", "if", "len", "(", "data_asset_expectation_suite_keys", ")", ">", "0", ":", "html", "+=", "\"<ul>\"", "for", "es_key", "in", "data_asset_expectation_suite_keys", ":", "html", "+=", "\"<li><span class='expectation-suite'>Expectation Suite</span>: {:s}</li>\"", ".", "format", "(", "es_key", ".", "expectation_suite_name", ")", "html", "+=", "\"</ul>\"", "html", "+=", "\"</ul>\"", "else", ":", "display", "(", "HTML", "(", "\"\"\"<p>No data assets found in this data source.</p>\n<p>Read about how batch kwargs generators derive data assets from data sources:\n<a href=\"https://great-expectations.readthedocs.io/en/latest/how_to_add_data_source.html\">Data assets</a>\n</p>\"\"\"", ")", ")", "display", "(", "HTML", "(", "html", ")", ")" ]
[ 178, 0 ]
[ 253, 27 ]
python
en
['en', 'en', 'en']
True
display_column_expectations_as_section
( expectation_suite, column, include_styling=True, return_without_displaying=False, )
This is a utility function to render all of the Expectations in an ExpectationSuite with the same column name as an HTML block. By default, the HTML block is rendered using ExpectationSuiteColumnSectionRenderer and the view is rendered using DefaultJinjaSectionView. Therefore, it should look exactly the same as the default renderer for build_docs. Example usage: exp = context.get_expectation_suite("notable_works_by_charles_dickens", "BasicDatasetProfiler") display_column_expectations_as_section(exp, "Type")
This is a utility function to render all of the Expectations in an ExpectationSuite with the same column name as an HTML block.
def display_column_expectations_as_section( expectation_suite, column, include_styling=True, return_without_displaying=False, ): """This is a utility function to render all of the Expectations in an ExpectationSuite with the same column name as an HTML block. By default, the HTML block is rendered using ExpectationSuiteColumnSectionRenderer and the view is rendered using DefaultJinjaSectionView. Therefore, it should look exactly the same as the default renderer for build_docs. Example usage: exp = context.get_expectation_suite("notable_works_by_charles_dickens", "BasicDatasetProfiler") display_column_expectations_as_section(exp, "Type") """ # TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class column_expectation_list = [ e for e in expectation_suite.expectations if "column" in e.kwargs and e.kwargs["column"] == column ] # TODO: Handle the case where zero evrs match the column name document = ( ExpectationSuiteColumnSectionRenderer() .render(column_expectation_list) .to_json_dict() ) view = DefaultJinjaSectionView().render({"section": document, "section_loop": 1}) return _render_for_jupyter( view, include_styling, return_without_displaying, )
[ "def", "display_column_expectations_as_section", "(", "expectation_suite", ",", "column", ",", "include_styling", "=", "True", ",", "return_without_displaying", "=", "False", ",", ")", ":", "# TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class", "column_expectation_list", "=", "[", "e", "for", "e", "in", "expectation_suite", ".", "expectations", "if", "\"column\"", "in", "e", ".", "kwargs", "and", "e", ".", "kwargs", "[", "\"column\"", "]", "==", "column", "]", "# TODO: Handle the case where zero evrs match the column name", "document", "=", "(", "ExpectationSuiteColumnSectionRenderer", "(", ")", ".", "render", "(", "column_expectation_list", ")", ".", "to_json_dict", "(", ")", ")", "view", "=", "DefaultJinjaSectionView", "(", ")", ".", "render", "(", "{", "\"section\"", ":", "document", ",", "\"section_loop\"", ":", "1", "}", ")", "return", "_render_for_jupyter", "(", "view", ",", "include_styling", ",", "return_without_displaying", ",", ")" ]
[ 328, 0 ]
[ 364, 5 ]
python
en
['en', 'en', 'en']
True
display_profiled_column_evrs_as_section
( evrs, column, include_styling=True, return_without_displaying=False, )
This is a utility function to render all of the EVRs in an ExpectationSuite with the same column name as an HTML block. By default, the HTML block is rendered using ExpectationSuiteColumnSectionRenderer and the view is rendered using DefaultJinjaSectionView. Therefore, it should look exactly the same as the default renderer for build_docs. Example usage: display_column_evrs_as_section(exp, "my_column") WARNING: This method is experimental.
This is a utility function to render all of the EVRs in an ExpectationSuite with the same column name as an HTML block.
def display_profiled_column_evrs_as_section( evrs, column, include_styling=True, return_without_displaying=False, ): """This is a utility function to render all of the EVRs in an ExpectationSuite with the same column name as an HTML block. By default, the HTML block is rendered using ExpectationSuiteColumnSectionRenderer and the view is rendered using DefaultJinjaSectionView. Therefore, it should look exactly the same as the default renderer for build_docs. Example usage: display_column_evrs_as_section(exp, "my_column") WARNING: This method is experimental. """ # TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class column_evr_list = [ e for e in evrs.results if "column" in e.expectation_config.kwargs and e.expectation_config.kwargs["column"] == column ] # TODO: Handle the case where zero evrs match the column name document = ( ProfilingResultsColumnSectionRenderer().render(column_evr_list).to_json_dict() ) view = DefaultJinjaSectionView().render( { "section": document, "section_loop": {"index": 1}, } ) return _render_for_jupyter( view, include_styling, return_without_displaying, )
[ "def", "display_profiled_column_evrs_as_section", "(", "evrs", ",", "column", ",", "include_styling", "=", "True", ",", "return_without_displaying", "=", "False", ",", ")", ":", "# TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class", "column_evr_list", "=", "[", "e", "for", "e", "in", "evrs", ".", "results", "if", "\"column\"", "in", "e", ".", "expectation_config", ".", "kwargs", "and", "e", ".", "expectation_config", ".", "kwargs", "[", "\"column\"", "]", "==", "column", "]", "# TODO: Handle the case where zero evrs match the column name", "document", "=", "(", "ProfilingResultsColumnSectionRenderer", "(", ")", ".", "render", "(", "column_evr_list", ")", ".", "to_json_dict", "(", ")", ")", "view", "=", "DefaultJinjaSectionView", "(", ")", ".", "render", "(", "{", "\"section\"", ":", "document", ",", "\"section_loop\"", ":", "{", "\"index\"", ":", "1", "}", ",", "}", ")", "return", "_render_for_jupyter", "(", "view", ",", "include_styling", ",", "return_without_displaying", ",", ")" ]
[ 367, 0 ]
[ 408, 5 ]
python
en
['en', 'en', 'en']
True
display_column_evrs_as_section
( evrs, column, include_styling=True, return_without_displaying=False, )
Display validation results for a single column as a section. WARNING: This method is experimental.
Display validation results for a single column as a section.
def display_column_evrs_as_section( evrs, column, include_styling=True, return_without_displaying=False, ): """ Display validation results for a single column as a section. WARNING: This method is experimental. """ # TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class column_evr_list = [ e for e in evrs.results if "column" in e.expectation_config.kwargs and e.expectation_config.kwargs["column"] == column ] # TODO: Handle the case where zero evrs match the column name document = ( ValidationResultsColumnSectionRenderer().render(column_evr_list).to_json_dict() ) view = DefaultJinjaSectionView().render( { "section": document, "section_loop": {"index": 1}, } ) return _render_for_jupyter( view, include_styling, return_without_displaying, )
[ "def", "display_column_evrs_as_section", "(", "evrs", ",", "column", ",", "include_styling", "=", "True", ",", "return_without_displaying", "=", "False", ",", ")", ":", "# TODO: replace this with a generic utility function, preferably a method on an ExpectationSuite class", "column_evr_list", "=", "[", "e", "for", "e", "in", "evrs", ".", "results", "if", "\"column\"", "in", "e", ".", "expectation_config", ".", "kwargs", "and", "e", ".", "expectation_config", ".", "kwargs", "[", "\"column\"", "]", "==", "column", "]", "# TODO: Handle the case where zero evrs match the column name", "document", "=", "(", "ValidationResultsColumnSectionRenderer", "(", ")", ".", "render", "(", "column_evr_list", ")", ".", "to_json_dict", "(", ")", ")", "view", "=", "DefaultJinjaSectionView", "(", ")", ".", "render", "(", "{", "\"section\"", ":", "document", ",", "\"section_loop\"", ":", "{", "\"index\"", ":", "1", "}", ",", "}", ")", "return", "_render_for_jupyter", "(", "view", ",", "include_styling", ",", "return_without_displaying", ",", ")" ]
[ 411, 0 ]
[ 447, 5 ]
python
en
['en', 'error', 'th']
False
ACPragma.__init__
(self, rkey: str, location: str="-pragma-", *, name: str="-pragma-", kind: str="Pragma", apiVersion: Optional[str]=None, serialization: Optional[str]=None, **kwargs)
Initialize an ACPragma from the raw fields of its ACResource.
Initialize an ACPragma from the raw fields of its ACResource.
def __init__(self, rkey: str, location: str="-pragma-", *, name: str="-pragma-", kind: str="Pragma", apiVersion: Optional[str]=None, serialization: Optional[str]=None, **kwargs) -> None: """ Initialize an ACPragma from the raw fields of its ACResource. """ # print("ACPragma __init__ (%s %s)" % (kind, kwargs)) # First init our superclass... super().__init__(rkey, location, kind=kind, name=name, apiVersion=apiVersion, serialization=serialization, **kwargs)
[ "def", "__init__", "(", "self", ",", "rkey", ":", "str", ",", "location", ":", "str", "=", "\"-pragma-\"", ",", "*", ",", "name", ":", "str", "=", "\"-pragma-\"", ",", "kind", ":", "str", "=", "\"Pragma\"", ",", "apiVersion", ":", "Optional", "[", "str", "]", "=", "None", ",", "serialization", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "None", ":", "# print(\"ACPragma __init__ (%s %s)\" % (kind, kwargs))", "# First init our superclass...", "super", "(", ")", ".", "__init__", "(", "rkey", ",", "location", ",", "kind", "=", "kind", ",", "name", "=", "name", ",", "apiVersion", "=", "apiVersion", ",", "serialization", "=", "serialization", ",", "*", "*", "kwargs", ")" ]
[ 29, 4 ]
[ 48, 34 ]
python
en
['en', 'error', 'th']
False
test_func
()
My cool test.name
My cool test.name
def test_func(): """ My cool test.name """ assert True
[ "def", "test_func", "(", ")", ":", "assert", "True" ]
[ 0, 0 ]
[ 2, 15 ]
python
en
['en', 'en', 'en']
True
declaration_matcher_t.__init__
( self, name=None, decl_type=None, header_dir=None, header_file=None)
:param decl_type: declaration type to match by. For example :class:`enumeration_t`. :type decl_type: any class that derives from :class:`declaration_t` class :param name: declaration name, could be full name. :type name: str :param header_dir: absolute directory path :type header_dir: str :param header_file: absolute file path :type header_file: str
:param decl_type: declaration type to match by. For example :class:`enumeration_t`. :type decl_type: any class that derives from :class:`declaration_t` class
def __init__( self, name=None, decl_type=None, header_dir=None, header_file=None): """ :param decl_type: declaration type to match by. For example :class:`enumeration_t`. :type decl_type: any class that derives from :class:`declaration_t` class :param name: declaration name, could be full name. :type name: str :param header_dir: absolute directory path :type header_dir: str :param header_file: absolute file path :type header_file: str """ # An other option is that pygccxml will create absolute path using # os.path.abspath function. But I think this is just wrong, because # abspath builds path using current working directory. This behavior # is fragile and very difficult to find a bug. matcher_base_t.__init__(self) self.decl_type = decl_type self.__name = None self.__opt_is_tmpl_inst = None self.__opt_tmpl_name = None self.__opt_is_full_name = None self.__decl_name_only = None # Set the name through the setter. self.name = name self.header_dir = header_dir self.header_file = header_file if self.header_dir: self.header_dir = utils.normalize_path(self.header_dir) if not os.path.isabs(self.header_dir): raise RuntimeError( "Path to header directory should be absolute!") if self.header_file: self.header_file = utils.normalize_path(self.header_file) if not os.path.isabs(self.header_file): raise RuntimeError("Path to header file should be absolute!")
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ")", ":", "# An other option is that pygccxml will create absolute path using", "# os.path.abspath function. But I think this is just wrong, because", "# abspath builds path using current working directory. This behavior", "# is fragile and very difficult to find a bug.", "matcher_base_t", ".", "__init__", "(", "self", ")", "self", ".", "decl_type", "=", "decl_type", "self", ".", "__name", "=", "None", "self", ".", "__opt_is_tmpl_inst", "=", "None", "self", ".", "__opt_tmpl_name", "=", "None", "self", ".", "__opt_is_full_name", "=", "None", "self", ".", "__decl_name_only", "=", "None", "# Set the name through the setter.", "self", ".", "name", "=", "name", "self", ".", "header_dir", "=", "header_dir", "self", ".", "header_file", "=", "header_file", "if", "self", ".", "header_dir", ":", "self", ".", "header_dir", "=", "utils", ".", "normalize_path", "(", "self", ".", "header_dir", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "self", ".", "header_dir", ")", ":", "raise", "RuntimeError", "(", "\"Path to header directory should be absolute!\"", ")", "if", "self", ".", "header_file", ":", "self", ".", "header_file", "=", "utils", ".", "normalize_path", "(", "self", ".", "header_file", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "self", ".", "header_file", ")", ":", "raise", "RuntimeError", "(", "\"Path to header file should be absolute!\"", ")" ]
[ 29, 4 ]
[ 78, 77 ]
python
en
['en', 'error', 'th']
False
variable_matcher_t.__init__
( self, name=None, decl_type=None, header_dir=None, header_file=None)
:param decl_type: variable type :type decl_type: string or instance of :class:`type_t` derived class
:param decl_type: variable type :type decl_type: string or instance of :class:`type_t` derived class
def __init__( self, name=None, decl_type=None, header_dir=None, header_file=None): """ :param decl_type: variable type :type decl_type: string or instance of :class:`type_t` derived class """ declaration_matcher_t.__init__( self, name=name, decl_type=variable.variable_t, header_dir=header_dir, header_file=header_file) self._decl_type = decl_type
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ")", ":", "declaration_matcher_t", ".", "__init__", "(", "self", ",", "name", "=", "name", ",", "decl_type", "=", "variable", ".", "variable_t", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ")", "self", ".", "_decl_type", "=", "decl_type" ]
[ 189, 4 ]
[ 206, 35 ]
python
en
['en', 'error', 'th']
False
calldef_matcher_t.__init__
( self, name=None, return_type=None, arg_types=None, decl_type=None, header_dir=None, header_file=None)
:param return_type: callable return type :type return_type: string or instance of :class:`type_t` derived class :type arg_types: list :param arg_types: list of function argument types. `arg_types` can contain. Any item within the list could be string or instance of :class:`type_t` derived class. If you don't want some argument to participate in match you can put None. For example: .. code-block:: python calldef_matcher_t( arg_types=[ 'int &', None ] ) will match all functions that takes 2 arguments, where the first one is reference to integer and second any
:param return_type: callable return type :type return_type: string or instance of :class:`type_t` derived class
def __init__( self, name=None, return_type=None, arg_types=None, decl_type=None, header_dir=None, header_file=None): """ :param return_type: callable return type :type return_type: string or instance of :class:`type_t` derived class :type arg_types: list :param arg_types: list of function argument types. `arg_types` can contain. Any item within the list could be string or instance of :class:`type_t` derived class. If you don't want some argument to participate in match you can put None. For example: .. code-block:: python calldef_matcher_t( arg_types=[ 'int &', None ] ) will match all functions that takes 2 arguments, where the first one is reference to integer and second any """ if None is decl_type: decl_type = calldef.calldef_t declaration_matcher_t.__init__( self, name=name, decl_type=decl_type, header_dir=header_dir, header_file=header_file) self.return_type = return_type self.arg_types = arg_types
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ")", ":", "if", "None", "is", "decl_type", ":", "decl_type", "=", "calldef", ".", "calldef_t", "declaration_matcher_t", ".", "__init__", "(", "self", ",", "name", "=", "name", ",", "decl_type", "=", "decl_type", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ")", "self", ".", "return_type", "=", "return_type", "self", ".", "arg_types", "=", "arg_types" ]
[ 260, 4 ]
[ 299, 34 ]
python
en
['en', 'error', 'th']
False
operator_matcher_t.__init__
( self, name=None, symbol=None, return_type=None, arg_types=None, decl_type=None, header_dir=None, header_file=None)
:param symbol: operator symbol :type symbol: str
:param symbol: operator symbol :type symbol: str
def __init__( self, name=None, symbol=None, return_type=None, arg_types=None, decl_type=None, header_dir=None, header_file=None): """ :param symbol: operator symbol :type symbol: str """ if None is decl_type: decl_type = calldef_members.operator_t calldef_matcher_t.__init__( self, name=name, return_type=return_type, arg_types=arg_types, decl_type=decl_type, header_dir=header_dir, header_file=header_file) self.symbol = symbol
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "symbol", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ")", ":", "if", "None", "is", "decl_type", ":", "decl_type", "=", "calldef_members", ".", "operator_t", "calldef_matcher_t", ".", "__init__", "(", "self", ",", "name", "=", "name", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "decl_type", "=", "decl_type", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ")", "self", ".", "symbol", "=", "symbol" ]
[ 358, 4 ]
[ 381, 28 ]
python
en
['en', 'error', 'th']
False
current_default_thread_limiter
()
Get the default `~trio.CapacityLimiter` used by `trio.to_thread.run_sync`. The most common reason to call this would be if you want to modify its :attr:`~trio.CapacityLimiter.total_tokens` attribute.
Get the default `~trio.CapacityLimiter` used by `trio.to_thread.run_sync`.
def current_default_thread_limiter(): """Get the default `~trio.CapacityLimiter` used by `trio.to_thread.run_sync`. The most common reason to call this would be if you want to modify its :attr:`~trio.CapacityLimiter.total_tokens` attribute. """ try: limiter = _limiter_local.get() except LookupError: limiter = CapacityLimiter(DEFAULT_LIMIT) _limiter_local.set(limiter) return limiter
[ "def", "current_default_thread_limiter", "(", ")", ":", "try", ":", "limiter", "=", "_limiter_local", ".", "get", "(", ")", "except", "LookupError", ":", "limiter", "=", "CapacityLimiter", "(", "DEFAULT_LIMIT", ")", "_limiter_local", ".", "set", "(", "limiter", ")", "return", "limiter" ]
[ 32, 0 ]
[ 45, 18 ]
python
en
['en', 'en', 'en']
True
to_thread_run_sync
(sync_fn, *args, cancellable=False, limiter=None)
Convert a blocking operation into an async operation using a thread. These two lines are equivalent:: sync_fn(*args) await trio.to_thread.run_sync(sync_fn, *args) except that if ``sync_fn`` takes a long time, then the first line will block the Trio loop while it runs, while the second line allows other Trio tasks to continue working while ``sync_fn`` runs. This is accomplished by pushing the call to ``sync_fn(*args)`` off into a worker thread. From inside the worker thread, you can get back into Trio using the functions in `trio.from_thread`. Args: sync_fn: An arbitrary synchronous callable. *args: Positional arguments to pass to sync_fn. If you need keyword arguments, use :func:`functools.partial`. cancellable (bool): Whether to allow cancellation of this operation. See discussion below. limiter (None, or CapacityLimiter-like object): An object used to limit the number of simultaneous threads. Most commonly this will be a `~trio.CapacityLimiter`, but it could be anything providing compatible :meth:`~trio.CapacityLimiter.acquire_on_behalf_of` and :meth:`~trio.CapacityLimiter.release_on_behalf_of` methods. This function will call ``acquire_on_behalf_of`` before starting the thread, and ``release_on_behalf_of`` after the thread has finished. If None (the default), uses the default `~trio.CapacityLimiter`, as returned by :func:`current_default_thread_limiter`. **Cancellation handling**: Cancellation is a tricky issue here, because neither Python nor the operating systems it runs on provide any general mechanism for cancelling an arbitrary synchronous function running in a thread. This function will always check for cancellation on entry, before starting the thread. But once the thread is running, there are two ways it can handle being cancelled: * If ``cancellable=False``, the function ignores the cancellation and keeps going, just like if we had called ``sync_fn`` synchronously. This is the default behavior. * If ``cancellable=True``, then this function immediately raises `~trio.Cancelled`. In this case **the thread keeps running in background** – we just abandon it to do whatever it's going to do, and silently discard any return value or errors that it raises. Only use this if you know that the operation is safe and side-effect free. (For example: :func:`trio.socket.getaddrinfo` uses a thread with ``cancellable=True``, because it doesn't really affect anything if a stray hostname lookup keeps running in the background.) The ``limiter`` is only released after the thread has *actually* finished – which in the case of cancellation may be some time after this function has returned. If :func:`trio.run` finishes before the thread does, then the limiter release method will never be called at all. .. warning:: You should not use this function to call long-running CPU-bound functions! In addition to the usual GIL-related reasons why using threads for CPU-bound work is not very effective in Python, there is an additional problem: on CPython, `CPU-bound threads tend to "starve out" IO-bound threads <https://bugs.python.org/issue7946>`__, so using threads for CPU-bound work is likely to adversely affect the main thread running Trio. If you need to do this, you're better off using a worker process, or perhaps PyPy (which still has a GIL, but may do a better job of fairly allocating CPU time between threads). Returns: Whatever ``sync_fn(*args)`` returns. Raises: Exception: Whatever ``sync_fn(*args)`` raises.
Convert a blocking operation into an async operation using a thread.
async def to_thread_run_sync(sync_fn, *args, cancellable=False, limiter=None): """Convert a blocking operation into an async operation using a thread. These two lines are equivalent:: sync_fn(*args) await trio.to_thread.run_sync(sync_fn, *args) except that if ``sync_fn`` takes a long time, then the first line will block the Trio loop while it runs, while the second line allows other Trio tasks to continue working while ``sync_fn`` runs. This is accomplished by pushing the call to ``sync_fn(*args)`` off into a worker thread. From inside the worker thread, you can get back into Trio using the functions in `trio.from_thread`. Args: sync_fn: An arbitrary synchronous callable. *args: Positional arguments to pass to sync_fn. If you need keyword arguments, use :func:`functools.partial`. cancellable (bool): Whether to allow cancellation of this operation. See discussion below. limiter (None, or CapacityLimiter-like object): An object used to limit the number of simultaneous threads. Most commonly this will be a `~trio.CapacityLimiter`, but it could be anything providing compatible :meth:`~trio.CapacityLimiter.acquire_on_behalf_of` and :meth:`~trio.CapacityLimiter.release_on_behalf_of` methods. This function will call ``acquire_on_behalf_of`` before starting the thread, and ``release_on_behalf_of`` after the thread has finished. If None (the default), uses the default `~trio.CapacityLimiter`, as returned by :func:`current_default_thread_limiter`. **Cancellation handling**: Cancellation is a tricky issue here, because neither Python nor the operating systems it runs on provide any general mechanism for cancelling an arbitrary synchronous function running in a thread. This function will always check for cancellation on entry, before starting the thread. But once the thread is running, there are two ways it can handle being cancelled: * If ``cancellable=False``, the function ignores the cancellation and keeps going, just like if we had called ``sync_fn`` synchronously. This is the default behavior. * If ``cancellable=True``, then this function immediately raises `~trio.Cancelled`. In this case **the thread keeps running in background** – we just abandon it to do whatever it's going to do, and silently discard any return value or errors that it raises. Only use this if you know that the operation is safe and side-effect free. (For example: :func:`trio.socket.getaddrinfo` uses a thread with ``cancellable=True``, because it doesn't really affect anything if a stray hostname lookup keeps running in the background.) The ``limiter`` is only released after the thread has *actually* finished – which in the case of cancellation may be some time after this function has returned. If :func:`trio.run` finishes before the thread does, then the limiter release method will never be called at all. .. warning:: You should not use this function to call long-running CPU-bound functions! In addition to the usual GIL-related reasons why using threads for CPU-bound work is not very effective in Python, there is an additional problem: on CPython, `CPU-bound threads tend to "starve out" IO-bound threads <https://bugs.python.org/issue7946>`__, so using threads for CPU-bound work is likely to adversely affect the main thread running Trio. If you need to do this, you're better off using a worker process, or perhaps PyPy (which still has a GIL, but may do a better job of fairly allocating CPU time between threads). Returns: Whatever ``sync_fn(*args)`` returns. Raises: Exception: Whatever ``sync_fn(*args)`` raises. """ await trio.lowlevel.checkpoint_if_cancelled() if limiter is None: limiter = current_default_thread_limiter() # Holds a reference to the task that's blocked in this function waiting # for the result – or None if this function was cancelled and we should # discard the result. task_register = [trio.lowlevel.current_task()] name = f"trio.to_thread.run_sync-{next(_thread_counter)}" placeholder = ThreadPlaceholder(name) # This function gets scheduled into the Trio run loop to deliver the # thread's result. def report_back_in_trio_thread_fn(result): def do_release_then_return_result(): # release_on_behalf_of is an arbitrary user-defined method, so it # might raise an error. If it does, we want that error to # replace the regular return value, and if the regular return was # already an exception then we want them to chain. try: return result.unwrap() finally: limiter.release_on_behalf_of(placeholder) result = outcome.capture(do_release_then_return_result) if task_register[0] is not None: trio.lowlevel.reschedule(task_register[0], result) current_trio_token = trio.lowlevel.current_trio_token() def worker_fn(): TOKEN_LOCAL.token = current_trio_token try: ret = sync_fn(*args) if inspect.iscoroutine(ret): # Manually close coroutine to avoid RuntimeWarnings ret.close() raise TypeError( "Trio expected a sync function, but {!r} appears to be " "asynchronous".format(getattr(sync_fn, "__qualname__", sync_fn)) ) return ret finally: del TOKEN_LOCAL.token def deliver_worker_fn_result(result): try: current_trio_token.run_sync_soon(report_back_in_trio_thread_fn, result) except trio.RunFinishedError: # The entire run finished, so the task we're trying to contact is # certainly long gone -- it must have been cancelled and abandoned # us. pass await limiter.acquire_on_behalf_of(placeholder) try: start_thread_soon(worker_fn, deliver_worker_fn_result) except: limiter.release_on_behalf_of(placeholder) raise def abort(_): if cancellable: task_register[0] = None return trio.lowlevel.Abort.SUCCEEDED else: return trio.lowlevel.Abort.FAILED return await trio.lowlevel.wait_task_rescheduled(abort)
[ "async", "def", "to_thread_run_sync", "(", "sync_fn", ",", "*", "args", ",", "cancellable", "=", "False", ",", "limiter", "=", "None", ")", ":", "await", "trio", ".", "lowlevel", ".", "checkpoint_if_cancelled", "(", ")", "if", "limiter", "is", "None", ":", "limiter", "=", "current_default_thread_limiter", "(", ")", "# Holds a reference to the task that's blocked in this function waiting", "# for the result – or None if this function was cancelled and we should", "# discard the result.", "task_register", "=", "[", "trio", ".", "lowlevel", ".", "current_task", "(", ")", "]", "name", "=", "f\"trio.to_thread.run_sync-{next(_thread_counter)}\"", "placeholder", "=", "ThreadPlaceholder", "(", "name", ")", "# This function gets scheduled into the Trio run loop to deliver the", "# thread's result.", "def", "report_back_in_trio_thread_fn", "(", "result", ")", ":", "def", "do_release_then_return_result", "(", ")", ":", "# release_on_behalf_of is an arbitrary user-defined method, so it", "# might raise an error. If it does, we want that error to", "# replace the regular return value, and if the regular return was", "# already an exception then we want them to chain.", "try", ":", "return", "result", ".", "unwrap", "(", ")", "finally", ":", "limiter", ".", "release_on_behalf_of", "(", "placeholder", ")", "result", "=", "outcome", ".", "capture", "(", "do_release_then_return_result", ")", "if", "task_register", "[", "0", "]", "is", "not", "None", ":", "trio", ".", "lowlevel", ".", "reschedule", "(", "task_register", "[", "0", "]", ",", "result", ")", "current_trio_token", "=", "trio", ".", "lowlevel", ".", "current_trio_token", "(", ")", "def", "worker_fn", "(", ")", ":", "TOKEN_LOCAL", ".", "token", "=", "current_trio_token", "try", ":", "ret", "=", "sync_fn", "(", "*", "args", ")", "if", "inspect", ".", "iscoroutine", "(", "ret", ")", ":", "# Manually close coroutine to avoid RuntimeWarnings", "ret", ".", "close", "(", ")", "raise", "TypeError", "(", "\"Trio expected a sync function, but {!r} appears to be \"", "\"asynchronous\"", ".", "format", "(", "getattr", "(", "sync_fn", ",", "\"__qualname__\"", ",", "sync_fn", ")", ")", ")", "return", "ret", "finally", ":", "del", "TOKEN_LOCAL", ".", "token", "def", "deliver_worker_fn_result", "(", "result", ")", ":", "try", ":", "current_trio_token", ".", "run_sync_soon", "(", "report_back_in_trio_thread_fn", ",", "result", ")", "except", "trio", ".", "RunFinishedError", ":", "# The entire run finished, so the task we're trying to contact is", "# certainly long gone -- it must have been cancelled and abandoned", "# us.", "pass", "await", "limiter", ".", "acquire_on_behalf_of", "(", "placeholder", ")", "try", ":", "start_thread_soon", "(", "worker_fn", ",", "deliver_worker_fn_result", ")", "except", ":", "limiter", ".", "release_on_behalf_of", "(", "placeholder", ")", "raise", "def", "abort", "(", "_", ")", ":", "if", "cancellable", ":", "task_register", "[", "0", "]", "=", "None", "return", "trio", ".", "lowlevel", ".", "Abort", ".", "SUCCEEDED", "else", ":", "return", "trio", ".", "lowlevel", ".", "Abort", ".", "FAILED", "return", "await", "trio", ".", "lowlevel", ".", "wait_task_rescheduled", "(", "abort", ")" ]
[ 58, 0 ]
[ 206, 59 ]
python
en
['en', 'en', 'en']
True
_run_fn_as_system_task
(cb, fn, *args, trio_token=None)
Helper function for from_thread.run and from_thread.run_sync. Since this internally uses TrioToken.run_sync_soon, all warnings about raised exceptions canceling all tasks should be noted.
Helper function for from_thread.run and from_thread.run_sync.
def _run_fn_as_system_task(cb, fn, *args, trio_token=None): """Helper function for from_thread.run and from_thread.run_sync. Since this internally uses TrioToken.run_sync_soon, all warnings about raised exceptions canceling all tasks should be noted. """ if trio_token and not isinstance(trio_token, TrioToken): raise RuntimeError("Passed kwarg trio_token is not of type TrioToken") if not trio_token: try: trio_token = TOKEN_LOCAL.token except AttributeError: raise RuntimeError( "this thread wasn't created by Trio, pass kwarg trio_token=..." ) # Avoid deadlock by making sure we're not called from Trio thread try: trio.lowlevel.current_task() except RuntimeError: pass else: raise RuntimeError("this is a blocking function; call it from a thread") q = stdlib_queue.Queue() trio_token.run_sync_soon(cb, q, fn, args) return q.get().unwrap()
[ "def", "_run_fn_as_system_task", "(", "cb", ",", "fn", ",", "*", "args", ",", "trio_token", "=", "None", ")", ":", "if", "trio_token", "and", "not", "isinstance", "(", "trio_token", ",", "TrioToken", ")", ":", "raise", "RuntimeError", "(", "\"Passed kwarg trio_token is not of type TrioToken\"", ")", "if", "not", "trio_token", ":", "try", ":", "trio_token", "=", "TOKEN_LOCAL", ".", "token", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"this thread wasn't created by Trio, pass kwarg trio_token=...\"", ")", "# Avoid deadlock by making sure we're not called from Trio thread", "try", ":", "trio", ".", "lowlevel", ".", "current_task", "(", ")", "except", "RuntimeError", ":", "pass", "else", ":", "raise", "RuntimeError", "(", "\"this is a blocking function; call it from a thread\"", ")", "q", "=", "stdlib_queue", ".", "Queue", "(", ")", "trio_token", ".", "run_sync_soon", "(", "cb", ",", "q", ",", "fn", ",", "args", ")", "return", "q", ".", "get", "(", ")", ".", "unwrap", "(", ")" ]
[ 209, 0 ]
[ 237, 27 ]
python
en
['en', 'en', 'en']
True
from_thread_run
(afn, *args, trio_token=None)
Run the given async function in the parent Trio thread, blocking until it is complete. Returns: Whatever ``afn(*args)`` returns. Returns or raises whatever the given function returns or raises. It can also raise exceptions of its own: Raises: RunFinishedError: if the corresponding call to :func:`trio.run` has already completed, or if the run has started its final cleanup phase and can no longer spawn new system tasks. Cancelled: if the corresponding call to :func:`trio.run` completes while ``afn(*args)`` is running, then ``afn`` is likely to raise :exc:`trio.Cancelled`, and this will propagate out into RuntimeError: if you try calling this from inside the Trio thread, which would otherwise cause a deadlock. AttributeError: if no ``trio_token`` was provided, and we can't infer one from context. TypeError: if ``afn`` is not an asynchronous function. **Locating a Trio Token**: There are two ways to specify which `trio.run` loop to reenter: - Spawn this thread from `trio.to_thread.run_sync`. Trio will automatically capture the relevant Trio token and use it when you want to re-enter Trio. - Pass a keyword argument, ``trio_token`` specifiying a specific `trio.run` loop to re-enter. This is useful in case you have a "foreign" thread, spawned using some other framework, and still want to enter Trio.
Run the given async function in the parent Trio thread, blocking until it is complete.
def from_thread_run(afn, *args, trio_token=None): """Run the given async function in the parent Trio thread, blocking until it is complete. Returns: Whatever ``afn(*args)`` returns. Returns or raises whatever the given function returns or raises. It can also raise exceptions of its own: Raises: RunFinishedError: if the corresponding call to :func:`trio.run` has already completed, or if the run has started its final cleanup phase and can no longer spawn new system tasks. Cancelled: if the corresponding call to :func:`trio.run` completes while ``afn(*args)`` is running, then ``afn`` is likely to raise :exc:`trio.Cancelled`, and this will propagate out into RuntimeError: if you try calling this from inside the Trio thread, which would otherwise cause a deadlock. AttributeError: if no ``trio_token`` was provided, and we can't infer one from context. TypeError: if ``afn`` is not an asynchronous function. **Locating a Trio Token**: There are two ways to specify which `trio.run` loop to reenter: - Spawn this thread from `trio.to_thread.run_sync`. Trio will automatically capture the relevant Trio token and use it when you want to re-enter Trio. - Pass a keyword argument, ``trio_token`` specifiying a specific `trio.run` loop to re-enter. This is useful in case you have a "foreign" thread, spawned using some other framework, and still want to enter Trio. """ def callback(q, afn, args): @disable_ki_protection async def unprotected_afn(): coro = coroutine_or_error(afn, *args) return await coro async def await_in_trio_thread_task(): q.put_nowait(await outcome.acapture(unprotected_afn)) try: trio.lowlevel.spawn_system_task(await_in_trio_thread_task, name=afn) except RuntimeError: # system nursery is closed q.put_nowait( outcome.Error(trio.RunFinishedError("system nursery is closed")) ) return _run_fn_as_system_task(callback, afn, *args, trio_token=trio_token)
[ "def", "from_thread_run", "(", "afn", ",", "*", "args", ",", "trio_token", "=", "None", ")", ":", "def", "callback", "(", "q", ",", "afn", ",", "args", ")", ":", "@", "disable_ki_protection", "async", "def", "unprotected_afn", "(", ")", ":", "coro", "=", "coroutine_or_error", "(", "afn", ",", "*", "args", ")", "return", "await", "coro", "async", "def", "await_in_trio_thread_task", "(", ")", ":", "q", ".", "put_nowait", "(", "await", "outcome", ".", "acapture", "(", "unprotected_afn", ")", ")", "try", ":", "trio", ".", "lowlevel", ".", "spawn_system_task", "(", "await_in_trio_thread_task", ",", "name", "=", "afn", ")", "except", "RuntimeError", ":", "# system nursery is closed", "q", ".", "put_nowait", "(", "outcome", ".", "Error", "(", "trio", ".", "RunFinishedError", "(", "\"system nursery is closed\"", ")", ")", ")", "return", "_run_fn_as_system_task", "(", "callback", ",", "afn", ",", "*", "args", ",", "trio_token", "=", "trio_token", ")" ]
[ 240, 0 ]
[ 291, 78 ]
python
en
['en', 'en', 'en']
True
from_thread_run_sync
(fn, *args, trio_token=None)
Run the given sync function in the parent Trio thread, blocking until it is complete. Returns: Whatever ``fn(*args)`` returns. Returns or raises whatever the given function returns or raises. It can also raise exceptions of its own: Raises: RunFinishedError: if the corresponding call to `trio.run` has already completed. RuntimeError: if you try calling this from inside the Trio thread, which would otherwise cause a deadlock. AttributeError: if no ``trio_token`` was provided, and we can't infer one from context. TypeError: if ``fn`` is an async function. **Locating a Trio Token**: There are two ways to specify which `trio.run` loop to reenter: - Spawn this thread from `trio.to_thread.run_sync`. Trio will automatically capture the relevant Trio token and use it when you want to re-enter Trio. - Pass a keyword argument, ``trio_token`` specifiying a specific `trio.run` loop to re-enter. This is useful in case you have a "foreign" thread, spawned using some other framework, and still want to enter Trio.
Run the given sync function in the parent Trio thread, blocking until it is complete.
def from_thread_run_sync(fn, *args, trio_token=None): """Run the given sync function in the parent Trio thread, blocking until it is complete. Returns: Whatever ``fn(*args)`` returns. Returns or raises whatever the given function returns or raises. It can also raise exceptions of its own: Raises: RunFinishedError: if the corresponding call to `trio.run` has already completed. RuntimeError: if you try calling this from inside the Trio thread, which would otherwise cause a deadlock. AttributeError: if no ``trio_token`` was provided, and we can't infer one from context. TypeError: if ``fn`` is an async function. **Locating a Trio Token**: There are two ways to specify which `trio.run` loop to reenter: - Spawn this thread from `trio.to_thread.run_sync`. Trio will automatically capture the relevant Trio token and use it when you want to re-enter Trio. - Pass a keyword argument, ``trio_token`` specifiying a specific `trio.run` loop to re-enter. This is useful in case you have a "foreign" thread, spawned using some other framework, and still want to enter Trio. """ def callback(q, fn, args): @disable_ki_protection def unprotected_fn(): ret = fn(*args) if inspect.iscoroutine(ret): # Manually close coroutine to avoid RuntimeWarnings ret.close() raise TypeError( "Trio expected a sync function, but {!r} appears to be " "asynchronous".format(getattr(fn, "__qualname__", fn)) ) return ret res = outcome.capture(unprotected_fn) q.put_nowait(res) return _run_fn_as_system_task(callback, fn, *args, trio_token=trio_token)
[ "def", "from_thread_run_sync", "(", "fn", ",", "*", "args", ",", "trio_token", "=", "None", ")", ":", "def", "callback", "(", "q", ",", "fn", ",", "args", ")", ":", "@", "disable_ki_protection", "def", "unprotected_fn", "(", ")", ":", "ret", "=", "fn", "(", "*", "args", ")", "if", "inspect", ".", "iscoroutine", "(", "ret", ")", ":", "# Manually close coroutine to avoid RuntimeWarnings", "ret", ".", "close", "(", ")", "raise", "TypeError", "(", "\"Trio expected a sync function, but {!r} appears to be \"", "\"asynchronous\"", ".", "format", "(", "getattr", "(", "fn", ",", "\"__qualname__\"", ",", "fn", ")", ")", ")", "return", "ret", "res", "=", "outcome", ".", "capture", "(", "unprotected_fn", ")", "q", ".", "put_nowait", "(", "res", ")", "return", "_run_fn_as_system_task", "(", "callback", ",", "fn", ",", "*", "args", ",", "trio_token", "=", "trio_token", ")" ]
[ 294, 0 ]
[ 343, 77 ]
python
en
['en', 'en', 'en']
True
ExpectColumnDistinctValuesToBeInSet.validate_configuration
(self, configuration: Optional[ExpectationConfiguration])
Validating that user has inputted a value set and that configuration has been initialized
Validating that user has inputted a value set and that configuration has been initialized
def validate_configuration(self, configuration: Optional[ExpectationConfiguration]): """Validating that user has inputted a value set and that configuration has been initialized""" super().validate_configuration(configuration) try: assert "value_set" in configuration.kwargs, "value_set is required" assert ( isinstance(configuration.kwargs["value_set"], (list, set, dict)) or configuration.kwargs["value_set"] is None ), "value_set must be a list, set, or None" if isinstance(configuration.kwargs["value_set"], dict): assert ( "$PARAMETER" in configuration.kwargs["value_set"] ), 'Evaluation Parameter dict for value_set kwarg must have "$PARAMETER" key' except AssertionError as e: raise InvalidExpectationConfigurationError(str(e)) return True
[ "def", "validate_configuration", "(", "self", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", ")", ":", "super", "(", ")", ".", "validate_configuration", "(", "configuration", ")", "try", ":", "assert", "\"value_set\"", "in", "configuration", ".", "kwargs", ",", "\"value_set is required\"", "assert", "(", "isinstance", "(", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ",", "(", "list", ",", "set", ",", "dict", ")", ")", "or", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", "is", "None", ")", ",", "\"value_set must be a list, set, or None\"", "if", "isinstance", "(", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ",", "dict", ")", ":", "assert", "(", "\"$PARAMETER\"", "in", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ")", ",", "'Evaluation Parameter dict for value_set kwarg must have \"$PARAMETER\" key'", "except", "AssertionError", "as", "e", ":", "raise", "InvalidExpectationConfigurationError", "(", "str", "(", "e", ")", ")", "return", "True" ]
[ 271, 4 ]
[ 287, 19 ]
python
en
['en', 'en', 'en']
True
bind_aliases
(decls)
This function binds between class and it's typedefs. Deprecated since 1.9.0, will be removed in 2.0.0 :param decls: list of all declarations :rtype: None
This function binds between class and it's typedefs.
def bind_aliases(decls): """ This function binds between class and it's typedefs. Deprecated since 1.9.0, will be removed in 2.0.0 :param decls: list of all declarations :rtype: None """ warnings.warn( "The bind_aliases function is deprecated", DeprecationWarning) declarations_joiner.bind_aliases(decls)
[ "def", "bind_aliases", "(", "decls", ")", ":", "warnings", ".", "warn", "(", "\"The bind_aliases function is deprecated\"", ",", "DeprecationWarning", ")", "declarations_joiner", ".", "bind_aliases", "(", "decls", ")" ]
[ 491, 0 ]
[ 505, 43 ]
python
en
['en', 'error', 'th']
False
source_reader_t.__init__
(self, configuration, cache=None, decl_factory=None)
:param configuration: Instance of :class:`xml_generator_configuration_t` class, that contains GCC-XML or CastXML configuration. :param cache: Reference to cache object, that will be updated after a file has been parsed. :type cache: Instance of :class:`cache_base_t` class :param decl_factory: Declarations factory, if not given default declarations factory( :class:`decl_factory_t` ) will be used.
:param configuration: Instance of :class:`xml_generator_configuration_t` class, that contains GCC-XML or CastXML configuration.
def __init__(self, configuration, cache=None, decl_factory=None): """ :param configuration: Instance of :class:`xml_generator_configuration_t` class, that contains GCC-XML or CastXML configuration. :param cache: Reference to cache object, that will be updated after a file has been parsed. :type cache: Instance of :class:`cache_base_t` class :param decl_factory: Declarations factory, if not given default declarations factory( :class:`decl_factory_t` ) will be used. """ self.logger = utils.loggers.cxx_parser self.__search_directories = [] self.__config = configuration self.__cxx_std = utils.cxx_standard(configuration.cflags) self.__search_directories.append(configuration.working_directory) self.__search_directories.extend(configuration.include_paths) if not cache: cache = declarations_cache.dummy_cache_t() self.__dcache = cache self.__config.raise_on_wrong_settings() self.__decl_factory = decl_factory if not decl_factory: self.__decl_factory = declarations.decl_factory_t() self.__xml_generator_from_xml_file = None
[ "def", "__init__", "(", "self", ",", "configuration", ",", "cache", "=", "None", ",", "decl_factory", "=", "None", ")", ":", "self", ".", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "self", ".", "__search_directories", "=", "[", "]", "self", ".", "__config", "=", "configuration", "self", ".", "__cxx_std", "=", "utils", ".", "cxx_standard", "(", "configuration", ".", "cflags", ")", "self", ".", "__search_directories", ".", "append", "(", "configuration", ".", "working_directory", ")", "self", ".", "__search_directories", ".", "extend", "(", "configuration", ".", "include_paths", ")", "if", "not", "cache", ":", "cache", "=", "declarations_cache", ".", "dummy_cache_t", "(", ")", "self", ".", "__dcache", "=", "cache", "self", ".", "__config", ".", "raise_on_wrong_settings", "(", ")", "self", ".", "__decl_factory", "=", "decl_factory", "if", "not", "decl_factory", ":", "self", ".", "__decl_factory", "=", "declarations", ".", "decl_factory_t", "(", ")", "self", ".", "__xml_generator_from_xml_file", "=", "None" ]
[ 42, 4 ]
[ 71, 49 ]
python
en
['en', 'error', 'th']
False
source_reader_t.xml_generator_from_xml_file
(self)
Configuration object containing information about the xml generator read from the xml file. Returns: utils.xml_generators: configuration object
Configuration object containing information about the xml generator read from the xml file.
def xml_generator_from_xml_file(self): """ Configuration object containing information about the xml generator read from the xml file. Returns: utils.xml_generators: configuration object """ return self.__xml_generator_from_xml_file
[ "def", "xml_generator_from_xml_file", "(", "self", ")", ":", "return", "self", ".", "__xml_generator_from_xml_file" ]
[ 74, 4 ]
[ 82, 49 ]
python
en
['en', 'error', 'th']
False
source_reader_t.__create_command_line
(self, source_file, xml_file)
Generate the command line used to build xml files. Depending on the chosen xml_generator a different command line is built. The gccxml option may be removed once gccxml support is dropped (this was the original c++ xml_generator, castxml is replacing it now).
Generate the command line used to build xml files.
def __create_command_line(self, source_file, xml_file): """ Generate the command line used to build xml files. Depending on the chosen xml_generator a different command line is built. The gccxml option may be removed once gccxml support is dropped (this was the original c++ xml_generator, castxml is replacing it now). """ if self.__config.xml_generator == "gccxml": return self.__create_command_line_gccxml(source_file, xml_file) elif self.__config.xml_generator == "castxml": return self.__create_command_line_castxml(source_file, xml_file)
[ "def", "__create_command_line", "(", "self", ",", "source_file", ",", "xml_file", ")", ":", "if", "self", ".", "__config", ".", "xml_generator", "==", "\"gccxml\"", ":", "return", "self", ".", "__create_command_line_gccxml", "(", "source_file", ",", "xml_file", ")", "elif", "self", ".", "__config", ".", "xml_generator", "==", "\"castxml\"", ":", "return", "self", ".", "__create_command_line_castxml", "(", "source_file", ",", "xml_file", ")" ]
[ 84, 4 ]
[ 98, 76 ]
python
en
['en', 'error', 'th']
False
source_reader_t.__add_symbols
(self, cmd)
Add all additional defined and undefined symbols.
Add all additional defined and undefined symbols.
def __add_symbols(self, cmd): """ Add all additional defined and undefined symbols. """ if self.__config.define_symbols: symbols = self.__config.define_symbols cmd.append(''.join( [' -D"%s"' % def_symbol for def_symbol in symbols])) if self.__config.undefine_symbols: un_symbols = self.__config.undefine_symbols cmd.append(''.join( [' -U"%s"' % undef_symbol for undef_symbol in un_symbols])) return cmd
[ "def", "__add_symbols", "(", "self", ",", "cmd", ")", ":", "if", "self", ".", "__config", ".", "define_symbols", ":", "symbols", "=", "self", ".", "__config", ".", "define_symbols", "cmd", ".", "append", "(", "''", ".", "join", "(", "[", "' -D\"%s\"'", "%", "def_symbol", "for", "def_symbol", "in", "symbols", "]", ")", ")", "if", "self", ".", "__config", ".", "undefine_symbols", ":", "un_symbols", "=", "self", ".", "__config", ".", "undefine_symbols", "cmd", ".", "append", "(", "''", ".", "join", "(", "[", "' -U\"%s\"'", "%", "undef_symbol", "for", "undef_symbol", "in", "un_symbols", "]", ")", ")", "return", "cmd" ]
[ 239, 4 ]
[ 255, 18 ]
python
en
['en', 'error', 'th']
False
source_reader_t.create_xml_file
(self, source_file, destination=None)
This method will generate a xml file using an external tool. The external tool can be either gccxml or castxml. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for GCC-XML or CastXML. :type destination: str :rtype: path to xml file.
This method will generate a xml file using an external tool.
def create_xml_file(self, source_file, destination=None): """ This method will generate a xml file using an external tool. The external tool can be either gccxml or castxml. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for GCC-XML or CastXML. :type destination: str :rtype: path to xml file. """ xml_file = destination # If file specified, remove it to start else create new file name if xml_file: utils.remove_file_no_raise(xml_file, self.__config) else: xml_file = utils.create_temp_file_name(suffix='.xml') ffname = source_file if not os.path.isabs(ffname): ffname = self.__file_full_name(source_file) command_line = self.__create_command_line(ffname, xml_file) process = subprocess.Popen( args=command_line, shell=True, stdout=subprocess.PIPE) try: gccxml_reports = [] while process.poll() is None: line = process.stdout.readline() if line.strip(): gccxml_reports.append(line.rstrip()) for line in process.stdout.readlines(): if line.strip(): gccxml_reports.append(line.rstrip()) exit_status = process.returncode gccxml_msg = os.linesep.join([str(s) for s in gccxml_reports]) if self.__config.ignore_gccxml_output: if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (gccxml_msg, exit_status)) else: if gccxml_msg or exit_status or not \ os.path.isfile(xml_file): if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + " xml file does not exist") else: raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (gccxml_msg, exit_status)) except Exception: utils.remove_file_no_raise(xml_file, self.__config) raise finally: process.wait() process.stdout.close() return xml_file
[ "def", "create_xml_file", "(", "self", ",", "source_file", ",", "destination", "=", "None", ")", ":", "xml_file", "=", "destination", "# If file specified, remove it to start else create new file name", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "else", ":", "xml_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.xml'", ")", "ffname", "=", "source_file", "if", "not", "os", ".", "path", ".", "isabs", "(", "ffname", ")", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "command_line", "=", "self", ".", "__create_command_line", "(", "ffname", ",", "xml_file", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", "=", "command_line", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "try", ":", "gccxml_reports", "=", "[", "]", "while", "process", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "process", ".", "stdout", ".", "readline", "(", ")", "if", "line", ".", "strip", "(", ")", ":", "gccxml_reports", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "for", "line", "in", "process", ".", "stdout", ".", "readlines", "(", ")", ":", "if", "line", ".", "strip", "(", ")", ":", "gccxml_reports", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "exit_status", "=", "process", ".", "returncode", "gccxml_msg", "=", "os", ".", "linesep", ".", "join", "(", "[", "str", "(", "s", ")", "for", "s", "in", "gccxml_reports", "]", ")", "if", "self", ".", "__config", ".", "ignore_gccxml_output", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "gccxml_msg", ",", "exit_status", ")", ")", "else", ":", "if", "gccxml_msg", "or", "exit_status", "or", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\" xml file does not exist\"", ")", "else", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "gccxml_msg", ",", "exit_status", ")", ")", "except", "Exception", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "raise", "finally", ":", "process", ".", "wait", "(", ")", "process", ".", "stdout", ".", "close", "(", ")", "return", "xml_file" ]
[ 257, 4 ]
[ 330, 23 ]
python
en
['en', 'error', 'th']
False
source_reader_t.create_xml_file_from_string
(self, content, destination=None)
Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for GCC-XML generated file :type destination: str :rtype: returns file name of GCC-XML generated file
Creates XML file from text.
def create_xml_file_from_string(self, content, destination=None): """ Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for GCC-XML generated file :type destination: str :rtype: returns file name of GCC-XML generated file """ header_file = utils.create_temp_file_name(suffix='.h') try: with open(header_file, "w+") as header: header.write(content) xml_file = self.create_xml_file(header_file, destination) finally: utils.remove_file_no_raise(header_file, self.__config) return xml_file
[ "def", "create_xml_file_from_string", "(", "self", ",", "content", ",", "destination", "=", "None", ")", ":", "header_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.h'", ")", "try", ":", "with", "open", "(", "header_file", ",", "\"w+\"", ")", "as", "header", ":", "header", ".", "write", "(", "content", ")", "xml_file", "=", "self", ".", "create_xml_file", "(", "header_file", ",", "destination", ")", "finally", ":", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "return", "xml_file" ]
[ 332, 4 ]
[ 352, 23 ]
python
en
['en', 'error', 'th']
False
source_reader_t.read_cpp_source_file
(self, source_file)
Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str
Reads C++ source file and returns declarations tree
def read_cpp_source_file(self, source_file): """ Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str """ xml_file = '' try: ffname = self.__file_full_name(source_file) self.logger.debug("Reading source file: [%s].", ffname) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug( "File has not been found in cache, parsing...") xml_file = self.create_xml_file(ffname) decls, files = self.__parse_xml_file(xml_file) self.__dcache.update( ffname, self.__config, decls, files) else: self.logger.debug(( "File has not been changed, reading declarations " + "from cache.")) except Exception: if xml_file: utils.remove_file_no_raise(xml_file, self.__config) raise if xml_file: utils.remove_file_no_raise(xml_file, self.__config) return decls
[ "def", "read_cpp_source_file", "(", "self", ",", "source_file", ")", ":", "xml_file", "=", "''", "try", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "self", ".", "logger", ".", "debug", "(", "\"Reading source file: [%s].\"", ",", "ffname", ")", "decls", "=", "self", ".", "__dcache", ".", "cached_value", "(", "ffname", ",", "self", ".", "__config", ")", "if", "not", "decls", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been found in cache, parsing...\"", ")", "xml_file", "=", "self", ".", "create_xml_file", "(", "ffname", ")", "decls", ",", "files", "=", "self", ".", "__parse_xml_file", "(", "xml_file", ")", "self", ".", "__dcache", ".", "update", "(", "ffname", ",", "self", ".", "__config", ",", "decls", ",", "files", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "(", "\"File has not been changed, reading declarations \"", "+", "\"from cache.\"", ")", ")", "except", "Exception", ":", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "raise", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "return", "decls" ]
[ 357, 4 ]
[ 389, 20 ]
python
en
['en', 'error', 'th']
False
source_reader_t.read_xml_file
(self, xml_file)
Read generated XML file. :param xml_file: path to xml file :type xml_file: str :rtype: declarations tree
Read generated XML file.
def read_xml_file(self, xml_file): """ Read generated XML file. :param xml_file: path to xml file :type xml_file: str :rtype: declarations tree """ assert self.__config is not None ffname = self.__file_full_name(xml_file) self.logger.debug("Reading xml file: [%s]", xml_file) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug("File has not been found in cache, parsing...") decls, _ = self.__parse_xml_file(ffname) self.__dcache.update(ffname, self.__config, decls, []) else: self.logger.debug( "File has not been changed, reading declarations from cache.") return decls
[ "def", "read_xml_file", "(", "self", ",", "xml_file", ")", ":", "assert", "self", ".", "__config", "is", "not", "None", "ffname", "=", "self", ".", "__file_full_name", "(", "xml_file", ")", "self", ".", "logger", ".", "debug", "(", "\"Reading xml file: [%s]\"", ",", "xml_file", ")", "decls", "=", "self", ".", "__dcache", ".", "cached_value", "(", "ffname", ",", "self", ".", "__config", ")", "if", "not", "decls", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been found in cache, parsing...\"", ")", "decls", ",", "_", "=", "self", ".", "__parse_xml_file", "(", "ffname", ")", "self", ".", "__dcache", ".", "update", "(", "ffname", ",", "self", ".", "__config", ",", "decls", ",", "[", "]", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been changed, reading declarations from cache.\"", ")", "return", "decls" ]
[ 391, 4 ]
[ 415, 20 ]
python
en
['en', 'error', 'th']
False
source_reader_t.read_string
(self, content)
Reads a Python string that contains C++ code, and return the declarations tree.
Reads a Python string that contains C++ code, and return the declarations tree.
def read_string(self, content): """ Reads a Python string that contains C++ code, and return the declarations tree. """ header_file = utils.create_temp_file_name(suffix='.h') with open(header_file, "w+") as f: f.write(content) try: decls = self.read_file(header_file) except Exception: utils.remove_file_no_raise(header_file, self.__config) raise utils.remove_file_no_raise(header_file, self.__config) return decls
[ "def", "read_string", "(", "self", ",", "content", ")", ":", "header_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.h'", ")", "with", "open", "(", "header_file", ",", "\"w+\"", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")", "try", ":", "decls", "=", "self", ".", "read_file", "(", "header_file", ")", "except", "Exception", ":", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "raise", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "return", "decls" ]
[ 417, 4 ]
[ 435, 20 ]
python
en
['en', 'error', 'th']
False
Load
(build_files, format, default_variables={}, includes=[], depth='.', params=None, check=False, circular_check=True, duplicate_basename_check=True)
Loads one or more specified build files. default_variables and includes will be copied before use. Returns the generator for the specified format and the data returned by loading the specified build files.
Loads one or more specified build files. default_variables and includes will be copied before use. Returns the generator for the specified format and the data returned by loading the specified build files.
def Load(build_files, format, default_variables={}, includes=[], depth='.', params=None, check=False, circular_check=True, duplicate_basename_check=True): """ Loads one or more specified build files. default_variables and includes will be copied before use. Returns the generator for the specified format and the data returned by loading the specified build files. """ if params is None: params = {} if '-' in format: format, params['flavor'] = format.split('-', 1) default_variables = copy.copy(default_variables) # Default variables provided by this program and its modules should be # named WITH_CAPITAL_LETTERS to provide a distinct "best practice" namespace, # avoiding collisions with user and automatic variables. default_variables['GENERATOR'] = format default_variables['GENERATOR_FLAVOR'] = params.get('flavor', '') # Format can be a custom python file, or by default the name of a module # within gyp.generator. if format.endswith('.py'): generator_name = os.path.splitext(format)[0] path, generator_name = os.path.split(generator_name) # Make sure the path to the custom generator is in sys.path # Don't worry about removing it once we are done. Keeping the path # to each generator that is used in sys.path is likely harmless and # arguably a good idea. path = os.path.abspath(path) if path not in sys.path: sys.path.insert(0, path) else: generator_name = 'gyp.generator.' + format # These parameters are passed in order (as opposed to by key) # because ActivePython cannot handle key parameters to __import__. generator = __import__(generator_name, globals(), locals(), generator_name) for (key, val) in generator.generator_default_variables.items(): default_variables.setdefault(key, val) # Give the generator the opportunity to set additional variables based on # the params it will receive in the output phase. if getattr(generator, 'CalculateVariables', None): generator.CalculateVariables(default_variables, params) # Give the generator the opportunity to set generator_input_info based on # the params it will receive in the output phase. if getattr(generator, 'CalculateGeneratorInputInfo', None): generator.CalculateGeneratorInputInfo(params) # Fetch the generator specific info that gets fed to input, we use getattr # so we can default things and the generators only have to provide what # they need. generator_input_info = { 'non_configuration_keys': getattr(generator, 'generator_additional_non_configuration_keys', []), 'path_sections': getattr(generator, 'generator_additional_path_sections', []), 'extra_sources_for_rules': getattr(generator, 'generator_extra_sources_for_rules', []), 'generator_supports_multiple_toolsets': getattr(generator, 'generator_supports_multiple_toolsets', False), 'generator_wants_static_library_dependencies_adjusted': getattr(generator, 'generator_wants_static_library_dependencies_adjusted', True), 'generator_wants_sorted_dependencies': getattr(generator, 'generator_wants_sorted_dependencies', False), 'generator_filelist_paths': getattr(generator, 'generator_filelist_paths', None), } # Process the input specific to this generator. result = gyp.input.Load(build_files, default_variables, includes[:], depth, generator_input_info, check, circular_check, duplicate_basename_check, params['parallel'], params['root_targets']) return [generator] + result
[ "def", "Load", "(", "build_files", ",", "format", ",", "default_variables", "=", "{", "}", ",", "includes", "=", "[", "]", ",", "depth", "=", "'.'", ",", "params", "=", "None", ",", "check", "=", "False", ",", "circular_check", "=", "True", ",", "duplicate_basename_check", "=", "True", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "if", "'-'", "in", "format", ":", "format", ",", "params", "[", "'flavor'", "]", "=", "format", ".", "split", "(", "'-'", ",", "1", ")", "default_variables", "=", "copy", ".", "copy", "(", "default_variables", ")", "# Default variables provided by this program and its modules should be", "# named WITH_CAPITAL_LETTERS to provide a distinct \"best practice\" namespace,", "# avoiding collisions with user and automatic variables.", "default_variables", "[", "'GENERATOR'", "]", "=", "format", "default_variables", "[", "'GENERATOR_FLAVOR'", "]", "=", "params", ".", "get", "(", "'flavor'", ",", "''", ")", "# Format can be a custom python file, or by default the name of a module", "# within gyp.generator.", "if", "format", ".", "endswith", "(", "'.py'", ")", ":", "generator_name", "=", "os", ".", "path", ".", "splitext", "(", "format", ")", "[", "0", "]", "path", ",", "generator_name", "=", "os", ".", "path", ".", "split", "(", "generator_name", ")", "# Make sure the path to the custom generator is in sys.path", "# Don't worry about removing it once we are done. Keeping the path", "# to each generator that is used in sys.path is likely harmless and", "# arguably a good idea.", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "else", ":", "generator_name", "=", "'gyp.generator.'", "+", "format", "# These parameters are passed in order (as opposed to by key)", "# because ActivePython cannot handle key parameters to __import__.", "generator", "=", "__import__", "(", "generator_name", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "generator_name", ")", "for", "(", "key", ",", "val", ")", "in", "generator", ".", "generator_default_variables", ".", "items", "(", ")", ":", "default_variables", ".", "setdefault", "(", "key", ",", "val", ")", "# Give the generator the opportunity to set additional variables based on", "# the params it will receive in the output phase.", "if", "getattr", "(", "generator", ",", "'CalculateVariables'", ",", "None", ")", ":", "generator", ".", "CalculateVariables", "(", "default_variables", ",", "params", ")", "# Give the generator the opportunity to set generator_input_info based on", "# the params it will receive in the output phase.", "if", "getattr", "(", "generator", ",", "'CalculateGeneratorInputInfo'", ",", "None", ")", ":", "generator", ".", "CalculateGeneratorInputInfo", "(", "params", ")", "# Fetch the generator specific info that gets fed to input, we use getattr", "# so we can default things and the generators only have to provide what", "# they need.", "generator_input_info", "=", "{", "'non_configuration_keys'", ":", "getattr", "(", "generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", ",", "'path_sections'", ":", "getattr", "(", "generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", ",", "'extra_sources_for_rules'", ":", "getattr", "(", "generator", ",", "'generator_extra_sources_for_rules'", ",", "[", "]", ")", ",", "'generator_supports_multiple_toolsets'", ":", "getattr", "(", "generator", ",", "'generator_supports_multiple_toolsets'", ",", "False", ")", ",", "'generator_wants_static_library_dependencies_adjusted'", ":", "getattr", "(", "generator", ",", "'generator_wants_static_library_dependencies_adjusted'", ",", "True", ")", ",", "'generator_wants_sorted_dependencies'", ":", "getattr", "(", "generator", ",", "'generator_wants_sorted_dependencies'", ",", "False", ")", ",", "'generator_filelist_paths'", ":", "getattr", "(", "generator", ",", "'generator_filelist_paths'", ",", "None", ")", ",", "}", "# Process the input specific to this generator.", "result", "=", "gyp", ".", "input", ".", "Load", "(", "build_files", ",", "default_variables", ",", "includes", "[", ":", "]", ",", "depth", ",", "generator_input_info", ",", "check", ",", "circular_check", ",", "duplicate_basename_check", ",", "params", "[", "'parallel'", "]", ",", "params", "[", "'root_targets'", "]", ")", "return", "[", "generator", "]", "+", "result" ]
[ 49, 0 ]
[ 130, 29 ]
python
en
['en', 'error', 'th']
False
NameValueListToDict
(name_value_list)
Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is.
Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is.
def NameValueListToDict(name_value_list): """ Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is. """ result = { } for item in name_value_list: tokens = item.split('=', 1) if len(tokens) == 2: # If we can make it an int, use that, otherwise, use the string. try: token_value = int(tokens[1]) except ValueError: token_value = tokens[1] # Set the variable to the supplied value. result[tokens[0]] = token_value else: # No value supplied, treat it as a boolean and set it. result[tokens[0]] = True return result
[ "def", "NameValueListToDict", "(", "name_value_list", ")", ":", "result", "=", "{", "}", "for", "item", "in", "name_value_list", ":", "tokens", "=", "item", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "tokens", ")", "==", "2", ":", "# If we can make it an int, use that, otherwise, use the string.", "try", ":", "token_value", "=", "int", "(", "tokens", "[", "1", "]", ")", "except", "ValueError", ":", "token_value", "=", "tokens", "[", "1", "]", "# Set the variable to the supplied value.", "result", "[", "tokens", "[", "0", "]", "]", "=", "token_value", "else", ":", "# No value supplied, treat it as a boolean and set it.", "result", "[", "tokens", "[", "0", "]", "]", "=", "True", "return", "result" ]
[ 132, 0 ]
[ 152, 15 ]
python
en
['en', 'error', 'th']
False
RegenerateAppendFlag
(flag, values, predicate, env_name, options)
Regenerate a list of command line flags, for an option of action='append'. The |env_name|, if given, is checked in the environment and used to generate an initial list of options, then the options that were specified on the command line (given in |values|) are appended. This matches the handling of environment variables and command line flags where command line flags override the environment, while not requiring the environment to be set when the flags are used again.
Regenerate a list of command line flags, for an option of action='append'.
def RegenerateAppendFlag(flag, values, predicate, env_name, options): """Regenerate a list of command line flags, for an option of action='append'. The |env_name|, if given, is checked in the environment and used to generate an initial list of options, then the options that were specified on the command line (given in |values|) are appended. This matches the handling of environment variables and command line flags where command line flags override the environment, while not requiring the environment to be set when the flags are used again. """ flags = [] if options.use_environment and env_name: for flag_value in ShlexEnv(env_name): value = FormatOpt(flag, predicate(flag_value)) if value in flags: flags.remove(value) flags.append(value) if values: for flag_value in values: flags.append(FormatOpt(flag, predicate(flag_value))) return flags
[ "def", "RegenerateAppendFlag", "(", "flag", ",", "values", ",", "predicate", ",", "env_name", ",", "options", ")", ":", "flags", "=", "[", "]", "if", "options", ".", "use_environment", "and", "env_name", ":", "for", "flag_value", "in", "ShlexEnv", "(", "env_name", ")", ":", "value", "=", "FormatOpt", "(", "flag", ",", "predicate", "(", "flag_value", ")", ")", "if", "value", "in", "flags", ":", "flags", ".", "remove", "(", "value", ")", "flags", ".", "append", "(", "value", ")", "if", "values", ":", "for", "flag_value", "in", "values", ":", "flags", ".", "append", "(", "FormatOpt", "(", "flag", ",", "predicate", "(", "flag_value", ")", ")", ")", "return", "flags" ]
[ 165, 0 ]
[ 185, 14 ]
python
en
['en', 'en', 'en']
True
RegenerateFlags
(options)
Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate.
Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.)
def RegenerateFlags(options): """Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate. """ def FixPath(path): path = gyp.common.FixIfRelativePath(path, options.depth) if not path: return os.path.curdir return path def Noop(value): return value # We always want to ignore the environment when regenerating, to avoid # duplicate or changed flags in the environment at the time of regeneration. flags = ['--ignore-environment'] for name, metadata in options._regeneration_metadata.iteritems(): opt = metadata['opt'] value = getattr(options, name) value_predicate = metadata['type'] == 'path' and FixPath or Noop action = metadata['action'] env_name = metadata['env_name'] if action == 'append': flags.extend(RegenerateAppendFlag(opt, value, value_predicate, env_name, options)) elif action in ('store', None): # None is a synonym for 'store'. if value: flags.append(FormatOpt(opt, value_predicate(value))) elif options.use_environment and env_name and os.environ.get(env_name): flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name)))) elif action in ('store_true', 'store_false'): if ((action == 'store_true' and value) or (action == 'store_false' and not value)): flags.append(opt) elif options.use_environment and env_name: print >>sys.stderr, ('Warning: environment regeneration unimplemented ' 'for %s flag %r env_name %r' % (action, opt, env_name)) else: print >>sys.stderr, ('Warning: regeneration unimplemented for action %r ' 'flag %r' % (action, opt)) return flags
[ "def", "RegenerateFlags", "(", "options", ")", ":", "def", "FixPath", "(", "path", ")", ":", "path", "=", "gyp", ".", "common", ".", "FixIfRelativePath", "(", "path", ",", "options", ".", "depth", ")", "if", "not", "path", ":", "return", "os", ".", "path", ".", "curdir", "return", "path", "def", "Noop", "(", "value", ")", ":", "return", "value", "# We always want to ignore the environment when regenerating, to avoid", "# duplicate or changed flags in the environment at the time of regeneration.", "flags", "=", "[", "'--ignore-environment'", "]", "for", "name", ",", "metadata", "in", "options", ".", "_regeneration_metadata", ".", "iteritems", "(", ")", ":", "opt", "=", "metadata", "[", "'opt'", "]", "value", "=", "getattr", "(", "options", ",", "name", ")", "value_predicate", "=", "metadata", "[", "'type'", "]", "==", "'path'", "and", "FixPath", "or", "Noop", "action", "=", "metadata", "[", "'action'", "]", "env_name", "=", "metadata", "[", "'env_name'", "]", "if", "action", "==", "'append'", ":", "flags", ".", "extend", "(", "RegenerateAppendFlag", "(", "opt", ",", "value", ",", "value_predicate", ",", "env_name", ",", "options", ")", ")", "elif", "action", "in", "(", "'store'", ",", "None", ")", ":", "# None is a synonym for 'store'.", "if", "value", ":", "flags", ".", "append", "(", "FormatOpt", "(", "opt", ",", "value_predicate", "(", "value", ")", ")", ")", "elif", "options", ".", "use_environment", "and", "env_name", "and", "os", ".", "environ", ".", "get", "(", "env_name", ")", ":", "flags", ".", "append", "(", "FormatOpt", "(", "opt", ",", "value_predicate", "(", "os", ".", "environ", ".", "get", "(", "env_name", ")", ")", ")", ")", "elif", "action", "in", "(", "'store_true'", ",", "'store_false'", ")", ":", "if", "(", "(", "action", "==", "'store_true'", "and", "value", ")", "or", "(", "action", "==", "'store_false'", "and", "not", "value", ")", ")", ":", "flags", ".", "append", "(", "opt", ")", "elif", "options", ".", "use_environment", "and", "env_name", ":", "print", ">>", "sys", ".", "stderr", ",", "(", "'Warning: environment regeneration unimplemented '", "'for %s flag %r env_name %r'", "%", "(", "action", ",", "opt", ",", "env_name", ")", ")", "else", ":", "print", ">>", "sys", ".", "stderr", ",", "(", "'Warning: regeneration unimplemented for action %r '", "'flag %r'", "%", "(", "action", ",", "opt", ")", ")", "return", "flags" ]
[ 187, 0 ]
[ 235, 14 ]
python
en
['en', 'en', 'en']
True
RegeneratableOptionParser.add_option
(self, *args, **kw)
Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth
Add an option to the parser.
def add_option(self, *args, **kw): """Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth """ env_name = kw.pop('env_name', None) if 'dest' in kw and kw.pop('regenerate', True): dest = kw['dest'] # The path type is needed for regenerating, for optparse we can just treat # it as a string. type = kw.get('type') if type == 'path': kw['type'] = 'string' self.__regeneratable_options[dest] = { 'action': kw.get('action'), 'type': type, 'env_name': env_name, 'opt': args[0], } optparse.OptionParser.add_option(self, *args, **kw)
[ "def", "add_option", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "env_name", "=", "kw", ".", "pop", "(", "'env_name'", ",", "None", ")", "if", "'dest'", "in", "kw", "and", "kw", ".", "pop", "(", "'regenerate'", ",", "True", ")", ":", "dest", "=", "kw", "[", "'dest'", "]", "# The path type is needed for regenerating, for optparse we can just treat", "# it as a string.", "type", "=", "kw", ".", "get", "(", "'type'", ")", "if", "type", "==", "'path'", ":", "kw", "[", "'type'", "]", "=", "'string'", "self", ".", "__regeneratable_options", "[", "dest", "]", "=", "{", "'action'", ":", "kw", ".", "get", "(", "'action'", ")", ",", "'type'", ":", "type", ",", "'env_name'", ":", "env_name", ",", "'opt'", ":", "args", "[", "0", "]", ",", "}", "optparse", ".", "OptionParser", ".", "add_option", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")" ]
[ 242, 2 ]
[ 271, 55 ]
python
en
['en', 'en', 'en']
True
aws_credentials
()
Mocked AWS Credentials for moto.
Mocked AWS Credentials for moto.
def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ["AWS_ACCESS_KEY_ID"] = "testing" os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" os.environ["AWS_SECURITY_TOKEN"] = "testing" os.environ["AWS_SESSION_TOKEN"] = "testing"
[ "def", "aws_credentials", "(", ")", ":", "os", ".", "environ", "[", "\"AWS_ACCESS_KEY_ID\"", "]", "=", "\"testing\"", "os", ".", "environ", "[", "\"AWS_SECRET_ACCESS_KEY\"", "]", "=", "\"testing\"", "os", ".", "environ", "[", "\"AWS_SECURITY_TOKEN\"", "]", "=", "\"testing\"", "os", ".", "environ", "[", "\"AWS_SESSION_TOKEN\"", "]", "=", "\"testing\"" ]
[ 335, 0 ]
[ 340, 47 ]
python
en
['en', 'en', 'en']
True
LatexFormatter.get_style_defs
(self, arg='')
Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored.
Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored.
def get_style_defs(self, arg=''): """ Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored. """ cp = self.commandprefix styles = [] for name, definition in iteritems(self.cmd2def): styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % (cp, name, definition)) return STYLE_TEMPLATE % {'cp': self.commandprefix, 'styles': '\n'.join(styles)}
[ "def", "get_style_defs", "(", "self", ",", "arg", "=", "''", ")", ":", "cp", "=", "self", ".", "commandprefix", "styles", "=", "[", "]", "for", "name", ",", "definition", "in", "iteritems", "(", "self", ".", "cmd2def", ")", ":", "styles", ".", "append", "(", "r'\\expandafter\\def\\csname %s@tok@%s\\endcsname{%s}'", "%", "(", "cp", ",", "name", ",", "definition", ")", ")", "return", "STYLE_TEMPLATE", "%", "{", "'cp'", ":", "self", ".", "commandprefix", ",", "'styles'", ":", "'\\n'", ".", "join", "(", "styles", ")", "}" ]
[ 317, 4 ]
[ 328, 61 ]
python
en
['en', 'error', 'th']
False
lone_object_filter
(image, min_size=2, connectivity=1, kernel_size=3)
Replaces isolated, contiguous regions of values in a raster with values representing the surrounding pixels. More specifically, this reduces noise in a raster by setting contiguous regions of values greater than a specified minimum size to the modal value in a specified neighborhood. The default argument values filter out lone, singular pixels. This filter is not idempotent, so it may need to be applied repeatedly until the output stops changing or the results are acceptable. Args: image (numpy.ndarray): The image to filter. Must not contain NaNs. min_size (int): Defines the minimum number of contiguous pixels that will not be set to the modal value of their neighborhood. Must be greater than 2. Setting this to 1 is pointless, since this function will then do nothing to the raster. connectivity (int): The maximum distance between any two pixels such that they are considered one group. For example, a connectivity of 1 considers only adjacent values to be within one group, but a connectivity of 2 also considers diagonally connected values to be within one group. Must be greater than 0. kernel_size (int or float): The diameter of the circular kernel to use for the modal filter. If there are still contiguous regions of pixels that should be set to the modal value of their neighborhood, increase this value to remove them. This parameter generally should scale roughly with the square root of the `min_size` parameter. Note that the larger this value is, the more detail may be lost in the image and the slower this function will run. Returns: The filtered image. Authors: Andrew Lubawy ([email protected])\n John Rattz ([email protected])
Replaces isolated, contiguous regions of values in a raster with values representing the surrounding pixels.
def lone_object_filter(image, min_size=2, connectivity=1, kernel_size=3): """ Replaces isolated, contiguous regions of values in a raster with values representing the surrounding pixels. More specifically, this reduces noise in a raster by setting contiguous regions of values greater than a specified minimum size to the modal value in a specified neighborhood. The default argument values filter out lone, singular pixels. This filter is not idempotent, so it may need to be applied repeatedly until the output stops changing or the results are acceptable. Args: image (numpy.ndarray): The image to filter. Must not contain NaNs. min_size (int): Defines the minimum number of contiguous pixels that will not be set to the modal value of their neighborhood. Must be greater than 2. Setting this to 1 is pointless, since this function will then do nothing to the raster. connectivity (int): The maximum distance between any two pixels such that they are considered one group. For example, a connectivity of 1 considers only adjacent values to be within one group, but a connectivity of 2 also considers diagonally connected values to be within one group. Must be greater than 0. kernel_size (int or float): The diameter of the circular kernel to use for the modal filter. If there are still contiguous regions of pixels that should be set to the modal value of their neighborhood, increase this value to remove them. This parameter generally should scale roughly with the square root of the `min_size` parameter. Note that the larger this value is, the more detail may be lost in the image and the slower this function will run. Returns: The filtered image. Authors: Andrew Lubawy ([email protected])\n John Rattz ([email protected]) """ assert kernel_size % 2 == 1, "The parameter `kernel_size` must be an odd number." image_min, image_max = image.min(), image.max() image_dtype = image.dtype image = np.interp(image, [image_min, image_max], [0,255]).astype(np.uint8) modal_filtered = modal(image, create_circular_mask(kernel_size, kernel_size)) da = xr.DataArray(image) for i, val in enumerate(np.unique(image)): # Determine the pixels with this value that will be not be filtered (True to keep). layer = remove_small_objects(image == val, min_size=min_size, connectivity=connectivity) # Select the values from the image that will remain (filter it). filtered = da.where(layer) if i == 0 else filtered.combine_first(da.where(layer)) # Fill in the removed values with their local modes. filtered_nan_mask = np.isnan(filtered.values) filtered.values[filtered_nan_mask] = modal_filtered[filtered_nan_mask] filtered.values = np.interp(filtered.values, [0,255], [image_min, image_max]).astype(image_dtype) return filtered.values
[ "def", "lone_object_filter", "(", "image", ",", "min_size", "=", "2", ",", "connectivity", "=", "1", ",", "kernel_size", "=", "3", ")", ":", "assert", "kernel_size", "%", "2", "==", "1", ",", "\"The parameter `kernel_size` must be an odd number.\"", "image_min", ",", "image_max", "=", "image", ".", "min", "(", ")", ",", "image", ".", "max", "(", ")", "image_dtype", "=", "image", ".", "dtype", "image", "=", "np", ".", "interp", "(", "image", ",", "[", "image_min", ",", "image_max", "]", ",", "[", "0", ",", "255", "]", ")", ".", "astype", "(", "np", ".", "uint8", ")", "modal_filtered", "=", "modal", "(", "image", ",", "create_circular_mask", "(", "kernel_size", ",", "kernel_size", ")", ")", "da", "=", "xr", ".", "DataArray", "(", "image", ")", "for", "i", ",", "val", "in", "enumerate", "(", "np", ".", "unique", "(", "image", ")", ")", ":", "# Determine the pixels with this value that will be not be filtered (True to keep).", "layer", "=", "remove_small_objects", "(", "image", "==", "val", ",", "min_size", "=", "min_size", ",", "connectivity", "=", "connectivity", ")", "# Select the values from the image that will remain (filter it).", "filtered", "=", "da", ".", "where", "(", "layer", ")", "if", "i", "==", "0", "else", "filtered", ".", "combine_first", "(", "da", ".", "where", "(", "layer", ")", ")", "# Fill in the removed values with their local modes.", "filtered_nan_mask", "=", "np", ".", "isnan", "(", "filtered", ".", "values", ")", "filtered", ".", "values", "[", "filtered_nan_mask", "]", "=", "modal_filtered", "[", "filtered_nan_mask", "]", "filtered", ".", "values", "=", "np", ".", "interp", "(", "filtered", ".", "values", ",", "[", "0", ",", "255", "]", ",", "[", "image_min", ",", "image_max", "]", ")", ".", "astype", "(", "image_dtype", ")", "return", "filtered", ".", "values" ]
[ 9, 0 ]
[ 66, 26 ]
python
en
['en', 'error', 'th']
False
apply_filter
(statistic, filter_output, padded_arr, filter_shape)
Creates a mean, median, or standard deviation filtered version of an `xarray.DataArray`. Parameters ---------- filter_output: xarray.DataArray The `xarray.DataArray` to store the filtered values in. Must contain the values to filter. This object is modified.** statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. padded_arr: numpy.ndarray A NumPy array with a shape matching `filter_output` padded for `filter_shape`. filter_shape: list-like of int A list-like of 2 positive integers defining the shape of the filter kernel.
Creates a mean, median, or standard deviation filtered version of an `xarray.DataArray`.
def apply_filter(statistic, filter_output, padded_arr, filter_shape): """ Creates a mean, median, or standard deviation filtered version of an `xarray.DataArray`. Parameters ---------- filter_output: xarray.DataArray The `xarray.DataArray` to store the filtered values in. Must contain the values to filter. This object is modified.** statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. padded_arr: numpy.ndarray A NumPy array with a shape matching `filter_output` padded for `filter_shape`. filter_shape: list-like of int A list-like of 2 positive integers defining the shape of the filter kernel. """ # For each point in the first two dimensions of `dataarray`... for i in range(filter_output.shape[0]): for j in range(filter_output.shape[1]): padded_arr_segment = padded_arr[i:i + filter_shape[0], j:j + filter_shape[1]] if statistic == 'mean': filter_output.values[i, j] = np.nanmean(padded_arr_segment) elif statistic == 'median': filter_output.values[i, j] = np.nanmedian(padded_arr_segment) elif statistic == 'std': filter_output.values[i, j] = np.nanstd(padded_arr_segment) return filter_output
[ "def", "apply_filter", "(", "statistic", ",", "filter_output", ",", "padded_arr", ",", "filter_shape", ")", ":", "# For each point in the first two dimensions of `dataarray`...", "for", "i", "in", "range", "(", "filter_output", ".", "shape", "[", "0", "]", ")", ":", "for", "j", "in", "range", "(", "filter_output", ".", "shape", "[", "1", "]", ")", ":", "padded_arr_segment", "=", "padded_arr", "[", "i", ":", "i", "+", "filter_shape", "[", "0", "]", ",", "j", ":", "j", "+", "filter_shape", "[", "1", "]", "]", "if", "statistic", "==", "'mean'", ":", "filter_output", ".", "values", "[", "i", ",", "j", "]", "=", "np", ".", "nanmean", "(", "padded_arr_segment", ")", "elif", "statistic", "==", "'median'", ":", "filter_output", ".", "values", "[", "i", ",", "j", "]", "=", "np", ".", "nanmedian", "(", "padded_arr_segment", ")", "elif", "statistic", "==", "'std'", ":", "filter_output", ".", "values", "[", "i", ",", "j", "]", "=", "np", ".", "nanstd", "(", "padded_arr_segment", ")", "return", "filter_output" ]
[ 72, 0 ]
[ 102, 24 ]
python
en
['en', 'error', 'th']
False
stats_filter_3d_composite_2d
(dataarray, statistic, filter_size=1, time_dim='time')
Returns a mean, median, or standard deviation filter composite of a 3D `xarray.DataArray` with a time dimension. This makes a 2D composite of a 3D array by stretching the filter kernel across time. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs. Parameters ---------- dataarray: xarray.DataArray The data to create a filtered version of. Must have 3 dimensions, with the last being 'time'. statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. filter_size: int The size of the filter to use. Must be positive and should be odd. The filter shape will be `(filter_size, filter_size)`. time_dim: str The string name of the time dimension.
Returns a mean, median, or standard deviation filter composite of a 3D `xarray.DataArray` with a time dimension. This makes a 2D composite of a 3D array by stretching the filter kernel across time. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs.
def stats_filter_3d_composite_2d(dataarray, statistic, filter_size=1, time_dim='time'): """ Returns a mean, median, or standard deviation filter composite of a 3D `xarray.DataArray` with a time dimension. This makes a 2D composite of a 3D array by stretching the filter kernel across time. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs. Parameters ---------- dataarray: xarray.DataArray The data to create a filtered version of. Must have 3 dimensions, with the last being 'time'. statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. filter_size: int The size of the filter to use. Must be positive and should be odd. The filter shape will be `(filter_size, filter_size)`. time_dim: str The string name of the time dimension. """ time_ax_num = dataarray.get_axis_num(time_dim) dataarray_non_time_dims = np.concatenate((np.arange(time_ax_num), np.arange(time_ax_num + 1, len(dataarray.dims)))) filter_dims = np.array(dataarray.dims)[dataarray_non_time_dims] filter_coords = {dim: dataarray.coords[dim] for dim in filter_dims} filter_output = xr.DataArray(np.full(np.array(dataarray.shape)[dataarray_non_time_dims], np.nan), coords=filter_coords, dims=filter_dims) if filter_size == 1: agg_func_kwargs = dict(a=dataarray.values, axis=time_ax_num) if statistic == 'mean': filter_output.values[:] = np.nanmean(**agg_func_kwargs) elif statistic == 'median': filter_output.values[:] = np.nanmedian(**agg_func_kwargs) elif statistic == 'std': filter_output.values[:] = np.nanstd(**agg_func_kwargs) else: # Allocate a Numpy array containing the content of `dataarray`, but padded # with NaNs to ensure the statistics are correct at the x and y extremities of the data. flt_shp = np.array((filter_size, filter_size)) shp = np.array(dataarray.shape)[dataarray_non_time_dims] pad_shp = (*(shp + flt_shp - 1), dataarray.shape[time_ax_num]) padding = (flt_shp - 1) // 2 # The number of NaNs from an edge of the padding to the data. padded_arr = np.full(pad_shp, np.nan) padded_arr[padding[0]:pad_shp[0] - padding[0], padding[1]:pad_shp[1] - padding[1]] = dataarray.values filter_output = apply_filter(statistic, filter_output, padded_arr, flt_shp) return filter_output
[ "def", "stats_filter_3d_composite_2d", "(", "dataarray", ",", "statistic", ",", "filter_size", "=", "1", ",", "time_dim", "=", "'time'", ")", ":", "time_ax_num", "=", "dataarray", ".", "get_axis_num", "(", "time_dim", ")", "dataarray_non_time_dims", "=", "np", ".", "concatenate", "(", "(", "np", ".", "arange", "(", "time_ax_num", ")", ",", "np", ".", "arange", "(", "time_ax_num", "+", "1", ",", "len", "(", "dataarray", ".", "dims", ")", ")", ")", ")", "filter_dims", "=", "np", ".", "array", "(", "dataarray", ".", "dims", ")", "[", "dataarray_non_time_dims", "]", "filter_coords", "=", "{", "dim", ":", "dataarray", ".", "coords", "[", "dim", "]", "for", "dim", "in", "filter_dims", "}", "filter_output", "=", "xr", ".", "DataArray", "(", "np", ".", "full", "(", "np", ".", "array", "(", "dataarray", ".", "shape", ")", "[", "dataarray_non_time_dims", "]", ",", "np", ".", "nan", ")", ",", "coords", "=", "filter_coords", ",", "dims", "=", "filter_dims", ")", "if", "filter_size", "==", "1", ":", "agg_func_kwargs", "=", "dict", "(", "a", "=", "dataarray", ".", "values", ",", "axis", "=", "time_ax_num", ")", "if", "statistic", "==", "'mean'", ":", "filter_output", ".", "values", "[", ":", "]", "=", "np", ".", "nanmean", "(", "*", "*", "agg_func_kwargs", ")", "elif", "statistic", "==", "'median'", ":", "filter_output", ".", "values", "[", ":", "]", "=", "np", ".", "nanmedian", "(", "*", "*", "agg_func_kwargs", ")", "elif", "statistic", "==", "'std'", ":", "filter_output", ".", "values", "[", ":", "]", "=", "np", ".", "nanstd", "(", "*", "*", "agg_func_kwargs", ")", "else", ":", "# Allocate a Numpy array containing the content of `dataarray`, but padded", "# with NaNs to ensure the statistics are correct at the x and y extremities of the data.", "flt_shp", "=", "np", ".", "array", "(", "(", "filter_size", ",", "filter_size", ")", ")", "shp", "=", "np", ".", "array", "(", "dataarray", ".", "shape", ")", "[", "dataarray_non_time_dims", "]", "pad_shp", "=", "(", "*", "(", "shp", "+", "flt_shp", "-", "1", ")", ",", "dataarray", ".", "shape", "[", "time_ax_num", "]", ")", "padding", "=", "(", "flt_shp", "-", "1", ")", "//", "2", "# The number of NaNs from an edge of the padding to the data.", "padded_arr", "=", "np", ".", "full", "(", "pad_shp", ",", "np", ".", "nan", ")", "padded_arr", "[", "padding", "[", "0", "]", ":", "pad_shp", "[", "0", "]", "-", "padding", "[", "0", "]", ",", "padding", "[", "1", "]", ":", "pad_shp", "[", "1", "]", "-", "padding", "[", "1", "]", "]", "=", "dataarray", ".", "values", "filter_output", "=", "apply_filter", "(", "statistic", ",", "filter_output", ",", "padded_arr", ",", "flt_shp", ")", "return", "filter_output" ]
[ 105, 0 ]
[ 158, 24 ]
python
en
['en', 'error', 'th']
False
stats_filter_2d
(dataarray, statistic, filter_size=3)
Returns a mean, median, or standard deviation filter of a 2D `xarray.DataArray`. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs. Parameters ---------- dataarray: xarray.DataArray The data to create a filtered version of. Must have 2 dimensions. statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. filter_size: int The size of the filter to use. Must be positive and should be odd. The filter shape will be `(filter_size, filter_size)`.
Returns a mean, median, or standard deviation filter of a 2D `xarray.DataArray`. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs.
def stats_filter_2d(dataarray, statistic, filter_size=3): """ Returns a mean, median, or standard deviation filter of a 2D `xarray.DataArray`. This function is more accurate than using SciPy or scikit-image methods, because those don't handle the extremities ideally (edges and corners). Specifically, only values actually inside the filter should be considered, so the data is padded with NaNs when "convolving" `dataarray` with an equally-weighted, rectangular kernel of shape `(filter_size, filter_size)`. This function is resilient to NaNs. Parameters ---------- dataarray: xarray.DataArray The data to create a filtered version of. Must have 2 dimensions. statistic: string The name of the statistic to use for the filter. The possible values are ['mean', 'median', 'std']. filter_size: int The size of the filter to use. Must be positive and should be odd. The filter shape will be `(filter_size, filter_size)`. """ if filter_size == 1: return dataarray filter_output = dataarray.copy() kernel = np.ones((filter_size, filter_size)) if statistic == 'mean': filter_output.values[:] = scipy.signal.convolve2d(filter_output.values, kernel, mode="same") / kernel.size elif statistic == 'median': filter_output.values[:] = scipy.ndimage.median_filter(filter_output.values, footprint=kernel) elif statistic == 'std': # Calculate standard deviation as stddev(X) = sqrt(E(X^2) - E(X)^2). im = dataarray.values im2 = im ** 2 ones = np.ones(im.shape) s = scipy.signal.convolve2d(im, kernel, mode="same") s2 = scipy.signal.convolve2d(im2, kernel, mode="same") ns = scipy.signal.convolve2d(ones, kernel, mode="same") filter_output.values[:] = np.sqrt((s2 - s ** 2 / ns) / ns) return filter_output
[ "def", "stats_filter_2d", "(", "dataarray", ",", "statistic", ",", "filter_size", "=", "3", ")", ":", "if", "filter_size", "==", "1", ":", "return", "dataarray", "filter_output", "=", "dataarray", ".", "copy", "(", ")", "kernel", "=", "np", ".", "ones", "(", "(", "filter_size", ",", "filter_size", ")", ")", "if", "statistic", "==", "'mean'", ":", "filter_output", ".", "values", "[", ":", "]", "=", "scipy", ".", "signal", ".", "convolve2d", "(", "filter_output", ".", "values", ",", "kernel", ",", "mode", "=", "\"same\"", ")", "/", "kernel", ".", "size", "elif", "statistic", "==", "'median'", ":", "filter_output", ".", "values", "[", ":", "]", "=", "scipy", ".", "ndimage", ".", "median_filter", "(", "filter_output", ".", "values", ",", "footprint", "=", "kernel", ")", "elif", "statistic", "==", "'std'", ":", "# Calculate standard deviation as stddev(X) = sqrt(E(X^2) - E(X)^2).", "im", "=", "dataarray", ".", "values", "im2", "=", "im", "**", "2", "ones", "=", "np", ".", "ones", "(", "im", ".", "shape", ")", "s", "=", "scipy", ".", "signal", ".", "convolve2d", "(", "im", ",", "kernel", ",", "mode", "=", "\"same\"", ")", "s2", "=", "scipy", ".", "signal", ".", "convolve2d", "(", "im2", ",", "kernel", ",", "mode", "=", "\"same\"", ")", "ns", "=", "scipy", ".", "signal", ".", "convolve2d", "(", "ones", ",", "kernel", ",", "mode", "=", "\"same\"", ")", "filter_output", ".", "values", "[", ":", "]", "=", "np", ".", "sqrt", "(", "(", "s2", "-", "s", "**", "2", "/", "ns", ")", "/", "ns", ")", "return", "filter_output" ]
[ 161, 0 ]
[ 201, 24 ]
python
en
['en', 'error', 'th']
False
AdminSiteTests.test_users_listed
(self)
Test that users are listed on user page
Test that users are listed on user page
def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email)
[ "def", "test_users_listed", "(", "self", ")", ":", "url", "=", "reverse", "(", "'admin:core_user_changelist'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "url", ")", "self", ".", "assertContains", "(", "res", ",", "self", ".", "user", ".", "name", ")", "self", ".", "assertContains", "(", "res", ",", "self", ".", "user", ".", "email", ")" ]
[ 20, 4 ]
[ 26, 49 ]
python
en
['en', 'en', 'en']
True
AdminSiteTests.test_user_change_page
(self)
Test that the user edit page works
Test that the user edit page works
def test_user_change_page(self): """Test that the user edit page works""" url = reverse('admin:core_user_change', args=[self.user.id]) res = self.client.get(url) self.assertEqual(res.status_code, 200)
[ "def", "test_user_change_page", "(", "self", ")", ":", "url", "=", "reverse", "(", "'admin:core_user_change'", ",", "args", "=", "[", "self", ".", "user", ".", "id", "]", ")", "res", "=", "self", ".", "client", ".", "get", "(", "url", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "200", ")" ]
[ 28, 4 ]
[ 33, 46 ]
python
en
['en', 'en', 'en']
True
AdminSiteTests.test_create_user_page
(self)
Test that the create user page works
Test that the create user page works
def test_create_user_page(self): """Test that the create user page works""" url = reverse('admin:core_user_add') res = self.client.get(url) self.assertEqual(res.status_code, 200)
[ "def", "test_create_user_page", "(", "self", ")", ":", "url", "=", "reverse", "(", "'admin:core_user_add'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "url", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "200", ")" ]
[ 35, 4 ]
[ 40, 46 ]
python
en
['en', 'en', 'en']
True
TeamcityServiceMessages.testStarted
(self, testName, captureStandardOutput=None, flowId=None, metainfo=None)
:param metainfo: Used to pass any payload from test runner to Intellij. See IDEA-176950
def testStarted(self, testName, captureStandardOutput=None, flowId=None, metainfo=None): """ :param metainfo: Used to pass any payload from test runner to Intellij. See IDEA-176950 """ self.message('testStarted', name=testName, captureStandardOutput=captureStandardOutput, flowId=flowId, metainfo=metainfo)
[ "def", "testStarted", "(", "self", ",", "testName", ",", "captureStandardOutput", "=", "None", ",", "flowId", "=", "None", ",", "metainfo", "=", "None", ")", ":", "self", ".", "message", "(", "'testStarted'", ",", "name", "=", "testName", ",", "captureStandardOutput", "=", "captureStandardOutput", ",", "flowId", "=", "flowId", ",", "metainfo", "=", "metainfo", ")" ]
[ 144, 4 ]
[ 149, 129 ]
python
en
['en', 'error', 'th']
False
_library_not_loaded_test
( tmp_path_factory, cli_input, library_name, library_import_name, my_caplog, monkeypatch, )
This test requires that a library is NOT installed. It tests that: - a helpful error message is returned to install the missing library - the expected tree structure is in place - the config yml contains an empty dict in its datasource entry
This test requires that a library is NOT installed. It tests that: - a helpful error message is returned to install the missing library - the expected tree structure is in place - the config yml contains an empty dict in its datasource entry
def _library_not_loaded_test( tmp_path_factory, cli_input, library_name, library_import_name, my_caplog, monkeypatch, ): """ This test requires that a library is NOT installed. It tests that: - a helpful error message is returned to install the missing library - the expected tree structure is in place - the config yml contains an empty dict in its datasource entry """ basedir = tmp_path_factory.mktemp("test_cli_init_diff") runner = CliRunner(mix_stderr=False) monkeypatch.chdir(basedir) result = runner.invoke( cli, ["--v3-api", "init", "--no-view"], input=cli_input, catch_exceptions=False ) stdout = result.output print(stdout) assert "Always know what to expect from your data" in stdout assert "What data would you like Great Expectations to connect to" in stdout assert "Which database backend are you using" in stdout assert "Give your new Datasource a short name" in stdout assert ( """Next, we will configure database credentials and store them in the `my_db` section of this config file: great_expectations/uncommitted/config_variables.yml""" in stdout ) assert ( f"""Great Expectations relies on the library `{library_import_name}` to connect to your data, \ but the package `{library_name}` containing this library is not installed. Would you like Great Expectations to try to execute `pip install {library_name}` for you?""" in stdout ) assert ( f"""\nOK, exiting now. - Please execute `pip install {library_name}` before trying again.""" in stdout ) assert "Profiling" not in stdout assert "Building" not in stdout assert "Data Docs" not in stdout assert "Great Expectations is now set up" not in stdout assert result.exit_code == 1 assert os.path.isdir(os.path.join(basedir, "great_expectations")) config_path = os.path.join(basedir, "great_expectations/great_expectations.yml") assert os.path.isfile(config_path) config = yaml.load(open(config_path)) assert config["datasources"] == dict() obs_tree = gen_directory_tree_str(os.path.join(basedir, "great_expectations")) assert ( obs_tree == """\ great_expectations/ .gitignore great_expectations.yml checkpoints/ expectations/ .ge_store_backend_id notebooks/ pandas/ validation_playground.ipynb spark/ validation_playground.ipynb sql/ validation_playground.ipynb plugins/ custom_data_docs/ renderers/ styles/ data_docs_custom_styles.css views/ uncommitted/ config_variables.yml data_docs/ validations/ .ge_store_backend_id """ ) assert_no_logging_messages_or_tracebacks(my_caplog, result)
[ "def", "_library_not_loaded_test", "(", "tmp_path_factory", ",", "cli_input", ",", "library_name", ",", "library_import_name", ",", "my_caplog", ",", "monkeypatch", ",", ")", ":", "basedir", "=", "tmp_path_factory", ".", "mktemp", "(", "\"test_cli_init_diff\"", ")", "runner", "=", "CliRunner", "(", "mix_stderr", "=", "False", ")", "monkeypatch", ".", "chdir", "(", "basedir", ")", "result", "=", "runner", ".", "invoke", "(", "cli", ",", "[", "\"--v3-api\"", ",", "\"init\"", ",", "\"--no-view\"", "]", ",", "input", "=", "cli_input", ",", "catch_exceptions", "=", "False", ")", "stdout", "=", "result", ".", "output", "print", "(", "stdout", ")", "assert", "\"Always know what to expect from your data\"", "in", "stdout", "assert", "\"What data would you like Great Expectations to connect to\"", "in", "stdout", "assert", "\"Which database backend are you using\"", "in", "stdout", "assert", "\"Give your new Datasource a short name\"", "in", "stdout", "assert", "(", "\"\"\"Next, we will configure database credentials and store them in the `my_db` section\nof this config file: great_expectations/uncommitted/config_variables.yml\"\"\"", "in", "stdout", ")", "assert", "(", "f\"\"\"Great Expectations relies on the library `{library_import_name}` to connect to your data, \\\nbut the package `{library_name}` containing this library is not installed.\n Would you like Great Expectations to try to execute `pip install {library_name}` for you?\"\"\"", "in", "stdout", ")", "assert", "(", "f\"\"\"\\nOK, exiting now.\n - Please execute `pip install {library_name}` before trying again.\"\"\"", "in", "stdout", ")", "assert", "\"Profiling\"", "not", "in", "stdout", "assert", "\"Building\"", "not", "in", "stdout", "assert", "\"Data Docs\"", "not", "in", "stdout", "assert", "\"Great Expectations is now set up\"", "not", "in", "stdout", "assert", "result", ".", "exit_code", "==", "1", "assert", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "basedir", ",", "\"great_expectations\"", ")", ")", "config_path", "=", "os", ".", "path", ".", "join", "(", "basedir", ",", "\"great_expectations/great_expectations.yml\"", ")", "assert", "os", ".", "path", ".", "isfile", "(", "config_path", ")", "config", "=", "yaml", ".", "load", "(", "open", "(", "config_path", ")", ")", "assert", "config", "[", "\"datasources\"", "]", "==", "dict", "(", ")", "obs_tree", "=", "gen_directory_tree_str", "(", "os", ".", "path", ".", "join", "(", "basedir", ",", "\"great_expectations\"", ")", ")", "assert", "(", "obs_tree", "==", "\"\"\"\\\ngreat_expectations/\n .gitignore\n great_expectations.yml\n checkpoints/\n expectations/\n .ge_store_backend_id\n notebooks/\n pandas/\n validation_playground.ipynb\n spark/\n validation_playground.ipynb\n sql/\n validation_playground.ipynb\n plugins/\n custom_data_docs/\n renderers/\n styles/\n data_docs_custom_styles.css\n views/\n uncommitted/\n config_variables.yml\n data_docs/\n validations/\n .ge_store_backend_id\n\"\"\"", ")", "assert_no_logging_messages_or_tracebacks", "(", "my_caplog", ",", "result", ")" ]
[ 14, 0 ]
[ 102, 63 ]
python
en
['en', 'error', 'th']
False
test_init_install_sqlalchemy
(caplog, tmp_path_factory, monkeypatch)
WARNING: THIS TEST IS AWFUL AND WE HATE IT.
WARNING: THIS TEST IS AWFUL AND WE HATE IT.
def test_init_install_sqlalchemy(caplog, tmp_path_factory, monkeypatch): """WARNING: THIS TEST IS AWFUL AND WE HATE IT.""" # This test is as much about changing the entire test environment with side effects as it is about actually testing # the observed behavior. library_import_name = "sqlalchemy" library_name = "sqlalchemy" cli_input = "\n\n2\nn\n" basedir = tmp_path_factory.mktemp("test_cli_init_diff") runner = CliRunner(mix_stderr=False) monkeypatch.chdir(basedir) result = runner.invoke( cli, ["--v3-api", "init", "--no-view"], input=cli_input, catch_exceptions=False ) stdout = result.output assert "Always know what to expect from your data" in stdout assert "What data would you like Great Expectations to connect to" in stdout assert ( f"""Great Expectations relies on the library `{library_import_name}` to connect to your data, \ but the package `{library_name}` containing this library is not installed. Would you like Great Expectations to try to execute `pip install {library_name}` for you?""" in stdout ) # NOW, IN AN EVIL KNOWN ONLY TO SLEEPLESS PROGRAMMERS, WE USE OUR UTILITY TO INSTALL SQLALCHEMY _ = execute_shell_command_with_progress_polling("pip install sqlalchemy")
[ "def", "test_init_install_sqlalchemy", "(", "caplog", ",", "tmp_path_factory", ",", "monkeypatch", ")", ":", "# This test is as much about changing the entire test environment with side effects as it is about actually testing", "# the observed behavior.", "library_import_name", "=", "\"sqlalchemy\"", "library_name", "=", "\"sqlalchemy\"", "cli_input", "=", "\"\\n\\n2\\nn\\n\"", "basedir", "=", "tmp_path_factory", ".", "mktemp", "(", "\"test_cli_init_diff\"", ")", "runner", "=", "CliRunner", "(", "mix_stderr", "=", "False", ")", "monkeypatch", ".", "chdir", "(", "basedir", ")", "result", "=", "runner", ".", "invoke", "(", "cli", ",", "[", "\"--v3-api\"", ",", "\"init\"", ",", "\"--no-view\"", "]", ",", "input", "=", "cli_input", ",", "catch_exceptions", "=", "False", ")", "stdout", "=", "result", ".", "output", "assert", "\"Always know what to expect from your data\"", "in", "stdout", "assert", "\"What data would you like Great Expectations to connect to\"", "in", "stdout", "assert", "(", "f\"\"\"Great Expectations relies on the library `{library_import_name}` to connect to your data, \\\nbut the package `{library_name}` containing this library is not installed.\n Would you like Great Expectations to try to execute `pip install {library_name}` for you?\"\"\"", "in", "stdout", ")", "# NOW, IN AN EVIL KNOWN ONLY TO SLEEPLESS PROGRAMMERS, WE USE OUR UTILITY TO INSTALL SQLALCHEMY", "_", "=", "execute_shell_command_with_progress_polling", "(", "\"pip install sqlalchemy\"", ")" ]
[ 114, 0 ]
[ 142, 77 ]
python
en
['en', 'en', 'en']
True
MetaPandasDataset.column_map_expectation
(cls, func)
Constructs an expectation using column-map semantics. The MetaPandasDataset implementation replaces the "column" parameter supplied by the user with a pandas Series object containing the actual column from the relevant pandas dataframe. This simplifies the implementing expectation logic while preserving the standard Dataset signature and expected behavior. See :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>` \ for full documentation of this function.
Constructs an expectation using column-map semantics.
def column_map_expectation(cls, func): """Constructs an expectation using column-map semantics. The MetaPandasDataset implementation replaces the "column" parameter supplied by the user with a pandas Series object containing the actual column from the relevant pandas dataframe. This simplifies the implementing expectation logic while preserving the standard Dataset signature and expected behavior. See :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>` \ for full documentation of this function. """ argspec = inspect.getfullargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper( self, column, mostly=None, result_format=None, row_condition=None, condition_parser=None, *args, **kwargs, ): if result_format is None: result_format = self.default_expectation_args["result_format"] result_format = parse_result_format(result_format) if row_condition and self._supports_row_condition: data = self._apply_row_condition( row_condition=row_condition, condition_parser=condition_parser ) else: data = self series = data[column] if func.__name__ in [ "expect_column_values_to_not_be_null", "expect_column_values_to_be_null", ]: # Counting the number of unexpected values can be expensive when there is a large # number of np.nan values. # This only happens on expect_column_values_to_not_be_null expectations. # Since there is no reason to look for most common unexpected values in this case, # we will instruct the result formatting method to skip this step. # FIXME rename to mapped_ignore_values? boolean_mapped_null_values = np.full(series.shape, False) result_format["partial_unexpected_count"] = 0 else: boolean_mapped_null_values = series.isnull().values element_count = int(len(series)) # FIXME rename nonnull to non_ignored? nonnull_values = series[boolean_mapped_null_values == False] nonnull_count = int((boolean_mapped_null_values == False).sum()) boolean_mapped_success_values = func(self, nonnull_values, *args, **kwargs) success_count = np.count_nonzero(boolean_mapped_success_values) unexpected_list = list( nonnull_values[boolean_mapped_success_values == False] ) unexpected_index_list = list( nonnull_values[boolean_mapped_success_values == False].index ) if "output_strftime_format" in kwargs: output_strftime_format = kwargs["output_strftime_format"] parsed_unexpected_list = [] for val in unexpected_list: if val is None: parsed_unexpected_list.append(val) else: if isinstance(val, str): val = parse(val) parsed_unexpected_list.append( datetime.strftime(val, output_strftime_format) ) unexpected_list = parsed_unexpected_list success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly ) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list, ) # FIXME Temp fix for result format if func.__name__ in [ "expect_column_values_to_not_be_null", "expect_column_values_to_be_null", ]: del return_obj["result"]["unexpected_percent_nonmissing"] del return_obj["result"]["missing_count"] del return_obj["result"]["missing_percent"] try: del return_obj["result"]["partial_unexpected_counts"] del return_obj["result"]["partial_unexpected_list"] except KeyError: pass return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "column_map_expectation", "(", "cls", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "@", "cls", ".", "expectation", "(", "argspec", ")", "@", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "column", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "row_condition", "=", "None", ",", "condition_parser", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ",", ")", ":", "if", "result_format", "is", "None", ":", "result_format", "=", "self", ".", "default_expectation_args", "[", "\"result_format\"", "]", "result_format", "=", "parse_result_format", "(", "result_format", ")", "if", "row_condition", "and", "self", ".", "_supports_row_condition", ":", "data", "=", "self", ".", "_apply_row_condition", "(", "row_condition", "=", "row_condition", ",", "condition_parser", "=", "condition_parser", ")", "else", ":", "data", "=", "self", "series", "=", "data", "[", "column", "]", "if", "func", ".", "__name__", "in", "[", "\"expect_column_values_to_not_be_null\"", ",", "\"expect_column_values_to_be_null\"", ",", "]", ":", "# Counting the number of unexpected values can be expensive when there is a large", "# number of np.nan values.", "# This only happens on expect_column_values_to_not_be_null expectations.", "# Since there is no reason to look for most common unexpected values in this case,", "# we will instruct the result formatting method to skip this step.", "# FIXME rename to mapped_ignore_values?", "boolean_mapped_null_values", "=", "np", ".", "full", "(", "series", ".", "shape", ",", "False", ")", "result_format", "[", "\"partial_unexpected_count\"", "]", "=", "0", "else", ":", "boolean_mapped_null_values", "=", "series", ".", "isnull", "(", ")", ".", "values", "element_count", "=", "int", "(", "len", "(", "series", ")", ")", "# FIXME rename nonnull to non_ignored?", "nonnull_values", "=", "series", "[", "boolean_mapped_null_values", "==", "False", "]", "nonnull_count", "=", "int", "(", "(", "boolean_mapped_null_values", "==", "False", ")", ".", "sum", "(", ")", ")", "boolean_mapped_success_values", "=", "func", "(", "self", ",", "nonnull_values", ",", "*", "args", ",", "*", "*", "kwargs", ")", "success_count", "=", "np", ".", "count_nonzero", "(", "boolean_mapped_success_values", ")", "unexpected_list", "=", "list", "(", "nonnull_values", "[", "boolean_mapped_success_values", "==", "False", "]", ")", "unexpected_index_list", "=", "list", "(", "nonnull_values", "[", "boolean_mapped_success_values", "==", "False", "]", ".", "index", ")", "if", "\"output_strftime_format\"", "in", "kwargs", ":", "output_strftime_format", "=", "kwargs", "[", "\"output_strftime_format\"", "]", "parsed_unexpected_list", "=", "[", "]", "for", "val", "in", "unexpected_list", ":", "if", "val", "is", "None", ":", "parsed_unexpected_list", ".", "append", "(", "val", ")", "else", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "parse", "(", "val", ")", "parsed_unexpected_list", ".", "append", "(", "datetime", ".", "strftime", "(", "val", ",", "output_strftime_format", ")", ")", "unexpected_list", "=", "parsed_unexpected_list", "success", ",", "percent_success", "=", "self", ".", "_calc_map_expectation_success", "(", "success_count", ",", "nonnull_count", ",", "mostly", ")", "return_obj", "=", "self", ".", "_format_map_output", "(", "result_format", ",", "success", ",", "element_count", ",", "nonnull_count", ",", "len", "(", "unexpected_list", ")", ",", "unexpected_list", ",", "unexpected_index_list", ",", ")", "# FIXME Temp fix for result format", "if", "func", ".", "__name__", "in", "[", "\"expect_column_values_to_not_be_null\"", ",", "\"expect_column_values_to_be_null\"", ",", "]", ":", "del", "return_obj", "[", "\"result\"", "]", "[", "\"unexpected_percent_nonmissing\"", "]", "del", "return_obj", "[", "\"result\"", "]", "[", "\"missing_count\"", "]", "del", "return_obj", "[", "\"result\"", "]", "[", "\"missing_percent\"", "]", "try", ":", "del", "return_obj", "[", "\"result\"", "]", "[", "\"partial_unexpected_counts\"", "]", "del", "return_obj", "[", "\"result\"", "]", "[", "\"partial_unexpected_list\"", "]", "except", "KeyError", ":", "pass", "return", "return_obj", "inner_wrapper", ".", "__name__", "=", "func", ".", "__name__", "inner_wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "inner_wrapper" ]
[ 43, 4 ]
[ 159, 28 ]
python
en
['en', 'lb', 'en']
True
MetaPandasDataset.column_pair_map_expectation
(cls, func)
The column_pair_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a pair of columns.
The column_pair_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a pair of columns.
def column_pair_map_expectation(cls, func): """ The column_pair_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a pair of columns. """ argspec = inspect.getfullargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper( self, column_A, column_B, mostly=None, ignore_row_if="both_values_are_missing", result_format=None, row_condition=None, condition_parser=None, *args, **kwargs, ): if result_format is None: result_format = self.default_expectation_args["result_format"] if row_condition: self = self.query(row_condition).reset_index(drop=True) series_A = self[column_A] series_B = self[column_B] if ignore_row_if == "both_values_are_missing": boolean_mapped_null_values = series_A.isnull() & series_B.isnull() elif ignore_row_if == "either_value_is_missing": boolean_mapped_null_values = series_A.isnull() | series_B.isnull() elif ignore_row_if == "never": boolean_mapped_null_values = series_A.map(lambda x: False) else: raise ValueError("Unknown value of ignore_row_if: %s", (ignore_row_if,)) assert len(series_A) == len( series_B ), "Series A and B must be the same length" # This next bit only works if series_A and _B are the same length element_count = int(len(series_A)) nonnull_count = (boolean_mapped_null_values == False).sum() nonnull_values_A = series_A[boolean_mapped_null_values == False] nonnull_values_B = series_B[boolean_mapped_null_values == False] nonnull_values = [ value_pair for value_pair in zip(list(nonnull_values_A), list(nonnull_values_B)) ] boolean_mapped_success_values = func( self, nonnull_values_A, nonnull_values_B, *args, **kwargs ) success_count = boolean_mapped_success_values.sum() unexpected_list = [ value_pair for value_pair in zip( list( series_A[ (boolean_mapped_success_values == False) & (boolean_mapped_null_values == False) ] ), list( series_B[ (boolean_mapped_success_values == False) & (boolean_mapped_null_values == False) ] ), ) ] unexpected_index_list = list( series_A[ (boolean_mapped_success_values == False) & (boolean_mapped_null_values == False) ].index ) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly ) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list, ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "column_pair_map_expectation", "(", "cls", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "@", "cls", ".", "expectation", "(", "argspec", ")", "@", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "column_A", ",", "column_B", ",", "mostly", "=", "None", ",", "ignore_row_if", "=", "\"both_values_are_missing\"", ",", "result_format", "=", "None", ",", "row_condition", "=", "None", ",", "condition_parser", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ",", ")", ":", "if", "result_format", "is", "None", ":", "result_format", "=", "self", ".", "default_expectation_args", "[", "\"result_format\"", "]", "if", "row_condition", ":", "self", "=", "self", ".", "query", "(", "row_condition", ")", ".", "reset_index", "(", "drop", "=", "True", ")", "series_A", "=", "self", "[", "column_A", "]", "series_B", "=", "self", "[", "column_B", "]", "if", "ignore_row_if", "==", "\"both_values_are_missing\"", ":", "boolean_mapped_null_values", "=", "series_A", ".", "isnull", "(", ")", "&", "series_B", ".", "isnull", "(", ")", "elif", "ignore_row_if", "==", "\"either_value_is_missing\"", ":", "boolean_mapped_null_values", "=", "series_A", ".", "isnull", "(", ")", "|", "series_B", ".", "isnull", "(", ")", "elif", "ignore_row_if", "==", "\"never\"", ":", "boolean_mapped_null_values", "=", "series_A", ".", "map", "(", "lambda", "x", ":", "False", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown value of ignore_row_if: %s\"", ",", "(", "ignore_row_if", ",", ")", ")", "assert", "len", "(", "series_A", ")", "==", "len", "(", "series_B", ")", ",", "\"Series A and B must be the same length\"", "# This next bit only works if series_A and _B are the same length", "element_count", "=", "int", "(", "len", "(", "series_A", ")", ")", "nonnull_count", "=", "(", "boolean_mapped_null_values", "==", "False", ")", ".", "sum", "(", ")", "nonnull_values_A", "=", "series_A", "[", "boolean_mapped_null_values", "==", "False", "]", "nonnull_values_B", "=", "series_B", "[", "boolean_mapped_null_values", "==", "False", "]", "nonnull_values", "=", "[", "value_pair", "for", "value_pair", "in", "zip", "(", "list", "(", "nonnull_values_A", ")", ",", "list", "(", "nonnull_values_B", ")", ")", "]", "boolean_mapped_success_values", "=", "func", "(", "self", ",", "nonnull_values_A", ",", "nonnull_values_B", ",", "*", "args", ",", "*", "*", "kwargs", ")", "success_count", "=", "boolean_mapped_success_values", ".", "sum", "(", ")", "unexpected_list", "=", "[", "value_pair", "for", "value_pair", "in", "zip", "(", "list", "(", "series_A", "[", "(", "boolean_mapped_success_values", "==", "False", ")", "&", "(", "boolean_mapped_null_values", "==", "False", ")", "]", ")", ",", "list", "(", "series_B", "[", "(", "boolean_mapped_success_values", "==", "False", ")", "&", "(", "boolean_mapped_null_values", "==", "False", ")", "]", ")", ",", ")", "]", "unexpected_index_list", "=", "list", "(", "series_A", "[", "(", "boolean_mapped_success_values", "==", "False", ")", "&", "(", "boolean_mapped_null_values", "==", "False", ")", "]", ".", "index", ")", "success", ",", "percent_success", "=", "self", ".", "_calc_map_expectation_success", "(", "success_count", ",", "nonnull_count", ",", "mostly", ")", "return_obj", "=", "self", ".", "_format_map_output", "(", "result_format", ",", "success", ",", "element_count", ",", "nonnull_count", ",", "len", "(", "unexpected_list", ")", ",", "unexpected_list", ",", "unexpected_index_list", ",", ")", "return", "return_obj", "inner_wrapper", ".", "__name__", "=", "func", ".", "__name__", "inner_wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "inner_wrapper" ]
[ 162, 4 ]
[ 264, 28 ]
python
en
['en', 'error', 'th']
False
MetaPandasDataset.multicolumn_map_expectation
(cls, func)
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns.
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns.
def multicolumn_map_expectation(cls, func): """ The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns. """ argspec = inspect.getfullargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper( self, column_list, mostly=None, ignore_row_if="all_values_are_missing", result_format=None, row_condition=None, condition_parser=None, *args, **kwargs, ): if result_format is None: result_format = self.default_expectation_args["result_format"] if row_condition: self = self.query(row_condition).reset_index(drop=True) test_df = self[column_list] if ignore_row_if == "all_values_are_missing": boolean_mapped_skip_values = test_df.isnull().all(axis=1) elif ignore_row_if == "any_value_is_missing": boolean_mapped_skip_values = test_df.isnull().any(axis=1) elif ignore_row_if == "never": boolean_mapped_skip_values = pd.Series([False] * len(test_df)) else: raise ValueError("Unknown value of ignore_row_if: %s", (ignore_row_if,)) boolean_mapped_success_values = func( self, test_df[boolean_mapped_skip_values == False], *args, **kwargs ) success_count = boolean_mapped_success_values.sum() nonnull_count = (~boolean_mapped_skip_values).sum() element_count = len(test_df) unexpected_list = test_df[ (boolean_mapped_skip_values == False) & (boolean_mapped_success_values == False) ] unexpected_index_list = list(unexpected_list.index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly ) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list.to_dict(orient="records"), unexpected_index_list, ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "multicolumn_map_expectation", "(", "cls", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "@", "cls", ".", "expectation", "(", "argspec", ")", "@", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "column_list", ",", "mostly", "=", "None", ",", "ignore_row_if", "=", "\"all_values_are_missing\"", ",", "result_format", "=", "None", ",", "row_condition", "=", "None", ",", "condition_parser", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ",", ")", ":", "if", "result_format", "is", "None", ":", "result_format", "=", "self", ".", "default_expectation_args", "[", "\"result_format\"", "]", "if", "row_condition", ":", "self", "=", "self", ".", "query", "(", "row_condition", ")", ".", "reset_index", "(", "drop", "=", "True", ")", "test_df", "=", "self", "[", "column_list", "]", "if", "ignore_row_if", "==", "\"all_values_are_missing\"", ":", "boolean_mapped_skip_values", "=", "test_df", ".", "isnull", "(", ")", ".", "all", "(", "axis", "=", "1", ")", "elif", "ignore_row_if", "==", "\"any_value_is_missing\"", ":", "boolean_mapped_skip_values", "=", "test_df", ".", "isnull", "(", ")", ".", "any", "(", "axis", "=", "1", ")", "elif", "ignore_row_if", "==", "\"never\"", ":", "boolean_mapped_skip_values", "=", "pd", ".", "Series", "(", "[", "False", "]", "*", "len", "(", "test_df", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown value of ignore_row_if: %s\"", ",", "(", "ignore_row_if", ",", ")", ")", "boolean_mapped_success_values", "=", "func", "(", "self", ",", "test_df", "[", "boolean_mapped_skip_values", "==", "False", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "success_count", "=", "boolean_mapped_success_values", ".", "sum", "(", ")", "nonnull_count", "=", "(", "~", "boolean_mapped_skip_values", ")", ".", "sum", "(", ")", "element_count", "=", "len", "(", "test_df", ")", "unexpected_list", "=", "test_df", "[", "(", "boolean_mapped_skip_values", "==", "False", ")", "&", "(", "boolean_mapped_success_values", "==", "False", ")", "]", "unexpected_index_list", "=", "list", "(", "unexpected_list", ".", "index", ")", "success", ",", "percent_success", "=", "self", ".", "_calc_map_expectation_success", "(", "success_count", ",", "nonnull_count", ",", "mostly", ")", "return_obj", "=", "self", ".", "_format_map_output", "(", "result_format", ",", "success", ",", "element_count", ",", "nonnull_count", ",", "len", "(", "unexpected_list", ")", ",", "unexpected_list", ".", "to_dict", "(", "orient", "=", "\"records\"", ")", ",", "unexpected_index_list", ",", ")", "return", "return_obj", "inner_wrapper", ".", "__name__", "=", "func", ".", "__name__", "inner_wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "inner_wrapper" ]
[ 267, 4 ]
[ 336, 28 ]
python
en
['en', 'error', 'th']
False
PandasDataset.get_crosstab
( self, column_A, column_B, bins_A=None, bins_B=None, n_bins_A=None, n_bins_B=None, )
Get crosstab of column_A and column_B, binning values if necessary
Get crosstab of column_A and column_B, binning values if necessary
def get_crosstab( self, column_A, column_B, bins_A=None, bins_B=None, n_bins_A=None, n_bins_B=None, ): """Get crosstab of column_A and column_B, binning values if necessary""" series_A = self.get_binned_values(self[column_A], bins_A, n_bins_A) series_B = self.get_binned_values(self[column_B], bins_B, n_bins_B) return pd.crosstab(series_A, columns=series_B)
[ "def", "get_crosstab", "(", "self", ",", "column_A", ",", "column_B", ",", "bins_A", "=", "None", ",", "bins_B", "=", "None", ",", "n_bins_A", "=", "None", ",", "n_bins_B", "=", "None", ",", ")", ":", "series_A", "=", "self", ".", "get_binned_values", "(", "self", "[", "column_A", "]", ",", "bins_A", ",", "n_bins_A", ")", "series_B", "=", "self", ".", "get_binned_values", "(", "self", "[", "column_B", "]", ",", "bins_B", ",", "n_bins_B", ")", "return", "pd", ".", "crosstab", "(", "series_A", ",", "columns", "=", "series_B", ")" ]
[ 542, 4 ]
[ 554, 54 ]
python
en
['en', 'en', 'en']
True
PandasDataset.get_binned_values
(self, series, bins, n_bins)
Get binned values of series. Args: Series (pd.Series): Input series bins (list): Bins for the series. List of numeric if series is numeric or list of list of series values else. n_bins (int): Number of bins. Ignored if bins is not None.
Get binned values of series.
def get_binned_values(self, series, bins, n_bins): """ Get binned values of series. Args: Series (pd.Series): Input series bins (list): Bins for the series. List of numeric if series is numeric or list of list of series values else. n_bins (int): Number of bins. Ignored if bins is not None. """ if n_bins is None: n_bins = 10 if series.dtype in ["int", "float"]: if bins is not None: bins = sorted(np.unique(bins)) if np.min(series) < bins[0]: bins = [np.min(series)] + bins if np.max(series) > bins[-1]: bins = bins + [np.max(series)] if bins is None: bins = np.histogram_bin_edges(series[series.notnull()], bins=n_bins) # Make sure max of series is included in rightmost bin bins[-1] = np.nextafter(bins[-1], bins[-1] + 1) # Create labels for returned series # Used in e.g. crosstab that is printed as observed value in data docs. precision = int(np.log10(min(bins[1:] - bins[:-1]))) + 2 labels = [ f"[{round(lower, precision)}, {round(upper, precision)})" for lower, upper in zip(bins[:-1], bins[1:]) ] if any(np.isnan(series)): # Missing get digitized into bin = n_bins+1 labels += ["(missing)"] return pd.Categorical.from_codes( codes=np.digitize(series, bins=bins) - 1, categories=labels, ordered=True, ) else: if bins is None: value_counts = series.value_counts(sort=True) if len(value_counts) < n_bins + 1: return series.fillna("(missing)") else: other_values = sorted(value_counts.index[n_bins:]) replace = {value: "(other)" for value in other_values} else: replace = dict() for x in bins: replace.update({value: ", ".join(x) for value in x}) return ( series.replace(to_replace=replace) .fillna("(missing)") .astype("category") )
[ "def", "get_binned_values", "(", "self", ",", "series", ",", "bins", ",", "n_bins", ")", ":", "if", "n_bins", "is", "None", ":", "n_bins", "=", "10", "if", "series", ".", "dtype", "in", "[", "\"int\"", ",", "\"float\"", "]", ":", "if", "bins", "is", "not", "None", ":", "bins", "=", "sorted", "(", "np", ".", "unique", "(", "bins", ")", ")", "if", "np", ".", "min", "(", "series", ")", "<", "bins", "[", "0", "]", ":", "bins", "=", "[", "np", ".", "min", "(", "series", ")", "]", "+", "bins", "if", "np", ".", "max", "(", "series", ")", ">", "bins", "[", "-", "1", "]", ":", "bins", "=", "bins", "+", "[", "np", ".", "max", "(", "series", ")", "]", "if", "bins", "is", "None", ":", "bins", "=", "np", ".", "histogram_bin_edges", "(", "series", "[", "series", ".", "notnull", "(", ")", "]", ",", "bins", "=", "n_bins", ")", "# Make sure max of series is included in rightmost bin", "bins", "[", "-", "1", "]", "=", "np", ".", "nextafter", "(", "bins", "[", "-", "1", "]", ",", "bins", "[", "-", "1", "]", "+", "1", ")", "# Create labels for returned series", "# Used in e.g. crosstab that is printed as observed value in data docs.", "precision", "=", "int", "(", "np", ".", "log10", "(", "min", "(", "bins", "[", "1", ":", "]", "-", "bins", "[", ":", "-", "1", "]", ")", ")", ")", "+", "2", "labels", "=", "[", "f\"[{round(lower, precision)}, {round(upper, precision)})\"", "for", "lower", ",", "upper", "in", "zip", "(", "bins", "[", ":", "-", "1", "]", ",", "bins", "[", "1", ":", "]", ")", "]", "if", "any", "(", "np", ".", "isnan", "(", "series", ")", ")", ":", "# Missing get digitized into bin = n_bins+1", "labels", "+=", "[", "\"(missing)\"", "]", "return", "pd", ".", "Categorical", ".", "from_codes", "(", "codes", "=", "np", ".", "digitize", "(", "series", ",", "bins", "=", "bins", ")", "-", "1", ",", "categories", "=", "labels", ",", "ordered", "=", "True", ",", ")", "else", ":", "if", "bins", "is", "None", ":", "value_counts", "=", "series", ".", "value_counts", "(", "sort", "=", "True", ")", "if", "len", "(", "value_counts", ")", "<", "n_bins", "+", "1", ":", "return", "series", ".", "fillna", "(", "\"(missing)\"", ")", "else", ":", "other_values", "=", "sorted", "(", "value_counts", ".", "index", "[", "n_bins", ":", "]", ")", "replace", "=", "{", "value", ":", "\"(other)\"", "for", "value", "in", "other_values", "}", "else", ":", "replace", "=", "dict", "(", ")", "for", "x", "in", "bins", ":", "replace", ".", "update", "(", "{", "value", ":", "\", \"", ".", "join", "(", "x", ")", "for", "value", "in", "x", "}", ")", "return", "(", "series", ".", "replace", "(", "to_replace", "=", "replace", ")", ".", "fillna", "(", "\"(missing)\"", ")", ".", "astype", "(", "\"category\"", ")", ")" ]
[ 556, 4 ]
[ 617, 13 ]
python
en
['en', 'error', 'th']
False
PandasDataset.expect_column_values_to_be_of_type
( self, column, type_, **kwargs # Since we've now received the default arguments *before* the expectation decorator, we need to # ensure we only pass what we actually received. Hence, we'll use kwargs # mostly=None, # result_format=None, # row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None )
The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below). In Pandas, columns *may* be typed, or they may be of the generic "object" type which can include rows with different storage types in the same column. To respect that implementation, the expect_column_values_to_be_of_type expectations will first attempt to use the column dtype information to determine whether the column is restricted to the provided type. If that is possible, then expect_column_values_to_be_of_type will return aggregate information including an observed_value, similarly to other backends. If it is not possible (because the column dtype is "object" but a more specific type was specified), then PandasDataset will use column map semantics: it will return map expectation results and check each value individually, which can be substantially slower. Unfortunately, the "object" type is also used to contain any string-type columns (including 'str' and numpy 'string_' (bytes)); consequently, it is not possible to test for string columns using aggregate semantics.
The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below).
def expect_column_values_to_be_of_type( self, column, type_, **kwargs # Since we've now received the default arguments *before* the expectation decorator, we need to # ensure we only pass what we actually received. Hence, we'll use kwargs # mostly=None, # result_format=None, # row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None ): """ The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below). In Pandas, columns *may* be typed, or they may be of the generic "object" type which can include rows with different storage types in the same column. To respect that implementation, the expect_column_values_to_be_of_type expectations will first attempt to use the column dtype information to determine whether the column is restricted to the provided type. If that is possible, then expect_column_values_to_be_of_type will return aggregate information including an observed_value, similarly to other backends. If it is not possible (because the column dtype is "object" but a more specific type was specified), then PandasDataset will use column map semantics: it will return map expectation results and check each value individually, which can be substantially slower. Unfortunately, the "object" type is also used to contain any string-type columns (including 'str' and numpy 'string_' (bytes)); consequently, it is not possible to test for string columns using aggregate semantics. """ # Short-circuit if the dtype tells us; in that case use column-aggregate (vs map) semantics if ( self[column].dtype != "object" or type_ is None or type_ in ["object", "object_", "O"] ): res = self._expect_column_values_to_be_of_type__aggregate( column, type_, **kwargs ) # Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an # existing expectation, but it should be definitely kept in sync # We do not need this bookkeeping if we are in an active validation: if self._active_validation: return res # First, if there is an existing expectation of this type, delete it. Then change the one we created to be # of the proper expectation_type existing_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="expect_column_values_to_be_of_type", kwargs={"column": column}, ) ) if len(existing_expectations) == 1: self._expectation_suite.expectations.pop(existing_expectations[0]) # Now, rename the expectation we just added new_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="_expect_column_values_to_be_of_type__aggregate", kwargs={"column": column}, ) ) assert len(new_expectations) == 1 old_config = self._expectation_suite.expectations[new_expectations[0]] new_config = ExpectationConfiguration( expectation_type="expect_column_values_to_be_of_type", kwargs=old_config.kwargs, meta=old_config.meta, success_on_last_run=old_config.success_on_last_run, ) self._expectation_suite.expectations[new_expectations[0]] = new_config else: res = self._expect_column_values_to_be_of_type__map(column, type_, **kwargs) # Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an # existing expectation, but it should be definitely kept in sync # We do not need this bookkeeping if we are in an active validation: if self._active_validation: return res # First, if there is an existing expectation of this type, delete it. Then change the one we created to be # of the proper expectation_type existing_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="expect_column_values_to_be_of_type", kwargs={"column": column}, ) ) if len(existing_expectations) == 1: self._expectation_suite.expectations.pop(existing_expectations[0]) # Now, rename the expectation we just added new_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="_expect_column_values_to_be_of_type__map", kwargs={"column": column}, ) ) assert len(new_expectations) == 1 old_config = self._expectation_suite.expectations[new_expectations[0]] new_config = ExpectationConfiguration( expectation_type="expect_column_values_to_be_of_type", kwargs=old_config.kwargs, meta=old_config.meta, success_on_last_run=old_config.success_on_last_run, ) self._expectation_suite.expectations[new_expectations[0]] = new_config return res
[ "def", "expect_column_values_to_be_of_type", "(", "self", ",", "column", ",", "type_", ",", "*", "*", "kwargs", "# Since we've now received the default arguments *before* the expectation decorator, we need to", "# ensure we only pass what we actually received. Hence, we'll use kwargs", "# mostly=None,", "# result_format=None,", "# row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None", ")", ":", "# Short-circuit if the dtype tells us; in that case use column-aggregate (vs map) semantics", "if", "(", "self", "[", "column", "]", ".", "dtype", "!=", "\"object\"", "or", "type_", "is", "None", "or", "type_", "in", "[", "\"object\"", ",", "\"object_\"", ",", "\"O\"", "]", ")", ":", "res", "=", "self", ".", "_expect_column_values_to_be_of_type__aggregate", "(", "column", ",", "type_", ",", "*", "*", "kwargs", ")", "# Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an", "# existing expectation, but it should be definitely kept in sync", "# We do not need this bookkeeping if we are in an active validation:", "if", "self", ".", "_active_validation", ":", "return", "res", "# First, if there is an existing expectation of this type, delete it. Then change the one we created to be", "# of the proper expectation_type", "existing_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_of_type\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "if", "len", "(", "existing_expectations", ")", "==", "1", ":", "self", ".", "_expectation_suite", ".", "expectations", ".", "pop", "(", "existing_expectations", "[", "0", "]", ")", "# Now, rename the expectation we just added", "new_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"_expect_column_values_to_be_of_type__aggregate\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "assert", "len", "(", "new_expectations", ")", "==", "1", "old_config", "=", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "new_config", "=", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_of_type\"", ",", "kwargs", "=", "old_config", ".", "kwargs", ",", "meta", "=", "old_config", ".", "meta", ",", "success_on_last_run", "=", "old_config", ".", "success_on_last_run", ",", ")", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "=", "new_config", "else", ":", "res", "=", "self", ".", "_expect_column_values_to_be_of_type__map", "(", "column", ",", "type_", ",", "*", "*", "kwargs", ")", "# Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an", "# existing expectation, but it should be definitely kept in sync", "# We do not need this bookkeeping if we are in an active validation:", "if", "self", ".", "_active_validation", ":", "return", "res", "# First, if there is an existing expectation of this type, delete it. Then change the one we created to be", "# of the proper expectation_type", "existing_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_of_type\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "if", "len", "(", "existing_expectations", ")", "==", "1", ":", "self", ".", "_expectation_suite", ".", "expectations", ".", "pop", "(", "existing_expectations", "[", "0", "]", ")", "# Now, rename the expectation we just added", "new_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"_expect_column_values_to_be_of_type__map\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "assert", "len", "(", "new_expectations", ")", "==", "1", "old_config", "=", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "new_config", "=", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_of_type\"", ",", "kwargs", "=", "old_config", ".", "kwargs", ",", "meta", "=", "old_config", ".", "meta", ",", "success_on_last_run", "=", "old_config", ".", "success_on_last_run", ",", ")", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "=", "new_config", "return", "res" ]
[ 671, 4 ]
[ 782, 18 ]
python
en
['en', 'error', 'th']
False
PandasDataset.expect_column_values_to_be_in_type_list
( self, column, type_list, **kwargs # Since we've now received the default arguments *before* the expectation decorator, we need to # ensure we only pass what we actually received. Hence, we'll use kwargs # mostly=None, # result_format = None, # row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None )
The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below). In Pandas, columns *may* be typed, or they may be of the generic "object" type which can include rows with different storage types in the same column. To respect that implementation, the expect_column_values_to_be_of_type expectations will first attempt to use the column dtype information to determine whether the column is restricted to the provided type. If that is possible, then expect_column_values_to_be_of_type will return aggregate information including an observed_value, similarly to other backends. If it is not possible (because the column dtype is "object" but a more specific type was specified), then PandasDataset will use column map semantics: it will return map expectation results and check each value individually, which can be substantially slower. Unfortunately, the "object" type is also used to contain any string-type columns (including 'str' and numpy 'string_' (bytes)); consequently, it is not possible to test for string columns using aggregate semantics.
The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below).
def expect_column_values_to_be_in_type_list( self, column, type_list, **kwargs # Since we've now received the default arguments *before* the expectation decorator, we need to # ensure we only pass what we actually received. Hence, we'll use kwargs # mostly=None, # result_format = None, # row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None ): """ The pandas implementation of this expectation takes kwargs mostly, result_format, include_config, catch_exceptions, and meta as other expectations, however it declares **kwargs because it needs to be able to fork into either aggregate or map semantics depending on the column type (see below). In Pandas, columns *may* be typed, or they may be of the generic "object" type which can include rows with different storage types in the same column. To respect that implementation, the expect_column_values_to_be_of_type expectations will first attempt to use the column dtype information to determine whether the column is restricted to the provided type. If that is possible, then expect_column_values_to_be_of_type will return aggregate information including an observed_value, similarly to other backends. If it is not possible (because the column dtype is "object" but a more specific type was specified), then PandasDataset will use column map semantics: it will return map expectation results and check each value individually, which can be substantially slower. Unfortunately, the "object" type is also used to contain any string-type columns (including 'str' and numpy 'string_' (bytes)); consequently, it is not possible to test for string columns using aggregate semantics. """ # Short-circuit if the dtype tells us; in that case use column-aggregate (vs map) semantics if self[column].dtype != "object" or type_list is None: res = self._expect_column_values_to_be_in_type_list__aggregate( column, type_list, **kwargs ) # Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an # existing expectation, but it should be definitely kept in sync # We do not need this bookkeeping if we are in an active validation: if self._active_validation: return res # First, if there is an existing expectation of this type, delete it. Then change the one we created to be # of the proper expectation_type existing_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_type_list", kwargs={"column": column}, ) ) if len(existing_expectations) == 1: self._expectation_suite.expectations.pop(existing_expectations[0]) new_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="_expect_column_values_to_be_in_type_list__aggregate", kwargs={"column": column}, ) ) assert len(new_expectations) == 1 old_config = self._expectation_suite.expectations[new_expectations[0]] new_config = ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_type_list", kwargs=old_config.kwargs, meta=old_config.meta, success_on_last_run=old_config.success_on_last_run, ) self._expectation_suite.expectations[new_expectations[0]] = new_config else: res = self._expect_column_values_to_be_in_type_list__map( column, type_list, **kwargs ) # Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an # existing expectation, but it should be definitely kept in sync # We do not need this bookkeeping if we are in an active validation: if self._active_validation: return res # First, if there is an existing expectation of this type, delete it. Then change the one we created to be # of the proper expectation_type existing_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_type_list", kwargs={"column": column}, ) ) if len(existing_expectations) == 1: self._expectation_suite.expectations.pop(existing_expectations[0]) # Now, rename the expectation we just added new_expectations = self._expectation_suite.find_expectation_indexes( ExpectationConfiguration( expectation_type="_expect_column_values_to_be_in_type_list__map", kwargs={"column": column}, ) ) assert len(new_expectations) == 1 old_config = self._expectation_suite.expectations[new_expectations[0]] new_config = ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_type_list", kwargs=old_config.kwargs, meta=old_config.meta, success_on_last_run=old_config.success_on_last_run, ) self._expectation_suite.expectations[new_expectations[0]] = new_config return res
[ "def", "expect_column_values_to_be_in_type_list", "(", "self", ",", "column", ",", "type_list", ",", "*", "*", "kwargs", "# Since we've now received the default arguments *before* the expectation decorator, we need to", "# ensure we only pass what we actually received. Hence, we'll use kwargs", "# mostly=None,", "# result_format = None,", "# row_condition=None, condition_parser=None, include_config=None, catch_exceptions=None, meta=None", ")", ":", "# Short-circuit if the dtype tells us; in that case use column-aggregate (vs map) semantics", "if", "self", "[", "column", "]", ".", "dtype", "!=", "\"object\"", "or", "type_list", "is", "None", ":", "res", "=", "self", ".", "_expect_column_values_to_be_in_type_list__aggregate", "(", "column", ",", "type_list", ",", "*", "*", "kwargs", ")", "# Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an", "# existing expectation, but it should be definitely kept in sync", "# We do not need this bookkeeping if we are in an active validation:", "if", "self", ".", "_active_validation", ":", "return", "res", "# First, if there is an existing expectation of this type, delete it. Then change the one we created to be", "# of the proper expectation_type", "existing_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_in_type_list\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "if", "len", "(", "existing_expectations", ")", "==", "1", ":", "self", ".", "_expectation_suite", ".", "expectations", ".", "pop", "(", "existing_expectations", "[", "0", "]", ")", "new_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"_expect_column_values_to_be_in_type_list__aggregate\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "assert", "len", "(", "new_expectations", ")", "==", "1", "old_config", "=", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "new_config", "=", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_in_type_list\"", ",", "kwargs", "=", "old_config", ".", "kwargs", ",", "meta", "=", "old_config", ".", "meta", ",", "success_on_last_run", "=", "old_config", ".", "success_on_last_run", ",", ")", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "=", "new_config", "else", ":", "res", "=", "self", ".", "_expect_column_values_to_be_in_type_list__map", "(", "column", ",", "type_list", ",", "*", "*", "kwargs", ")", "# Note: this logic is similar to the logic in _append_expectation for deciding when to overwrite an", "# existing expectation, but it should be definitely kept in sync", "# We do not need this bookkeeping if we are in an active validation:", "if", "self", ".", "_active_validation", ":", "return", "res", "# First, if there is an existing expectation of this type, delete it. Then change the one we created to be", "# of the proper expectation_type", "existing_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_in_type_list\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "if", "len", "(", "existing_expectations", ")", "==", "1", ":", "self", ".", "_expectation_suite", ".", "expectations", ".", "pop", "(", "existing_expectations", "[", "0", "]", ")", "# Now, rename the expectation we just added", "new_expectations", "=", "self", ".", "_expectation_suite", ".", "find_expectation_indexes", "(", "ExpectationConfiguration", "(", "expectation_type", "=", "\"_expect_column_values_to_be_in_type_list__map\"", ",", "kwargs", "=", "{", "\"column\"", ":", "column", "}", ",", ")", ")", "assert", "len", "(", "new_expectations", ")", "==", "1", "old_config", "=", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "new_config", "=", "ExpectationConfiguration", "(", "expectation_type", "=", "\"expect_column_values_to_be_in_type_list\"", ",", "kwargs", "=", "old_config", ".", "kwargs", ",", "meta", "=", "old_config", ".", "meta", ",", "success_on_last_run", "=", "old_config", ".", "success_on_last_run", ",", ")", "self", ".", "_expectation_suite", ".", "expectations", "[", "new_expectations", "[", "0", "]", "]", "=", "new_config", "return", "res" ]
[ 899, 4 ]
[ 1007, 18 ]
python
en
['en', 'error', 'th']
False
PandasDataset.expect_multicolumn_sum_to_equal
( self, column_list, sum_total, result_format=None, include_config=True, catch_exceptions=None, meta=None, )
Multi-Column Map Expectation Expects that sum of all rows for a set of columns is equal to a specific value Args: column_list (List[str]): \ Set of columns to be checked sum_total (int): \ expected sum of columns
Multi-Column Map Expectation
def expect_multicolumn_sum_to_equal( self, column_list, sum_total, result_format=None, include_config=True, catch_exceptions=None, meta=None, ): """ Multi-Column Map Expectation Expects that sum of all rows for a set of columns is equal to a specific value Args: column_list (List[str]): \ Set of columns to be checked sum_total (int): \ expected sum of columns """ return column_list.sum(axis=1) == sum_total
[ "def", "expect_multicolumn_sum_to_equal", "(", "self", ",", "column_list", ",", "sum_total", ",", "result_format", "=", "None", ",", "include_config", "=", "True", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ",", ")", ":", "return", "column_list", ".", "sum", "(", "axis", "=", "1", ")", "==", "sum_total" ]
[ 1856, 4 ]
[ 1875, 51 ]
python
en
['es', 'en', 'en']
True
LegacyDatasource.from_configuration
(cls, **kwargs)
Build a new datasource from a configuration dictionary. Args: **kwargs: configuration key-value pairs Returns: datasource (Datasource): the newly-created datasource
Build a new datasource from a configuration dictionary.
def from_configuration(cls, **kwargs): """ Build a new datasource from a configuration dictionary. Args: **kwargs: configuration key-value pairs Returns: datasource (Datasource): the newly-created datasource """ return cls(**kwargs)
[ "def", "from_configuration", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "*", "*", "kwargs", ")" ]
[ 113, 4 ]
[ 124, 28 ]
python
en
['en', 'error', 'th']
False
LegacyDatasource.build_configuration
( cls, class_name, module_name="great_expectations.datasource", data_asset_type=None, batch_kwargs_generators=None, **kwargs )
Build a full configuration object for a datasource, potentially including batch kwargs generators with defaults. Args: class_name: The name of the class for which to build the config module_name: The name of the module in which the datasource class is located data_asset_type: A ClassConfig dictionary batch_kwargs_generators: BatchKwargGenerators configuration dictionary **kwargs: Additional kwargs to be part of the datasource constructor's initialization Returns: A complete datasource configuration.
Build a full configuration object for a datasource, potentially including batch kwargs generators with defaults.
def build_configuration( cls, class_name, module_name="great_expectations.datasource", data_asset_type=None, batch_kwargs_generators=None, **kwargs ): """ Build a full configuration object for a datasource, potentially including batch kwargs generators with defaults. Args: class_name: The name of the class for which to build the config module_name: The name of the module in which the datasource class is located data_asset_type: A ClassConfig dictionary batch_kwargs_generators: BatchKwargGenerators configuration dictionary **kwargs: Additional kwargs to be part of the datasource constructor's initialization Returns: A complete datasource configuration. """ verify_dynamic_loading_support(module_name=module_name) class_ = load_class(class_name=class_name, module_name=module_name) configuration = class_.build_configuration( data_asset_type=data_asset_type, batch_kwargs_generators=batch_kwargs_generators, **kwargs ) return configuration
[ "def", "build_configuration", "(", "cls", ",", "class_name", ",", "module_name", "=", "\"great_expectations.datasource\"", ",", "data_asset_type", "=", "None", ",", "batch_kwargs_generators", "=", "None", ",", "*", "*", "kwargs", ")", ":", "verify_dynamic_loading_support", "(", "module_name", "=", "module_name", ")", "class_", "=", "load_class", "(", "class_name", "=", "class_name", ",", "module_name", "=", "module_name", ")", "configuration", "=", "class_", ".", "build_configuration", "(", "data_asset_type", "=", "data_asset_type", ",", "batch_kwargs_generators", "=", "batch_kwargs_generators", ",", "*", "*", "kwargs", ")", "return", "configuration" ]
[ 127, 4 ]
[ 156, 28 ]
python
en
['en', 'error', 'th']
False
LegacyDatasource.__init__
( self, name, data_context=None, data_asset_type=None, batch_kwargs_generators=None, **kwargs )
Build a new datasource. Args: name: the name for the datasource data_context: data context to which to connect data_asset_type (ClassConfig): the type of DataAsset to produce batch_kwargs_generators: BatchKwargGenerators to add to the datasource
Build a new datasource.
def __init__( self, name, data_context=None, data_asset_type=None, batch_kwargs_generators=None, **kwargs ): """ Build a new datasource. Args: name: the name for the datasource data_context: data context to which to connect data_asset_type (ClassConfig): the type of DataAsset to produce batch_kwargs_generators: BatchKwargGenerators to add to the datasource """ self._data_context = data_context self._name = name if isinstance(data_asset_type, str): warnings.warn( "String-only configuration for data_asset_type is deprecated. Use module_name and class_name instead.", DeprecationWarning, ) self._data_asset_type = data_asset_type self._datasource_config = kwargs self._batch_kwargs_generators = {} self._datasource_config["data_asset_type"] = data_asset_type if batch_kwargs_generators is not None: self._datasource_config["batch_kwargs_generators"] = batch_kwargs_generators
[ "def", "__init__", "(", "self", ",", "name", ",", "data_context", "=", "None", ",", "data_asset_type", "=", "None", ",", "batch_kwargs_generators", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_data_context", "=", "data_context", "self", ".", "_name", "=", "name", "if", "isinstance", "(", "data_asset_type", ",", "str", ")", ":", "warnings", ".", "warn", "(", "\"String-only configuration for data_asset_type is deprecated. Use module_name and class_name instead.\"", ",", "DeprecationWarning", ",", ")", "self", ".", "_data_asset_type", "=", "data_asset_type", "self", ".", "_datasource_config", "=", "kwargs", "self", ".", "_batch_kwargs_generators", "=", "{", "}", "self", ".", "_datasource_config", "[", "\"data_asset_type\"", "]", "=", "data_asset_type", "if", "batch_kwargs_generators", "is", "not", "None", ":", "self", ".", "_datasource_config", "[", "\"batch_kwargs_generators\"", "]", "=", "batch_kwargs_generators" ]
[ 158, 4 ]
[ 188, 88 ]
python
en
['en', 'error', 'th']
False
LegacyDatasource.name
(self)
Property for datasource name
Property for datasource name
def name(self): """ Property for datasource name """ return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 191, 4 ]
[ 195, 25 ]
python
en
['en', 'error', 'th']
False
LegacyDatasource.data_context
(self)
Property for attached DataContext
Property for attached DataContext
def data_context(self): """ Property for attached DataContext """ return self._data_context
[ "def", "data_context", "(", "self", ")", ":", "return", "self", ".", "_data_context" ]
[ 202, 4 ]
[ 206, 33 ]
python
en
['en', 'error', 'th']
False
LegacyDatasource._build_generators
(self)
Build batch kwargs generator objects from the datasource configuration. Returns: None
Build batch kwargs generator objects from the datasource configuration.
def _build_generators(self): """ Build batch kwargs generator objects from the datasource configuration. Returns: None """ try: for generator in self._datasource_config["batch_kwargs_generators"].keys(): self.get_batch_kwargs_generator(generator) except KeyError: pass
[ "def", "_build_generators", "(", "self", ")", ":", "try", ":", "for", "generator", "in", "self", ".", "_datasource_config", "[", "\"batch_kwargs_generators\"", "]", ".", "keys", "(", ")", ":", "self", ".", "get_batch_kwargs_generator", "(", "generator", ")", "except", "KeyError", ":", "pass" ]
[ 208, 4 ]
[ 219, 16 ]
python
en
['en', 'error', 'th']
False