Ejemplo n.º 1
0
def runRandomWalk(nbmanchots, run, iterations):

    for i in range(run):
        tabMachines = creerManchots(nbmanchots)
        nbiterations1.append(i+1)
        gains1.append(rw.rechercheAleatoire(iterations, tabMachines))
    print(gains1)
    return nbiterations1, gains1
Ejemplo n.º 2
0
import GraphGenerator as GG
import Graph as G
import RandomWalk

graph = GG.generate_graph("twenty_nodes.brite")
#graph = G.generateGraph(100,5)
src = 1
dest = 4
print graph
print "src : " + str(src)
print "dest : " + str(dest)

print "random walk path is :", RandomWalk.randomWalk(graph, src, dest)
print "shortest path: ", G.shortest_path(graph, src, dest)
Ejemplo n.º 3
0
from RandomWalk import *
import numpy as np
import matplotlib.pyplot as plt


def error(result):
    return np.sqrt(
        sum(
            abs(result[1:6] - [1 / 6.0, 2 / 6.0, 3 / 6.0, 4 / 6.0, 5 / 6.0])**
            2) / 5)


A = RandomWalk(3)
A_result = A.TD(100, 0.05, 1)
print(A_result)
print(error(A_result))

B = RandomWalk(3)
B_result = B.MC(100, 0.03, 1)
print(B_result)
print(error(B_result))

episode_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300]
TDalpha = [0.15, 0.1, 0.05]
MCalpha = [0.03, 0.02, 0.01]
TDresult = np.zeros((3, len(episode_list)))
MCresult = np.zeros((3, len(episode_list)))

N = 1000
for kk in range(N):
    for jj in range(3):
Ejemplo n.º 4
0
import random
import RandomWalk

import matplotlib.pyplot as plt
import statsmodels.api as sm
# set seed so we have everytime the same output
random.seed(7)
'''
# file = pd.read_csv("")
rng = pd.date_range("1/1/2000",periods=1000, freq="H")
rng[:5]
ts = pd.Series(np.random.randn(len(rng)),index=rng)
'''

ts = RandomWalk.random_generator(1000)
# Show the head of the file
ts.head()

# Plot the time series
# plt.plot(ts)
# plt.show()

# Take hourly means
ts.resample("H").mean()

# check stationarity of data
from statsmodels.tsa.stattools import adfuller


def test_stationarity(timeseries):
Ejemplo n.º 5
0
            words = line[:-1].split(' ')
            # edge_data_by_type如果没有words[0]则针对它创建一个list
            if words[0] not in edge_data_by_type:
                edge_data_by_type[words[0]] = list()
            x, y = words[1], words[2]
            edge_data_by_type[words[0]].append((x, y))
            all_nodes.append(x)
            all_nodes.append(y)
    # 去掉重复元素
    all_nodes = list(set(all_nodes))
    print('Total training nodes: ' + str(len(all_nodes)))
    return edge_data_by_type, all_nodes


# 下面为模拟GCN部分
datasets = RandomWalk.pre_trained('./data')
zkc = nx.Graph()
_, all_nodes = load_training_data('./data/train.txt')

# 给所有节点排序
order = sorted(list(all_nodes))
# A为构建的邻接矩阵
A = to_numpy_matrix(zkc, nodelist=order)
# 给邻接矩阵强行加入自环
I = np.eye(A.shape[0])
A_hat = A + I
# 求A_hat的度矩阵(degree matrix)
D_hat = np.array(np.sum(A_hat, axis=0))[0]
D_hat = np.matrix(np.diag(D_hat))

# 随机初始化权重
Ejemplo n.º 6
0
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, writers
import mpl_toolkits.mplot3d.axes3d as axes3d

import RandomWalk

interval = 50           # In milliseconds
boxSize = 20

randomWalk3D = RandomWalk.RandomWalk(dimension=3, boxSize=boxSize)

axesLimits = (-boxSize, boxSize)

fig = plt.figure()
ax = axes3d.Axes3D(fig, xlim=axesLimits, ylim=axesLimits, zlim=axesLimits)
line, = ax.plot([], [], [])

