コード例 #1
0
    def __init__(self, number, myWorldState, agType=""):
        # the environment
        self.agOperatingSets = []
        self.number = number
        # self.news = np.zeros(common.dim+3) # contiene l'ultima notizia
        # [id-fonte, id-mittente, data, topics(dim)]

        if myWorldState != 0:
            self.myWorldState = myWorldState
        self.agType = agType

        self.state = np.array([random.random() for i in range(common.dim)])
        self.state = self.state / self.state.sum()

        if graph.getGraph() == 0:
            graph.createGraph()  # if first agent create the graph
        common.G.add_node(self.number, agent=self)  # adds himself
        if common.cycle == 1:  # create link only if you are only at the first step of the clock and if you are the last user
            if len(common.G.nodes()) == common.N_AGENTS:
                graph.initializeEdges()  # if last creates edges

        self.active = True
        self.databaseCols = [
            'id-n', 'new', 'id-source', 'date-creation', 'relevance',
            'id-send', 'date-send', 'id-recive', 'date-recive'
        ]
        self.database = {}
        print("agent", self.agType, "#", self.number, "has been created")
コード例 #2
0
def main():
    # user input
    print('1 - Input K and calculate')
    print('2 - Input your own test data raw')
    # print('3 - Draw graph")
    user_input = raw_input("Please enter k for calulation: ")
    if user_input == '1':
        calculateWithK(-1)
    if user_input == '2':
        receiveTestDataInputByUser()
    if user_input == '3':
        createGraph()
コード例 #3
0
ファイル: HMM.py プロジェクト: letsdeckersousa/bigdata_basic
def aPosterioriDecoding(seq, fileNameEmis, fileNameTrans):
    statesGraph = graph.createGraph(fileNameEmis,
                                    fileNameTrans)  # it's a dictionary
    f = forward(seq, fileNameEmis, fileNameTrans)
    b = backward(seq, fileNameEmis, fileNameTrans)
    seq = seq[1:-1]
    psm = f[len(f) - 1][len(f[0]) - 1]
    pi = matrix.createMatrix(len(statesGraph["A"]["A", "States"]), len(seq),
                             0.)
    print "F:"
    matrix.printMatrix(f)
    print "B:"
    matrix.printMatrix(b)
    print "Seq:", seq
    print "Size of Seq: ", len(seq)

    for i in range(len(seq)):  #pi(i) -> position in the sequence = collunms
        scores = []
        for k in range(1, len(statesGraph["A"][
                "A", "States"])):  #num of states that produce chars = lines
            scores.append((f[k][i + 1] * b[k][i + 1]) / psm)
        pi[0][i] = scores.index(max(scores)) + 1  #states are from 1 to lines-1
        pi[1][i] = scores[0]
        pi[2][i] = scores[1]

        del (scores)
    return pi
コード例 #4
0
ファイル: regex.py プロジェクト: george-miller/regex
def compile(regex):
    result = syntax.test(regex)
    if result >= 0:
        print "{0}{1}{2}{3}".format(regex[:result], bcolors.FAIL,
                                    regex[result:], bcolors.ENDC)
        print "regex.compile: Error at index " + str(result)
        return None
    else:
        return graph.createGraph(regex)
コード例 #5
0
ファイル: TestSearcher.py プロジェクト: george-miller/regex
def run():
	for test in testGraphs:
		g = graph.createGraph(test[0])
		found = findAll(test[1], g)
		if len(test[2]) != len(found):
			for i in found: print i
			print 
			for i in test[2]: print i
			raise Exception("Expected array of length {0} but got {1}.".format(len(test[2]), len(found)))
		for result in test[2]:
			if not result in found:
				raise Exception("Expected [{0}] in {1}".format(result, [str(s) for s in found]))
