예제 #1
0
def pointXRadius(stn):
    '''Using sampling within the polytope defined
       by the stn and a region around it defined by
       its surface area to find its surface area to
       volume ratio'''

    stn = stnConverter.dictToMatrix(stn)
    minimall = minimal(stn)
    largestInterval = 0
    for i in range(len(minimall[0])):
        if minimall[i][0] - minimall[0][i] > largestInterval:
            largestInterval = minimall[i][0] - minimall[0][i]

    radius = largestInterval / 2.0
    ratio = 0
    leftRatio = float('inf')
    leftRadius = 0
    rightRatio = 0
    rightRadius = largestInterval
    while ratio < TARGET_RATIO - EPSILON or ratio > TARGET_RATIO + EPSILON:
        ratio = resilience(stn, NUM_SAMPLES, False, "exact", radius, False)
        if ratio > TARGET_RATIO:
            leftRadius = radius
        else:
            rightRadius = radius
        radius = (leftRadius + rightRadius) / 2.0
    return radius
예제 #2
0
def wilsonFlex(stn):
    ''' input:  stn, a distance matrix
        output: the Wilson metric for flexibility
    '''
    stn = stnConverter.dictToMatrix(stn)
    n = len(stn)
    tplus = [0] * n
    tminus = [0] * n
    prob = LpProblem("LP", LpMaximize)

    # add variables and t- <= t+ constraints
    for i in range(0, n):
        tplus[i] = LpVariable("tp" + str(i))
        tminus[i] = LpVariable("tm" + str(i))
        prob += tminus[i] - tplus[i] <= 0

    # maximize all (t+ - t-)
    prob += sum([tplus[i] - tminus[i] for i in range(1, n)])

    # add constraints
    prob += tplus[0] == 0
    prob += tminus[0] == 0
    for i in range(n):
        for j in range(n):
            if i != j and stn[i][j] != float("inf"):
                prob += tplus[i] - tminus[j] <= stn[i][j]

    status = prob.solve()

    flex = sum([value(x) for x in tplus]) - sum([value(x) for x in tminus])
    return flex
예제 #3
0
def naiveVolFlex(d):
    stn = stnConverter.dictToMatrix(d)
    n = len(stn)
    flex = 1
    for i in range(1, n):
        flex *= stn[i][0] + stn[0][i]
    return flex
예제 #4
0
def realMinList(stn):
    origList = getList(stn)
    newList = getList(
        stnConverter.matrixToDict(test.minimal(
            stnConverter.dictToMatrix(stn))))
    finalList = []
    for ineq in origList:
        if ineq in newList:
            finalList.append(ineq)
    return finalList
예제 #5
0
def hunsbergerFlex(stn):
    ''' Takes distance matrix of STN,
        returns Hunsberger flexibility
    '''
    n = len(stn.keys())
    flex = naiveFlex(stn)
    stnn = stnConverter.dictToMatrix(stn)
    for i in range(1, n):
        for j in range(i + 1, n):
            flex += stnn[i][j] + stnn[j][i]
    return flex
예제 #6
0
def naiveFlex(d):
    ''' input:  stn, a distance matrix
        output: the naive flexibility metric  
    '''
    stn = stnConverter.dictToMatrix(d)
    n = len(stn)

    flex = 0
    for i in range(1, n):
        flex += stn[i][0] + stn[0][i]

    return flex
예제 #7
0
def earlyBird(ineqDict):
    n = len(ineqDict.keys())
    earlyPoint = [0] * n

    matrix = stnConverter.dictToMatrix(ineqDict)
    matrix = test.minimal(matrix)
    ineqDict = stnConverter.matrixToDict(matrix)

    for i in range(n - 1, 0, -1):
        earlyPoint[i] = -50000
        for ineq in ineqDict[i]:
            start = ineq[0]
            end = ineq[1]
            constraint = ineq[2]

            if i == start and (start < end or end == 0):
                earlyPoint[i] = max(earlyPoint[end] - constraint,
                                    earlyPoint[i])
    return earlyPoint
