Пример #1
0
def main():
    initialize()
    eventHandler = EventHandler()
    frameRateHandler = FrameRateHandler(60)

    squareSize = 100
    totalSize = squareSize * 3
    offsetY = squareSize
    offsetX = 0
    backColor = Color(0, 0, 0)
    mainSurface = pygame.display.set_mode(
        (totalSize + offsetX, totalSize + offsetY))

    gameBoard = GameBoard(0, offsetY, eventHandler, mainSurface)

    while True:
        frameRateHandler.updateStart()
        eventHandler.update()

        if eventHandler.quit or eventHandler.keys.release[K_ESCAPE]:
            break

        gameBoard.update()

        mainSurface.fill(backColor)
        gameBoard.draw()

        pygame.display.flip()

        frameRateHandler.updateEnd()
Пример #2
0
def start_simulation():
    global param,OD_pairs,edges,edge_pairs,OD,demand_input,demand_data,msa_flow,destination_data
    for i in range(len(param)):
        for j in range(5):
            param[i][j] = param[i][j].get()    # Converting the gui object into its corresponding value

    for i in range(len(OD_pairs)):
        for j in range(2):
            OD_pairs[i][j] = OD_pairs[i][j].get()   # Converting the gui object into its corresponding value

    # GUI related
    alist = root.winfo_children()
    for item in alist:
        if(item.winfo_children()):
            alist.extend(item.winfo_children())
    for item in alist:
        item.destroy()

    # Updating the edge dictionary storing length width density and cell number corresponding to a particular link
    for i in range(len(param)):
        n1,n2,l,w,k = int(param[i][0]),int(param[i][1]),float(param[i][2]),float(param[i][3]),int(param[i][4])
        edges[n1][n2] = [l,w,k,int(math.ceil(l/0.225))]
        edge_pairs.append([n1,n2])
        incoming_links[n2].append(i)    #Adding i to the incoming links corresponding to node n2
        outgoing_links[n1].append(i)    #Adding i to the outgoing links corresponding to node n1

    for i in range(len(OD_pairs)):
        o,d = map(int,(OD_pairs[i][0],OD_pairs[i][1]))
        OD.append([o,d])

    for i in OD:
        demand_input[i[0]][i[1]] = [0, 0, 0, 0]

    # Opening the demand1.txt file that contains the class wise demand data for each O-D pair separated by space
    file = open('demand.txt', 'r')
    demand = file.readlines()
    for i in range(len(demand)):
        demand[i] = list(map(int,demand[i].split()))    #Storing the first line corresponding to demand1 file
    for i in range(len(OD)):
        for j in range(len(demand)):
            demand_data[tuple(OD[i])].append(demand[j][i * 4:(i + 1) * 4])  #Storing four values at a time and appending that to the corresponding O-D pair in demand_data dictionary

    for i in OD:
        for j in range(simtime):
            msa_flow[(i[0],i[1])].append([0,0,0,0]) #Initializing the msa flow

    for i in OD:
        destination_data[i[1]] = [0,0,0,0] #initializing the destination flow corresponding to each destination node that stores the flow coming out of the network at every destination node

    initialize()    #Calling the initialize function
    OD_dictionary()     #Calling the OD_dictionary function
    linkpath_calculation()  #Calling the link_path calculation function
    flow_visual()  # Calling the flow visualization method
Пример #3
0
def main():
	initialize()
	eventHandler = EventHandler()
	frameRateHandler = FrameRateHandler(60)
	meshDict = loadMeshes()

	backColor = Color(0, 0, 0)
	mainSurface = pygame.display.set_mode((1280, 720))

	objectHandler = ObjectHandler(eventHandler, frameRateHandler, mainSurface, meshDict)

	interfaceHandler = InterfaceHandler(objectHandler)

	tankMesh = RawMesh([
		("body", [(8, 0), (40, 0), (48, 8), (48, 40), (40, 48), (8, 48), (0, 40), (0, 8)]),
		("gun", [(0, 0), (45, 0), (45, 10), (0, 10)], (5, 5))
	])

	playerMesh = Mesh(tankMesh, (0, 0))



	while True:
		frameRateHandler.updateStart()
		eventHandler.update()

		if eventHandler.quit or eventHandler.keys.release[K_ESCAPE]:
			break

		objectHandler.update()

		mainSurface.fill(backColor)
		objectHandler.draw()
		interfaceHandler.draw()

		pygame.display.flip()

		frameRateHandler.updateEnd()