コード例 #6
0
ファイル: HMM.py プロジェクト: letsdeckersousa/bigdata_basic
def viterbi(seq, filenameEmission, filenameTransmission):
    forwardGraph = graph.createGraph(filenameEmission, filenameTransmission)
    #print forwardGraph
    char = seq[1]
    states = forwardGraph["E"]["E", "States"]
    statesCompl = states[:]
    statesCompl.insert(0, "0")
    statesCompl.append("0")
    m = matrix.createMatrix(len(states) + 2, len(seq), 0)
    trace = matrix.createMatrix(len(states) + 2, len(seq), -1)
    # intialisation part
    matrix.atualiseValueIntoMatrix(m, 0, 0, 1)
    # recurrence part
    # recurrence 1
    trace[1][1] = trace[2][1] = 0
    for i in range(1, len(m) - 1):
        m[i][1] = float(forwardGraph["A"]["0", statesCompl[i]]) * float(
            forwardGraph["E"][statesCompl[i], char])
    # recurrence 2
    for j in range(2, len(m[0]) - 1):  #jump the first 2 collumns
        char = seq[j]
        for i in range(1, len(m) - 1):  # jump the begin and end states
            scores = []
            for l in range(1, len(m) - 1):
                #print "L:",statesCompl[l],", K:",statesCompl[i]
                scores.append(
                    float(m[l][j - 1]) *
                    float(forwardGraph["A"][statesCompl[l], statesCompl[i]]) *
                    float(forwardGraph["E"][statesCompl[i], char]))
                '''print "partial value: ",scores[-1]
                print "lines value:", float(m[l][j-1])
                print "AKL: ",float(forwardGraph["A"][statesCompl[l],statesCompl[i]])
                print "Elc: ", float(forwardGraph["E"][statesCompl[i],char])'''

            m[i][j] = max(scores)
            #print "Max: ", scores.index(max(scores))+1
            trace[i][j] = scores.index(max(scores)) + 1
            #print (m[i][j])
            #print "---------------------------------"
            del (scores)
    scores = []
    for i in range(1, len(m) - 1):
        scores.append(
            float(m[i][len(m[0]) - 2]) *
            float(forwardGraph["A"][statesCompl[i], "0"]))
    m[len(m) - 1][len(m[0]) - 1] = max(scores)
    trace[len(m) - 1][len(m[0]) - 1] = scores.index(max(scores)) + 1
    #print "__________________________"
    #matrix.printMatrix(m)
    #matrix.printMatrix(trace)
    return trace
コード例 #7
0
ファイル: TestSearcher.py プロジェクト: george-miller/regex
def run():
    for test in testGraphs:
        g = graph.createGraph(test[0])
        found = findAll(test[1], g)
        if len(test[2]) != len(found):
            for i in found:
                print i
            print
            for i in test[2]:
                print i
            raise Exception("Expected array of length {0} but got {1}.".format(
                len(test[2]), len(found)))
        for result in test[2]:
            if not result in found:
                raise Exception("Expected [{0}] in {1}".format(
                    result, [str(s) for s in found]))
コード例 #8
0
ファイル: app.py プロジェクト: chuckry/hollywood_duos
def entry():
	# Read posted values
	_name = request.form['inputName']
	_type = request.form['inputType']
	_excl = request.form['exclusivity']
	_genres = request.form.getlist('check')
	_runtime = request.form['runtime']

	# Validate information
	if _name and _type:
		results = json.loads(duos.run(_name, _type, _excl, _genres, _runtime))
		if results['Error'] == 1:
			return "Couldn't find " + json.loads(results)['Person'] + "!"
		else:
			# pprint.pprint(results)
			return graph.createGraph(results)
	else:
		return "Complete required fields!"
コード例 #9
0
ファイル: writeVideo.py プロジェクト: YumanYIN/Pro
def writeVideo(path, listOfPic, listOfRec, numOfPic):

    global lenOfPic
    global widOfPic

    lenOfPic = len(listOfPic[0][0])
    widOfPic = len(listOfPic[0])
    graphPoints = []

    for i in range(0, numOfPic):  # the i th picture in the video

        # get list of all of information of rectangles in the i th picture
        temp = slicing.slicingFunction(listOfPic[i], listOfRec[i], i + 1, path,
                                       widOfPic, lenOfPic)
        graphPoints.append(temp)

    graphs = []
    x = 0

    # to found a directory
    if not os.path.exists(path + '/GXL'):
        os.makedirs(path + '/GXL')

    for graphPoint in graphPoints:
        # to create graphs for pictures according to the list of all of information of rectangles
        G = graph.createGraph(graphPoint, 150)

        # to save these graphs
        graph.writeGraph(G, x, path + "/GXL/")
        graphs.append(G)
        x += 1

    for i in range(0, len(graphs) - 1):
        match.match2Graph(graphs[i], graphs[i + 1])
        drawNewGraph(graphs[i], path, i)
    drawNewGraph(graphs[len(graphs) - 1], path, len(graphs) - 1)

    size = (lenOfPic, widOfPic)

    productVideo.picvideo(path + '/graphs', size)

    print("done")