예제 #8
0
def rigidPoint(ineqDict, metric):
    minimalSTN = test.minimal(stnConverter.dictToMatrix(ineqDict))
    indices = range(0, len(minimalSTN))
    flexSchedule = [0] * (len(minimalSTN))

    while indices:
        maxFlex = 10000000
        maxIndex = -1
        time = -1

        for index in indices:
            timepoint = ((minimalSTN[0][index] + minimalSTN[index][0]) /
                         2) - minimalSTN[index][0]
            newMat = copy.deepcopy(minimalSTN)
            newMat[index][0] = -timepoint
            newMat[0][index] = timepoint
            if len(indices) > 1:
                currFlex = metricFunctions.sphericalMetric(
                    stnConverter.matrixToDict(newMat),
                    len(indices) - 1, metric)
            else:
                currFlex = 1
            if currFlex < maxFlex:
                # print 'currFlex: '  + str(currFlex)
                # print 'maxFlex: ' + str(maxFlex)
                maxFlex = currFlex
                maxIndex = index
                time = timepoint

        indexToAssign = maxIndex
        # delete the chosen index from the list of indices still to be assigned
        # print "THIS INDEX"
        # print indexToAssign
        indices.remove(indexToAssign)
        # assign the index a random time that can satisfy the STN
        flexSchedule[indexToAssign] = time

        # recalculate the minimal STN with this event nailed down
        minimalSTN[indexToAssign][0] = -time
        minimalSTN[0][indexToAssign] = time
        minimalSTN = test.minimal(minimalSTN)
    return flexSchedule
예제 #9
0
def midPoint(ineqDict):
    minimalSTN = test.minimal(stnConverter.dictToMatrix(ineqDict))
    indices = range(0, len(minimalSTN))
    midSchedule = [0] * (len(minimalSTN))

    while indices:

        indexToAssign = random.choice(indices)
        time = ((minimalSTN[0][indexToAssign] + minimalSTN[indexToAssign][0]) /
                2) - minimalSTN[indexToAssign][0]
        # delete the chosen index from the list of indices still to be assigned
        # print "THIS INDEX"
        # print indexToAssign
        indices.remove(indexToAssign)
        # assign the index a random time that can satisfy the STN
        midSchedule[indexToAssign] = time

        # recalculate the minimal STN with this event nailed down
        minimalSTN[indexToAssign][0] = -time
        minimalSTN[0][indexToAssign] = time
        minimalSTN = test.minimal(minimalSTN)

    return midSchedule
예제 #10
0
def closestBoundary(S, p):
    S = stnConverter.matrixToDict(test.minimal(stnConverter.dictToMatrix(S)))

    # throw out the zeroeth coordinate of the point because that is
    # the zero timepoint and isn't part of a given schedule
    p = [0] + [coord - p[0] for coord in p[1:]]

    r = sys.maxint

    # Loop through all the constraints and adjust r, the radius,
    # effectively finding the distance to the closest boundary of
    # the solution space for the STN
    for l in S.values():
        for inequal in l:
            start = inequal[0]
            end = inequal[1]
            constraint = inequal[2]

            temp = constraint - p[end] + p[start]
            if start != 0 and end != 0:
                temp /= math.sqrt(2)

            r = min(temp, r)
    return r
