예제 #1
0
def main():
    mesh_filename = 'meshes/mini-airfoil.p.part'

    cell2nodes = read_mesh_from_file(mesh_filename, 'cell_to_ord_nodes', int, frozenset)
    node2node = read_mesh_from_file(mesh_filename, 'node_to_node', int, frozenset)
    # DEBUGGING
    global nodes2cell
    nodes2cell = invert_list(cell2nodes)
    ## END DEBUGGING

    # Setup conditions
    seed(7)
    start_node = randint(0, len(node2node) - 1)
    start_node = 58

    # Go
    cell2ord = dict()
    quad_search = QuadSearch(node2node)
    for count, c in enumerate(quad_search.visit(start_node, BestFirstSearchCandidates)):
        # print c
        cell2ord[c.get_cell_id()] = count

    def cell_labeller(old_cell, new_cell):
        if old_cell in cell2ord:
            return '*%d*' % cell2ord[old_cell]
        else:
            return old_cell

    draw(label_cells=cell_labeller)
예제 #2
0
def generate_schema(entries, resources):
    resource_names = nlp.plural_extend(resources)
    model = {}
    hateoas_model = {}
    nlp_model = nlp.resource_analysis(resources, resource_names)
    model = nlp_model['model']
    hateoas_model = nlp_model['graph']
    with open('data.txt', 'w') as outfile:
        json.dump(model, outfile, indent=4)
    with open('graph.txt', 'w') as outfile:
        json.dump(hateoas_model, outfile, indent=4)
    # with open('data.txt') as data_file:
    #     model = json.load(data_file)
    # with open('graph.txt') as data_file:
    #     hateoas_model = json.load(data_file)
    graph.draw(hateoas_model)
    oas_schema = formatter.generate_swagger(model)
    oas_schema['info'] = {}
    for entry in entries:
        field = entry[0]
        text = entry[1].get()
        if field in ['title', 'description', 'version']:
            oas_schema['info'][field] = text
        elif field in ['basePath', 'host']:
            oas_schema[field] = text
    oas_schema['swagger'] = '2.0'
    oas_schema['schemes'] = ['https']
    oas_schema['produces'] = ['application/json']

    with open('swagger.json', 'w') as outfile:
        json.dump(oas_schema, outfile, indent=4)
    with open('swagger.yaml', 'w') as outfile:
        yaml.dump(oas_schema, outfile, indent=4)
예제 #3
0
    def _draw_graph(self, title, graph, rect, label_color=white, label_font=textutils.largeFont):
        # Create title and get remaining space
        content = layout.make_titled_rect(
            self.screen, rect, title, label_color, self.background_color, label_font, 8, 4
        )

        # Draw graph
        graph.draw(self.screen, content)
예제 #4
0
파일: main.py 프로젝트: Dahoon-Hong/poc
def show_index():
    img_name = 'graph.png'
    graph.draw(img_name)

    env = Environment(loader=FileSystemLoader('./'))
    template = env.get_template('index.html')

    return render_template(template, user_image='/file/' + img_name)
예제 #5
0
 def run_graph(self) -> None:
     '''Grab input from tk.entrys'''
     is_good, argum = self.validate()
     if is_good:
         self.error_var.set('')
         try:
             graph.draw(*argum, self.tk_int_var.get(), self.menu.get())  # pylint: disable=no-value-for-parameter
         except ValueError:
             self.error_var.set("Function does not exist in range")
예제 #6
0
    def _draw_graph(self,
                    title,
                    graph,
                    rect,
                    label_color=white,
                    label_font=textutils.largeFont):
        # Create title and get remaining space
        content = layout.make_titled_rect(self.screen, rect, title,
                                          label_color, self.background_color,
                                          label_font, 8, 4)

        # Draw graph
        graph.draw(self.screen, content)
예제 #7
0
def update(timer):
    sphd.clear()
    t = weather.temperature()
    p = weather.pressure()
    # Record
    if timer % 60 == 0: log(t, p)
    # Draw
    if (timer / 10) % 2 == 0 or len(history['temperature']) < 5:
        s = round(t if (timer / 5) % 2 == 0 else p, 3)
        typography.write("%s" % s)
    else:
        graph.draw(history['temperature' if
                           (timer / 5) % 2 == 0 else 'pressure'])
    sphd.show()
    # Trim history
    history['temperature'] = history['temperature'][-60:]
    history['pressure'] = history['pressure'][-60:]