コード例 #10
0
ファイル: HMM.py プロジェクト: letsdeckersousa/bigdata_basic
def backward(seq, filenameEmission, filenameTransmission):
    backwardGraph = graph.createGraph(filenameEmission, filenameTransmission)
    #print backwardGraph
    char = seq[len(seq) - 2]
    states = backwardGraph["E"]["E", "States"]
    statesCompl = states[:]
    statesCompl.insert(0, "0")
    statesCompl.append("0")
    seq = seq[:-1]
    m = matrix.createMatrix(len(states) + 2, len(seq), 0)
    # intialisation part
    # the final state
    for i in range(1, len(m) - 1):
        m[i][len(m[0]) - 1] = float(backwardGraph["A"][statesCompl[i], "0"])
    #matrix.printMatrix(m)
    # recurrence
    for j in range(len(m[0]) - 2, 0, -1):  #jump the first 2 collumns
        char = seq[j + 1]
        #print "char:", char
        for i in range(1, len(m) - 1):  # jump the begin and end states
            for l in range(len(m) - 2, 0, -1):
                #print "L:",statesCompl[l],", K:",statesCompl[i]
                m[i][j] += float(m[l][j + 1]) * float(backwardGraph["A"][
                    statesCompl[i], statesCompl[l]]) * float(
                        backwardGraph["E"][statesCompl[l], char])
                ''' print "partial value: ",float(m[i][j])
                print "lines value:", float(m[l][j+1])
                print "Alk: ",float(backwardGraph["A"][statesCompl[i],statesCompl[l]])
                print "Elc: ", float(backwardGraph["E"][statesCompl[l],char])'''
    for l in range(1, len(m) - 1):
        m[0][0] += float(m[l][1]) * float(
            backwardGraph["A"]["0", statesCompl[l]]) * float(
                backwardGraph["E"][statesCompl[l], seq[1]])
        '''print "psm: ",psm
        print "lines value:", float(m[l][j+1])
        print "Alk: ",float(backwardGraph["A"]["0",statesCompl[l]])
        print "Elc: ", float(backwardGraph["E"][statesCompl[l],seq[1]])
        print "Char: ", seq[1]'''
    #matrix.printMatrix(m)
    return m
コード例 #11
0
ファイル: HMM.py プロジェクト: letsdeckersousa/bigdata_basic
def forward(seq, filenameEmission, filenameTransmission):
    forwardGraph = graph.createGraph(filenameEmission, filenameTransmission)
    #print forwardGraph
    char = seq[1]
    states = forwardGraph["E"]["E", "States"]
    statesCompl = states[:]
    statesCompl.insert(0, "0")
    statesCompl.append("0")
    statesCompl = ["0", "Y", "N", "0"]
    print statesCompl

    m = matrix.createMatrix(len(states) + 2, len(seq), 0)
    # intialisation part
    matrix.atualiseValueIntoMatrix(m, 0, 0, 1)
    # recurrence part
    # recurrence 1
    for i in range(1, len(m) - 1):
        m[i][1] = float(forwardGraph["A"]["0", statesCompl[i]]) * float(
            forwardGraph["E"][statesCompl[i], char])
    # recurrence 2
    for j in range(2, len(m[0]) - 1):  #jump the first 2 collumns
        char = seq[j]
        for i in range(1, len(m) - 1):  # jump the begin and end states
            for l in range(1, len(m) - 1):
                #print "L:",statesCompl[l],", K:",statesCompl[i]
                m[i][j] += float(m[l][j - 1]) * float(
                    forwardGraph["A"][statesCompl[l], statesCompl[i]]) * float(
                        forwardGraph["E"][statesCompl[i], char])
                '''print "partial value: ",float(m[i][j])
                print "lines value:", float(m[l][j-1])
                print "AKL: ",float(forwardGraph["A"][statesCompl[l],statesCompl[i]])
                print "Elc: ", float(forwardGraph["E"][statesCompl[i],char])'''
    for i in range(1, len(m) - 1):
        m[len(m) - 1][len(m[0]) - 1] += float(m[i][len(m[0]) - 2]) * float(
            forwardGraph["A"][statesCompl[i], "0"])
    matrix.printMatrix(m)
    return m
