Пример #1
0
def sample(STN, success='default', LP='original', gauss=False):
    if LP == 'original':
        _, bounds, epsilons = originalLP(STN.copy(), naiveObj=False)
    elif LP == 'proportion':
        _, _, bounds, epsilons = proportionLP(STN.copy())
    else:
        _, _, bounds, epsilons = maxminLP(STN.copy())

    original, shrinked = newInterval(STN, epsilons)
    if not gauss:
        degree = calculateMetric(original, shrinked)[2]
    else:
        degree = calculateMetric(original, shrinked, gauss)

    schedule = {}
    for i in list(STN.verts.keys()):
        if i not in STN.uncontrollables:
            time = (bounds[(i, '-')].varValue + bounds[(i, '+')].varValue) / 2
            schedule[i] = time

    # Collect the sample data.
    count = 0
    for i in range(10000):
        if success == 'default':
            result = sampleOnce(original, shrinked, gauss)
        else:
            result = altSampleOnce(STN, schedule.copy(), gauss)
        if result:
            count += 1

    success = float(count / 10000)

    return degree, success
Пример #2
0
def processOptimal():
    json_folder = input("Please input folder with json file:\n")
    json_list = glob.glob(os.path.join(json_folder, '*.json'))

    result = {}
    for fname in json_list:
        p, f = os.path.split(fname)
        print("Processing: ", f)

        STN = loadSTNfromJSONfile(fname)
        new_STN, count = relaxSearch(STN.copy())
        new, orig, degree = dynamicMetric(STN.copy(), new_STN.copy())

        result[f] = {}
        result[f]['shrinked'] = new
        result[f]['original'] = orig
        result[f]['degree'] = degree

    output_folder = input("Please input output folder:\n")
    filename = os.path.join(output_folder, 'result_optimal.json')

    with open(filename, 'w') as f:
        json.dump(result, f)

    return result
Пример #3
0
def readNeos(filename, json_folder):
    f = open(filename, 'r')
    for i in range(3):
        line = f.readline()

    obj_value = float(line[17:])
    actual = math.exp(obj_value)

    p, f = os.path.split(filename)
    fname = f[:-4] + '.json'
    json_file = os.path.join(json_folder, fname)

    STN = loadSTNfromJSONfile(json_file)
    result, conflicts, bounds, weight = DC_Checker(STN.copy(), report=False)
    contingent = bounds['contingent']

    total = 1
    for (i, j) in list(STN.contingentEdges.keys()):
        edge = STN.contingentEdges[(i, j)]
        length = edge.Cij + edge.Cji
        total *= length

        if (i, j) not in contingent:
            actual *= length

    return actual, total, float(actual / total)
Пример #4
0
def generateParallelChain(agent, task):
    total_event = ((2 * task) + 1) * agent + 1

    while True:
        new = STN()
        new.addVertex(0)

        for i in range(total_event):
            new.addVertex(i + 1)

        contingent = True
        for i in range(agent):
            start = ((2 * task) + 1) * i + 1
            end = ((2 * task) + 1) * (i + 1)
            new.addEdge(0, start, 0, 15)

            for j in range(start, end):
                type = 'stcu' if contingent else 'stc'
                contingent = not contingent

                if type == 'stcu':
                    # low = round(random.uniform(10, 20), 2)
                    # high = round(random.uniform(30, 40), 2)
                    low = random.randint(10, 20)
                    high = random.randint(30, 40)
                    new.addEdge(j, j + 1, low, high, type='stcu')
                else:
                    # low = round(random.uniform(5, 10), 2)
                    # high = round(random.uniform(30, 35), 2)
                    low = random.randint(5, 10)
                    high = random.randint(35, 40)
                    new.addEdge(j, j + 1, low, high)

            new.addEdge(end, total_event, -10, 10)

        num_activity = (2 * task) + 1
        max_length = max([e.Cij + e.Cji for e in list(new.edges.values())])
        up_bound = max_length * num_activity

        # low = round(random.uniform(0.35*up_bound, 0.45*up_bound), 2)
        # high = round(random.uniform(0.5*up_bound, 0.6*up_bound), 2)
        low = random.randint(int(0.45 * up_bound), int(0.53 * up_bound))
        high = random.randint(int(0.55 * up_bound), int(0.65 * up_bound))
        new.addEdge(0, total_event, low, high)

        print("\n\nChecking consistensy...")
        if not new.isConsistent():
            continue

        print("Checking Dynamic Controllability...")
        try:
            result, conflicts, bounds, weight = DC_Checker(new.copy(),
                                                           report=False)
        except Exception:
            continue

        if result:
            return new
