コード例 #1
0
def plot_gantt(instance, by="JOB", grouping=True):
    # Affiche le diagram de Gantt
    # Input : Objet de type Instance

    # df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-01', Resource='Apple'),
    #      dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource='Grape'),
    #     dict(Task="Job C", Start='2009-04-20', Finish='2009-09-30', Resource='Banana')]

    # Création d'une liste de dictionnaire
    # Parcours les jobs de l'instance

    if len(instance.jobs_list) > 8:
        colors = []
        for i in range(1, len(instance.jobs_list) + 1):
            r = lambda: random.randint(0, 255)
            current_colors = '#%02X%02X%02X' % (r(), r(), r())
            colors.append(current_colors)

    df = []
    for j in instance.jobs_list:
        # Parcours les tâches de jobs
        for t in j.list_task:
            # On associe chaque
            if by == "JOB":
                df.append(
                    dict(Task="Job  #" + str(t.jobID),
                         Start=datetime.fromordinal(t.startDate + 1),
                         Finish=datetime.fromordinal(t.finishDate + 1),
                         Resource="Machine #" + str(t.machineID)))
            elif by == "MACHINE":
                df.append(
                    dict(Task="Machine  #" + str(t.machineID),
                         Start=datetime.fromordinal(t.startDate + 1),
                         Finish=datetime.fromordinal(t.finishDate + 1),
                         Resource="Job #" + str(t.jobID)))

    if len(instance.jobs_list) > 8:
        fig = ff.create_gantt(df,
                              index_col='Resource',
                              reverse_colors=False,
                              show_colorbar=True,
                              group_tasks=grouping,
                              show_hover_fill=True,
                              showgrid_x=True,
                              showgrid_y=True,
                              colors=colors)
    else:
        fig = ff.create_gantt(df,
                              index_col='Resource',
                              reverse_colors=False,
                              show_colorbar=True,
                              group_tasks=grouping,
                              show_hover_fill=True,
                              showgrid_x=True,
                              showgrid_y=True)

    fig.layout.xaxis.tickformat = '%'
    go.FigureWidget(fig)
    fig.show()
コード例 #2
0
ファイル: plot.py プロジェクト: shinying/SA
def ganttplot(tasks, tugs):
    colors = dict()
    for task in tasks:
        #     color = "rgb({}, {}, {})".format(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        color = 'rgb(128, 138, 135)'
        colors[str(task.id)] = color
    colors['delay_time'] = 'rgb(255,153,51)'
    colors['move_time'] = 'rgb(0,204,204)'
    colors['work_time'] = 'rgb(128, 138, 135)'

    df = []
    tasks.sort(key=lambda x: x.start_time_real)
    for task in tasks:
        df.append(
            dict(Task=str(task.id),
                 Start=task.start_time_real,
                 Finish=task.start_time_real + task.work_time,
                 Resource=str(task.id)))
        df.append(
            dict(Task=str(task.id),
                 Start=task.start_time,
                 Finish=task.start_time_real,
                 Resource='delay_time'))

    fig = ff.create_gantt(df,
                          colors=colors,
                          index_col='Resource',
                          show_colorbar=True,
                          group_tasks=True)
    pp.plot(fig, filename='task-gantt', world_readable=True, auto_open=False)

    df = []
    for tug in tugs:
        ts = copy.copy(tug.ts)
        while ts:
            move = ts.popleft()
            start = ts.popleft()
            end = ts.popleft()
            df.append(
                dict(Task=str(tug.tug_id),
                     Start=move,
                     Finish=start,
                     Resource='move_time'))
            df.append(
                dict(Task=str(tug.tug_id),
                     Start=start,
                     Finish=end,
                     Resource='work_time'))

    fig = ff.create_gantt(df,
                          group_tasks=True,
                          show_colorbar=True,
                          colors=colors,
                          index_col='Resource',
                          showgrid_x=True)
    pp.plot(fig, filename='tug-worktime-gantt', world_readable=True)
コード例 #3
0
    def Plot_Gantt_Chart(self):
        # ------------------------------- Ploting the results by using Plotly Gantt Chart ---------------------------------------------- #
        print(
            f'{"The shape of the OutputData_Of_Lines:  "}{self.OutputData_Of_Lines.shape[0]}'
        )
        color_dict = dict(
            zip(self.OutputData_Of_Lines.Resource.unique(), [
                'rgb({},{},{})'.format(i[0], i[1], i[2]) for i in list(
                    np.random.randint(255,
                                      size=(len(self.OutputData_Of_Lines.
                                                Resource.unique()), 3)))
            ]))
        fig = ff.create_gantt(
            self.OutputData_Of_Lines.to_dict(orient='records'),
            colors=color_dict,
            index_col="Resource",
            title="Genetic Algorithm based Optimization",
            show_colorbar=True,
            bar_width=0.3,
            showgrid_x=False,
            showgrid_y=True,
            show_hover_fill=True)

        fig_html = pio.to_html(fig)
        # fig.show()
        # print(fig_html)
        # fig.write_image(r"CLS_GanttChart.png")
        return fig_html