コード例 #12
0
def button4():
    graph.createFunModuleGraph(lf, listOfFunNames, listOfFunCC)
    graph.create_function_graph(lf, listOfFunNames, listOfFunCC)
    graph.createGraph(lf)
    matplotlib.pyplot.show()
コード例 #13
0
ファイル: db.py プロジェクト: christian-drewes/blackjacksim
def graphWins():
    graph.createGraph(countWins('p1_wins'), countWins('palt_wins'),
                      countWins('d1_wins'), countWins('dalt_wins'))
コード例 #14
0
			total_blocking.append(0)
		else:
			total_blocking.append(block[i]/reqs[i])
	return total_blocking

for i in sched_pol:
	print("Executions of heuristic {}".format(i))
	#begin the experiments
	for j in range(execution_times):
		print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
		print("Execution #{} of heuristic {}".format(j,i))
		print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
		#simulation environment
		env = simpy.Environment()
		#create the graph
		gp = g.createGraph()
		#create the control plane
		cp = sim.Control_Plane(env, "Graph", gp, i, "fog_first")
		#traffic generator
		tg = sim.Traffic_Generator(env,sim.distribution, None, cp)
		#create the rrhs
		cp.createRRHs(g.rrhs_amount,env)
		random.shuffle(g.rrhs)
		#create fog nodes
		g.addFogNodes(gp, g.fogs)
		#add RRHs to the graph
		g.addRRHs(gp, 0, 64, "0")
		g.addRRHs(gp, 64, 128, "1")
		g.addRRHs(gp, 128, 192, "2")
		g.addRRHs(gp, 192, 256, "3")
		g.addRRHs(gp, 256, 320, "4")
コード例 #15
0
import graph

vertices = [0, 1, 2, 3, 4, 5]
edges = ((5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1))
adj = graph.createGraph(vertices, edges)
print "Graph:", adj

parent = {}


def dfs(u, adj):
    for v in adj[u]:
        if v not in parent:
            parent[v] = u
            dfs(v, adj)


def complete_dfs(vertices, adj):
    parent = {}

    for s in vertices:
        if s not in parent:
            parent[s] = None
            dfs(s, adj)

    return parent


# try algorithm
dfs(5, adj)
print "DFS result (parent dictionary): ", parent
コード例 #16
0
ファイル: enron.py プロジェクト: asantinc/nlp_enron
        pair = pairs[hashKey]
        output = pair[0]+' '+pair[1]
        email = jointEmailsDict[hashKey]
        sorted_words, stemTokenDict = getImportantWords(email, myIDF, stemmer)
        sorted_words = [stemTokenDict[x[0]] for x in sorted_words]
        best_10_words = sorted_words[:10]                       #get the top 10 words based on frequency and IDF
        keywords = ' '.join(best_10_words)
        output += '\t'+keywords+'\n'
        pairFile.write(output)
    pairFile.close()
         

if __name__ == '__main__':

    #get Enron graph
    [outNodes, sinkNodesSet, inNodes, sendReceiveDict] = graph.createGraph(GRAPH)

    #PAGERANK and HITS
    [AuthDict, HubDict] = hits.getHubsAuth(outNodes, inNodes, HUB_FILE, AUTH_FILE, ITERATIONS)
    pagerankDict = pageRank.getPageRank(outNodes, sinkNodesSet, ITERATIONS, PR_FILE, LAMBDA)
    
    #This part is useless unless GraphViz is installed
    if PRODUCE_GRAPH == True:
        #Take the union of people
        tempSet = set(pagerankDict.keys()).union(set(AuthDict.keys()))
        importantEmployees = tempSet.union(HubDict.keys())          #list of all emails of the important people 
        #Remove useless pete davis
        importantEmployees.remove('*****@*****.**')     

        #ROLES and EMAILS passed around
        roleDict = getRoles(ROLES)     
コード例 #17
0
def drawModel(model):
    createGraph(model["name"], model["activation_values"], model["weights"],
                model["biases"],
                ["Epoch #" + model["epochs"] + " RMSE", model["RMSE"]])