Пример #4
0
def DoubleMoonTest():
    myann = NeuralNetwork('Dong Dong Network')
    myann.model.SetInputLayer(2)
    myann.model.SetOutputLayer('SoftMax')
    myann.model.SetFullConnectLayer([(15,'ReLu'),(2,None)])
    Na = 500
    Nb = 500
    (x,y) = initialize(10,6,-4,Na,Nb)
    x = x.transpose()
    yy = np.zeros([Na+Nb,2])
    for i in range(Na+Nb):
       if y[0,i]==1:
           yy[i,0] = 1
       else:
           yy[i,1] = 1
    myann.setSamples(x,yy)
    myann.MiniBatch_Train(700,2000)
Пример #5
0
def DoubleMoonTest():
    myann = NeuralNetwork('Dong Dong Network')
    myann.model.SetInputLayer(2)
    myann.model.SetOutputLayer('SoftMax')
    myann.model.SetFullConnectLayer([(15, 'ReLu'), (2, None)])
    Na = 500
    Nb = 500
    (x, y) = initialize(10, 6, -4, Na, Nb)
    x = x.transpose()
    yy = np.zeros([Na + Nb, 2])
    for i in range(Na + Nb):
        if y[0, i] == 1:
            yy[i, 0] = 1
        else:
            yy[i, 1] = 1
    myann.setSamples(x, yy)
    myann.MiniBatch_Train(700, 2000)
Пример #6
0
def DoubleMoonTest():
    myann = NeuralNetwork('Dong Dong Network')
    myann.model.SetInputLayer(2)
    myann.model.SetOutputLayer('SoftMax')
    myann.model.SetFullConnectLayer([(15,'ReLu'),(2,None)])



    Na = 500
    Nb = 500
    (x,y) = initialize(10,6,-4,Na,Nb)
    #y[y==0]=-1    #use tanh to classify
    yy = np.zeros([2,Na+Nb])
    for i in range(Na+Nb):
       if y[0,i]==1:
           yy[0,i] = 1
       else:
           yy[1,i] = 1
    myann.setSamples(x,yy)
    #myann.setSamples(x,y)
    myann.MiniBatch_Train(700,2000)
Пример #7
0
def main():
    # Prompts users for a file name containing the graph structure.
    graph_name = input('Graph Structure File: ')
    node_list = read_graph(graph_name)
    # Prompts users for a file name containing the possibles values of the nodes.
    val_name = input('Node Value File: ')
    node_list = read_val(val_name, node_list)
    # Prompts users for a file name containing the probabilities.
    prob_name = input('Probability File: ')
    node_list = read_prob(prob_name, node_list)
    # Initializes the graph structure.
    evidence, node_list = initialize(node_list)
    exit_flag = False
    while not exit_flag:
        # Resets the nodes and evidence to their initial values.
        node_list = read_graph(graph_name)
        node_list = read_val(val_name, node_list)
        node_list = read_prob(prob_name, node_list)
        evidence, node_list = initialize(node_list)
        # Prompts the user for a node and value of interest.
        int_node = input('Input the node of interest and its value (ex: A1): ')
        # Prompts the user for all the evidence.
        evi_nodes = input('Input all evidence nodes (ex: B1 C0 D1). If there is no evidence, type None: ')
        if evi_nodes == 'None':
            # Gets the name and value associated with the node of interest.
            interest_name, interest_val = name_val(int_node)
            # Since there is no evidence, we need only the marginal distribution given no evidence, which we
            # initialized as 'Empty.'
            cond_prob = node_list[interest_name].cond[interest_val]['Empty']
            print('The conditional probability of', int_node, 'given no evidence is', '{0:0.4f}.'.format(cond_prob))
        else:
            # Gets the name and value associated with the node of interest.
            interest_name, interest_val = name_val(int_node)
            # Updates the network for every evidence given.
            evidence_list = evi_nodes.split(' ')
            for e in evidence_list:
                evidence, node_list = update(e, node_list, evidence)
            # Creates a list of the evidence.
            evi_list = list()
            for v in evidence:
                evi_list.append(v + str(evidence[v]))
            # Gets the conditional probability given the evidence.
            try:
                cond_prob = node_list[interest_name].cond[interest_val][tuple(sorted(evi_list))]
            # If the exact conditional probability doesn't exist, then a message wasn't sent, so we have to
            # use a different metric.
            except KeyError:
                # Gets a list of all the conditional probabilities.
                cond_list = list(node_list[interest_name].cond[interest_val].keys())
                # Scores each conditional probability by the number of shared indices with the evidence.
                score_dict = score(evi_list, cond_list)
                # The one with the most amount of similar indices is the one that we want.
                condition = max(score_dict, key=score_dict.get)
                cond_prob = node_list[interest_name].cond[interest_val][condition]
            print('The conditional probability of', int_node, 'given', evi_nodes, 'is', '{0:0.4f}.'.format(cond_prob))
        # Cycling exit prompt, for convenience.
        exit_prompt = input('Would you like to make another query? (Y or N): ')
        if exit_prompt == 'Y':
            exit_flag = False
        else:
            exit_flag = True