コード例 #4
0
def process_product():
    planeqp = db.session.query(PlanEQP).filter()
    df1 = pd.read_sql(planeqp.statement, planeqp.session.bind)
    df1.rename(columns={
        "start_t": "Start",
        "end_t": "Finish",
        "id": "Task"
    },
               inplace=True)

    df1 = df1.to_dict('records')
    for i in df1:
        i['Task'] = StdLineEQP.query.filter_by(
            id=i['line_eqp_id']).first().eqp_id

    fig = ff.create_gantt(df1,
                          index_col='prod_id',
                          title='Process by products',
                          group_tasks=True,
                          show_colorbar=True,
                          bar_width=0.2,
                          showgrid_x=True,
                          showgrid_y=True)

    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON
コード例 #5
0
def plot_gantt(sol):
    df, ls_ress = [], []
    T = [random_color() for _ in range(len(sol.list_boat))]
    for elem in zip(sol.list_boat, sol.list_quays):
        start, end, task, ressource = elem[0].starting_time, elem[
            0].ending_time, elem[
                1].lib, elem[0].name + '  ::  ' + elem[0].type_boat
        start = fast_conv(start)
        end = fast_conv(end)
        ls_ress.append(ressource)
        df.append(dict(Task=task, Start=start, Finish=end, Resource=ressource))
    colors, k = dict(), 0
    for boat in ls_ress:
        colors[boat] = 'rgb(' + str(T[k][0]) + ', ' + str(
            T[k][1]) + ', ' + str(T[k][2]) + ')'
        k += 1
        #T = [el+15 for el in T]
        #print([elm for elm in T])
    fig = ff.create_gantt(df,
                          colors=colors,
                          index_col='Resource',
                          title='Daily Schedule',
                          show_colorbar=True,
                          bar_width=0.4,
                          showgrid_x=True,
                          showgrid_y=True,
                          group_tasks=True)
    plot(fig)
コード例 #6
0
ファイル: final.py プロジェクト: rpdalka/SI_206_Final_Project
def user_lifespan():
    conn = sqlite.connect(DBNAME)
    cur = conn.cursor()
    data = []
    colors = []

    # Get all the authors
    sqlStatement = 'SELECT Name, BirthDate, DeathDate FROM Authors'
    cur.execute(sqlStatement)
    c = 0
    for row in cur:
        colors.append(COLORS[c])
        c += 1
        if row[2] == 'Alive':
            fin = datetime.date.today()
            aName = row[0] + '*'
        else:
            fin = row[2].split('(')[1].split(')')[0]
            aName = row[0]
        data.append(
            dict(Task='',
                 Start=row[1].split('(')[1].split(')')[0],
                 Finish=fin,
                 Resource=aName))

    fig = ff.create_gantt(data,
                          colors=colors,
                          index_col='Resource',
                          title='Author Lifespans (*Alive)',
                          reverse_colors=True,
                          show_colorbar=True)
    py.plot(fig, filename='author-lifespans')
コード例 #7
0
    def campaigns_gantt(self, colors: dict = None, layout: dict = None):
        df = self.__campaigns.reset_index()

        df['Finish'] = df['End']
        df['Resource'] = df['Product']
        df['Task'] = df['Suite']
        df = df.to_dict('records')

        gantt = ff.create_gantt(df,
                                colors=colors,
                                index_col='Resource',
                                group_tasks=True,
                                showgrid_x=True,
                                showgrid_y=True)

        for gantt_row, campaign in zip(gantt['data'], df):
            text = '<br>'.join([
                '{}: {}'.format(key, val) for key, val in campaign.items()
                if key not in {'index', 'Finish', 'Resource', 'Task'}
            ])
            gantt_row.update({'text': text})

        if layout is None:
            gantt['layout'].update({
                'title': '',
                'xaxis': {
                    'tickangle': -30,
                    'side': 'bottom'
                }
            })
        else:
            gantt['layout'].update(layout)

        return opy.iplot(gantt)
コード例 #8
0
def gantt(start, finish, name, skip=1):
    df = []
    colors = {}
    for t, (st, fin, nm) in enumerate(zip(start, finish, name)):
        for pl_st, pl_fin, n in zip(st, fin, nm):
            start_dt = minute2dt(skip * t + pl_st)
            end_dt = minute2dt(skip * t + pl_fin)

            if n not in colors:
                seed(n)
                clr = "rgb(" + str(255 * random()) + "," + str(
                    255 * random()) + "," + str(255 * random()) + ")"
                colors[n] = clr

            dt_str = '%Y-%m-%d %X'
            df.append(
                dict(Task="Minute " + str(skip * t),
                     Start=start_dt.strftime(dt_str),
                     Finish=end_dt.strftime(dt_str),
                     Resource=n))

    plot(
        ff.create_gantt(df,
                        colors=colors,
                        index_col='Resource',
                        show_colorbar=True,
                        group_tasks=True,
                        showgrid_x=True))