コード例 #18
0
ファイル: main.py プロジェクト: dhanushkamathS/dietTracker
def main():

    #no arguments
    if (len(sys.argv) == 1):
        helps()
        return

    # with one arguments
    if (len(sys.argv) == 2):

        argument = str(sys.argv[1])

        if (argument == "ls"):
            listCurrentDayFood()
            return
        elif (argument == "dls"):
            detailedListCurrentDayFood()
            return
        elif (argument == "lsdb"):
            ListFoodInInventory()
            return

        elif (argument == "cal"):
            if (caloriesConsumed() == -1):
                print("calorie not set")
                return
            if (caloriesConsumed() == 0):
                print(
                    f"set calorie : %d cal consumed : %d cal balanced : %d cal"
                    % (getLimitCaloriesInDB(), getCalorieOfDay(),
                       caloriesConsumed()))
            elif (caloriesConsumed() < 0):
                print(
                    f"set calorie : %d cal consumed : %d cal surplus : +%d cal"
                    % (getLimitCaloriesInDB(), getCalorieOfDay(),
                       caloriesConsumed() * -1))

            else:
                print(
                    f"set calorie : %d cal consumed : %d cal deficit : -%d cal"
                    % (getLimitCaloriesInDB(), getCalorieOfDay(),
                       caloriesConsumed()))

        elif (argument == "graph"):
            createGraph()
            return
        elif (argument == "help"):
            helps()
            return
        else:
            print("invalid command")
            return

    #with two arguments
    if (len(sys.argv) == 3):
        argument = sys.argv[1]
        if (argument == "setcal"):
            try:
                setLimitCaloriesInDB(int(sys.argv[2]))
                print("calorie set")
                return
            except:
                print("invalid input")
                return
        if (argument == "rm"):
            removeFoodToUserStorage(sys.argv[2])
            return
        if (argument == "rmdb"):
            removeFoodFromInventory(sys.argv[2])
            return
        else:
            print("invalid command")
            return

    #with three arguments
    if (len(sys.argv) == 4):
        argument = sys.argv[1]
        if (argument == "add"):
            try:
                addFoodToUserStorage(sys.argv[2], int(sys.argv[3]))
                return
            except:
                print("invalid command")
                return
        else:
            print("invalid command")
            return
#with five arguments
#addFoodToInventory(foodName,carbs,protein,fat)
    if (len(sys.argv) == 6):
        argument = sys.argv[1]
        if (argument == "addtodb"):
            try:
                addFoodToInventory(sys.argv[2], int(sys.argv[3]),
                                   int(sys.argv[4]), int(sys.argv[5]))
                return
            except:
                print("invalid command")
                return
        else:
            print("invalid command")
            return

    #with six arguments
    if (len(sys.argv) == 7):
        argument = sys.argv[1]
        if (argument == "updateindb"):
            try:
                newname = sys.argv[3] if (sys.argv[3] != "-1") else -1
                updateFoodInInventory(sys.argv[2], newname, int(sys.argv[4]),
                                      int(sys.argv[5]), int(sys.argv[6]))
                return
            except:
                print("invalid command")
                return
        else:
            print("invalid command")
            return

    else:
        print("invalid command")
        return
コード例 #19
0
def button4():
    graph.createFunModuleGraph(lf)
    graph.create_function_graph(lf)
    graph.createGraph(lf)
    matplotlib.pyplot.show()
