Пример #1
0
def Main(input_file):
    """Finds the optimized seating arrangement for the dinner table for the highest possible score

    The "score" of a table is determined by the following criteria:

    1 point for every adjacent pair (seated next to each other) of people with one a host and the other a guest. 2
    points for every opposite pair (seated across from each other) of people with one a host and the other a guest.
    h(p1, p2) + h(p2, p1) points for every adjacent or opposite pair of people p1, p2 where h(p1,2) is the preference
        function between two people

    inputs:
        File name for initializing the dinner table
    returns:
        None

    """
    # Increase the recursion limit max (used for the optomization function)
    sys.setrecursionlimit(100000)
    # Get all the people at the dinner table
    persons = Parse(input_file)
    # Optimize the seating arrangements for the highest score
    score, people = Optimize(persons, 0, 1, float("-inf"))
    # Print the result in the desired format
    print(score)
    people.sort(key=lambda x: x.GetNumber())
    for person in people:
        print(str(person.GetNumber()) + " " + str(person.GetPosition()))
Пример #2
0
    def move(self, desX0, desY0):

        optimize = Optimize(self.canvas, Notes.instances)
        list = optimize.sort()
        count = 0

        for rects in Notes.instances:
            desX0 = list[count][0]
            desY0 = list[count][1]
            count = count + 1
            if (not rects.moveable):
                continue

            if ((rects.x0 == desX0) & (rects.y0 == desY0)):
                rects.moveable = False
                continue

            pos = self.canvas.coords(rects.data)
            x0 = pos[0]
            y0 = pos[1]
            x1 = pos[2]
            y1 = pos[3]

            if (x0 > desX0):
                self.canvas.move(rects.data, -rects.xspeed, 0)
                self.canvas.move(rects.label, -rects.xspeed, 0)

            elif (x0 < desX0):
                self.canvas.move(rects.data, rects.xspeed, 0)
                self.canvas.move(rects.label, rects.xspeed, 0)

            if (y0 > desY0):
                self.canvas.move(rects.data, 0, -rects.yspeed)
                self.canvas.move(rects.label, 0, -rects.yspeed)

            elif (y0 < desY0):
                self.canvas.move(rects.data, 0, rects.yspeed)
                self.canvas.move(rects.label, 0, rects.yspeed)

            rects.x0 = x0
            rects.y0 = y0
            rects.x1 = x1
            rects.y1 = y1

        self.canvas.update()
        time.sleep(self.speed)
Пример #3
0
 def Othogonize(self, df):
     df = df.dropna()
     df = df.reset_index(drop=True)
     newdf = df.drop('ticker', 1)
     colnames = newdf.columns
     arraytbeo = np.array(newdf)
     otho = pd.DataFrame(Opt.Gram_Schmidt(arraytbeo), columns=colnames)
     otho.insert(0, 'ticker', df['ticker'])
     otho[colnames] = otho[colnames].apply(lambda x: stats.zscore(x))
     return (otho)
Пример #4
0
def main():
    Settings.init()

    default_radius = 2
    default_height = 5

    # Load in image and seeds
    filename = 'testdata.tif'
    img = tif.imread(filename)
    seedfilename = 'testdata_maxima_binary.tif'
    seeds = s.get_seeds(seedfilename)

    cylinder = cyl.Cylinder(default_radius, default_height)
    vis.render_gauss(cylinder)

    best_score, best_theta, best_psi = Optimize.optimize_angle(cylinder, seeds[257], img)