コード例 #9
0
def draw_gantt(uri, draw_type):
    result = []
    with open(uri) as f:
        for line in f:
            result.append(make_dict(line))
        f.close()

    machines_list = find_machines(result)

    final = []
    for item in machines_list:
        result_aux = result
        result_aux = filter_by_param('Machine', item, result_aux)
        result_aux = filter_by_param('type', '0', result_aux)
        final.append(result_aux)

    aux = []
    for items in final:
        pre_aux = create_start_end_dict(items, draw_type)
        for item in pre_aux:
            aux.append(item)

    colors = {
        'Sub product 0': random_colors(),
        'Sub product 1': random_colors(),
        'Sub product 2': random_colors(),
        'Sub product 3': random_colors()
    }
    init_notebook_mode(connected=True)
    fig = ff.create_gantt(aux,
                          colors=colors,
                          index_col='Resource',
                          show_colorbar=True,
                          group_tasks=True)
    py.iplot(fig)
    def draw_gantt_chart(self, path, benchmark_name, max_x):
        gantt_info = []
        for _, job in self.jobs.items():
            for op in job.ops:
                if not isinstance(op, DummyOperation):
                    temp = OrderedDict()
                    temp['Task'] = "Machine" + str(op.machine_id)
                    temp['Start'] = op.start_time
                    temp['Finish'] = op.end_time
                    temp['Resource'] = "Job" + str(op.job_id)
                    gantt_info.append(temp)
        gantt_info = sorted(gantt_info, key=lambda k: k['Task'])
        color = OrderedDict()
        for g in gantt_info:
            _r = random.randrange(0, 255, 1)
            _g = random.randrange(0, 255, 1)
            _b = random.randrange(0, 255, 1)
            rgb = 'rgb({}, {}, {})'.format(_r, _g, _b)
            color[g['Resource']] = rgb
        fig = ff.create_gantt(gantt_info,
                              colors=color,
                              show_colorbar=True,
                              group_tasks=True,
                              index_col='Resource',
                              title=benchmark_name + ' gantt chart',
                              showgrid_x=True,
                              showgrid_y=True)
        fig['layout']['xaxis'].update({'type': None})
        fig['layout']['xaxis'].update({'range': [0, max_x]})
        fig['layout']['xaxis'].update({'title': 'time'})

        plot(fig, filename=path)
コード例 #11
0
def coil_Tracking_callback(date, _, df):
    if date is not None:
        df = get_coil_tracking()
        df1 = df[df["Date"] == date]
        if len(df1):
            color_range = []
            for i in df1[:]:
                import random
                r = lambda: random.randint(0, 255)
                color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
                color_range.append(color)
            chart = ff.create_gantt(df1,
                                    colors=color_range,
                                    title='coil Production Tracking',
                                    show_colorbar=True,
                                    bar_width=0.5,
                                    showgrid_x=True,
                                    showgrid_y=True)

            fig = go.Figure(chart)
            return fig, "Showing Chart For {}".format(date)
        else:
            figure = {
                'data': [],
                'layout': {
                    'title': 'No Data Found',
                }
            }
            return figure, "NO Data found for Date {}".format(date)
コード例 #12
0
def graph_fig_adherencia_tiempo(id_paciente_ini):
    df_grafico = informacion_grafico_adherencia(id_paciente_ini)
    df_grafico["consistenciareclamacion"].replace(
        {
            0: "No Reclama",
            -1: "No Aplica",
            1: "Reclama"
        }, inplace=True)
    # los números 1 y 0 ahora son STR
    df_grafico.rename(columns={"categoria": "Task"}, inplace=True)
    df_grafico.rename(columns={"fecha_emision": "Start"}, inplace=True)
    df_grafico.rename(columns={"fechasiguienterecla": "Finish"}, inplace=True)
    df_grafico.rename(columns={"consistenciareclamacion": "Resource"},
                      inplace=True)

    colors = {
        'No Aplica': 'rgb(255,255,0)',
        'Reclama': 'rgb(0,255,0)',
        'No Reclama': 'rgb(255,0,0)'
    }

    fig_adherencia_tiempo = ff.create_gantt(
        df_grafico,
        index_col="Resource",
        title='reclamación de medicamentos en el tiempo',
        colors=colors,
        show_colorbar=True,
        group_tasks=True)

    return fig_adherencia_tiempo