コード例 #20
0
def simulation(numTimeSteps, xSteps, ySteps, occupied, occupiedOld,
               totNumCells, xPos, yPos, deathTime, pro, proOld, densityScale,
               lamda, k, fib, vegf, ySubstrate, vegfOld, tolerance, h, xLength,
               fibOld, xVector, yVector, movement, maxCell, birthTime,
               divideTime):
    densityMax = 6
    k18 = 0.55555555
    k20 = 0.0496031736
    k25 = 5736.899771
    k26 = .00001859
    m1 = 2
    # child = 0.25      # 12 hours iteration 5400
    child = 0.125  # 6 hours iteration 2700
    # child = 0.0625      # 3 hours iteration 1350
    fibThreshold = 0.6
    workspace = zeros((ySteps, xSteps))
    file = open("tracking_backtracks.txt", "w")
    file2 = open("prolif_death.txt", "w")

    # Cycle through time steps
    for time in range(numTimeSteps - 1):
        # Copy occupied into occupiedOld
        for x in range(xSteps):
            for y in range(ySteps):
                occupiedOld[y][x] = occupied[y][x]
        # Cycle through cells
        for cell in range(totNumCells):
            # At first assume no movement
            x = xPos[cell][time]
            y = yPos[cell][time]
            xPos[cell][time + 1] = x
            yPos[cell][time + 1] = y

            # If cell has left the capillary
            # not including dividing and death right now because it doesn't work with anastomosis
            #'''
            # DETERMINE IF CELL HAS DIVIDED OR DIED
            if deathTime[cell] == numTimeSteps - 1 and y > 0:
                # add statement to test if dead
                # cell dies/leaves simulation if it reaches the tumour
                if y == ySteps - 1:
                    deathTime[cell] = time
                    occupied[y][x] -= 1

                # calculate average protease values at time and time-1
                # surrounding mesh points usually equals 4 unless it is a boundary condition
                proMinus0 = 0
                proMinus1 = 0
                count = 0

                #LEFT
                if x > 0:
                    proMinus0 = proMinus0 + pro[2 * y][x - 1]
                    proMinus1 = proMinus1 + proOld[2 * y][x - 1]
                    count += 1

                #RIGHT
                if x < xSteps - 1:
                    proMinus0 = proMinus0 + pro[2 * y][x]
                    proMinus1 = proMinus1 + proOld[2 * y][x]
                    count += 1

                #UP
                if y > 0:
                    proMinus0 = proMinus0 + pro[2 * y - 1][x]
                    proMinus1 = proMinus1 + proOld[2 * y - 1][x]
                    count += 1

                #DOWN
                if y < ySteps:
                    proMinus0 = proMinus0 + pro[2 * y + 1][x - 1]
                    proMinus1 = proMinus1 + proOld[2 * y + 1][x - 1]
                    count += 1

                proMinus0 = proMinus0 / count
                proMinus1 = proMinus1 / count

                # logistic term is always 0 becauce denScale times occupied is always greater than densitymax
                if densityScale * occupied[y][x] > densityMax:
                    logistic = 0
                else:
                    logistic = 1 - densityScale * occupied[y][x] / densityMax

                G = k25 * (exp(-k26 * proMinus0**m1) *
                           (1 - k26 * m1 * proMinus0**m1)) / (
                               1 + k25 * proMinus0 * exp(-k26 * proMinus0**m1))

                proDependent = G * (proMinus0 - proMinus1) / k

                if proDependent >= 0:
                    # haven't figured out logistic term yet
                    # divideProb = (k * k18 + G * logistic * (proMinus0 - proMinus1)) * \
                    #             heaviside(time - divideTime[cell] - child * numTimeSteps)
                    divideProb = (k * k18 + G * (proMinus0 - proMinus1)) * \
                                 heaviside(time - divideTime[cell] - child * numTimeSteps)
                    deathProb = k * k20
                else:
                    divideProb = k * k18 * heaviside(time - divideTime[cell] -
                                                     child * numTimeSteps)
                    deathProb = k * k20 - G * (proMinus0 - proMinus1)

                # not sure if I need this part
                #if divideProb < 0:
                #    divideProb = 0
                #if divideProb > 1 - deathProb:
                #    divideProb = 1

                randomNum = random()

                if randomNum < deathProb:
                    file2.write("\n\nTIME: " + str(time) + "\n")
                    file2.write("CELL: " + str(cell) + "\n")
                    file2.write("cell position: y = " + str(y) + " x = " +
                                str(x) + "\n")
                    file2.write("average protease at time - 1 : " +
                                str(proMinus1) + "\n")
                    file2.write("average protease at time: " + str(proMinus0) +
                                "\n")
                    #file2.write("logistic growth term: " + str(logistic) + "\n")
                    file2.write("Protease dependent term: " +
                                str(proDependent) + "\n")
                    file2.write("Probability of division: " + str(divideProb) +
                                "\n")
                    file2.write("Probability of death: " + str(deathProb) +
                                "\n")
                    file2.write("Probability of doing nothing: " +
                                str(1 - deathProb - divideProb) + "\n")
                    file2.write("random number: " + str(randomNum) + "\n")
                    file2.write("G: " + str(G) + "\n")
                    file2.write("CELL DIED")
                    deathTime[cell] = time
                    occupied[y][x] -= 1
                    createGraph(ySubstrate, xSteps, vegf, fib, pro, xVector,
                                yVector, workspace, time)

                elif randomNum < deathProb + divideProb:
                    if totNumCells >= maxCell:
                        print("too many cells. DO NOT DIVIDE")
                    elif totNumCells < maxCell:
                        file2.write("\n\nTIME: " + str(time) + "\n")
                        file2.write("CELL: " + str(cell) + "\n")
                        file2.write("cell position: y = " + str(y) + " x = " +
                                    str(x) + "\n")
                        file2.write("average protease at time - 1 : " +
                                    str(proMinus1) + "\n")
                        file2.write("average protease at time: " +
                                    str(proMinus0) + "\n")
                        #file2.write("logistic growth term: " + str(logistic) + "\n")
                        file2.write("Protease dependent term: " +
                                    str(proDependent) + "\n")
                        file2.write("Probability of division: " +
                                    str(divideProb) + "\n")
                        file2.write("Probability of death: " + str(deathProb) +
                                    "\n")
                        file2.write("Probability of doing nothing: " +
                                    str(1 - deathProb - divideProb) + "\n")
                        file2.write("random number: " + str(randomNum) + "\n")
                        file2.write("G: " + str(G) + "\n")
                        file2.write("CELL DIVIDED")
                        xPos[totNumCells][time + 1] = x
                        yPos[totNumCells][time + 1] = y
                        occupied[y][x] += 1
                        deathTime[totNumCells] = numTimeSteps - 1
                        birthTime[totNumCells] = time
                        divideTime[cell] = time
                        divideTime[totNumCells] = time
                        totNumCells += 1
                        createGraph(ySubstrate, xSteps, vegf, fib, pro,
                                    xVector, yVector, workspace, time)

            # DETERMINE IF/WHERE THE CELL MOVES
            if deathTime[cell] == numTimeSteps - 1:
                stay = pStay(y, lamda, k)
                left, T = pMove(x, y, 0, pro, fib, vegf, xSteps, ySteps, lamda,
                                k)
                right, T = pMove(x, y, 1, pro, fib, vegf, xSteps, ySteps,
                                 lamda, k)
                up, T = pMove(x, y, 2, pro, fib, vegf, xSteps, ySteps, lamda,
                              k)
                rand = random()
                # Check if cell can escape the capillary
                if y == 0:
                    if x == 0:
                        fibcap = fib[0][0]
                    elif x == xSteps - 1:
                        fibcap = fib[0][xSteps - 2]
                    else:
                        fibcap = (fib[0][x - 1] + fib[0][x]) / 2
                    if fibcap < fibThreshold:
                        rand = 2
                file = move(cell, time, stay, left, right, up, rand, yPos,
                            xPos, occupied, fib, vegf, pro, movement, file, T)
                '''
                # ANASTOMOSIS
                
                if yPos[cell][time + 1] > 0:
                    if workspace[yPos[cell][time + 1]][xPos[cell][time + 1]] != 0 and \
                            workspace[yPos[cell][time + 1]][xPos[cell][time + 1]] != cell + 2 and \
                            workspace[yPos[cell][time + 1]][xPos[cell][time + 1]] != cell + 3.5:
                        print("cell ran into another capillary")
                        deathTime[cell] = time + 1
                        occupied[yPos[cell][time + 1]][xPos[cell][time + 1]] -= 1

                workspace[yPos[cell][time]][xPos[cell][time]] = cell + 2
                workspace[yPos[cell][time + 1]][xPos[cell][time + 1]] = cell + 3.5
                '''

                # workspace without anastomosis
                workspace[yPos[cell][time]][xPos[cell][time]] = 1
                workspace[yPos[cell][time + 1]][xPos[cell][time + 1]] = 5

        total = 0
        for cell in range(totNumCells):
            if deathTime[cell] != numTimeSteps - 1:
                total += 1
        if total == totNumCells:
            print("ALL OF THE CELLS ARE DEAD")
            break

        updateVEGF(ySubstrate, xSteps, densityScale, occupiedOld, vegf,
                   vegfOld, k, tolerance, h, xLength)
        updateFib(ySubstrate, xSteps, densityScale, occupiedOld, fib, fibOld,
                  k, pro, tolerance, h)
        updatePro(ySubstrate, xSteps, densityScale, occupiedOld, pro, proOld,
                  k, vegfOld)

        print("time = " + str(time))

        if time % 500 == 0:
            createGraph(ySubstrate, xSteps, vegf, fib, pro, xVector, yVector,
                        workspace, time)

    return
