Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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... |
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... |
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__... |
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 ... |
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, ... |
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... |
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
... |
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')
>>>... |
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.... |
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... |
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... |
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)... |
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
... |
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
... |
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()
... |
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 ... |
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... |
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.
... |
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... |
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... |
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{}'... |
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)
... |
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 ... |
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... |
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 |
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... |
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... |
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_... |
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)
... |
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... |
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 [
... |
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_... |
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... |
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... |
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... |
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) +... |
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... |
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... |
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... |
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],
... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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():
... |
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,
... |
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... |
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... |
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) |
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())) |
def forward(self, x):
"""Feed-forward the model."""
return self.layers(x * (self._filter *
self.fs_filter).expand_as(x)) |
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 |
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... |
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... |
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),... |
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)
"... |
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... |
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)
"""
... |
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... |
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... |
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... |
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}']... |
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... |
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... |
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... |
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... |
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... |
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,... |
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
... |
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... |
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... |
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)
... |
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... |
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... |
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... |
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... |
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... |
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):... |
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... |
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... |
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... |
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)) |
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)
... |
def normal_noise(points):
"""Init a noise variable."""
return np.random.rand(1) * np.random.randn(points, 1) \
+ random.sample([2, -2], 1) |
def uniform_noise(points):
"""Init a uniform noise variable."""
return np.random.rand(1) * np.random.uniform(points, 1) \
+ random.sample([2, -2], 1) |
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 |
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]
... |
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... |
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(... |
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... |
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.
"""
... |
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... |
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... |
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... |
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-... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.