Пример #5
0
    def test_OptimizeTwoByTwo(self):
        person_number1 = 1
        person_type1 = "G"
        person1 = Person(person_number1, person_type1)
        person_number2 = 2
        person_type2 = "H"
        person2 = Person(person_number2, person_type2)
        person_number3 = 3
        person_type3 = "G"
        person3 = Person(person_number3, person_type3)
        person_number4 = 4
        person_type4 = "H"
        person4 = Person(person_number4, person_type4)

        person1.SetDown(person3)
        person2.SetDown(person4)
        person3.SetUp(person1)
        person4.SetUp(person2)

        person1.SetAdjRight(person2)
        person2.SetAdjLeft(person1)
        person3.SetAdjRight(person4)
        person4.SetAdjLeft(person3)

        person1.SetRelationTo(person2, 1)
        person1.SetRelationTo(person3, 2)
        person1.SetRelationTo(person4, 3)
        person2.SetRelationTo(person1, 4)
        person2.SetRelationTo(person3, 5)
        person2.SetRelationTo(person4, 6)
        person3.SetRelationTo(person1, 7)
        person3.SetRelationTo(person2, 8)
        person3.SetRelationTo(person4, 9)
        person4.SetRelationTo(person1, 10)
        person4.SetRelationTo(person2, 11)
        person4.SetRelationTo(person3, 12)

        dinnerTable = [person1, person2, person3, person4]

        score, people = Optimize(dinnerTable, 0, 1, float("-inf"))
        self.assertEqual(score, Calc(people))
def compiler_function(dag_circuit, coupling_map=None, gate_costs=None):
    #Instantiate an object of that class
    opt = Optimize(dag_circuit, coupling_map)
    #print(opt.qasm)
    #print(dag_circuit.qasm())

    #there are two cases:
    #1. the original qasm code can be exeucted on the platform after adjusted the id of qubit
    #2. the original qasm can't be exeucted by adjusting the id, then we have to use SWAP gates
    oriQASM = dag_circuit.qasm()
    opt.setQASM(oriQASM)

    #the QASM can be executed on the targat platform
    tarQASM = opt.qasm
    if opt.badCnot != []:
        oriQASM = opt.adjustID()
        #generate the final qasm code
    tarQASM = opt.generateQASM(oriQASM)
    tarQASM = opt.reduceSameGate(tarQASM)
    #generate the instance of DAGCircuit
    resCircuit = qasm_to_dag_circuit(tarQASM)
    return resCircuit
Пример #7
0
 def algorithm(self, event):
     optimize = Optimize(self.canvas, Notes.instances)
     list = optimize.sort()
Пример #8
0
import Segmentize
import DataAccesser
import PointCollection
import Optimize
import numpy as np

TEXT_STARTING_POINT = 1515628800  # UNIX Time Stamp for first stock market data in "PriceData"
trainStartTime = 1527811200  # The data we are considering to train
trainEndTime = 1528441200

Points = PointCollection.generateDataPoints(trainStartTime)

trainingPrices = DataAccesser.generate_price("PriceData", trainStartTime,
                                             trainEndTime, TEXT_STARTING_POINT)
trainingSegments = Segmentize.get_segments(trainingPrices)
theta = Optimize.findBestTheta(Points, trainingSegments)

testStartTime = trainEndTime
testEndTime = 100000000000

testingPrices = DataAccesser.generate_price("PriceData", testStartTime,
                                            testEndTime, TEXT_STARTING_POINT)
testSegments = Segmentize.get_segments(testingPrices)

m = Optimize.generateWeightageMatrix(Points, testSegments)
gradients = np.transpose(np.matrix([segment.grad for segment in testSegments]))
print("Predicted Gradients of BTC price")
print(np.matmul(m, theta))
print("\n Actual Gradient")
print(gradients)
Пример #9
0


# The parameters which are to be optimized are specified. This is done by initializing the dictionary 
# VariableParameters indexed by the elements whose parameters are being optimized including len()=8 arrays 
# of the form [0.,0.,1.,1.,0.,1.,0.], where 0 means the parameter is to be kept constant while 1 means it 
# is to be optimized. The Initial values of the parameters to be optimized are then set in the list ParamInit.
VariableParameters = {'Cu': numpy.array([1.,1.,1.,1.,1.,1.,1.]),
                      'Au': numpy.array([1.,1.,1.,1.,1.,1.,1.])}