예제 #8
0
    def printNetwork(outFile, latestLabel=None):
        alarmList = getRankedAlarms()
        name2idx = network['name2idx']
        v_prop = network['graph'].vertex_properties['info']
        v_color = network['graph'].vertex_properties['color']
        v_shape = network['graph'].vertex_properties['shape']

        for t, confidence in alarmList:
            v_shape[name2idx[t]] = 'circle'
            if t == latestLabel:
                v_color[name2idx[t]] = 'green'
            elif t in oracleQueries:
                v_color[name2idx[t]] = 'red'
            elif t not in labelledTuples:
                alpha = getAlpha(confidence)
                v_color[name2idx[t]] = '#0000FF' + alpha
            elif not labelledTuples[t]:
                v_color[name2idx[t]] = 'black'  # negative label
        graph.draw(network['graph'], outFile)
예제 #9
0
 def redrawWindow(self):
     for graph in self.graphs:
         graph.draw()
예제 #10
0
def schedule(conn, tasks, cpus):
    print(conn, "<< connections")
    print(tasks, "<< tasks")
    tasks_list = tasks.copy()
    levels = split_levels(conn)
    cp = find_critical_path(conn, tasks)  # fixme: iterate and check all pathes
    print(cp, "<< critical path")

    plan_task = [[i, [], []] for i, _ in enumerate(tasks)]  # (task, cpu, time)
    plan_copy = [[] for i in range(cpus)]  # (task, cpu, time)

    def data_ready(task):
        return plan_task[task][2][0] + tasks[task]

    def get_ready(time):
        """ List ready tasks (without data transfer)"""
        ready = list(set([t[0] for t in plan_task if t[1] and (time >= t[2][0] + tasks[t[0]])]))
        return ready

    def get_ready_cpus(time):
        """ List free cpus """
        cpus_lst = list(range(1, cpus+1))
        for t in plan_task:
            for i, _ in enumerate(t[1]):
                if t[2][i] <= time < (t[2][i] + tasks[t[0]]):
                    if t[1][i] in cpus_lst:
                        cpus_lst.remove(t[1][i])
        return cpus_lst

    def get_dependencies(task):
        return [i for i, v in enumerate(conn[:, task]) if v > 0]

    def get_calculated(time):
        ready = get_ready(time)
        return [t for t in range(len(tasks)) if is_sublist(get_dependencies(t), ready)]

    def get_ready_to_plan(time):
        ready = get_calculated(time)
        return ready

    def is_planned(task):
        return any(i[0] == task and i[1] for i in plan_task)

    def not_planned(tasks):
        return [int(t) for t in tasks if not is_planned(t)]

    def get_dependents(task):
        return [i for i, v in enumerate(conn[task]) if v > 0]

    def is_busy(time, cpu):
        return any(any(tx <= time < tx + tasks[t[0]] for tx in t[2]) for t in plan_task if t[1] and cpu in t[1])

    def get_execution_frame(from_time, w, cpu):
        ts = int(from_time)
        while not all(not is_busy(t, cpu) for t in range(ts, ts+int(w))):  # can be better
            ts += 1
        return ts

    def do_plan_copy(time, weighs, cpu, fake=True, nodups=False):
        if fake:
            _plan_task = deepcopy(plan_task)
            _plan_copy = deepcopy(plan_copy)
        else:
            _plan_task = plan_task
            _plan_copy = plan_copy
        time_added = [time]
        plans = []
        for d, w in weighs:
            d_cpu = _plan_task[d][1][0]
            if d_cpu == cpu: continue
            time_start = _plan_task[d][2][0] + tasks[d]
            mc1 = nearest_copy_ability(time_start, cpu, w)
            mc2 = nearest_copy_ability(time_start, d_cpu, w)
            plan = max(mc1, mc2)
            plans.append((d, w, plan, time_start))

        for d, w, plan, time_start in sorted(plans, key=lambda x:x[3]):
            d_cpu = _plan_task[d][1][0]
            mc1 = nearest_copy_ability(time_start, cpu, w)
            mc2 = nearest_copy_ability(time_start, d_cpu, w)
            plan = max(mc1, mc2)
            while mc1 != mc2:
                mc1 = nearest_copy_ability(plan, cpu, w)
                mc2 = nearest_copy_ability(plan, d_cpu, w)
                plan = max(mc1, mc2)

            weights_sub = sorted([(d, conn[d, r]) for d in get_dependencies(d)],
                             key=lambda x: x[1], reverse=True)
            predicted_rerun = do_plan_copy_predict(time, weights_sub, cpu)
            predicted_rerun = get_execution_frame(predicted_rerun, tasks[d], cpu)
            # compare
            if False or (not nodups and predicted_rerun + tasks[d] >= plan + w):
                _plan_copy[cpu-1].append((plan, plan + w, d+1, r+1))
                _plan_copy[d_cpu-1].append((plan, plan + w, d+1, r+1))
                time_added.append(plan + w)
            else:
                do_plan_copy(time, weights_sub, cpu)
                _plan_task[d][1].append(cpu)
                _plan_task[d][2].append(predicted_rerun)
                time_added.append(predicted_rerun + tasks[d])

        _plan_task[r][1].append(cpu)
        _plan_task[r][2].append(max(time_added))
        if not weighs:
            time_added = [0]
        return _plan_copy, _plan_task, max(time_added)

    def do_plan_copy_predict(time, weight, cpu, nodups=False):
        return do_plan_copy(time, weight, cpu, fake=True, nodups=nodups)[2]

    def is_busy_with_copying(time, cpu):
        return any(p[0] <= time < p[1] for p in plan_copy[cpu-1])

    def nearest_copy_ability(time, cpu, w):
        ts = int(time)
        while not all(not is_busy_with_copying(t, cpu) for t in range(ts, ts+int(w))):  # can be better, +1?
            ts += 1
        return ts

    time = 0
    while not_planned(range(len(tasks))):
        ready_cpus = get_ready_cpus(time)
        able_to_plan = not_planned(get_ready_to_plan(time))
        if not able_to_plan:
            time += 1
            continue
        for r in able_to_plan:
            if not ready_cpus:
                time += 1
                break
            weights = sorted([(d, conn[d, r]) for d in get_dependencies(r)],
                             key=lambda x: x[1], reverse=True)
            preferred_cpus = [plan_task[i][1][0] for i, w in weights]
            # sort weights
            print(r+1, get_dependencies(r), weights, preferred_cpus, ready_cpus)
            if preferred_cpus:
                cpu = pop_priorities(ready_cpus, preferred_cpus)
            else:
                cpu = ready_cpus.pop()
            pt = do_plan_copy_predict(time, weights, cpu)

            if get_execution_frame(time, tasks[r], cpu) > time:
                continue

            # predict CPU
            predicted = [pt]
            for i in range(int(time), int(pt)+1):
                _ready_cpus = get_ready_cpus(i)
                if _ready_cpus:
                    _cpu = pop_priorities(_ready_cpus, preferred_cpus)
                    predicted.append(do_plan_copy_predict(i, weights, _cpu))

            if min(predicted) < pt:
                continue

            plan_copy, plan_task, _ = do_plan_copy(time, weights, cpu, fake=False)
        else:
            time += 1

    draw(plan_task, plan_copy, tasks, time+15, cpus, cp)
