INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
applies a function to each of the keys in a dictionary
def map_vals(func, dict_): """ applies a function to each of the keys in a dictionary Args: func (callable): a function or indexable object dict_ (dict): a dictionary Returns: newdict: transformed dictionary CommandLine: python -m ubelt.util_dict map_vals Exam...
r Swaps the keys and values in a dictionary.
def invert_dict(dict_, unique_vals=True): r""" Swaps the keys and values in a dictionary. Args: dict_ (dict): dictionary to invert unique_vals (bool): if False, inverted keys are returned in a set. The default is True. Returns: dict: inverted Notes: The...
Recursively casts a AutoDict into a regular dictionary. All nested AutoDict values are also converted.
def to_dict(self): """ Recursively casts a AutoDict into a regular dictionary. All nested AutoDict values are also converted. Returns: dict: a copy of this dict without autovivification Example: >>> from ubelt.util_dict import AutoDict >>> au...
CommandLine: python - m ubelt. _win32_links _win32_can_symlink
def _win32_can_symlink(verbose=0, force=0, testing=0): """ CommandLine: python -m ubelt._win32_links _win32_can_symlink Example: >>> # xdoc: +REQUIRES(WIN32) >>> import ubelt as ub >>> _win32_can_symlink(verbose=1, force=1, testing=1) """ global __win32_can_symlink__...
Windows helper for ub. symlink
def _symlink(path, link, overwrite=0, verbose=0): """ Windows helper for ub.symlink """ if exists(link) and not os.path.islink(link): # On windows a broken link might still exist as a hard link or a # junction. Overwrite it if it is a file and we cannot symlink. # However, if it ...
Perform a real symbolic link if possible. However on most versions of windows you need special privledges to create a real symlink. Therefore we try to create a symlink but if that fails we fallback to using a junction.
def _win32_symlink2(path, link, allow_fallback=True, verbose=0): """ Perform a real symbolic link if possible. However, on most versions of windows you need special privledges to create a real symlink. Therefore, we try to create a symlink, but if that fails we fallback to using a junction. AFAIK, ...
Creates real symlink. This will only work in versions greater than Windows Vista. Creating real symlinks requires admin permissions or at least specially enabled symlink permissions. On Windows 10 enabling developer mode should give you these permissions.
def _win32_symlink(path, link, verbose=0): """ Creates real symlink. This will only work in versions greater than Windows Vista. Creating real symlinks requires admin permissions or at least specially enabled symlink permissions. On Windows 10 enabling developer mode should give you these permission...
On older ( pre 10 ) versions of windows we need admin privledges to make symlinks however junctions seem to work.
def _win32_junction(path, link, verbose=0): """ On older (pre 10) versions of windows we need admin privledges to make symlinks, however junctions seem to work. For paths we do a junction (softlink) and for files we use a hard link CommandLine: python -m ubelt._win32_links _win32_junction ...
Determines if a path is a win32 junction
def _win32_is_junction(path): """ Determines if a path is a win32 junction CommandLine: python -m ubelt._win32_links _win32_is_junction Example: >>> # xdoc: +REQUIRES(WIN32) >>> import ubelt as ub >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction') >>>...
Returns the location that the junction points raises ValueError if path is not a junction.
def _win32_read_junction(path): """ Returns the location that the junction points, raises ValueError if path is not a junction. CommandLine: python -m ubelt._win32_links _win32_read_junction Example: >>> # xdoc: +REQUIRES(WIN32) >>> import ubelt as ub >>> root = ub....
rmtree for win32 that treats junctions like directory symlinks. The junction removal portion may not be safe on race conditions.
def _win32_rmtree(path, verbose=0): """ rmtree for win32 that treats junctions like directory symlinks. The junction removal portion may not be safe on race conditions. There is a known issue that prevents shutil.rmtree from deleting directories with junctions. https://bugs.python.org/issue3122...
Test if two hard links point to the same location
def _win32_is_hardlinked(fpath1, fpath2): """ Test if two hard links point to the same location CommandLine: python -m ubelt._win32_links _win32_is_hardlinked Example: >>> # xdoc: +REQUIRES(WIN32) >>> import ubelt as ub >>> root = ub.ensure_app_cache_dir('ubelt', 'win32...
Using the windows cmd shell to get information about a directory
def _win32_dir(path, star=''): """ Using the windows cmd shell to get information about a directory """ from ubelt import util_cmd import re wrapper = 'cmd /S /C "{}"' # the /S will preserve all inner quotes command = 'dir /-C "{}"{}'.format(path, star) wrapped = wrapper.format(command)...
Returns generators that double with each value returned Config includes optional start value
def parse_generator_doubling(config): """ Returns generators that double with each value returned Config includes optional start value """ start = 1 if 'start' in config: start = int(config['start']) # We cannot simply use start as the variable, because of scoping # limitations ...
Parse a contains validator which takes as the config a simple string to find
def parse(config): """ Parse a contains validator, which takes as the config a simple string to find """ if not isinstance(config, basestring): raise TypeError("Contains input must be a simple string") validator = ContainsValidator() validator.contains_string = config ...
Retrieve the adjacency matrix from the nx. DiGraph or numpy array.
def retrieve_adjacency_matrix(graph, order_nodes=None, weight=False): """Retrieve the adjacency matrix from the nx.DiGraph or numpy array.""" if isinstance(graph, np.ndarray): return graph elif isinstance(graph, nx.DiGraph): if order_nodes is None: order_nodes = graph.nodes() ...
r Compute precision - recall statistics for directed graphs. Precision recall statistics are useful to compare algorithms that make predictions with a confidence score. Using these statistics performance of an algorithms given a set threshold ( confidence score ) can be approximated. Area under the precision - recall c...
def precision_recall(target, prediction, low_confidence_undirected=False): r"""Compute precision-recall statistics for directed graphs. Precision recall statistics are useful to compare algorithms that make predictions with a confidence score. Using these statistics, performance of an algorithms ...
r Compute the Structural Hamming Distance. The Structural Hamming Distance ( SHD ) is a standard distance to compare graphs by their adjacency matrix. It consists in computing the difference between the two ( binary ) adjacency matrixes: every edge that is either missing or not in the target graph is counted as a mista...
def SHD(target, pred, double_for_anticausal=True): r"""Compute the Structural Hamming Distance. The Structural Hamming Distance (SHD) is a standard distance to compare graphs by their adjacency matrix. It consists in computing the difference between the two (binary) adjacency matrixes: every edge t...
Compute the Strutural Intervention Distance. [ R wrapper ] The Structural Intervention Distance ( SID ) is a new distance for graphs introduced by Peters and Bühlmann ( 2013 ). This distance was created to account for the shortcomings of the SHD metric for a causal sense. It consists in computing the path between all t...
def SID(target, pred): """Compute the Strutural Intervention Distance. [R wrapper] The Structural Intervention Distance (SID) is a new distance for graphs introduced by Peters and Bühlmann (2013). This distance was created to account for the shortcomings of the SHD metric for a causal sense. ...
Apply causal discovery on observational data using CCDr.
def create_graph_from_data(self, data, **kwargs): """Apply causal discovery on observational data using CCDr. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the CCDR algorithm. """ # Building set...
Redefine the causes of the graph.
def init_variables(self, verbose=False): """Redefine the causes of the graph.""" for j in range(1, self.nodes): nb_parents = np.random.randint(0, min([self.parents_max, j])+1) for i in np.random.choice(range(0, j), nb_parents, replace=False): self.adjacency_matrix...
Generate data from an FCM containing cycles.
def generate(self, rescale=True): """Generate data from an FCM containing cycles.""" if self.cfunctions is None: self.init_variables() for i in nx.topological_sort(self.g): # Root cause if not sum(self.adjacency_matrix[:, i]): self.data['V{}'...
Save data to the csv format by default in two separate files.
def to_csv(self, fname_radical, **kwargs): """ Save data to the csv format by default, in two separate files. Optional keyword arguments can be passed to pandas. """ if self.data is not None: self.data.to_csv(fname_radical+'_data.csv', index=False, **kwargs) ...
Launch an R script starting from a template and replacing text in file before execution.
def launch_R_script(template, arguments, output_function=None, verbose=True, debug=False): """Launch an R script, starting from a template and replacing text in file before execution. Args: template (str): path to the template of the R script arguments (dict): Arguments ...
Execute a subprocess to check the package s availability.
def check_R_package(self, package): """Execute a subprocess to check the package's availability. Args: package (str): Name of the package to be tested. Returns: bool: `True` if the package is available, `False` otherwise """ test_package = not bool(launc...
Bin variables w/ normalization.
def bin_variable(var, bins='fd'): # bin with normalization """Bin variables w/ normalization.""" var = np.array(var).astype(np.float) var = (var - np.mean(var)) / np.std(var) var = np.digitize(var, np.histogram(var, bins=bins)[1]) return var
Perform the independence test.
def predict(self, a, b, **kwargs): """Perform the independence test. :param a: input data :param b: input data :type a: array-like, numerical data :type b: array-like, numerical data :return: dependency statistic (1=Highly dependent, 0=Not dependent) :rtype: floa...
Orient a graph using the method defined by the arguments.
def predict(self, df_data, graph=None, **kwargs): """Orient a graph using the method defined by the arguments. Depending on the type of `graph`, this function process to execute different functions: 1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is execu...
Evaluate a graph taking account of the hardware.
def graph_evaluation(data, adj_matrix, gpu=None, gpu_id=0, **kwargs): """Evaluate a graph taking account of the hardware.""" gpu = SETTINGS.get_default(gpu=gpu) device = 'cuda:{}'.format(gpu_id) if gpu else 'cpu' obs = th.FloatTensor(data).to(device) cgnn = CGNN_model(adj_matrix, data.shape[0], gpu_...
Parallelize the various runs of CGNN to evaluate a graph.
def parallel_graph_evaluation(data, adj_matrix, nb_runs=16, nb_jobs=None, **kwargs): """Parallelize the various runs of CGNN to evaluate a graph.""" nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs) if nb_runs == 1: return graph_evaluation(data, adj_matrix, **kwargs) ...
Hill Climbing optimization: a greedy exploration algorithm.
def hill_climbing(data, graph, **kwargs): """Hill Climbing optimization: a greedy exploration algorithm.""" nodelist = list(data.columns) data = scale(data.values).astype('float32') tested_candidates = [nx.adj_matrix(graph, nodelist=nodelist, weight=None)] best_score = parallel_graph_evaluation(data...
Generate according to the topological order of the graph.
def forward(self): """Generate according to the topological order of the graph.""" self.noise.data.normal_() if not self.confounding: for i in self.topological_order: self.generated[i] = self.blocks[i](th.cat([v for c in [ ...
Run the CGNN on a given graph.
def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None, idx=0, lr=0.01, **kwargs): """Run the CGNN on a given graph.""" verbose = SETTINGS.get_default(verbose=verbose) optim = th.optim.Adam(self.parameters(), lr=lr) self.score.zero_() with trange(train_...
Use CGNN to create a graph from scratch. All the possible structures are tested which leads to a super exponential complexity. It would be preferable to start from a graph skeleton for large graphs.
def create_graph_from_data(self, data): """Use CGNN to create a graph from scratch. All the possible structures are tested, which leads to a super exponential complexity. It would be preferable to start from a graph skeleton for large graphs. Args: data (pandas.DataFrame): O...
Modify and improve a directed acyclic graph solution using CGNN.
def orient_directed_graph(self, data, dag, alg='HC'): """Modify and improve a directed acyclic graph solution using CGNN. Args: data (pandas.DataFrame): Observational data on which causal discovery has to be performed. dag (nx.DiGraph): Graph that provides the ini...
Orient the undirected graph using GNN and apply CGNN to improve the graph.
def orient_undirected_graph(self, data, umg, alg='HC'): """Orient the undirected graph using GNN and apply CGNN to improve the graph. Args: data (pandas.DataFrame): Observational data on which causal discovery has to be performed. umg (nx.Graph): Graph that provid...
Evaluate the entropy of the input variable.
def eval_entropy(x): """Evaluate the entropy of the input variable. :param x: input variable 1D :return: entropy of x """ hx = 0. sx = sorted(x) for i, j in zip(sx[:-1], sx[1:]): delta = j-i if bool(delta): hx += np.log(np.abs(delta)) hx = hx / (len(x) - 1) +...
Integral approximation estimator for causal inference.
def integral_approx_estimator(x, y): """Integral approximation estimator for causal inference. :param x: input variable x 1D :param y: input variable y 1D :return: Return value of the IGCI model >0 if x->y otherwise if return <0 """ a, b = (0., 0.) x = np.array(x) y = np.array(y) id...
Evaluate a pair using the IGCI model.
def predict_proba(self, a, b, **kwargs): """Evaluate a pair using the IGCI model. :param a: Input variable 1D :param b: Input variable 1D :param kwargs: {refMeasure: Scaling method (gaussian, integral or None), estimator: method used to evaluate the pairs (entrop...
Projects the causal pair to the RKHS using the sampled kernel approximation.
def featurize_row(self, x, y): """ Projects the causal pair to the RKHS using the sampled kernel approximation. Args: x (np.ndarray): Variable 1 y (np.ndarray): Variable 2 Returns: np.ndarray: projected empirical distributions into a single fixed-size vector...
Train the model.
def fit(self, x, y): """Train the model. Args: x_tr (pd.DataFrame): CEPC format dataframe containing the pairs y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs """ train = np.vstack((np.array([self.featurize_row(row.iloc[0], ...
Predict the causal score using a trained RCC model
def predict_proba(self, x, y=None, **kwargs): """ Predict the causal score using a trained RCC model Args: x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset. args (numpy.array): second variable (optional depending on the 1st argument). Retu...
For one variable predict its neighbours.
def predict_features(self, df_features, df_target, nh=20, idx=0, dropout=0., activation_function=th.nn.ReLU, lr=0.01, l1=0.1, batch_size=-1, train_epochs=1000, test_epochs=1000, device=None, verbose=None, nb_runs=3): """For one variable...
Build a skeleton using a pairwise independence criterion.
def predict_undirected_graph(self, data): """Build a skeleton using a pairwise independence criterion. Args: data (pandas.DataFrame): Raw data table Returns: networkx.Graph: Undirected graph representing the skeleton. """ graph = Graph() for idx...
Run feature selection for one node: wrapper around self. predict_features.
def run_feature_selection(self, df_data, target, idx=0, **kwargs): """Run feature selection for one node: wrapper around ``self.predict_features``. Args: df_data (pandas.DataFrame): All the observational data target (str): Name of the target variable idx (int...
Predict the skeleton of the graph from raw data.
def predict(self, df_data, threshold=0.05, **kwargs): """Predict the skeleton of the graph from raw data. Returns iteratively the feature selection algorithm on each node. Args: df_data (pandas.DataFrame): data to construct a graph from threshold (float): cutoff value f...
Run GIES on an undirected graph.
def orient_undirected_graph(self, data, graph): """Run GIES on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by the GIES alg...
Run the GIES algorithm.
def create_graph_from_data(self, data): """Run the GIES algorithm. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the GIES algorithm. """ # Building setup w/ arguments. self.arguments['{S...
Setting up and running GIES with all arguments.
def _run_gies(self, data, fixedGaps=None, verbose=True): """Setting up and running GIES with all arguments.""" # Run gies id = str(uuid.uuid4()) os.makedirs('/tmp/cdt_gies' + id + '/') self.arguments['{FOLDER}'] = '/tmp/cdt_gies' + id + '/' def retrieve_result(): ...
Plot SAM s various losses.
def plot_curves(i_batch, adv_loss, gen_loss, l1_reg, cols): """Plot SAM's various losses.""" from matplotlib import pyplot as plt if i_batch == 0: try: ax.clear() ax.plot(range(len(adv_plt)), adv_plt, "r-", linewidth=1.5, markersize=4, ...
Plot generated pairs of variables.
def plot_gen(epoch, batch, generated_variables, pairs_to_plot=[[0, 1]]): """Plot generated pairs of variables.""" from matplotlib import pyplot as plt if epoch == 0: plt.ion() plt.clf() for (i, j) in pairs_to_plot: plt.scatter(generated_variables[i].data.cpu().numpy( ), batc...
Execute the SAM model.
def run_SAM(df_data, skeleton=None, **kwargs): """Execute the SAM model. :param df_data: Input data; either np.array or pd.DataFrame """ gpu = kwargs.get('gpu', False) gpu_no = kwargs.get('gpu_no', 0) train_epochs = kwargs.get('train_epochs', 1000) test_epochs = kwargs.get('test_epochs', 1...
Reset the parameters.
def reset_parameters(self): """Reset the parameters.""" stdv = 1. / math.sqrt(self.weight.size(1)) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv)
Feed - forward through the network.
def forward(self, input): """Feed-forward through the network.""" return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt()))
Feed - forward the model.
def forward(self, x): """Feed-forward the model.""" return self.layers(x * (self._filter * self.fs_filter).expand_as(x))
Feed - forward the model.
def forward(self, x): """Feed-forward the model.""" for i in self.noise: i.data.normal_() self.generated_variables = [self.blocks[i]( th.cat([x, self.noise[i]], 1)) for i in range(self.cols)] return self.generated_variables
Execute SAM on a dataset given a skeleton or not.
def predict(self, data, graph=None, nruns=6, njobs=None, gpus=0, verbose=None, plot=False, plot_generated_pair=False, return_list_results=False): """Execute SAM on a dataset given a skeleton or not. Args: data (pandas.DataFrame): Observational data for estimation of causal r...
Infer causal relationships between 2 variables using the RECI statistic
def predict_proba(self, a, b, **kwargs): """ Infer causal relationships between 2 variables using the RECI statistic :param a: Input variable 1 :param b: Input variable 2 :return: Causation coefficient (Value : 1 if a->b and -1 if b->a) :rtype: float """ return s...
Compute the RECI fit score
def b_fit_score(self, x, y): """ Compute the RECI fit score Args: x (numpy.ndarray): Variable 1 y (numpy.ndarray): Variable 2 Returns: float: RECI fit score """ x = np.reshape(minmax_scale(x), (-1, 1)) y = np.reshape(minmax_scale(y),...
Infer causal relationships between 2 variables using the CDS statistic
def predict_proba(self, a, b, **kwargs): """ Infer causal relationships between 2 variables using the CDS statistic Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 Returns: float: Causation score (Value : 1 if a->b and -1 if b->a) "...
Computes the cds statistic from variable 1 to variable 2
def cds_score(self, x_te, y_te): """ Computes the cds statistic from variable 1 to variable 2 Args: x_te (numpy.ndarray): Variable 1 y_te (numpy.ndarray): Variable 2 Returns: float: CDS fit score """ if type(x_te) == np.ndarray: x...
Prediction method for pairwise causal inference using the ANM model.
def predict_proba(self, a, b, **kwargs): """Prediction method for pairwise causal inference using the ANM model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 Returns: float: Causation score (Value : 1 if a->b and -1 if b->a) """ ...
Compute the fitness score of the ANM model in the x - > y direction.
def anm_score(self, x, y): """Compute the fitness score of the ANM model in the x->y direction. Args: a (numpy.ndarray): Variable seen as cause b (numpy.ndarray): Variable seen as effect Returns: float: ANM fit score """ gp = GaussianProcessR...
Run PC on an undirected graph.
def orient_undirected_graph(self, data, graph, **kwargs): """Run PC on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by PC o...
Run the PC algorithm.
def create_graph_from_data(self, data, **kwargs): """Run the PC algorithm. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by PC on the given data. """ # Building setup w/ arguments. self.argu...
Setting up and running pc with all arguments.
def _run_pc(self, data, fixedEdges=None, fixedGaps=None, verbose=True): """Setting up and running pc with all arguments.""" # Checking coherence of arguments # print(self.arguments) if (self.arguments['{CITEST}'] == self.dir_CI_test['hsic'] and self.arguments['{METHOD_INDEP}']...
Computes the cds statistic from variable 1 to variable 2
def b_fit_score(self, x, y): """ Computes the cds statistic from variable 1 to variable 2 Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 Returns: float: BF fit score """ x = np.reshape(scale(x), (-1, 1)) y = np.resh...
Predict the graph skeleton.
def predict(self, data, alpha=0.01, max_iter=2000, **kwargs): """ Predict the graph skeleton. Args: data (pandas.DataFrame): observational data alpha (float): regularization parameter max_iter (int): maximum number of iterations Returns: networkx...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additiona...
Autoset GPU parameters using CUDA_VISIBLE_DEVICES variables.
def autoset_settings(set_var): """Autoset GPU parameters using CUDA_VISIBLE_DEVICES variables. Return default config if variable not set. :param set_var: Variable to set. Must be of type ConfigSettings """ try: devices = ast.literal_eval(os.environ["CUDA_VISIBLE_DEVICES"]) if type(d...
Output some information on CUDA - enabled devices on your computer including current memory usage. Modified to only get number of devices.
def check_cuda_devices(): """Output some information on CUDA-enabled devices on your computer, including current memory usage. Modified to only get number of devices. It's a port of https://gist.github.com/f0k/0d6431e3faa60bffc788f8b4daa029b1 from C to Python with ctypes, so it can run without compilin...
Get the default parameters as defined in the Settings instance.
def get_default(self, *args, **kwargs): """Get the default parameters as defined in the Settings instance. This function proceeds to seamlessly retrieve the argument to pass through, depending on either it was overidden or not: If no argument was overridden in a function of the toolbox,...
Convert a ChaLearn Cause effect pairs challenge format into numpy. ndarray.
def read_causal_pairs(filename, scale=True, **kwargs): """Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray. :param filename: path of the file to read or DataFrame containing the data :type filename: str or pandas.DataFrame :param scale: Scale the data :type scale: bool ...
Read a file ( containing an adjacency matrix ) and convert it into a directed or undirected networkx graph.
def read_adjacency_matrix(filename, directed=True, **kwargs): """Read a file (containing an adjacency matrix) and convert it into a directed or undirected networkx graph. :param filename: file to read or DataFrame containing the data :type filename: str or pandas.DataFrame :param directed: Return d...
Read a file ( containing list of edges ) and convert it into a directed or undirected networkx graph.
def read_list_edges(filename, directed=True, **kwargs): """Read a file (containing list of edges) and convert it into a directed or undirected networkx graph. :param filename: file to read or DataFrame containing the data :type filename: str or pandas.DataFrame :param directed: Return directed grap...
Compute the loss model.
def forward(self, pred, target): """Compute the loss model. :param pred: predicted Variable :param target: Target Variable :return: Loss """ loss = th.FloatTensor([0]) for i in range(1, self.moments): mk_pred = th.mean(th.pow(pred, i), 0) ...
Compute the test statistic
def predict(self, a, b): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic """ a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return (m...
Compute the test statistic
def predict(self, a, b): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic """ a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return sp...
Compute the test statistic
def predict(self, a, b, sig=[-1, -1], maxpnt=500): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 sig (list): [0] (resp [1]) is kernel size for a(resp b) (set to median distance if -1) maxpnt (int): maximum numb...
Generic predict method chooses which subfunction to use for a more suited.
def predict(self, x, *args, **kwargs): """Generic predict method, chooses which subfunction to use for a more suited. Depending on the type of `x` and of `*args`, this function process to execute different functions in the priority order: 1. If ``args[0]`` is a ``networkx.(Di)G...
Generic dataset prediction function.
def predict_dataset(self, x, **kwargs): """Generic dataset prediction function. Runs the score independently on all pairs. Args: x (pandas.DataFrame): a CEPC format Dataframe. kwargs (dict): additional arguments for the algorithms Returns: pandas.Da...
Orient an undirected graph using the pairwise method defined by the subclass.
def orient_graph(self, df_data, graph, nb_runs=6, printout=None, **kwargs): """Orient an undirected graph using the pairwise method defined by the subclass. The pairwise method is ran on every undirected edge. Args: df_data (pandas.DataFrame): Data umg (networkx.Graph):...
Run the algorithm on an undirected graph.
def orient_undirected_graph(self, data, graph): """Run the algorithm on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given...
Run the algorithm on a directed_graph.
def orient_directed_graph(self, data, graph): """Run the algorithm on a directed_graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.DiGraph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given sk...
Run the algorithm on data.
def create_graph_from_data(self, data): """Run the algorithm on data. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the algorithm. """ # Building setup w/ arguments. self.arguments['{SC...
Compute the gaussian kernel on a 1D vector.
def computeGaussKernel(x): """Compute the gaussian kernel on a 1D vector.""" xnorm = np.power(euclidean_distances(x, x), 2) return np.exp(-xnorm / (2.0))
Init a root cause with a Gaussian Mixture Model w/ a spherical covariance type.
def gmm_cause(points, k=4, p1=2, p2=2): """Init a root cause with a Gaussian Mixture Model w/ a spherical covariance type.""" g = GMM(k, covariance_type="spherical") g.fit(np.random.randn(300, 1)) g.means_ = p1 * np.random.randn(k, 1) g.covars_ = np.power(abs(p2 * np.random.randn(k, 1) + 1), 2) ...
Init a noise variable.
def normal_noise(points): """Init a noise variable.""" return np.random.rand(1) * np.random.randn(points, 1) \ + random.sample([2, -2], 1)
Init a uniform noise variable.
def uniform_noise(points): """Init a uniform noise variable.""" return np.random.rand(1) * np.random.uniform(points, 1) \ + random.sample([2, -2], 1)
Mechanism function.
def mechanism(self, x): """Mechanism function.""" result = np.\ zeros((self.points, 1)) for i in range(self.points): result[i, 0] = self.a * self.b * (x[i] + self.c) / (1 + abs(self.b * (x[i] + self.c))) return result + self.noise
Mechanism function.
def mechanism(self, causes): """Mechanism function.""" result = np.zeros((self.points, 1)) for i in range(self.points): pre_add_effect = 0 for c in range(causes.shape[1]): pre_add_effect += causes[i, c] pre_add_effect += self.noise[i] ...
Mechanism function.
def mechanism(self, x, par): """Mechanism function.""" list_coeff = self.polycause[par] result = np.zeros((self.points, 1)) for i in range(self.points): for j in range(self.d+1): result[i, 0] += list_coeff[j]*np.power(x[i], j) result[i, 0] = min(re...
Mechanism function.
def mechanism(self, x): """Mechanism function.""" self.nb_step += 1 x = np.reshape(x, (x.shape[0], 1)) if(self.nb_step < 5): cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) elif(...
Mechanism function.
def mechanism(self, x): """Mechanism function.""" layers = [] layers.append(th.nn.modules.Linear(self.n_causes+1, self.nh)) layers.append(th.nn.Tanh()) layers.append(th.nn.modules.Linear(self.nh, 1)) self.layers = th.nn.Sequential(*layers) data = x.astype('floa...
Runs Jarfo independently on all pairs.
def predict_dataset(self, df): """Runs Jarfo independently on all pairs. Args: x (pandas.DataFrame): a CEPC format Dataframe. kwargs (dict): additional arguments for the algorithms Returns: pandas.DataFrame: a Dataframe with the predictions. """ ...
Use Jarfo to predict the causal direction of a pair of vars.
def predict_proba(self, a, b, idx=0, **kwargs): """ Use Jarfo to predict the causal direction of a pair of vars. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 idx (int): (optional) index number for printing purposes Returns: f...
Python implementation/ translation of network deconvolution by MIT - KELLIS LAB.
def network_deconvolution(mat, **kwargs): """Python implementation/translation of network deconvolution by MIT-KELLIS LAB. .. note:: code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution) LICENSE: MIT-KELLIS LAB AUTHORS: Algorithm was programmed by...
Implementation of the Context Likelihood or Relatedness Network algorithm.
def clr(M, **kwargs): """Implementation of the Context Likelihood or Relatedness Network algorithm. Args: mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes it is a relevance matrix where mat(i,j) represents the similarity content between nodes i and j. Elements o...
Implementation of the ARACNE algorithm.
def aracne(m, **kwargs): """Implementation of the ARACNE algorithm. Args: mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes it is a relevance matrix where mat(i,j) represents the similarity content between nodes i and j. Elements of matrix should be non-...
Apply deconvolution to a networkx graph.
def remove_indirect_links(g, alg="aracne", **kwargs): """Apply deconvolution to a networkx graph. Args: g (networkx.Graph): Graph to apply deconvolution to alg (str): Algorithm to use ('aracne', 'clr', 'nd') kwargs (dict): extra options for algorithms Returns: networkx.Graph: g...