コード例 #21
0
ファイル: part4.py プロジェクト: skytthe/31390-AUS
#!/usr/bin/env python3

import numpy as np
import networkx as nx

from graph import createGraph
from algorithms import *

if __name__ == "__main__":

    G = createGraph()

    print('###############')
    print('# DFS_low #####')
    print('###############')
    DFS_low(G, 0, 23)
    print('\n\n')

    print('#######################')
    print('# DFS_low_christopher #')
    print('#######################')
    DFS_low_CHRISTOPHER(G, 0, 23)
    print('\n\n')

    print('###############')
    print('# DFS_high    #')
    print('###############')
    DFS_high(G, 0, 23)
    print('\n\n')

    print('########################')
コード例 #22
0
def button3():
    graph.createGraph(lf)
    matplotlib.pyplot.show()
コード例 #23
0
def train(
    data=[[1], [2], [3]],
    targets=[[3], [2], [1]],
    layers=[1, 2, 1],
    output_bias=False,
    randWeightsLimits=[0, 1],
    activation_function=ReLU,
    cost_function=squared_error_CF,
    epochs=1,
    learning_rate=0.01,
    bias_learning_rate=None,
    pauseEpoch=False,
    pauseIteration=False,
    viz=[True, True, False]
):  #[plainchart, graph at end of training, graph at start of epoch or iteration]
    #flexibility to have different learning rates for bias
    if bias_learning_rate == None:
        bias_learning_rate = learning_rate

    #set up neural network architecture
    weights, biases = cnn(layers, randWeightsLimits, output_bias)
    RMSEs = []
    #run epochs
    print("Training " + activation_function.__name__ + " nn of layers " +
          str(layers))

    RMSE = 0
    for epoch in range(0, epochs):
        #restart error measurement
        squared_error_sum = 0

        #shuffle the data and corresponding targets
        c = list(zip(data, targets))
        random.shuffle(c)
        data, targets = zip(*c)

        #iterate over each data point
        print("Epoch " + str(epoch + 1) + "/" + str(epochs))

        for data_x_targets_index in range(0, len(data)):
            #collect data points
            input_set = data[data_x_targets_index]
            target_set = targets[data_x_targets_index]
            #forward prop, back prop and update weights
            activation_values = forwardSingleDataPoint(input_set, weights,
                                                       biases,
                                                       activation_function)

            squared_error, weight_gradients, bias_gradients = backwardSingleDataPoint(
                activation_values, target_set, weights, activation_function,
                cost_function)

            if epoch == 0 and data_x_targets_index == 0 and viz[
                    2] or pauseIteration:
                graph_name = activation_function.__name__ + " - Ep #" + str(
                    epoch) + ", It #" + str(
                        data_x_targets_index) + " @ lr " + str(learning_rate)
                createGraph(graph_name, activation_values, weights, biases,
                            ["0.5 * error^2", squared_error])

            if pauseIteration:
                print("weight gradients")
                print(weight_gradients)

                print("bias gradients")
                print(bias_gradients)

                input("Press Enter to start next iteration...")

            weights, biases = update(weights, biases, weight_gradients,
                                     bias_gradients, learning_rate,
                                     bias_learning_rate)

            #add to sum to calculate RMSE at end of epoch
            squared_error_sum += squared_error

        RMSE = (squared_error_sum / len(data))**(0.5)
        #print chart in terminal

        if epoch > 0:
            RMSEs.append(RMSE)
        print("RMSE :" + str(RMSE))

        if pauseEpoch:
            print("weights")
            print(weights)

            print("biases")
            print(biases)

            print("weight gradients")
            print(weight_gradients)

            print("bias gradients")
            print(bias_gradients)

            input("Press Enter to start next epoch...")

    #print RMSE Chart
    if epochs > 1 and viz[0]:
        chart = plainchart.PlainChart(RMSEs,
                                      style=plainchart.PlainChart.scatter)
        print(chart.render())
    #create nn graph
    graph_name = activation_function.__name__ + " - Epoch " + str(
        epochs) + ' @ lr ' + str(learning_rate)
    if viz[1]:
        print("Creating NN graph...")
        graph = createGraph(graph_name, activation_values, weights, biases,
                            ["Epoch #" + str(epochs) + " RMSE",
                             str(RMSE)])

    #save model
    model = {
        "weights": weights,
        "biases": biases,
        "layers": layers,
        "lr": learning_rate,
        "af": str(activation_function),
        "cf": str(cost_function),
        "RMSE": RMSE,
        "name": graph_name,
        "activation_values": activation_values,
        "epochs": epochs
    }

    #notify
    print("Completed training of " + activation_function.__name__ +
          " nn of layers " + str(layers))
    return model