Elements = VariableParameters.keys()
# The alloys desired are given in ElementsAllyos
#ElementsAlloys = ['AuCu3']
ElementsAlloys = []


# Experimental values picked from tabel
ParamInit = []
for i in Elements:
    for j in range(7):
        if VariableParameters[i][j] == 1:
            ParamInit.append(parameters[i][j])

# The ErrorFunction object is created using the chosen elements and variable parameters
ErrorFunc = EF(Elements,ElementsAlloys,VariableParameters)

# The minimization simplex algorithm is run using the ErrorFunction.
print Optim.fmin(ErrorFunc.ErFu,ParamInit,xtol=0.001,ftol=0.001)



Пример #10
0
filename = 'testdata.tif'
whole_img = tif.imread(filename)
#seedfilename = 'testdata_maxima_binary.tif'
#seeds = s.get_seeds(seedfilename)
#seed = [37, 39, 7]
#seed = [42, 48, 7]
#seed = [46, 57, 7]
#seed = [53, 84, 5]
seed = [63, 96, 1]


cylinder = Cylinder(default_radius, default_height, psf=2, first=True)

# Correct indices (if negative) and pad cropped image if necessary
indices = cylinder.get_image_indices(seed)
corrected_indices, pad_sequence = check_bounds(indices, whole_img)

cropped_img = whole_img[corrected_indices]
padded_cropped_img = np.pad(cropped_img, pad_sequence, mode='constant')
score, best_theta, best_psi = opt.optimize_angle(cylinder, seed, padded_cropped_img)
cylinder.rotate(best_psi, best_theta)

vis.overlay_cylinder('output.tif', whole_img, cylinder, seed)

#best_score, best_theta, best_psi = Optimize.optimize_angle(cylinder, seeds[257], img)

#fit_score = cylinder._score_correlation(img)

#if __name__ == '__main__':
#   main()
Пример #11
0
    for l in range(1,L-1):
        y=Opt(y,l)
        etmp=E(y,y)
        eplt.append(etmp)
        print([t,etmp])