예제 #11
0
#!/usr/bin/env python3

# Example:
# ./print_bnet.py named_cons_all.txt.cep Alarm.txt GroundTruth.txt output.svg
# This program will also generate output.svg.map that contains tha mapping
# from vertex numbers to nodes

import graph
import logging
import re
import sys
import util

from graph_tool.all import *

cons_file = sys.argv[1]
alarm_file = sys.argv[2]
ground_truth_file = sys.argv[3]
output_file = sys.argv[4]
old_alarm_file = sys.argv[5] if len(sys.argv) == 6 else None

alarms = util.read_alarm(alarm_file)
old_alarms = set() if old_alarm_file is None else util.read_alarm(
    old_alarm_file)
ground_truths = util.read_alarm(ground_truth_file)

g = graph.build_graph(cons_file, alarms)['graph']
graph.prepare_visualization(g, alarms, old_alarms, ground_truths)
graph.draw(g, output_file)
graph.print_node_id(g, output_file + '.map')
예제 #12
0
def dynamic_page():
    return graph.draw()
예제 #13
0
 def dynamics(cls, area, *args):
     df = cls.areaData(area)
     graph.draw(df, area, *args)
예제 #14
0
def plotSoybeanOilData():
	soyOilF_df = pullquandl.pullSoybeanOilFutures()
	soyOilCTR_df = pullquandl.pullSoybeanOilCTR()
	graph.draw(soyOilF_df, 'Total Long Short Ratio Of Soybean Oil Future since 2006', 'Total Longs/Total Shorts', \
		soyOilCTR_df, 'Cumulative Daily Returns For Soybean Oil since 1959', 'Cumulative Daily Returns For Soybean Oil')