コード例 #13
0
def draw_schedule():
    global schedule
    today = datetime.now()
    df = []
    counter = 1
    for worker in schedule.workers:
        for task in worker:
            st_date = today + timedelta(task.time_s)
            end_date = today + timedelta(task.time_e)
            dt = dict(Task='Worker' + str(counter),
                      Start=st_date,
                      Finish=end_date,
                      Resource='Tasks')
            df.append(dt)
        counter += 1

    colors = {'Tasks': 'rgb(200, 200, 200)'}

    fig = ff.create_gantt(df,
                          colors=colors,
                          index_col='Resource',
                          show_colorbar=True,
                          group_tasks=False,
                          showgrid_x=True)
    file_name = filedialog.asksaveasfilename(title="Select file to save",
                                             filetypes=[("HTML files",
                                                         "*.html")],
                                             defaultextension='.html')
    fig.write_html(file_name)
コード例 #14
0
    def plot(self):
        print(self.new_crew_index)
        df = []
        # df.append(dict(Task='Launch Time', Start=str(43200), Finish=str(46800), Crew='0'))
        # df.append(dict(Task='Dinner Time', Start=str(61200), Finish=str(64800), Crew='0'))
        _colors = {}
        set_of_crews = set()
        for jj in job.Job.all_jobs:
            jid = jj.jid
            crewid = self.np_all_job_assigned_crew[jid]
            if crewid != -1:
                set_of_crews.add(crewid)
            randr = random.randint(0, 255)
            randg = random.randint(0, 255)
            randb = random.randint(0, 255)
            _colors[str(crewid)] = 'rgb(' + str(randr) + ', ' + str(
                randg) + ', ' + str(randb) + ')'
            df.append(
                dict(Task=jj.run,
                     Start=str(jj.start_time),
                     Finish=str(jj.end_time),
                     Crew=str(crewid)))

        fig = ff.create_gantt(df,
                              height=1000,
                              index_col='Crew',
                              title='Crew Schedule',
                              show_colorbar=True,
                              group_tasks=True,
                              showgrid_x=True,
                              showgrid_y=True,
                              colors=_colors)
        fig.show()
コード例 #15
0
def plot_gantt(task_metadata, objective_value, color_palette):
    """
    plots the task_speed_scaling gantt chart given the metadata
    :param task_metadata: metadata
    :param objective_value: value of objective for current value
    :param color_palette: rgb tuples for colors to use
    :return:
    """
    df = []
    colors = {}
    # print(task_metadata)
    for task_key in task_metadata:
        task = task_metadata[task_key]
        df.append(dict(Task=str("Machine " + str(task['machine'])), Start=task['start'], Finish=task['end'], Machine=task['task']))
        if task['task'] < len(color_palette):
            color = color_palette[task['task']]
        else:
            color = (random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1))
            color_palette.append(color)
        colors[task['task']] = color
    title = "Speed Scaling Gantt Chart for Objective: " + str(objective_value)
    fig = ff.create_gantt(df, colors=colors, index_col='Machine', show_colorbar=True, group_tasks=True, showgrid_x=True, showgrid_y=True, title=title)
    fig.update_xaxes(type='linear')
    fig.show("notebook")
    return color_palette
コード例 #16
0
ファイル: io.py プロジェクト: AMyachev/bachelor_degree
def create_gantt_chart(schedule, filename='gantt_chart.html'):
    """
    :param schedule: Schedule object
    :param filename: str object
    :return:
    """
    def sec_to_date_time(secs):  # secs count from 1970-01-01 03:00:00
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(secs))

    texts = []
    tasks_schedule = []
    format = "Start: %s, Finish: %s, Job #%d"
    for index_job in schedule.jobs:
        for process_time in schedule.process_times(index_job):
            start_date = sec_to_date_time(process_time.begin_time)
            end_date = sec_to_date_time(process_time.end_time)
            machine_number = process_time.machine_index + 1  # index -> number
            tasks_schedule.append(
                dict(Task="Machine #%d" % machine_number,
                     Start=start_date,
                     Finish=end_date))
            text = format % (start_date, end_date, index_job + 1)
            texts.append(text)

    gantt_chart = ff.create_gantt(tasks_schedule, group_tasks=True)

    for dict_counter in range(len(gantt_chart["data"])):
        gantt_chart["data"][dict_counter].update(text=texts[dict_counter],
                                                 hoverinfo="text")

    plotly.offline.plot(gantt_chart, filename=filename, auto_open=True)
コード例 #17
0
def plot_operations(jobs_data, operation_results):
    df = []

    for j in range(len(jobs_data)):
        for o in get_operation_indexes_for_job_j(j, jobs_data):
            operation = get_operation_x(o, jobs_data)
            df.append(
                dict(Task=f"Machine-{operation[0]}  ", Start=operation_results[o], Finish=operation_results[o] + operation[1],
                     Resource=f"Job-{j}"))

    colors = {'Job-0': 'rgb(76,59,77)',
              'Job-1': 'rgb(165,56,96)',
              'Job-2': 'rgb(97,201,168)',
              'Job-3': 'rgb(255,238,219)'}

    fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True,
                          group_tasks=True, bar_width=0.3, title='Solution')

    fig.layout.xaxis = dict(
        automargin=True,
        dtick=1,
        title_text="Time t")

    fig.layout.yaxis.autorange = True

    fig.show()