plt.plot(eplt)
"""

eplt = []
yT = []
"end vectors blow up for MPS(5,3,2)"
"I think im doing LCon from the wrong direction"
for t in range(0, 5):
    y = Cononical_Form.RCon(y, 0)
    yT.append(y)
    for l in range(1, L - 1):
        y = Cononical_Form.LCon(y, L - l)
    for l in range(1, L - 1):
        y = Optimize.Opt(y, l)
        yT.append(y)
        etmp = Hamiltonain_MPO.E(y, y)
        eplt.append(etmp)
        print([t, etmp])
        y = Cononical_Form.RCon(y, l)
        yT.append(y)

plt.plot(eplt)
## Initialize the model
model = PyTorchDGP.DeepRegressionModel_ODE([1, 2, D_OUT],
                                           sigma=sigma,
                                           l=l,
                                           init_noise=noise,
                                           init_Student_scale=-2,
                                           N_ODE_parameters=N_ODE_parameters)

## Optimization loop
start_time = time.time()
n_optimization_stages = 13
for optimization_stage in range(n_optimization_stages):
    Optimize.Optimize_ODE(x,
                          y,
                          model,
                          dataset,
                          optimization_stage,
                          n_optimization_stages,
                          D_OUT,
                          Print=True)
stop_time = time.time()

## Save plot of ODE solution with parameters drawn from learned posterior
misc.plot(x.data.numpy(),
          y.data.numpy(),
          model,
          coefs,
          initial_cond,
          tmin,
          tmax,
          dataset,
          path='RESULTS/' + dataset + '_ode_dgp_1dgf_EXPERIMENT_' +
Пример #13
0
def get_optimized_courses(list):
    best_options = Optimize.optimize(list[0], list[1], list[2], list[3],
                                     list[4])
    return best_options
Пример #14
0
print("------------------------------------------------------------------------------------------------------------------")

print("Combining Fanduel Data with Predicted Data")



playerList = ReadWriteFiles.gen_description_and_fanduel_map(dictionary,csvFileName)

#write_playerList(playerList)

print("Done using Fanduel Data and now optimizing to find best predicted line-up")

#playerList = readPlayerList()
    

result = Optimize.optimize(playerList,totalSalary)

Util.format_print(result)

print("writing files to update information")
if(not isUpdated):
    ReadWriteFiles.writePlayerStats(currentMap)
    ReadWriteFiles.writeFeaturesFiles(trainingFeatures_arr,testingFeatures_arr,todayFeatures_arr)
    ReadWriteFiles.writeLabelsCSVFiles(trainingLabels_arr,testingLabels_arr)
    ReadWriteFiles.write_all_today_preds(preds)
    ReadWriteFiles.writeInjuredIDMap(injuredIDMap)
#final_preds could be different if player list from fanduel is updated
ReadWriteFiles.write_final_preds(result)


Пример #15
0
    def test_OptimizeThreeByTwo(self):
        person_number1 = 1
        person_type1 = "G"
        person1 = Person(person_number1, person_type1)
        person_number2 = 2
        person_type2 = "H"
        person2 = Person(person_number2, person_type2)
        person_number3 = 3
        person_type3 = "H"
        person3 = Person(person_number3, person_type3)
        person_number4 = 4
        person_type4 = "H"
        person4 = Person(person_number4, person_type4)
        person_number5 = 5
        person_type5 = "G"
        person5 = Person(person_number5, person_type5)
        person_number6 = 6
        person_type6 = "G"
        person6 = Person(person_number6, person_type6)

        person1.SetDown(person4)
        person2.SetDown(person5)
        person3.SetDown(person6)
        person4.SetUp(person1)
        person5.SetUp(person2)
        person6.SetUp(person3)

        person1.SetAdjRight(person2)
        person2.SetAdjLeft(person1)
        person2.SetAdjRight(person3)
        person3.SetAdjLeft(person2)
        person4.SetAdjRight(person5)
        person5.SetAdjLeft(person4)
        person5.SetAdjRight(person6)
        person6.SetAdjLeft(person5)

        person1.SetRelationTo(person2, -1)
        person1.SetRelationTo(person3, -5)
        person1.SetRelationTo(person4, 0)
        person1.SetRelationTo(person5, -9)
        person1.SetRelationTo(person6, -5)
        person2.SetRelationTo(person1, -8)
        person2.SetRelationTo(person3, -5)
        person2.SetRelationTo(person4, -7)
        person2.SetRelationTo(person5, -4)
        person2.SetRelationTo(person6, 9)
        person3.SetRelationTo(person1, 1)
        person3.SetRelationTo(person2, -2)
        person3.SetRelationTo(person4, 7)
        person3.SetRelationTo(person5, 8)
        person3.SetRelationTo(person6, 1)
        person4.SetRelationTo(person1, 2)
        person4.SetRelationTo(person2, 2)
        person4.SetRelationTo(person3, 7)
        person4.SetRelationTo(person5, 1)
        person4.SetRelationTo(person6, 0)
        person5.SetRelationTo(person1, 10)
        person5.SetRelationTo(person2, 6)
        person5.SetRelationTo(person3, -6)
        person5.SetRelationTo(person4, 0)
        person5.SetRelationTo(person6, 6)
        person6.SetRelationTo(person1, -8)
        person6.SetRelationTo(person2, -7)
        person6.SetRelationTo(person3, -6)
        person6.SetRelationTo(person4, -6)
        person6.SetRelationTo(person5, 7)

        dinnerTable = [person1, person2, person3, person4, person5, person6]

        score, people = Optimize(dinnerTable, 0, 1, float("-inf"))
        self.assertEqual(score, Calc(people))