def animate(i):
    line.set_data(randomWalk3D[0:i, 0], randomWalk3D[0:i, 1])   # set_data accepts x and y coordinates only
    line.set_3d_properties(randomWalk3D[0:i, 2])                # z coordinates must be given by this function
    ax.view_init(30, i)                                         # In order to make it even fancier, we rotate the graph at each step
    return line, ax

anim = FuncAnimation(fig, animate, interval=interval, blit=True, frames=len(randomWalk3D))

# If we want to save the animation, we have to switch off blit!!!
#anim = FuncAnimation(fig, animate, interval=interval, frames=len(randomWalk3D))
#anim.save("randomwalk.gif", writer='imagemagick')
#anim.save("randomwalk.mp4", extra_args=['-vcodec', 'libx264'])
Ejemplo n.º 7
0
def main():
    RandomWalk.demo()
    BrownianMotion.demo()
Ejemplo n.º 8
0
#create nodes for the network graphic

#Generate nodes for the graph
for key in network:
    address = ('localhost', key)
    OnionRoutingNetwork.OnionRouter(address)

# create Client
clientPort = 300
client2Port = 500

#Choose a random port as destination and add it to the message (default start is 1)
dest = random.randint(2, len(network))

randomPath = RandomWalk.randomWalk(network, 1, dest)
print "Sending message through", randomPath
print "Number of Nodes traversed by random walk: ", len(randomPath)

message = "Is this a potato?"

data = {"Path": randomPath, "Message": message}

send = json.dumps(data)

client = Application.Application(clientPort, proxyServerAddress, send)
client.connectToServer()

shortestPath = shortest_path(network, 1, dest)
print "Sending message with shortest path : ", shortestPath
print "Number of nodes traversed by shortest path: ", len(shortestPath)
#*******************************************************************
# set number of walks to average over and range of steps per walk
Nwalks = 100
Nsteps = range(1,100000,5000)

# define array to store displacements
dMean = []

# loop through step range
for i in Nsteps:
    d = []
    
    # loop through number of walks and steps per walk
    for j in range(Nwalks):
        # call RandomWalk3D from my random walk module
        xp,yp,zp,dist = walk.RandomWalk3D(i)
        d.append(dist)
        
    # get average displacement for N walks
    dAve = np.average(d)
    dMean.append(dAve)


# relation should be a power function so take logs of both sides
x = np.log(np.array(Nsteps))
y = np.log(np.array(dMean))
# calculate slope of log-log plot to get power coefficient
rise = y[len(y)-1] - y[0]
run = x[len(x)-1] - x[0]
slope = round(rise/run,3)
                tf.traffic(tfc,i,b)
            
        
        del settings.networkbuffer[:] #Clean the network buffer


        
        ##REMOVE ALL EDFES at the start ( node doesn't have info about neighboors - no memory of graph)
        for k in range(0,len(settings.nodesList)):
            for l in range(0,len(settings.nodesList)):
                if  GlobalGraph.G.has_edge(k,l):
                    GlobalGraph.G.remove_edge(k,l)
        
        #The mobile nodes --randomwalk 
        for n in range(0,len(settings.nodesList)):
            rw.mobility_of_node(n,0.1)
            
        # I have to call neighbors in order to make the possible connections  
        
        #############################################
        #After this, I have to find neighbors for active nodes using Findneighbors
        for n in range(0,len(settings.nodesList)):
            if settings.nodesList[n].node_state == 1:
                FindNeighbors.find_neighbors(settings.nodesList[n].node_name)
        #############################################
        #REDUCE THE LIFETIME of all the packets in the buffers of nodes
        rlt.reduce_lifetime(2,i) #reduce every time slot the lifetime - 2 --> life of packet is 50 time slots.

        #To this point, (in every time slot) every node know their neighbors and thus
        # it can send a packet or receive a packet (or both)