Пример #5
0
def set_dynamic_zeropoint(network: STN):
    network = network.copy()
    largish = 1000000.0

    if ZERO_ID not in network.verts:
        network.addVertex(ZERO_ID)

    adjacent_events = set(network.getAdjacent(ZERO_ID))
    for event in network.verts:
        if (event not in adjacent_events) and (event != ZERO_ID):
            network.addEdge(ZERO_ID, event, 0.0, largish)

    return network
Пример #6
0
def computeDynamic(nlp=False):
    uncertain_folder = input("Please input uncertain STNUs folder:\n")
    chain_folder = input("Please input chain STNUs folde:\n")

    listOfFile = []
    listOfFile += glob.glob(os.path.join(uncertain_folder, '*.json'))
    listOfFile += glob.glob(os.path.join(chain_folder, '*.json'))

    degree = {}
    for fname in listOfFile:
        p, f = os.path.split(fname)
        print("Processing: ", f)

        STN = loadSTNfromJSONfile(fname)
        new_STN, count = relaxSearch(STN.copy(), nlp=nlp)

        if not new_STN:
            degree[f] = 0
        else:
            degree[f] = dynamicMetric(STN.copy(), new_STN.copy())[2]

    return degree
Пример #7
0
def simulation(network: STN, size: int, verbose=False, gauss=False, relaxed=False) -> float:
    # Collect useful data from the original network
    contingent_pairs = network.contingentEdges.keys()
    contingents = {src: sink for (src, sink) in contingent_pairs}
    uncontrollables = set(contingents.values())

    if relaxed:
        dispatching_network, count, cycles, weights = relaxSearch(getMinLossBounds(network.copy(), 2))
        if dispatching_network == None:
            dispatching_network = network
    else:
        dispatching_network = network

    total_victories = 0
    dc_network = STNtoDCSTN(dispatching_network)
    dc_network.addVertex(ZERO_ID)

    controllability = dc_network.is_DC()
    if verbose:
        print("Finished checking DC...")

    # Detect if the network has an inconsistency in a fixed edge
    verts = dc_network.verts.keys()
    for vert in verts:
        if (vert, vert) in dc_network.edges:
            if verbose:
                print("Checking", vert)
            edge = dc_network.edges[vert, vert][0]
            if edge.weight < 0:
                dc_network.edges[(vert, vert)].remove(edge)
                dc_network.verts[vert].outgoing_normal.remove(edge)
                dc_network.verts[vert].incoming_normal.remove(edge)
                del dc_network.normal_edges[(vert, vert)]

    # Run the simulation
    for j in range(size):
        realization = generate_realization(network, gauss)
        copy = dc_network.copy()
        result = dispatch(dispatching_network, copy, realization, contingents,
                          uncontrollables, verbose)
        if verbose:
            print("Completed a simulation.")
        if result:
            total_victories += 1

    goodie = float(total_victories / size)
    if verbose:
        print(f"Worked {100*goodie}% of the time.")

    return goodie
Пример #8
0
def modelObjDynamic(STN, fname):
    epsilons, constraint, Obj = prepareDynamic(STN.copy())

    f = open(fname, 'w')
    for v, l, h in list(epsilons.values()):
        line = 'var ' + v + ' >= ' + str(l)

        if h != None:
            line += ', <= ' + str(h)

        line += ';'
        f.write(line + '\n')

    Obj_line = '\nmaximize VOLUME: ' + Obj + ';\n\n'
    f.write(Obj_line)

    constraint_line = 'subject to WEIGHT: ' + constraint + ';\n'
    f.write(constraint_line)

    f.close()