コード例 #18
0
ファイル: activities.py プロジェクト: tcsvn/pyadlml
def gantt(df):
    """
    """
    df_plt = df.copy()
    df_plt.columns = ['Start', 'Finish', 'Resource']
    df_plt['Task'] = 'Activity'
    fig = ff.create_gantt(df_plt,
                          index_col='Resource',
                          show_colorbar=True,
                          bar_width=0.2,
                          height=500,
                          width=None,
                          group_tasks=True,
                          showgrid_x=True,
                          showgrid_y=False)

    # Add range slider
    btn_12h = dict(count=12, label="12h", step="hour", stepmode="backward")
    btn_1d = dict(count=1, label="1d", step="day", stepmode="backward")
    btn_1w = dict(count=7, label="1w", step="day", stepmode="backward")
    btn_1m = dict(count=1, label="1m", step="month", stepmode="backward")
    #btn_all =
    fig.update_layout(xaxis=dict(
        rangeselector=dict(buttons=list([btn_12h, btn_1d, btn_1w, btn_1m
                                         ])  #, dict(step="all")
                           ),
        rangeslider=dict(visible=True),
        type="date"))
    return fig
コード例 #19
0
def draw_gantt(output_directory: str, filled_rows: Dict[str, List[Any]]) -> None:
    fig = ff.create_gantt(
        filled_rows["gantt_rows"],
        title="Raiden Analysis",
        show_colorbar=False,
        bar_width=0.5,
        showgrid_x=True,
        showgrid_y=True,
        height=928,
        width=1680,
    )

    fig["layout"].update(
        yaxis={
            # 'showticklabels':False
            "automargin": True
        },
        hoverlabel={"align": "left"},
    )

    div = py.offline.plot(fig, output_type="div")

    j2_env = Environment(
        loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))), trim_blocks=True
    )
    output_content = j2_env.get_template("chart_template.html").render(
        gantt_div=div, task_table=filled_rows["table_rows"]
    )

    with open(f"{output_directory}/{DEFAULT_GANTT_FILENAME}", "w") as text_file:
        text_file.write(output_content)
コード例 #20
0
    def gantt(x_data,y_data,f,color):
        df = [dict(Task="Job-1", Start='2017-01-01', Finish='2017-02-02', Resource='Complete'),
              dict(Task="Job-1", Start='2017-02-15', Finish='2017-03-15', Resource='Incomplete'),
              dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Not Started'),
              dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Complete'),
              dict(Task="Job-3", Start='2017-03-10', Finish='2017-03-20', Resource='Not Started'),
              dict(Task="Job-3", Start='2017-04-01', Finish='2017-04-20', Resource='Not Started'),
              dict(Task="Job-3", Start='2017-05-18', Finish='2017-06-18', Resource='Not Started'),
              dict(Task="Job-4", Start='2017-01-14', Finish='2017-03-14', Resource='Complete')]

        colors = {'Not Started': 'rgb(220, 0, 0)',
                  'Incomplete': (1, 0.9, 0.16),
                  'Complete': 'rgb(0, 255, 100)'}

        fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True,
                              group_tasks=True)
        fig.update_layout(template="plotly_white")

        fig.update_layout(
            title="graph",
            yaxis_title="s",
            xaxis_title="activity",
            autosize=True,
            template="plotly_white"
        )
        plot_div = plot(fig, output_type='div', include_plotlyjs=True)
        return plot_div
コード例 #21
0
def update_gantt(df_results):
    df_results.Inicio = df_results.Inicio.astype(int)
    df_results.Fim = df_results.Fim.astype(int)
    df_results.Tarefa = df_results.Tarefa.str.replace("A",'_LOTE_')
    df_results['Lote'] = ("LOTE_" + df_results.Tarefa.str.extract(".*_(?P<Lote>\d)")).values

    df_results.rename(columns = {
        'Tarefa': 'Task1', 
        'Recurso': 'Task',
        'Inicio': 'Start',
        'Fim': 'Finish',
        'Lote' : 'Lote'
    }, inplace=True)

    xlabels = df_results[['Task','Start','Finish']].sort_values(['Start','Finish']).groupby('Task').first().reset_index().sort_values('Start')['Task'].values

    pio.templates.default = "simple_white"