예제 #11
0
def pointBrawl(numTrials,
               dim,
               manWalk=False,
               posTime=False,
               randDim=False,
               multi=False,
               ray=False):

    chebMargin = 0
    centMargin = 0
    birdMargin = 0
    chebVCentMargin = 0
    chebVBirdMargin = 0
    centVBirdMargin = 0

    # Matric to store all the different quantities we may want to compute in a
    # simulation. The numbers on the right refer to indices of the matrix
    lol = [
        [],  # sphereMetric          0
        [],  # burgerMetric          1
        [],  # wilsonMetric          2
        [],  # radRatio              3
        [],  # naiveMetric           4
        [],  # chebMargin            5
        [],  # centMargin            6
        [],  # birdMargin            7
        [],  # chebVCentMargin       8
        [],  # chebVBirdMargin       9
        [],  # centVBirdMargin       10
        [],  # randomWalkCheb        11
        [],  # randomWalkCent        12
        [],  # randomWalkBird        13
        [],  # randomWalkManyPoints  14
        [],  # dimension             15
        [],  # STNs.                 16
    ]

    # Run the point arena on numTrials number of STNs
    procPool = mp.Pool(2)
    for i in range(numTrials):
        print "\nTrial " + str(i)
        chebAvg = 0
        centAvg = 0
        birdAvg = 0
        randAvg = 0

        numWalks = 100

        # Randomly choose the dimension between 2 and 10 events
        if randDim:
            dim = random.randint(2, 10)

        # generate STN with dim events, each constrained by 0 to 50
        genstn = stnConverter.matrixToDict(test.generateRandomSTN(dim, 0, 50))

        # minimize the STN because why not
        genstn = stnConverter.matrixToDict(
            test.minimal(stnConverter.dictToMatrix(genstn)))

        lol[15].append(dim)
        lol[16].append(genstn)

        # Metrics for analyzing an STN depending on what we are looking for.
        # This could be how "spherelike" the solution space is,
        sphereMet = metricFunctions.sphericalMetric(genstn, dim, "spherical")
        burgerMet = metricFunctions.sphericalMetric(genstn, dim, "burgers")
        wilsonMet = metricFunctions.sphericalMetric(genstn, dim, "wilson")
        radRatio = metricFunctions.sphericalMetric(genstn, dim, "radRatio")
        naiveMet = metricFunctions.sphericalMetric(genstn, dim, "hell")

        # Compute the possible "centers", or points we think may be optimal
        cheb = randomWalk.chebyshev(genstn)[0]
        cent = centroid(genstn)
        birdie = earlyBird(genstn)

        # Append the computed metric values to their respective rows
        lol[0].append(sphereMet)
        lol[1].append(burgerMet)
        lol[2].append(wilsonMet)
        lol[3].append(radRatio)
        lol[4].append(naiveMet)

        # Take the average of 100 randomWalks using 100 different points
        if not multi:
            for i in range(100):
                curr = simpleRandSched(genstn)
                for i in range(numWalks):
                    randAvg += randomWalk.perturb(genstn, curr, not ray,
                                                  posTime, ray)
        else:
            tuplist = [(genstn, numWalks, posTime, ray)] * 100
            results = procPool.map(mpRandoRandomWalker, tuplist)
            randAvg = sum(results)

        randAvg /= 100 * float(numWalks)

        # Take the average of 100 randomWalks starting at each "center"
        if not multi:
            for i in range(numWalks):
                chebAvg += randomWalk.perturb(genstn, cheb, not ray, posTime,
                                              ray)
                centAvg += randomWalk.perturb(genstn, cent, not ray, posTime,
                                              ray)
                birdAvg += randomWalk.perturb(genstn, birdie, not ray, posTime,
                                              ray)
        else:
            tup = [(genstn, cheb, cent, birdie, posTime, ray)] * numWalks
            results = procPool.map(mpCenterRandomWalker, tup)
            chebAvg = sum([res[0] for res in results])
            centAvg = sum([res[1] for res in results])
            birdAvg = sum([res[2] for res in results])

        chebAvg /= float(numWalks)
        centAvg /= float(numWalks)
        birdAvg /= float(numWalks)

        print "cheb " + "Average: " + str(chebAvg)
        print "cent " + "Average: " + str(centAvg)
        print "bird " + "Average: " + str(birdAvg)
        print "rand " + "Average: " + str(randAvg)

        # Compute the different margins of the centers vs each other
        if chebAvg == 0 and centAvg == 0:
            chebVCentMargin = 0
        else:
            chebVCentMargin = 2 * (chebAvg - centAvg) / (chebAvg + centAvg)
        if chebAvg == 0 and birdAvg == 0:
            chebVBirdMargin = 0
        else:
            chebVBirdMargin = 2 * (chebAvg - birdAvg) / (chebAvg + birdAvg)
        if centAvg == 0 and centAvg == 0:
            centVBirdMargin = 0
        else:
            centVBirdMargin = 2 * (centAvg - birdAvg) / (centAvg + birdAvg)

        # Compute the different margins of the centers vs random points
        if chebAvg == 0 and randAvg == 0:
            chebMargin = 0
        else:
            chebMargin = 2 * (chebAvg - randAvg) / (chebAvg + randAvg)
        if centAvg == 0 and randAvg == 0:
            centMargin = 0
        else:
            centMargin = 2 * (centAvg - randAvg) / (centAvg + randAvg)
        if birdAvg == 0 and randAvg == 0:
            birdMargin = 0
        else:
            birdMargin = 2 * (birdAvg - randAvg) / (birdAvg + randAvg)

        # Append the computed margins to their respective rows
        lol[5].append(chebMargin)
        lol[6].append(centMargin)
        lol[7].append(birdMargin)
        lol[8].append(chebVCentMargin)
        lol[9].append(chebVBirdMargin)
        lol[10].append(centVBirdMargin)

        # Append the computed randomWalk lengths starting at each center to
        # their respective rows
        lol[11].append(chebAvg)
        lol[12].append(centAvg)
        lol[13].append(birdAvg)
        lol[14].append(randAvg)

        print "SPHEERE " + str(sphereMet)
        print "BURGERS " + str(burgerMet)
        print "WILSOON " + str(wilsonMet)
        print "RAAAADD " + str(radRatio)
        print "NAIIIVE " + str(naiveMet)

    title = "THE_GRAND_BATTLE_ON_"
    if randDim:
        title += "MANY"
    else:
        title += str(dim)
    title += "_DIMENSIONS_"
    title += "AND_" + str(numTrials) + "_MILLION_TRIALS"
    if posTime:
        title += "_AS_TIME_MOVES_FORWARD!"
    if ray:
        title += "...IN A RAY!"

    # Code to store data in a json file
    with open(os.path.abspath('./Data/' + title + '.json'), 'w') as fp:
        json.dump(lol, fp)

    return lol