Пример #9
0
def prepareDynamic(STN):
    epsilons = {}
    result, conflicts, bounds, weight = DC_Checker(STN.copy())

    contingent = bounds['contingent']

    constraint = ''
    Obj = ''
    for i, j in list(contingent.keys()):
        edge, bound = contingent[(i, j)]
        length = edge.Cij + edge.Cji
        epsilons[j] = ('EPS_%i' % j, 0, length)

        constraint += epsilons[j][0] + ' + '
        Obj += 'log(' + str(length) + ' - ' + epsilons[j][0] + ') + '

    constraint = constraint[:-3] + ' >= ' + str(-weight)
    Obj = Obj[:-3]

    return epsilons, constraint, Obj
Пример #10
0
def compare(actual_Dict):
    dynamic_folder = input("Please input directory with DC STNUs:\n")
    uncertain_folder = input("Please input directory with uncertain STNUs:\n")

    compare_Dict = {}
    for x in list(actual_Dict.keys()):
        actual_volume = actual_Dict[x]

        if x[:7] == 'dynamic':
            fname = os.path.join(dynamic_folder, x + '.json')
        else:
            fname = os.path.join(uncertain_folder, x + '.json')

        STN = loadSTNfromJSONfile(fname)

        _, _, epsilons = originalLP(STN.copy())
        original, shrinked = newInterval(STN, epsilons)

        old, new, degree = calculateMetric(original, shrinked)
        actual = float(actual_volume / old)
        compare_Dict[x] = (degree, actual)

    return compare_Dict
Пример #11
0
def loadSTNfromJSONobj(jsonSTN, reduction=True, using_PSTN=True):
    stn = STN()

    # Add the root vertex and put it in the T_x set
    stn.addVertex(0, 0, None)
    # TODO: wtf? Why are we executing a point outside of a simulation in the
    # first place?
    stn.execute(0)
    agents = []

    # Add the vertices
    for v in jsonSTN['nodes']:
        # Accumulate a list of all the owners to retrieve the agents.
        if not v['owner_id'] in agents:
            agents.append(v['owner_id'])

        # We don't necessarily need a location, just set it to None if we don't.
        if not ('location' in v):
            v['location'] = None

        stn.addVertex(v['node_id'], v['local_id'], v['owner_id'],
                      v['location'])

        # TODO: Change edge adding to allow integers to refer to vertecies,
        # rather than actually connecting integers together. (silly legacy support)
        stn.addEdge(0, v['node_id'], float(v['min_domain']),
                    float(v['max_domain']))
        if 'executed' in v:
            if v['executed']:
                stn.execute(v['node_id'])

    # Add the edges
    for e in jsonSTN['constraints']:
        if 'distribution' in e and using_PSTN:
            stn.addEdge(e['first_node'], e['second_node'],
                        float(e['min_duration']), float(e['max_duration']),
                        e['distribution']['name'])
        else:
            stn.addEdge(e['first_node'], e['second_node'],
                        float(e['min_duration']), float(e['max_duration']))

    #numAgents = jsonSTN['num_agents']

    stn.numAgents = len(agents)  # NOTE: deprecated, agents replaces numAgents.
    stn.agents = agents

    if reduction:
        # Triangulate the STN
        stnCopy = stn.copy()
        agentWait = []
        # Set up the wait timer for agent load balancing
        for a in stn.agents:
            agentWait.append(0)

        # Perform the reduction
        while len(stnCopy.verts) > 1:
            for a in stn.agents:
                if agentWait[a] == 0:
                    created = stnreduce(stnCopy, a, stn)
                    agentWait[a] = created
                else:
                    agentWait[a] -= 1

    # Return back an dictionary for easy labelling of return types.
    # FIXME: Remove the deprecated numAgents value
    output_dict = {'stn': stn, 'agent_count': stn.numAgents}

    # Ideally, this would return a class, however, this is already butchering
    # quite a bit of legacy support, and a class would end up being even more
    # damaging.
    return output_dict