#, index_col='Lote'
    fig = ff.create_gantt(df_results, index_col='Lote', show_hover_fill = True, group_tasks=True, 
    showgrid_x=True, show_colorbar=True)
    fig['layout']['xaxis'].update({'type': None, 'title' : "Tempo (em unidades de tempo de produção, utc)"}) 
    fig['layout']['yaxis'].update({'title' : "Recursos", "categoryorder" : "array", "categoryarray" : xlabels})

    return fig
コード例 #22
0
    def plot_standard_operations(self, operation_results):

        for j in range(len(self.JOBS_DATA)):
            for o in self.get_operation_indexes_for_job_j(j):
                operation = self.get_operation_x(o)
                df.append(
                    dict(Task=f"Machine-{operation[0]}  ", Start=operation_results[o],
                         Finish=operation_results[o] + operation[1],
                         Resource=f"Job-{j}"))

        colors = {'Job-0': 'rgb(76,59,77)',
                  'Job-1': 'rgb(165,56,96)',
                  'Job-2': 'rgb(97,201,168)',
                  'Job-3': 'rgb(255,238,219)'}

        standard_op_fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True,
                                          group_tasks=True, bar_width=0.3, title='Solution')

        standard_op_fig.layout.xaxis = dict(
            automargin=True,
            dtick=1,
            title_text="Time t")

        standard_op_fig.layout.yaxis.autorange = True

        standard_op_fig.layout.legend = {'traceorder':'normal'}

        return standard_op_fig
コード例 #23
0
ファイル: gantt.py プロジェクト: wenshilin/k8s-benchmark
def draw_gantt(data: list, colors: dict, filename: str):
    fig = ff.create_gantt(data,
                          colors=colors,
                          index_col='Type',
                          group_tasks=True)
    os.makedirs('results/gantt', exist_ok=True)
    pyplt(fig, filename=f'results/gantt/{filename}.html', image_height=1800)
コード例 #24
0
 def show_chart(self):
     fig = ff.create_gantt(self.data,
                           index_col='Resource',
                           title='Chart of each part',
                           group_tasks=True,
                           show_colorbar=True)
     plotly.offline.plot(fig, filename='chart.html')
コード例 #25
0
def display_gantt_chart(G, begin=None, colors=None, reverse_colors=False, index_col='Type',
                        show_colorbar=True, title=None, bar_width=0.2, showgrid_x=True,
                        showgrid_y=True, group_tasks=True):
    """
    This function displays a Gantt chart representation
    of the dependency network
    """
    # If a begin date is not provided, use the begin date of G
    if begin is None:
        begin = G.graph['Begin']
        
    # Convert date string into datetime format
    begin = datetime.strptime(begin, '%Y-%m-%d').date()
    
    # If a title is not provided, use the title of G
    if title is None:
        title = G.graph['Title']
        
    # Convert graph G into a dataframe format that ff.create_gantt() can read
    df = to_dataframe(G, begin, index_col)
    
    # Create Gantt chart
    fig = ff.create_gantt(df, colors=colors, reverse_colors=reverse_colors, index_col=index_col,
                          show_colorbar=show_colorbar, title=title, bar_width=bar_width,
                          showgrid_x=showgrid_x, showgrid_y=showgrid_y, group_tasks=group_tasks)
    
    # Convert Gantt chart into a figure widget and display it
    f = go.FigureWidget(fig)
    display(f)
コード例 #26
0
ファイル: cova_app.py プロジェクト: jules2689/covasim
def get_gantt(int_pars=None, intervention_config=None):
    df = []
    response = {'id': 'test'}
    for key, scenario in int_pars.items():
        for timeline in scenario:
            task = intervention_config[key]['formTitle']
            level = task + ' ' + str(timeline.get('level', ''))
            df.append(
                dict(Task=task,
                     Start=timeline['start'],
                     Finish=timeline['end'],
                     Level=level))
    if len(df) > 0:
        fig = ff.create_gantt(df,
                              height=400,
                              index_col='Level',
                              title='Intervention timeline',
                              show_colorbar=True,
                              group_tasks=True,
                              showgrid_x=True,
                              showgrid_y=True)
        fig.update_xaxes(type='linear')
        response['json'] = fig.to_json()

    return response
コード例 #27
0
def DisplayJobshop(starts, durations, machines, name):
    """Simple function to display a jobshop solution using plotly."""

    jobs_count = len(starts)
    machines_count = len(starts[0])
    all_machines = range(0, machines_count)
    all_jobs = range(0, jobs_count)
    df = []
    for i in all_jobs:
        for j in all_machines:
            df.append(
                dict(Task='Resource%i' % machines[i][j],
                     Start=ToDate(starts[i][j]),
                     Finish=ToDate(starts[i][j] + durations[i][j]),
                     Resource='Job%i' % i))

    sorted_df = sorted(df, key=lambda k: k['Task'])

    pyo.init_notebook_mode()

    colors = {}
    cm = ColorManager()
    cm.SeedRandomColor(0)
    for i in all_jobs:
        colors['Job%i' % i] = cm.RandomColor()

    fig = ff.create_gantt(sorted_df,
                          colors=colors,
                          index_col='Resource',
                          title=name,
                          show_colorbar=False,
                          showgrid_x=True,
                          showgrid_y=True,
                          group_tasks=True)
    pyo.iplot(fig)