예제 #12
0
def simpleRandSched(dict):
    matrix_form = stnConverter.dictToMatrix(dict)
    minimal_matrix = test.minimal(matrix_form)
    # print minimal_matrix
    return test.getRandomSchedule(minimal_matrix)
예제 #13
0
def sphereVol(S, dim):
    chebsph = randomWalk.chebyshev(S)
    return test.sphereVolume(float(chebsph[1]), dim) / (
        test.naiveVolFlex(stnConverter.dictToMatrix(S)) + 0.00000001)
예제 #14
0
import randomSchedule
import torch
import torch.nn.functional as F

with open(os.path.abspath('./Data/' + 'ALL_OF_THE_DATA_30000' + '.json'),
          'r') as fp:
    datastuff = json.load(fp)

twoData = []
newData = []
walks = []

for i in range(30000):
    if datastuff[1][i] == 5:
        twoData.append(
            stnConverter.dictToMatrix(
                randomSchedule.fixStupidJSON(datastuff[0][i])))
        walks.append(datastuff[6][i])

for mat in twoData:
    newData.append(mat[0] + mat[1] + mat[2] + mat[3] + mat[4] + mat[5])

lengthTrain = int(0.8 * len(newData))

trainingSet = newData[:lengthTrain]
trainingLabels = walks[:lengthTrain]

testSet = newData[lengthTrain:]
testLabels = walks[lengthTrain:]


class Net(torch.nn.Module):