Пример #8
0
import pandas as pd
import sys
import time

input_file = ('''/Users/edz/Documents/Princeton/Senior/ORF411'''
              '''/OJ/not_grapefruit/Results/notgrapefruit2016.xlsm''')

# We also need the Results file of the previous year in order to
# initialize the inventory.
last_year_file = ('''/Users/edz/Documents/Princeton/Senior/ORF411'''
                  '''/OJ/not_grapefruit/Results/notgrapefruit2015.xlsm''')

print 'Initializing...'
start = time.time()
initial_inventory = initialize_inventory(last_year_file)
storages, processing_plants, groves, markets, decisions = initialize(
    input_file, initial_inventory)
print 'Initialization took {0}'.format(time.time() - start)

#### Test Storage
s = storages['S51']

# Test adding products
s.add_product('ORA', 500)
assert s.inventory['ORA'] == [500, 0, 0, 0]
s.add_product('POJ', 200)
assert s.inventory['POJ'] == [200, 0, 0, 0, 0, 0, 0, 0]

# Test aging
s.age()
assert s.inventory['ORA'] == [0, 500, 0, 0]
assert s.inventory['POJ'] == [0, 200, 0, 0, 0, 0, 0, 0]
Пример #9
0
#     'S59': {
#         'POJ': 82.316,
#         'FCOJ': 77.9730,
#         'ROJ': 86.51086
#     },
#     'S73': {
#         'POJ': 122.47359,
#         'FCOJ': 101.586,
#         'ROJ': 69.24297
#     }
# }

print 'Initializing...'
start = time.time()
initial_inventory, scheduled_to_ship_in = initialize_inventory(last_year_file)
storages, processing_plants, groves, markets, decisions = initialize(
    input_file, initial_inventory)
print 'Initialization took {0}'.format(time.time() - start)

sales = {'ORA': 0, 'POJ': 0, 'ROJ': 0, 'FCOJ': 0}
revenues = {'ORA': 0, 'POJ': 0, 'ROJ': 0, 'FCOJ': 0}
cost = {
    'purchase': {
        'raw': 0,
        'futures': {
            'ORA': 0,
            'FCOJ': 0
        }
    },
    'manufacturing': {
        'POJ': 0,
        'FCOJ': 0,
Пример #10
0
    w = 84  # links width
    h = 12  # links height
    init_angle = np.pi / 18
    sigma_p = 5
    sigma_th = 10 * np.pi / 180
    sigma_s = 2
    eps = 1e-5

    ## Initialize graph
    [pairs, node_ids, neighbor_dict, num_pairs] = initGraph()

    # initialize a message for each node
    displayImage_msg = observation.copy()
    msg_prev = dict()
    for pair in pairs:
        msg_prev[pair], gt_circle, gt_links = initialize(
            pair[1], num_components, init_angle, w, h)
        displayMessages(msg_prev[pair], labelFromId(pair[1]), displayImage_msg)
    cv2.imwrite("initialize.jpg", displayImage_msg)

    # iterate to converge
    for i in range(num_iterations):
        displayImage_msg = observation.copy()

        # NBP update of nonparametric message t -> s
        msg_curr = {}
        for pair in pairs:
            print("iter: {0}, pair:".format(i), pair, flush=True)
            no_u = False
            t_id = pair[0]  # t node
            s_id = pair[1]  # s node
            t_label = labelFromId(t_id)
Пример #11
0
    setPanel(3,(0,0,0))
    setPanel(4,(0,0,0))



# Already created savings-accounts.
# <Food and beverage> <Living costs> <Housing> <Transportation> <Leisure time>
accounts = ["50000000102", "50000000103","50000000104","50000000105","50000000106"]
#
accounts_dummy = ["50000000108","50000000109","50000000110","50000000111","50000000112"]


customer = "01011900123"
customer_dummy = "01011900124"

initialize(accounts, accounts_dummy, customer, customer_dummy)

last_balance = [1,1,1,1,1]
current_balance = [0,0,0,0,0]

print("The Matrix is now initialized.")
print("Welcome.")
print([getBalance(customer, acc) for acc in accounts])

while True:
    try:
        #Poll account balances
        current_balance = [getBalance(customer, acc) for acc in accounts]
        for i in range(0,N):
            if current_balance[i] != last_balance[i]:
                print('Account balance update for Account:',i, account_categories[i])
Пример #12
0
# Make sure you replace the API and/or APP key below
# with the ones for your account
import initialize
import api
from datadog import initialize, api

options = {
    'api_key': 'd15bc0c919de4948552c9fd532b03620',
}

initialize(**options)

print api.Tag.get_all()