예제 #15
0
파일: app.py 프로젝트: xnorkl/crawldad
import graph as g
import netcrawl as nc
import dash
import dash_core_components as dcc
import dash_html_components as html

edges = nc.edges()
graph = g.net_graph(edges)
g.plot(graph)

app = dash.Dash()
app.layout = html.Div([dcc.Graph(figure=g.draw(graph))])

app.run_server(debug=True)
예제 #16
0
import graph

g = graph.random_graph(6,0.3,directed=True,min_weight=1,max_weight=10)
graph.draw(g)
 def redrawWindow(self):
     for graph in self.graphs:
         graph.draw()
예제 #18
0
                if alt < costToReach[index]:
                    costToReach[index] = alt
                    previousNode[index] = u.index

    print(f'costs: {costToReach}')
    print(f'previousNodes: {previousNode}')


if __name__ == '__main__':
    nodes = 10
    edges = nodes * 3
    g = graph.graph(nodes, edges, weighted=True)
    k = nodes
    labels = list(range(1, k//3))
    costs = {x:x for x in labels}

    start = random.randint(0, nodes-1)
    while sum(g[start]) <= 0:
        start = random.randint(0, nodes-1)

    end = start
    while end == start or sum(g[end]) <= 0:
        end = random.randint(0, nodes-1)

    graph.print_matrix(g)
    print(start, end)

    algo(g, labels, costs, start, end)
    graph.draw(g, with_weights=True)
# I love to play around with colors :)
accent_color = '#c9c9c9'
indicators_color = '#598720'

# The use of normalized data is necessary for plotting the price and moving averages in the same graph.
data['Close'] = data_n['Close']
data[ci.moving_average_1_label] = data_n[ci.moving_average_1_label]
data[ci.moving_average_2_label] = data_n[ci.moving_average_2_label]
# data['ATR'] = data_n['ATR']
# data['MACD'] = data_n['MACD']
# data['Stochastics'] = data_n['Stochastics']
# data['RSI'] = data_n['RSI']

# Draw
draw(ticker,
     data[dataset_train_length:],
     predicted_data,
     ci,
     draw_moving_average_1=draw_moving_average_1,
     draw_moving_average_2=draw_moving_average_2,
     draw_ATR=draw_ATR,
     draw_MACD=draw_MACD,
     draw_Stochastics=draw_Stochastics,
     draw_RSI=draw_RSI,
     accent_color=accent_color,
     indicators_color=indicators_color)

show()
# save('graph.png')
예제 #20
0
def run(name, disbale_cache, validate, svalidate, s, draw, fetchall):
    MODEL = "./model_slim"

    if fetchall:
        print("Fetch all descriptions")
        names = filemanager.lotr_char_names()
        for name in names:
            filemanager.getCharacterDescription(name)

        print("DONE")
        #print("Train")
        #status = train.train(training_set)
        #if status == "OK":
        #    print("DONE")
        #    print("Successfully finished")
        #else:
        #    print("Error while training")
        return

    if s:
        if name in os.listdir("./data/silver/"):
            os.remove("./data/silver/" + name)
        silver = get_silver_family(name)
        print(silver)
        return

    if disbale_cache or name not in os.listdir("./data/family/"):
        if name in os.listdir("./data/family/"):
            os.remove("./data/family/" + name)

        if name in os.listdir("./data/silver/"):
            os.remove("./data/silver/" + name)

        family_tree = find_family_relations(to_read=[name], model=MODEL)
        family = graph.add_relations(family_tree, "./data/family/" + name)
    else:
        family = graph.get("./data/family/" + name)

    print("RUN 1")
    if validate:
        silver = get_silver_family(name)
        #(recall, precision, f1) = _validate(family, silver)

        #print("recall:", recall)
        #print("precisision:", precision)
        #print("F1:", f1)

        if draw:
            file1 = "./data/family/" + name
            file2 = "./data/silver/" + name
            graph.draw(file1, file2)
    else:
        if draw:
            file1 = "./data/family/" + name
            graph.draw(file1)

    if svalidate:
        family = None
        family_no_model = None
        silver = get_silver_family(name)

        if name not in os.listdir("./data/family/"):
            family_tree = find_family_relations(to_read=[name], model=MODEL)
            family = graph.add_relations(family_tree, "./data/family/" + name)
        else:
            family = graph.get("./data/family/" + name)

        if name not in os.listdir("./data/family_no_model/"):
            family_tree_no_model = find_family_relations(
                to_read=[name], model="en_core_web_sm")
            family_no_model = graph.add_relations(
                family_tree_no_model, "./data/family_no_model/" + name)
        else:
            family_no_model = graph.get("./data/family_no_model/" + name)

        latex_tabell(name, family_no_model, family, silver)

    print("MAIN DONE")
예제 #21
0
파일: draw.py 프로젝트: ivyl/graph-security
def main():
    args = parse_args()

    for graph_path in args.graph:
        graph = nx.read_gpickle(graph_path)
        draw(graph)
예제 #22
0
def GodSpeed():
    chart = graph.draw(Coin)
    if (Invested): In(chart)
    if (not Invested): Out(chart)
예제 #23
0
def draw_graphs(results_path):
    graph.draw(results_path)
예제 #24
0
    resources = preprocessor.main(args['folder'])
    if not resources:
        print(
            'No resources found, did you insert the correct resources folder?')
        sys.exit()
    resource_names = nlp.plural_extend(resources)
    print('Processing resources...')
    nlp_model = nlp.resource_analysis(resources, resource_names)
    model = nlp_model['model']
    resource_graph = nlp_model['resource_graph']
    state_graph = nlp_model['state_graph']
    with open('output_files/nlp_model.json', 'w') as outfile:
        json.dump(nlp_model, outfile, indent=4)

print('Generating files...')
graph.draw(resource_graph, state_graph, args['fixgraph'])

oas_schema = formatter.generate_swagger(model)
oas_schema['swagger'] = '2.0'
oas_schema['info'] = {
    "title": oas_settings['INFO']['title'],
    "description": oas_settings['INFO']['description'],
    "version": oas_settings['INFO']['version'],
    "termsOfService": oas_settings['INFO']['termsOfService'],
    "contact": {
        'name': oas_settings['CONTACT']['name'],
        'url': oas_settings['CONTACT']['url'],
        'email': oas_settings['CONTACT']['email']
    },
    "license": {
        'name': oas_settings['LICENSE']['name'],
예제 #25
0
def graph_draw(G, output):
    draw(G, output)
예제 #26
0
    PowerApproximation()
]

while True:
    function_table = mainboilerplate.read_function_table()
    functions = []
    for a in approximations:
        f = a.find_an_approximation(function_table)
        if f is not None:
            functions.append(f)

    functions.sort(key=lambda x: x.root_mean_square_deviation)
    results_table = PrettyTable()
    results_table.field_names = [
        "Функция", "Мера отклонения", "Среднеквадратичное отклонение"
    ]
    for f in functions:
        results_table.add_row(
            [f.text,
             round(f.s, 3),
             round(f.root_mean_square_deviation, 3)])
    logging.info(results_table)
    logging.info(
        "Аппроксимирующая функция с наименьшим среднеквадратическим отклонением: "
        + functions[0].text)

    graph.draw(function_table, functions)

    if input('\nЕще раз? [y/n] ') != 'y':
        break