def run(self, inputTour):
        tour = inputTour.copy()
        stop = False
        bestCost = math.inf
        sameCost = 0

        while not stop:
            index1 = randint(0, self.numberOfCities - 1)
            index2 = randint(0, self.numberOfCities - 1)
            city1 = tour[index1]
            city2 = tour[index2]
            tempTour = tour.copy()
            tempTour[index1] = city2
            tempTour[index2] = city1
            tempCost = getCost(tempTour, self.edges)

            if tempCost <= bestCost:
                tour = tempTour
                bestCost = tempCost

                if (tempCost == bestCost):
                    sameCost += 1
                else:
                    sameCost = 0

            stop = sameCost >= self.stopCriterion

        return tour, getCost(tour, self.edges)
def runInner(timestamps, max_iter=10):
    """
    Implements Inner algorithm

    Parameters
    ----------
    timestamps : list of tuples
        Sorted list of interactions [(t1, n1, n2), (t2, n3, n4),...], where t is timestamp, n1 and n2 are interactiong nodes.
        Nodes in the interactions are sorted lexicographically.
    maxiter : int
        maximum number of interactions

    Returns
    -------
    tuple of dicts
        (dict1, dict2): dict1 of a shape {n1: t1, n2: t2, ..} contains starting point t1 of activity interval of node n1, for every node,
                        dict2 of a shape {n1: t1, n2: t2, ..} contains ending point t1 of activity interval of node n1, for every node.

    """

    nodeEdgeIndex = utils.getIndex(timestamps, 'inner')
    m = getInitial(nodeEdgeIndex)
    alpha, alphaNodes = getAlphas(timestamps, m)
    Xstart, Xend = getSolution(alphaNodes, m)

    best = utils.getCost(Xstart, Xend)
    bestSol = (Xstart, Xend)

    for k in xrange(1, max_iter):
        m = getNextInput(nodeEdgeIndex, Xstart, Xend)
        alpha, alphaNodes = getAlphas(timestamps, m)
        Xstart, Xend = getSolution(alphaNodes, m)

        t = utils.getCost(Xstart, Xend)
        if t < best:
            best = t
            bestSol = (Xstart, Xend)
        else:
            break

    return bestSol[0], bestSol[1]
    def run(self):
        visitedCities = [False] * self.numberOfCities
        tour = []
        startingCity = randint(0, self.numberOfCities - 1)
        visitedCities[startingCity] = True
        tour.append(startingCity)
        currentIndex = 0
        while numberOfCitiesVisited(visitedCities) != self.numberOfCities:
            city = self.getNearestCity(tour[currentIndex], visitedCities)
            currentIndex += 1
            visitedCities[city] = True
            tour.append(city)

        return tour, getCost(tour, self.edges)
Beispiel #4
0
    def run(self):
        visitedCities = [False] * self.numberOfCities
        tour = []

        startingCity = randint(0, self.numberOfCities - 1)
        tour.append(startingCity)
        visitedCities[startingCity] = True

        while numberOfCitiesVisited(visitedCities) != self.numberOfCities:
            randomIndex = randint(0, self.numberOfCities - 1)
            if not visitedCities[randomIndex]:
                visitedCities[randomIndex] = True
                tour.append(randomIndex)

        return tour, getCost(tour, self.edges)
Beispiel #5
0
    def run(self, inputTour, inputCost, maxTries):
        stop = False
        bestTour = inputTour.copy()
        bestCost = inputCost
        oldTour = inputTour.copy()
        oldCost = inputCost
        sameCost = 0

        propabiltyOfAcceptance = 0.9

        while True:
            for counter in range(0, maxTries):
                index1 = randint(0, self.numberOfCities - 1)
                index2 = randint(0, self.numberOfCities - 1)
                city1 = oldTour[index1]
                city2 = oldTour[index2]
                tempTour = oldTour.copy()
                tempTour[index1] = city2
                tempTour[index2] = city1
                tempCost = getCost(tempTour, self.edges)

                if tempCost < oldCost:
                    oldTour = tempTour
                    oldCost = tempCost

                    if tempCost < bestCost:
                        bestCost = tempCost
                        bestTour = tempTour
                else:
                    rnd = (randint(0, 101) / 100)
                    if (rnd < propabiltyOfAcceptance):
                        oldCost = tempCost
                        oldTour = tempTour

            propabiltyOfAcceptance = 0.9 * propabiltyOfAcceptance
            if propabiltyOfAcceptance < 0.0000001:
                break

        return bestTour, bestCost
    Cost_IP, P_IP, R_IP, F_IP, Costmax_IP = [], [], [], [], []

    iterations = range(1, 11)

    for iter in iterations:
        if iter == 1:
            m = inner.getInitial(nodeEdgeIndex)
            Xstart, Xend = inner.runInner_iteration(timestamps, nodeEdgeIndex,
                                                    m)
        else:
            m = inner.getNextInput(nodeEdgeIndex, Xstart, Xend)
            Xstart, Xend = inner.runInner_iteration(timestamps, nodeEdgeIndex,
                                                    m)

        Cost_IP.append(
            utils.getCost(Xstart, Xend) / ((event_length - 1) * num_nodes))
        p, r, f = utils.compareGT(Xstart, Xend, active_truth, timestamps)
        P_IP.append(p)
        R_IP.append(r)
        F_IP.append(f)
        Costmax_IP.append(utils.getMax(Xstart, Xend) / (event_length - 1))

    name = 'test_convergence'
    plt.figure()
    plt.plot(iterations, Cost_IP, 'k')
    plt.xlabel('iterations', fontsize=25)
    plt.ylabel('Relative total length', fontsize=25)
    plt.tight_layout()
    plt.savefig(name + '_' + 'total.pdf')

    plt.figure()
    G = utils.generateGraph(n=num_nodes)
    print 'number of nodes in the background network:', G.number_of_nodes()
    print 'number of edges in the background network:', G.number_of_edges()

    timestamps, active_truth = utils.generateIntervals(
        G, event_length=event_length, overlap=overlap)

    print 'number of timestamps', len(timestamps)

    if alg == 'baseline':
        Xstart, Xend = baseline.baseline(timestamps)
    elif alg == 'inner':
        Xstart, Xend = inner_point.runInner(timestamps)
    elif alg == 'budget':
        Xstart, Xend = budget.runBudget(timestamps)
    else:
        print('no algorithm specified')
        exit()

    print

    print 'relative total length of solution =', utils.getCost(
        Xstart, Xend) / ((event_length - 1) * num_nodes)
    print 'relative maximum length of solution =', utils.getMax(
        Xstart, Xend) / (event_length - 1)
    p, r, f = utils.compareGT(Xstart, Xend, active_truth, timestamps)
    print 'precision =', p
    print 'recall =', r
    print 'f-measure =', f
 def isBestTour(self, tour):
     
     newCost = getCost(tour, self.edges)
     return newCost < bestCost, newCost