Ejemplo n.º 11
0
import RandomWalk
import matplotlib.pyplot as plt
while True:
    ant = RandomWalk.RandomWalk()
    ant.fill_walk()

    # 可使用形参dpi向figure()传递该分辨率,以有效地利用可用的屏幕空间
    plt.figure(dpi=128, figsize=(10, 6))
    plt.plot(ant.x_values, ant.y_values)
    # plt.scatter(ant.x_values,ant.y_values,s=1,c=ant.x_values,cmap=plt.cm.Blues)
    plt.scatter(ant.x_values[0], ant.y_values[0], s=40, color='red')
    plt.scatter(ant.x_values[-1], ant.y_values[-1], s=40, color='red')

    #隐藏坐标轴
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)
    plt.show()
    keep_running = input("Make another RandowWalk?[y/n]")
    if keep_running == 'n':
        print("Wish to meet you next time")
        break
Ejemplo n.º 12
0
def main():
    print("Starting AUROC..")
    #Get file path choices
    pathToPPINetworkFile = sys.argv[1]
    #pathToPPINetworkFile = 'Data/9606.protein.links.v11.0.txt'

    # Get output vectors from each algorithm

    PPI_Network = compute_if_not_cached(loader.load_graph,
                                        pathToPPINetworkFile,
                                        fileName=pathToPPINetworkFile)
    ground_truth_files = [
        'Data/MalaCard-protein-Endometriosis.diseasegenes.tsv',
        'Data/MalaCard-protein-ischaemic-stroke.diseasegenes.tsv',
        'Data/MalaCard-protein-lymphoma.diseasegenes.tsv'
    ]
    file_paths = [
        'Data/endometriosis-proteins.diseasegenes.tsv',
        'Data/lymphoma-proteins.diseasegenes.tsv',
        'Data/ischaemic-proteins.diseasegenes.tsv'
    ]
    prior_paths = [
        'Data/endometriosis-proteins.priors.tsv',
        'Data/lymphoma-proteins.priors.tsv',
        'Data/ischaemic-proteins.priors.tsv'
    ]
    names = ['endometriosis', 'lymphoma', 'ischaemic']

    for i in range(1, 3):
        # building ground truth
        ground_truth_vec = []
        with open(ground_truth_files[i], 'r') as input_file:
            input_file = input_file.readlines()
            for line in input_file:
                protein = line.rstrip('\n')
                ground_truth_vec.append(protein)
        gene_file = open(file_paths[i], 'r')
        file_contents = list(gene_file.readlines())
        # print(file_contents)
        for line in file_contents:
            protein = line.rstrip('\n')
            if protein not in ground_truth_vec:
                ground_truth_vec.append(protein)
        gene_file.close()
        print(ground_truth_vec)
        # building start and priors vector

        start_vector = loader.load_start_vector(file_paths[i], PPI_Network)
        priors_vector = pr.load_priors(prior_paths[i], PPI_Network)

        #getting output from algorithms
        start_time = time.time()
        output_RWR = rwr.random_walk(PPI_Network, start_vector)
        end_time = time.time()
        print("time for rwr:", end_time - start_time)
        start_time = time.time()
        output_PR = pr.page_rank(PPI_Network, start_vector, priors_vector)
        end_time = time.time()
        print("time for pr:", end_time - start_time)

        start_time = time.time()
        output_DK = dk.diffusion_kernel(PPI_Network, start_vector)
        end_time = time.time()
        print("time for dk:", end_time - start_time)

        #building roc curves

        start_time = time.time()
        name = "rwr-" + names[i]
        rwr_curve = roc_curve(output_RWR, ground_truth_vec, name)
        end_time = time.time()
        print("time for roc curve, rwr:", end_time - start_time)

        start_time = time.time()
        name = "pr-" + names[i]
        pr_curve = roc_curve(output_PR, ground_truth_vec, name)
        end_time = time.time()
        print("time for roc curve, pr:", end_time - start_time)
        start_time = time.time()

        start_time = time.time()
        name = "dk-" + names[i]
        dk_curve = roc_curve(output_DK, ground_truth_vec, name)
        end_time = time.time()
        print("time for roc curve, dk:", end_time - start_time)
        file_path = 'Results/' + names[i] + 'roc_curve.png'
        plt.ylabel('TPR')
        plt.xlabel('FPR')
        plt.title(names[i])
        plt.legend(loc='lower right')
        plt.savefig(file_path)  #moved from roc_curve
        plt.clf()  #moved from roc_curve
        print("Plots have been saved as png files in the Results folder.")