コード例 #28
0
ファイル: PostProcessing.py プロジェクト: jonathan-ship/SimPy
def gantt(data, process_list):
    list_part = list(data["Part"][data["Event"] == "part_created"])
    start = datetime.date(2020, 8, 31)
    r = lambda: random.randint(0, 255)
    dataframe = []
    # print('#%02X%02X%02X' % (r(),r(),r()))
    colors = ['#%02X%02X%02X' % (r(), r(), r())]

    for part in list_part:
        part_data = data[data["Part"] == part]
        #data_by_group = part_data.groupby(part_data["Process"])
        for i in process_list:
            group = part_data[part_data["Process"] == i]
            if (i != "Sink") and (i != "Source") and len(group) != 0:
                work_start = group[group["Event"] == "work_start"]
                work_start = list(work_start["Time"].reset_index(drop=True))
                work_finish = group[group["Event"] == "work_finish"]
                work_finish = list(work_finish["Time"].reset_index(drop=True))
                dataframe.append(
                    dict(Task=i,
                         Start=(start + datetime.timedelta(days=work_start[0])
                                ).isoformat(),
                         Finish=(start + datetime.timedelta(
                             days=work_finish[0])).isoformat(),
                         Resource=part))
                colors.append('#%02X%02X%02X' % (r(), r(), r()))
            else:
                pass

    fig = ff.create_gantt(dataframe,
                          colors=colors,
                          index_col='Resource',
                          group_tasks=True)
    fig.show()
コード例 #29
0
def draw_gantt(nb_jobs, nb_machines, machines, durations, detail):
    representation = list_to_npmatrix(detail)

    today = date.today()
    list_gantt = []
    for i in range(nb_jobs):
        for j in range(nb_machines):
            list_gantt.append([
                'r' + str(machines[i, j] + 1),
                str(today + timedelta(days=representation[i][j])),
                str(today + timedelta(days=representation[i][j]) +
                    timedelta(days=int(durations[i, j]))), 'Job' + str(i + 1)
            ])

    df = pd.DataFrame(list_gantt,
                      columns=['Task', 'Start', 'Finish', 'Resource'])

    colours = []
    for key in range(nb_jobs):
        colour = col_from_string(str(key))
        colours.append(f"#{colour}")

    fig = create_gantt(df,
                       colors=colours,
                       index_col='Resource',
                       show_colorbar=True,
                       group_tasks=True)

    fig.show()
コード例 #30
0
def gantt(request):
    # from url initial page
    prep_id = request.GET.get('prep_id')
    if not prep_id:
        prep_id = 'DK43'

    form = AnimalForm()  # A form bound to the GET data
    animals = Animal.objects.filter(prep_id=prep_id).order_by('prep_id')
    animal = Animal.objects.get(prep_id=prep_id)
    tasks = Task.objects.all()

    df = []
    for entry in tasks:
        task = dict(Task=entry.name,
                    Start=entry.start_date,
                    Finish=entry.end_date)
        df.append(task)
    fig = ff.create_gantt(df)
    gantt_div = plot(fig, output_type='div', include_plotlyjs=False)

    return render(request,
                  'tasks.html',
                  context={
                      'animals': animals,
                      'animal': animal,
                      'form': form,
                      'gantt_div': gantt_div,
                      'animal_title': prep_id
                  })
コード例 #31
0
ファイル: dashboard.py プロジェクト: DongjunLee/stalker-bot
def make_daily_schedule_fig(n):
    today_record_data = data_handler.read_record()
    activity_data = today_record_data["activity"]
    task_data = activity_data["task"]

    toggl_projects = [data["project"] for data in task_data]
    colors = {}
    for data in task_data:
        colors[data["project"]] = data["color"]

    today_date = datetime.date.today().isoformat()
    tomorrow_date = (datetime.date.today() + datetime.timedelta(days=1)).isoformat()

    df = [  # Labeling scores
        dict(Task=5, Start=today_date, Finish=today_date, Resource=toggl_projects[0]),
        dict(Task=4, Start=today_date, Finish=today_date, Resource=toggl_projects[0]),
        dict(Task=3, Start=today_date, Finish=today_date, Resource=toggl_projects[0]),
        dict(Task=2, Start=today_date, Finish=today_date, Resource=toggl_projects[0]),
        dict(Task=1, Start=today_date, Finish=today_date, Resource=toggl_projects[0]),
    ]

    # Labeling projects
    for project in toggl_projects:
        df.append(
            dict(Task=1, Start=tomorrow_date, Finish=tomorrow_date, Resource=project)
        )

    for data in task_data:
        task = {
            "Task": data.get("score", 3),
            "Start": arrow.get(data["start_time"]).format("YYYY-MM-DD HH:mm:ss"),
            "Finish": arrow.get(data["end_time"]).format("YYYY-MM-DD HH:mm:ss"),
            "Resource": data["project"],
            "Description": data["description"],
        }
        df.append(task)

    fig = ff.create_gantt(df, colors=colors, index_col='Resource', title='Daily Schedule', group_tasks=True,
                        show_colorbar=True, bar_width=0.3, showgrid_x=True, showgrid_y=True, width=1200, height=600)

    happy_data = activity_data["happy"]

    if len(happy_data) > 0:
        xs = [arrow.get(d["time"]).format("YYYY-MM-DD HH:mm:ss") for d in happy_data]
        ys = [d["score"]-1 for d in happy_data]

        scatter_trace=dict(
            type='scatter',
            mode="markers",
            marker=dict(
                size=10,
                color="#439C59",
                line=dict(
                    width=2,
                ),
            ),
            name="Happy",
            x=xs,
            y=ys,
        )
        fig['data'].append(scatter_trace)

    # Annotations
    fig['layout']['annotations'] = []
    for index, d in enumerate(fig['data']):
        if len(d['x']) != 2:
            continue

        start_date, end_date = d['x']
        start_score, end_score = d['y']
        if start_date == end_date or start_score != end_score:
            continue

        description = d.get("text", "")
        project_names = list(colors.keys())

        project_name = "Empty"
        for p_name in project_names:
            if description.startswith(p_name):
                project_name = p_name
                break

        if type(start_date) != datetime.datetime:
            start_date = parser.parse(start_date)
        if type(end_date) != datetime.datetime:
            end_date = parser.parse(end_date)

        up_ays = [-50, -90, -70, -110]
        down_ays = [50, 90, 70, 110]

        if start_score > 2:  # large than 3
            ays = up_ays
        else:
            ays = down_ays

        ay = ays[index % len(ays)]

        annotation = dict(
            x=start_date + (end_date - start_date) / 2,
            y=start_score,
            xref='x',
            yref='y',
            text=d.get("text", "None"),
            font=dict(
                family='Courier New, monospace',
                size=12,
                color='#fff'
            ),
            bgcolor=colors.get(project_name, "#DEDEDE"),
            bordercolor='#666',
            borderpad=2,
            arrowhead=7,
            ax=0,
            ay=ay,
            opacity=0.7,
        )
        fig['layout']['annotations'].append(annotation)

    return fig
コード例 #32
0
ファイル: plotly_generator.py プロジェクト: ami-lab/CONSERT
        partial_frame['Event Type'] = key
        all_frames.append(partial_frame)
df = pd.concat(all_frames)

# Keep only the needed columns
df = df[['type.type', 'annotationsStartTimeStamp', 'annotationsEndTimeStamp', 'Event Type']]

# Convert annotations to datetime from UNIX timestamps (dtype int64)
df['annotationsStartTimeStamp'] = pd.to_datetime(df['annotationsStartTimeStamp'], unit='ms')
df['annotationsEndTimeStamp'] = pd.to_datetime(df['annotationsEndTimeStamp'], unit='ms')

# Rename columns to match plotly conventions
df.rename(columns={'type.type': 'Task', 'annotationsStartTimeStamp': 'Start', 'annotationsEndTimeStamp': 'Finish'}, inplace=True)

# Sort dataframe so we get HLAs in the lower part of the Gantt
df.sort_values(by="Event Type", ascending=False, inplace=True)
df.reset_index(inplace=True)

# Set color map for different event types
colors = {'POS': 'rgb(211, 211, 211)', 'LLA': 'rgb(169, 169, 169)', 'HLA': 'rgb(0, 220, 0)'}

# Create Gantt figure
fig = ff.create_gantt(df, colors=colors, index_col='Event Type', title='HLA Recognition Scenario',
                      showgrid_y=True, show_colorbar=True, group_tasks=True)

# Tilt y labels 45 degrees (due to them being too long to display correctly)
fig['layout']['yaxis']['tickangle'] = 45

# Plot the figure in offline mode (this creates and opens the resulting HTML file)
plotly.offline.plot(fig, filename=OUTPUT_HTML)
コード例 #33
0
ファイル: gantt.py プロジェクト: gahoo/SNAP
 def prepare_gantt(df):
     return ff.create_gantt(df, group_tasks=True)
コード例 #34
0
ファイル: tools.py プロジェクト: plotly/plotly.py
 def create_gantt(*args, **kwargs):
     FigureFactory._deprecated('create_gantt')
     from plotly.figure_factory import create_gantt
     return create_gantt(*args, **kwargs)