Exemple #1
0
def convert(csvfilename: str, svgfilename: str, start: datetime = None, end: datetime = None, nwdays: List[int] = None):
    gantt.define_not_worked_days([] if nwdays is None else nwdays)  # for OmniFocus, every day is a working day
    af = ActionFactory()
    af.read_csv(csvfilename)

    projects = {}
    all_dates = [a.start_date for a in af.actions if a.start_date is not None] + \
                [a.due_date for a in af.actions if a.due_date is not None] + \
                [a.completion_date for a in af.actions if a.completion_date is not None] + \
                [datetime.date.today()]
    start = min(all_dates) if start is None else start
    end = max(all_dates) if end is None else end
    for action in af.actions:
        task_start = action.start_date or start
        task_end = action.completion_date or action.due_date or end

        task = gantt.Task(name=action.name,
                          start=task_start,
                          stop=task_end)

        if action.project not in projects:
            projects[action.project] = gantt.Project(name=action.project)
        projects[action.project].add_task(task)

    mainproject = gantt.Project()
    for project in projects.values():
        mainproject.add_task(project)

    mainproject.make_svg_for_tasks(svgfilename,
                                   start=start,
                                   end=end,
                                   today=datetime.date.today())
Exemple #2
0
    def Parse(self):
        # print("======== Start Parsing ==========")
        # find connections
        tmax = self.Start
        tmin = self.Start
        for t in self.Tasks:
            tt = self.Tasks[t]
            if len(tt.Before) > 0:
                tt.setBefore(self.Tasks[tt.Before])
            if len(tt.After) > 0:
                # print(tt.After)
                for t in tt.After.split(","):
                    tt.setAfter(self.Tasks["%s" % t])
            if tt.Parent != None:
                tt.Parent.addChild(tt)

        # Update times
        for t in self.Tasks:
            tt = self.Tasks[t]
            self.Start = min(self.Start, tt.Start)
            self.End = max(self.End, tt.End)
        self.Duration = workdays.networkdays(self.Start, self.End)
        self.gantt = gantt.Project(name=self.Name)

        for t in self.Tasks:
            tt = self.Tasks[t]
            self.gantt.add_task(tt.makeGanttItem())
Exemple #3
0
def create_gant(start, sprints, duration, name):
    # Change font default
    gantt.define_font_attributes(fill='white',
                                 stroke='white',
                                 stroke_width=1,
                                 font_family="Ubuntu")

    p1 = gantt.Project(name=name)

    if not isinstance(start, datetime.date):
        start_date = parse(start)
    else:
        start_date = start

    end_date = start_date + relativedelta(days=(duration + 2) * sprints)
    print(start_date, end_date)
    curr_t = None
    # Create some tasks
    for sprint in range(sprints):
        t = gantt.Task(name=f'Sprint {sprint}',
                       start=start_date,
                       duration=10,
                       percent_done=44,
                       color="#0000FF",
                       depends_of=curr_t)
        curr_t = t
        p1.add_task(t)

    p1.make_svg_for_tasks(filename='test_full.svg',
                          today=datetime.date.today(),
                          start=start_date,
                          end=end_date)
Exemple #4
0
 def __init__(self):
     self._tasks = {}
     self._dependencies = defaultdict(set)
     self._project = gantt.Project(name='Project 1')
     self._resources = {
         'egorov': gantt.Resource('egorov'),
         'pristupa': gantt.Resource('pristupa'),
     }
Exemple #5
0
def main():

    #   get our Jira connection information from env vars
    server = os.environ['JIRA_SERVER']  # e.g. http://myjiraservername:8080
    project = os.environ['JIRA_PROJECT']  # e.g. MYPROJECTNAME
    username = os.environ[
        'JIRA_USERNAME']  # your Jira username (username if Jira server, email if Jira Cloud)
    password = os.environ[
        'JIRA_PASSWORD']  # your password - note that for Jira Cloud you will need to use an API token

    #   this program is not a demonstration of error-checking, it is a demonstration of charting
    #   connect to the server
    options = {"server": server}
    jira = JIRA(options, basic_auth=(username, password))

    #   search for issues - REPLACE this with your query, the code assumes your query returns only Epics
    issues = jira.search_issues("(project=" + project +
                                ") and (issuetype=Epic) order by created DESC",
                                startAt=0)

    charttitle = "demo of Gantt chart of Jira epics"
    today = datetime.datetime.today()

    ganttchart = gantt.Project(charttitle)
    plotlylist = []
    for issue in issues:
        #   REPLACE customfield_xxxxx below with your Jira instance's custom field identifier for Epic Name - get that value from the XML Export issue view on an Epic
        epicname = issue.fields.customfield_10102
        #   construct the text for each Gantt bar and get the start/stop dates
        #   created and duedate are generally present on every Jira instance - change these fields if you need to
        #   e.g. you might also calculate the start date as the creation date of the earliest issue in the epic, and the end date as the end date of the latest issue
        taskname = epicname + " (" + issue.key + ") " + issue.fields.status.name
        startdate = datetime.datetime.strptime(issue.fields.created[0:10],
                                               '%Y-%m-%d')
        stopdate = datetime.datetime.strptime(issue.fields.duedate, '%Y-%m-%d')

        #   add the task to the gantt chart
        gantttask = gantt.Task(name=taskname, start=startdate, stop=stopdate)
        ganttchart.add_task(gantttask)

        #   add the task to the plotly chart
        plotlydictentry = dict(Task=taskname, Start=startdate, Finish=stopdate)
        plotlylist.append(plotlydictentry)


#   write the gantt chart to a file
    ganttchart.make_svg_for_tasks(filename="ganttchart.svg",
                                  today=today,
                                  scale=gantt.DRAW_WITH_WEEKLY_SCALE)

    #   the plotly chart will pop up in the browser
    plotlyfig = plotlyff.create_gantt(plotlylist,
                                      title=charttitle,
                                      showgrid_x=True,
                                      show_hover_fill=True)
    plotlyfig.show()
    def main(self, arguments):
        """The main application function, this is where it all starts properly"""
        generate_output = False

        calendar_year = None
        if arguments.calendar_year:
            calendar_year = arguments.calendar_year.strip()

        if arguments.calendar_yaml_file:
            if self.load_yaml_file(arguments.calendar_yaml_file.strip()):
                generate_output = True
            else:
                print(
                    """Failure while trying to load the YAML file, please check error message, fix the problem and try again"""
                )
        elif arguments.calendar_json_url:
            if self.load_json_url(arguments.calendar_json_url.strip(),
                                  calendar_year):
                generate_output = True
            else:
                print(
                    """Loading the JSON file from %s failed. Please check the supplied URL"""
                    % (arguments.calendar_json_url))
        else:
            print(
                """The supplied combination of parameters is not sufficient to do something. Please review"""
            )

        if generate_output:
            gantt.define_not_worked_days([])
            self.gantt_project = gantt.Project(name='C3VOC')

            self.create_calendar(not (arguments.calendar_monthly))

            if arguments.calendar_monthly:
                self.export_calendar_monthly(calendar_year,
                                             arguments.calendar_monthly_prefix,
                                             arguments.calendar_monthly_suffix)
            else:
                self.export_calendar_year(arguments.calendar_svg_file.strip(),
                                          calendar_year)

            return True

        return False
def gantt_svg_permalink(request, permalink):
    """Get the Gantt chart as an SVG, when a permalink has been
    specified. This is allowed to be accessed without a login, to make
    it easier to embed the permalink in places.

    """

    project = Project.objects.get(permalink=permalink)
    if not project:
        return HttpResponseNotFound()

    svg_buffer = io.BytesIO()
    with io.TextIOWrapper(svg_buffer) as output:
        db_resources = Resource.objects.all()
        resources = {
            resource.name: gantt.Resource(resource.name)
            for resource in db_resources
        }

        p = gantt.Project(name='Project 1')

        for resource in db_resources:
            for holiday in resource.holiday_set.all():
                resources[resource.name].add_vacations(holiday.date)

        tasks = Task.arrange_tasks()
        for task in tasks:
            task_obj = gantt.Task(name=task['name'],
                                  start=task['start_date'],
                                  duration=task['duration'],
                                  resources=[resources[task['resource']]])
            p.add_task(task_obj)

        p.make_svg_for_resources(filename=output,
                                 today=tasks[0]['start_date'],
                                 start=tasks[0]['start_date'],
                                 end=(max(task['end_date'] for task in tasks)))

        output.flush()

        return HttpResponse(svg_buffer.getvalue(),
                            content_type="image/svg+xml")
 def generate_chart(self):
     """
     Creates a version chart SVG.
     """
     p = gantt.Project(name=self.project.name)
     for version in self.project.versions:
         if hasattr(version, 'startDate') and hasattr(version, 'releaseDate'):
             start_date = (int(x) for x in version.startDate.split('-'))
             end_date = (int(x) for x in version.releaseDate.split('-'))
             task = gantt.Task(name=version.name,
                               start=datetime.date(*start_date),
                               stop=datetime.date(*end_date))
             p.add_task(task)
     today = datetime.date.today()
     p.make_svg_for_tasks(filename='{0}_dy.svg'.format(self.project.key),
                          today=today,
                          scale=gantt.DRAW_WITH_DAILY_SCALE)
     p.make_svg_for_tasks(filename='{0}_wk.svg'.format(self.project.key),
                          today=today,
                          scale=gantt.DRAW_WITH_WEEKLY_SCALE)
Exemple #9
0
    def gen(self):
        # Change font default
        gantt.define_font_attributes(fill='black',
                                     stroke='black',
                                     stroke_width=0,
                                     font_family="Verdana")

        self.gproject = gantt.Project(name=self.project.name)

        resources = {}
        for pid in self.peoples.idarray():
            resources[pid] = gantt.Resource(pid)

        for entity in self.entityes:
            resarray = []
            for people in entity.people:
                resarray.append(resources[people])

            task = gantt.Task(
                name=entity.id,
                fullname=entity.name,
                start=entity.starttime,
                stop=entity.endtime,
                #duration=(entity.endtime - entity.starttime).days,
                resources=resarray)
            self.gproject.add_task(task)

        tasks = self.gproject.get_tasks()
        for entity in self.entityes:
            task = None
            for t in tasks:
                if t.name == entity.id:
                    task = t
                    break
            froms = entity.dfrom
            for d in froms:
                for t in tasks:
                    if t.name == d.name:
                        task.add_depends([t])
                        break
        return self.gproject
 def generate_chart(self):
     """
     Creates an epic chart SVG.
     """
     p = gantt.Project(name=self.project.name)
     for epic in self.epics:
         if hasattr(epic.fields, 'startDate') and hasattr(epic.fields, 'releaseDate'):
             name = epic.fields.customfield_10007
             start_date = (int(x) for x in epic.fields.startDate.split('-'))
             end_date = (int(x) for x in epic.fields.releaseDate.split('-'))
             task = gantt.Task(name=name,
                               start=datetime.date(*start_date),
                               stop=datetime.date(*end_date))
             p.add_task(task)
     today = datetime.date.today()
     p.make_svg_for_tasks(filename='{0}_dy.svg'.format(self.project.key),
                          today=today,
                          scale=gantt.DRAW_WITH_DAILY_SCALE)
     p.make_svg_for_tasks(filename='{0}_wk.svg'.format(self.project.key),
                          today=today,
                          scale=gantt.DRAW_WITH_WEEKLY_SCALE)
Exemple #11
0
def test_Tasks():
    tSADU = gantt.Task(name='tache SADU',
                       start=datetime.date(2014, 12, 25),
                       duration=4)
    assert_equals((tSADU.start_date(), tSADU.end_date()),
                  (datetime.date(2014, 12, 26), datetime.date(2014, 12, 31)))
    assert_equals(tSADU.nb_elements(), 1)

    tSAST = gantt.Task(name='tache SAST',
                       start=datetime.date(2014, 12, 25),
                       stop=datetime.date(2014, 12, 31))
    assert_equals((tSAST.start_date(), tSAST.end_date()),
                  (datetime.date(2014, 12, 26), datetime.date(2014, 12, 31)))

    tDUST = gantt.Task(name='tache DUST',
                       stop=datetime.date(2014, 12, 31),
                       duration=4)
    assert_equals((tDUST.start_date(), tDUST.end_date()),
                  (datetime.date(2014, 12, 26), datetime.date(2014, 12, 31)))

    tDUSTSADU = gantt.Task(name='tache DUST SADU',
                           start=datetime.date(2015, 1, 1),
                           duration=4,
                           depends_of=[tDUST])
    assert_equals((tDUSTSADU.start_date(), tDUSTSADU.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tDUSTSAST = gantt.Task(name='tache DUST SAST',
                           start=datetime.date(2015, 1, 1),
                           stop=datetime.date(2015, 1, 7),
                           depends_of=[tDUST])
    assert_equals((tDUSTSAST.start_date(), tDUSTSAST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tDUSTDUST = gantt.Task(name='tache DUST DUST',
                           stop=datetime.date(2015, 1, 7),
                           duration=9,
                           depends_of=[tDUST])
    assert_equals((tDUSTDUST.start_date(), tDUSTDUST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tDUSTDUST2 = gantt.Task(name='tache DUST DUST2',
                            stop=datetime.date(2015, 1, 10),
                            duration=2,
                            depends_of=[tDUST])
    assert_equals((tDUSTDUST2.start_date(), tDUSTDUST2.end_date()),
                  (datetime.date(2015, 1, 8), datetime.date(2015, 1, 9)))

    tSADUSADU = gantt.Task(name='tache SADU SADU',
                           start=datetime.date(2015, 1, 1),
                           duration=4,
                           depends_of=[tSADU])
    assert_equals((tSADUSADU.start_date(), tSADUSADU.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSADUSAST = gantt.Task(name='tache SADU SAST',
                           start=datetime.date(2015, 1, 1),
                           stop=datetime.date(2015, 1, 7),
                           depends_of=[tSADU])
    assert_equals((tSADUSAST.start_date(), tSADUSAST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSADUDUST = gantt.Task(name='tache SADU DUST',
                           stop=datetime.date(2015, 1, 7),
                           duration=9,
                           depends_of=[tSADU])
    assert_equals((tSADUDUST.start_date(), tSADUDUST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSADUDUST2 = gantt.Task(name='tache SADU DUST2',
                            stop=datetime.date(2015, 1, 10),
                            duration=2,
                            depends_of=[tSADU])
    assert_equals((tSADUDUST2.start_date(), tSADUDUST2.end_date()),
                  (datetime.date(2015, 1, 8), datetime.date(2015, 1, 9)))

    tSASTSADU = gantt.Task(name='tache SAST SADU',
                           start=datetime.date(2015, 1, 1),
                           duration=4,
                           depends_of=[tSAST])
    assert_equals((tSASTSADU.start_date(), tSASTSADU.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSASTSAST = gantt.Task(name='tache SAST SAST',
                           start=datetime.date(2015, 1, 1),
                           stop=datetime.date(2015, 1, 7),
                           depends_of=[tSAST])
    assert_equals((tSASTSAST.start_date(), tSASTSAST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSASTDUST = gantt.Task(name='tache SAST DUST',
                           stop=datetime.date(2015, 1, 7),
                           duration=9,
                           depends_of=[tSAST])
    assert_equals((tSASTDUST.start_date(), tSASTDUST.end_date()),
                  (datetime.date(2015, 1, 2), datetime.date(2015, 1, 7)))

    tSASTDUST2 = gantt.Task(name='tache SAST DUST2',
                            stop=datetime.date(2015, 1, 10),
                            duration=2,
                            depends_of=[tSAST])
    assert_equals((tSASTDUST2.start_date(), tSASTDUST2.end_date()),
                  (datetime.date(2015, 1, 8), datetime.date(2015, 1, 9)))

    tBUG = gantt.Task(name='tBUG', start=datetime.date(2015, 1, 9), duration=7)
    assert_equals((tBUG.start_date(), tBUG.end_date()),
                  (datetime.date(2015, 1, 9), datetime.date(2015, 1, 19)))

    tBUG2 = gantt.Task(name='tBUG2',
                       start=datetime.date(2015, 1, 10),
                       duration=7)
    assert_equals((tBUG2.start_date(), tBUG2.end_date()),
                  (datetime.date(2015, 1, 12), datetime.date(2015, 1, 20)))

    tBUG3 = gantt.Task(name='tBUG3-,\'/()',
                       start=datetime.date(2015, 1, 10),
                       duration=7)

    p1 = gantt.Project(name='Projet 1')

    assert_equals(p1.nb_elements(), 0)

    p1.add_task(tSADU)
    p1.add_task(tSAST)
    p1.add_task(tDUST)
    p1.add_task(tDUSTSADU)
    p1.add_task(tDUSTSAST)
    p1.add_task(tDUSTDUST)
    p1.add_task(tDUSTDUST2)

    p1.add_task(tSADUSADU)
    p1.add_task(tSADUSAST)
    p1.add_task(tSADUDUST)
    p1.add_task(tSADUDUST2)

    p1.add_task(tSASTSADU)
    p1.add_task(tSASTSAST)
    p1.add_task(tSASTDUST)
    p1.add_task(tSASTDUST2)

    assert_equals(p1.is_in_project(tBUG), False)

    p1.add_task(tBUG)

    assert_equals(p1.is_in_project(tBUG), True)

    p1.add_task(tBUG2)
    p1.add_task(tBUG3)

    assert_equals(p1.nb_elements(), 18)

    assert_equals(p1.start_date(), datetime.date(2014, 12, 26))
    assert_equals(p1.end_date(), datetime.date(2015, 1, 20))

    p1.make_svg_for_tasks(filename='./h.svg',
                          today=datetime.date(2014, 12, 31))
    assert os.path.isfile('./h.svg')

    assert_equals(p1.get_resources(), [])
    assert_equals(len(p1.get_tasks()), 18)
    return
Exemple #12
0
def get_gantt_1():
    # Change font default
    gantt.define_font_attributes(fill='black',
                                 stroke='black',
                                 stroke_width=0,
                                 font_family="Verdana")

    # Add vacations for everyone
    gantt.add_vacations(datetime.date(2014, 12, 25))
    gantt.add_vacations(datetime.date(2015, 1, 1))
    gantt.add_vacations(datetime.date(2015, 1, 13))

    # Create two resources
    rANO = gantt.Resource('ANO')
    rJLS = gantt.Resource('JLS')

    # Add vacations for one lucky resource
    rANO.add_vacations(dfrom=datetime.date(2014, 12, 29),
                       dto=datetime.date(2015, 1, 4))
    rANO.add_vacations(dfrom=datetime.date(2015, 1, 6),
                       dto=datetime.date(2015, 1, 8))

    # Test if this resource is  avalaible for some dates
    print(rANO.is_available(datetime.date(2015, 1, 5)))
    print(rANO.is_available(datetime.date(2015, 1, 8)))
    print(rANO.is_available(datetime.date(2015, 1, 6)))
    print(rANO.is_available(datetime.date(2015, 1, 2)))
    print(rANO.is_available(datetime.date(2015, 1, 1)))

    # Create some tasks
    t1 = gantt.Task(name='tache1',
                    start=datetime.date(2014, 12, 25),
                    duration=4,
                    percent_done=44,
                    resources=[rANO],
                    color="#FF8080")
    t2 = gantt.Task(name='tache2',
                    start=datetime.date(2014, 12, 28),
                    duration=6,
                    resources=[rJLS])
    t7 = gantt.Task(name='tache7',
                    start=datetime.date(2014, 12, 28),
                    duration=5,
                    percent_done=50)
    t3 = gantt.Task(name='tache3',
                    start=datetime.date(2014, 12, 25),
                    duration=4,
                    depends_of=[t1, t7, t2],
                    resources=[rJLS])
    t4 = gantt.Task(name='tache4',
                    start=datetime.date(2015, 1, 1),
                    duration=4,
                    depends_of=t1,
                    resources=[rJLS])
    t5 = gantt.Task(name='tache5',
                    start=datetime.date(2014, 12, 23),
                    duration=3)
    t6 = gantt.Task(name='tache6',
                    start=datetime.date(2014, 12, 25),
                    duration=4,
                    depends_of=t7,
                    resources=[rANO])
    t8 = gantt.Task(name='tache8',
                    start=datetime.date(2014, 12, 25),
                    duration=4,
                    depends_of=t7,
                    resources=[rANO, rJLS])

    # Create a project
    p1 = gantt.Project(name='Projet 1')

    # Add tasks to this project
    p1.add_task(t1)
    p1.add_task(t7)
    p1.add_task(t2)
    p1.add_task(t3)
    p1.add_task(t5)
    p1.add_task(t8)

    # Create another project
    p2 = gantt.Project(name='Projet 2', color='#FFFF40')

    # Add tasks to this project
    p2.add_task(t2)
    p2.add_task(t4)

    # Create another project
    p = gantt.Project(name='Gantt')
    # wich contains the first two projects
    # and a single task
    p.add_task(p1)
    p.add_task(p2)
    p.add_task(t6)

    # Test cases for milestones
    # Create another project
    ptcm = gantt.Project(name='Test case for milestones')

    tcm11 = gantt.Task(name='tcm11',
                       start=datetime.date(2014, 12, 25),
                       duration=4)
    tcm12 = gantt.Task(name='tcm12',
                       start=datetime.date(2014, 12, 26),
                       duration=5)
    ms1 = gantt.Milestone(name=' ', depends_of=[tcm11, tcm12])
    tcm21 = gantt.Task(name='tcm21',
                       start=datetime.date(2014, 12, 30),
                       duration=4,
                       depends_of=[ms1])
    tcm22 = gantt.Task(name='tcm22',
                       start=datetime.date(2014, 12, 30),
                       duration=6,
                       depends_of=[ms1])
    ms2 = gantt.Milestone(name='MS2', depends_of=[ms1, tcm21, tcm22])
    tcm31 = gantt.Task(name='tcm31',
                       start=datetime.date(2014, 12, 30),
                       duration=6,
                       depends_of=[ms2])
    ms3 = gantt.Milestone(name='MS3', depends_of=[ms1])

    ptcm.add_task(tcm11)
    ptcm.add_task(tcm12)
    ptcm.add_task(ms1)
    ptcm.add_task(tcm21)
    ptcm.add_task(tcm22)
    ptcm.add_task(ms2)
    ptcm.add_task(tcm31)
    ptcm.add_task(ms3)

    p.add_task(ptcm)

    ##########################$ MAKE DRAW ###############
    p.make_svg_for_tasks(filename='./media/gantt/test_full.svg',
                         today=datetime.date(2014, 12, 31),
                         start=datetime.date(2014, 8, 22),
                         end=datetime.date(2015, 1, 14))
    p.make_svg_for_tasks(filename='./media/gantt/test_full2.svg',
                         today=datetime.date(2014, 12, 31))
    p.make_svg_for_tasks(filename='test.svg',
                         today=datetime.date(2014, 12, 31),
                         start=datetime.date(2015, 1, 3),
                         end=datetime.date(2015, 1, 6))
    p1.make_svg_for_tasks(filename='test_p1.svg',
                          today=datetime.date(2014, 12, 31))
    p2.make_svg_for_tasks(filename='test_p2.svg',
                          today=datetime.date(2014, 12, 31))
    p.make_svg_for_resources(filename='test_resources.svg',
                             today=datetime.date(2014, 12, 31),
                             resources=[rANO, rJLS])
    p.make_svg_for_tasks(filename='test_weekly.svg',
                         today=datetime.date(2014, 12, 31),
                         scale=gantt.DRAW_WITH_WEEKLY_SCALE)
    ##########################$ /MAKE DRAW ###############

    return '/media/gantt/test_full2.svg'
t5 = gantt.Task(name='tache5', start=datetime.date(2014, 12, 23), duration=3)
t6 = gantt.Task(
    name='tache6',
    start=datetime.date(2014, 12, 25),
    duration=4,
    depends_of=t7,
)
t8 = gantt.Task(
    name='tache8',
    start=datetime.date(2014, 12, 25),
    duration=4,
    depends_of=t7,
)

# Create a project
p1 = gantt.Project(name='Projet 1')

# Add tasks to this project
p1.add_task(t1)
p1.add_task(t7)
p1.add_task(t2)
p1.add_task(t3)
p1.add_task(t5)
p1.add_task(t8)

# Create another project
p2 = gantt.Project(name='Projet 2', color='#FFFF40')

# Add tasks to this project
p2.add_task(t2)
p2.add_task(t4)
def generate_diagram(project):
    gantt.define_font_attributes(
        fill='black',
        stroke='black',
        stroke_width=0,
        font_family="Verdana",
    )

    gantt.define_not_worked_days([])

    main_project = gantt.Project(name=project.title)

    gantt_performers = []
    gantt_tasks = []

    # taskdb = TaskDB(project=project)
    # tasks = taskdb.get_all_tasks()
    # tasks = Task.objects.filter(project=project)
    for performer in project.performers.all():
        if performer.tasks.all():
            gantt_performer = gantt.Project(name=performer.name)
            gantt_performers.append(gantt_performer)
            for task in performer.tasks.all():
                gantt_task = gantt.Task(name=task.title,
                                        start=task.date_start,
                                        duration=task.duration)
                gantt_performer.add_task(gantt_task)

    # for task in tasks:
    #     gantt_task = gantt.Task(
    #         name=task.title,
    #         start=task.date_start,
    #         duration=task.duration
    #     )
    #     if task.performers.all():
    #         for performer in task.performers.all():
    #             gantt_performer = gantt.Project(name=performer.name)
    #             gantt_performer.add_task(gantt_task)
    #             gantt_performers.append(gantt_performer)
    #     else:
    #         gantt_tasks.append(gantt_task)

    [main_project.add_task(task) for task in gantt_tasks]
    [main_project.add_task(task) for task in gantt_performers]

    today_time = datetime.datetime.now()
    today_date = datetime.date(today_time.year, today_time.month,
                               today_time.day)

    main_project.make_svg_for_tasks(filename=os.path.join(
        TMP_PATH,
        str(project.user) + '.svg'),
                                    today=today_date,
                                    start=project.date_start,
                                    end=project.date_end)

    with open(os.path.join(TMP_PATH, str(project.user) + '.svg'), 'r') as f:
        svg_string = f.read()

    svg_string = svg_string.replace('lightgray', '#D3D3D3').replace(
        'gray', '#808080').replace('#0000FF ', '#C2C5CC')

    with open(os.path.join(TMP_PATH, str(project.user) + '.svg'), 'w') as f:
        f.write(svg_string)

    drawing = svg2rlg(os.path.join(TMP_PATH, str(project.user) + '.svg'))
    renderPM.drawToFile(drawing,
                        os.path.join(TMP_PATH,
                                     str(project.user) + '.jpg'),
                        fmt="jpg")

    os.remove(os.path.join(TMP_PATH, str(project.user) + '.svg'))

    return os.path.join(TMP_PATH, str(project.user) + '.jpg')
Exemple #15
0
 def create_gantt(self, title):
     self.chart = gantt.Project(name=title)
Exemple #16
0
def dispatch(inputfile, outputfile, verbose, project_name, today, prefixdays,
             suffixdays, weeklyscale):
    global resource_list
    global task_list

    # Change font default
    gantt.define_font_attributes(fill='black',
                                 stroke='black',
                                 stroke_width=0,
                                 font_family="Verdana")

    df = read_excel(inputfile)  # , sheet_name="Data"¨)

    resource_list = []
    resources = split_items_by_comma(remove_nan(df['Owner'].unique()))

    if verbose != "no":
        print("Found resources", resources)

    for resource in resources:
        resource_list.append(gantt_resource(resource))

    if verbose != "no":
        #  print(df[1])
        print(len(df))

    task_list = []
    for i in range(len(df)):
        task = gantt_task(df["Task#"][i], df["Name"][i], df["Start Date"][i],
                          df["End Date"][i], df["#days long"][i],
                          df["%Done"][i], df["Owner"][i], df["Priority"][i],
                          df["Depend On"][i])
        task_list.append(task)
    for task in task_list:
        task.add_dependencies()
    task_index_list = list(range(len(task_list)))
    while len(task_index_list) > 0:
        unfinished_task = []
        for i in task_index_list:
            task = task_list[i]
            task.start_date = get_start_date(task)
            if task.end_date is None:
                if task.duration is not None:
                    if not task.is_milestone:
                        task.end_date = task.start_date + \
                            datetime.timedelta(days=task.duration)
            if verbose != "no":
                print("Task", task.name, "started at", task.start_date,
                      "end date", "duration", task.duration, task.end_date,
                      "owner", [_.name for _ in task.owner_list],
                      "is milestone", task.is_milestone, "depends_of",
                      [_.name for _ in task.depend_on])
            if task.generate_task_object() == 0:
                unfinished_task.append(i)
        task_index_list = unfinished_task

    # test printing
    p = gantt.Project(name=project_name)
    for task in task_list:
        p.add_task(task.task)

    start_date = get_earliest_start_date(task_list)
    end_date = get_latest_end_date(task_list)
    if weeklyscale == "yes":
        p.make_svg_for_tasks(
            filename=outputfile,
            today=string_to_date(today),
            start=start_date - datetime.timedelta(days=prefixdays),
            end=end_date + datetime.timedelta(days=suffixdays),
            scale=gantt.DRAW_WITH_WEEKLY_SCALE)
    else:
        p.make_svg_for_tasks(
            filename=outputfile,
            today=string_to_date(today),
            start=start_date - datetime.timedelta(days=prefixdays),
            end=end_date + datetime.timedelta(days=suffixdays),
            scale=gantt.DRAW_WITH_DAILY_SCALE)
Exemple #17
0
import gantt
from datetime import date, timedelta

WORKSHOP = "#55CDFC"
DEADLINE = "#F7A8B8"
DRAFT = "#DDDDDD"

plan_de_campagne = gantt.Project("Plan de campagne", color="#FF0018")

plan_de_campagne_tasks = [
    gantt.Task("Write plan de campagne",
               start=date(2020, 2, 3),
               duration=5 * 5),
    gantt.Task("Revise plan de campagne",
               start=date(2020, 3, 10),
               duration=5 * 2 - 1),
    gantt.Task("First draft plan de campagne",
               start=date(2020, 2, 28),
               duration=1,
               color=DRAFT),
    gantt.Task("Deadline plan de campagne",
               start=date(2020, 3, 9),
               duration=1,
               color=DEADLINE),
    gantt.Task("Second deadline plan de campagne",
               start=date(2020, 3, 23),
               duration=1,
               color=DEADLINE),
    gantt.Task("Workshop plan de campagne",
               start=date(2020, 2, 11),
               duration=1,
Exemple #18
0
                      df["Owner"][i], df["Priority"][i], df["Depend On"][i])
    task_list.append(task)
for task in task_list:
    task.add_dependencies()
for task in task_list:
    task.start_date = get_start_date(task)
    if task.end_date is None:
        if task.duration is not None:
            if not task.is_milestone:
                task.end_date = task.start_date + \
                    datetime.timedelta(days=task.duration)
    print("Task", task.name, "started at", task.start_date, "end date",
          "duration", task.duration, task.end_date, "owner",
          [_.name for _ in task.owner_list], "is milestone", task.is_milestone,
          "depends_of", [_.name for _ in task.depend_on])
    task.generate_task_object()

# test printing
p = gantt.Project(name="test")
#  for task in task_list:
#  p.add_task(task.task)
p.add_task(task_list[0].task)
p.add_task(task_list[1].task)
p.add_task(task_list[2].task)
p.add_task(task_list[4].task)
p.add_task(task_list[3].task)

p.make_svg_for_tasks(filename='test2.svg',
                     today=datetime.date(2020, 1, 31),
                     scale=gantt.DRAW_WITH_MONTHLY_SCALE)
Exemple #19
0
    return res


def getTaskColour(task):
    return {
        TaskStatus.COMPLETED: '#EEEFDC',
        TaskStatus.ARCHIVED: '#EEEFC4',
        TaskStatus.READY_FOR_UAT: '#F9CC4F',
        TaskStatus.ON_HOLD: '#EAE2D7'
    }.get(task.STATUS, '#FFFC7A')


resStatuses = convertCategoryAsResource(gantt_df['STATUS_LABEL'])
resPriorities = convertCategoryAsResource(gantt_df['TASK_PRIORITY_NAME'])

projectChart = gantt.Project(name=project.projectName)
for idx, task in gantt_df.iterrows():
    color = None
    startDate = task.START_DATE
    endDate = task.END_DATE

    deltaDays = max(1, (endDate - startDate).days + 1 -
                    num_of_weekends(startDate, endDate))
    #print(task.Summary, startDate, endDate, deltaDays, num_of_weekends(startDate, endDate))
    t = gantt.Task(task.TASK_RESUME,
                   start=startDate,
                   percent_done=100,
                   duration=deltaDays,
                   color=getTaskColour(task),
                   resources=[
                       resStatuses[task.STATUS_LABEL],
                             stroke_width=0,
                             font_family="Verdana")

sample_date = datetime.date(2018, 2, 10)

t1 = gantt.Task(name="task1", start=sample_date, duration=5)
t2 = gantt.Task(name="task2", start=sample_date, duration=3, depends_of=[t1])
t3 = gantt.Task(name="task3", start=sample_date, duration=4, depends_of=[t1])
t4 = gantt.Task(name="task4", start=sample_date, duration=6, depends_of=[t3])
t5 = gantt.Task(name="task5",
                start=sample_date,
                duration=4,
                depends_of=[t2, t3])
t6 = gantt.Task(name="task6", start=sample_date, duration=1, depends_of=[t4])
t7 = gantt.Task(name="task7",
                start=sample_date,
                duration=5,
                depends_of=[t4, t5, t6])

project = gantt.Project(name="SampleProject")
project.add_task(t1)
project.add_task(t2)
project.add_task(t3)
project.add_task(t4)
project.add_task(t5)
project.add_task(t6)
project.add_task(t7)

project.make_svg_for_tasks(filename="SampleProject.svg",
                           today=datetime.date(2018, 2, 1))
Exemple #21
0
                 resources=[DE],
                 percent_done=100,
                 color="#FF8080",
                 depends_of=t14)

t16 = gantt.Task(name='Create SOP for project',
                 start=datetime.date(2018, 12, 4),
                 duration=1,
                 resources=[DE],
                 percent_done=100,
                 color="#FF8080",
                 depends_of=t15)

#Create a project

p1 = gantt.Project(name='IT for Advanced Bioinformatics Applications')

# Add tasks

p1.add_task(t1)
p1.add_task(t2)
p1.add_task(t3)
p1.add_task(t4)
p1.add_task(t5)
p1.add_task(t6)
p1.add_task(t7)
p1.add_task(t8)
p1.add_task(t9)
p1.add_task(t10)
p1.add_task(t11)
p1.add_task(t12)
Exemple #22
0
                  resources=[ad])
ttt8 = gantt.Task(name='Dodanie end pointów dla tebeli schedule oraz office',
                  start=datetime.date(2018, 10, 12),
                  duration=4,
                  depends_of=[ttt1],
                  resources=[ad])
ttt9 = gantt.Task(name='Dodanie end pointów dla tebeli wallet',
                  start=datetime.date(2018, 10, 18),
                  duration=5,
                  depends_of=[ttt1],
                  resources=[ad])
ttt10 = gantt.Task(name='Dodanie end pointów dla tebeli visit',
                   start=datetime.date(2018, 10, 25),
                   duration=5,
                   depends_of=[ttt1],
                   resources=[ad])
ttt11 = gantt.Task(
    name='Dodanie end pointów dla tebeli payment oraz wallet_history',
    start=datetime.date(2018, 11, 3),
    duration=7,
    depends_of=[ttt1],
    resources=[ad])

tasks = [v for k, v in locals().items() if k.startswith('t')]

p1 = gantt.Project(name='DDC Clinic')

[p1.add_task(t) for t in tasks]

p1.make_svg_for_tasks(filename='test_p1.svg', today=datetime.date(2018, 9, 10))
Exemple #23
0
def generate_chart(df, start_date, end_date, save_file, input_root=None, max_depth=None):
    # Function to recursively define the order that nodes will be placed in
    def populate_order(value, current_depth):
        if max_depth:
            if current_depth == int(max_depth):
                return

        if node_data.loc[value, "CHILDREN"] == []:
            return

        else:
            children = node_data.loc[value, "CHILDREN"]
            for child in children:
                if children.index(child) + 1 <= math.ceil(len(children) / 2):
                    if child not in task_order.list:
                        task_order.add_left(child, task_order.list.index(value))
                        populate_order(child, current_depth + 1)

                else:
                    if child not in task_order.list:
                        task_order.add_right(child, task_order.list.index(value))
                        populate_order(child, current_depth + 1)

    gantt.define_font_attributes(fill='black',
                                 stroke='black',
                                 stroke_width=0,
                                 font_family="Verdana")

    # Import node data
    node_data = df
    node_data.replace(to_replace="nan", value="NONE", inplace=True)
    node_data["CHILDREN"] = node_data["CHILDREN"].apply(cell_to_list)
    node_data["PARENTS"] = node_data["PARENTS"].apply(cell_to_list)
    node_data["START"] = node_data["START"]

    project_list = node_data["PROJECT"].drop_duplicates().tolist()
    resource_list = node_data["RESOURCE"].drop_duplicates().tolist()
    roots = []

    # Find all root nodes
    for node in node_data.index:
        if node_data.loc[node, "PARENTS"] == []:
            roots.append(node)

    nodes = node_data.index.tolist()
    tasks = {}
    resources = {}
    projects = {}
    master_project = gantt.Project(name="Master Schedule")

    # Create resource objects
    for resource in resource_list:
        resources[resource] = gantt.Resource(name=resource)

    # Create project objects
    for project in project_list:
        projects[project] = gantt.Project(name=project)

    # Create task objects
    for node in nodes:
        datel = node_data.loc[node, "START"]
        year = int(datel[:4])
        month = int(datel[5:7])
        day = int(datel[8:10])
        tasks[node] = gantt.Task(name=node,
                                 start=datetime.date(year, month, day),
                                 duration=int(float(node_data.loc[node, "DURATION"])),
                                 resources=[resources[node_data.loc[node, "RESOURCE"]]],
                                 color=choose_color(node_data.loc[node, "RESOURCE"]))

    # Add dependencies to tasks
    for node in nodes:
        tasks[node].add_depends(depends_of=[tasks[i] if i != "NONE" else None for i in node_data.loc[node, "CHILDREN"]])

    task_order = Order()
    root_priority = []

    # If user selected a specific node to view, set it as the root
    if input_root:
        roots = [input_root]

    # Create a priority list of roots based off of number of child nodes
    for root in roots:
        root_priority.append([root, len(node_data.loc[root, "CHILDREN"])])

    root_priority = sorted(root_priority, key=lambda x: x[1], reverse=True)

    # Higher priority roots will be placed in chart first
    print("Arranging Nodes...\n=========================================")
    for root in root_priority:
        task_order.list.append(root[0])
        populate_order(root[0], 1)
        print("Node {} completed".format(root))

    # Rearrange roots according to their "center of mass" based off of child nodes
    print("Rearranging Roots...\n=========================================")
    for root in roots:
        best_index = 0
        task_order.list.remove(root)
        best_dcount = len(task_order.list)
        for i in range(len(task_order.list)):
            count_left = 0
            count_right = 0
            for child in node_data.loc[root, "CHILDREN"]:
                count_left += task_order.list[:i].count(child)
                count_right += task_order.list[i:].count(child)

            dcount = abs(count_right - count_left)

            if dcount < best_dcount:
                best_dcount, best_index = dcount, i

        task_order.add_right(root, best_index)
        print("Root {} completed".format(root))

    # Assign tasks to projects
    for key in task_order.list:
        projects[node_data.loc[key, "PROJECT"]].add_task(tasks[key])

    master_project.add_task(projects["Main"])

    # Create svg
    master_project.make_svg_for_tasks(filename=save_file,
                                      start=start_date,
                                      end=end_date)
Exemple #24
0
                depends_of=t1,
                resources=[rJLS])
t5 = gantt.Task(name='task5', start=datetime.date(2014, 12, 23), duration=3)
t6 = gantt.Task(name='task6',
                start=datetime.date(2014, 12, 25),
                duration=4,
                depends_of=t7,
                resources=[rANO])
t8 = gantt.Task(name='task8',
                start=datetime.date(2014, 12, 25),
                duration=4,
                depends_of=t7,
                resources=[rANO, rJLS])

# Create a project
p1 = gantt.Project(name='Project 1')

# Add tasks to this project
p1.add_task(t1)
p1.add_task(t7)
p1.add_task(t2)
p1.add_task(t3)
p1.add_task(t5)
p1.add_task(t8)

# Create another project
p2 = gantt.Project(name='Project 2', color='#FFFF40')

# Add tasks to this project
p2.add_task(t2)
p2.add_task(t4)
Exemple #25
0
 def Valider():
     liste_projet.append(gantt.Project(name=nom_projet.get()))
     fen.destroy()
Exemple #26
0
# Option parsing
parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('infile', help='(H)JSon file containing Gantt data')
parser.add_argument('--begin-date',
                    help='YYYY-MM-DD date to start Gantt chart at',
                    default=date_to_str(today))
parser.add_argument('--end-date',
                    help='YYYY-MM-DD date to end Gantt chart on',
                    default=date_to_str(today + datetime.timedelta(days=180)))
parser.add_argument('--name',
                    help='Base name of SVG file to output',
                    default='gantt')
args = parser.parse_args()

top_project = gantt.Project()

json = hjson.load(open(args.infile))

# These dictionaries are always indexed by lower-cased keys
people = {}
tasks = {}
projects = {}


def ensure_list(obj):
    if isinstance(obj, str):
        return [obj]
    return obj

#!/usr/bin/env python3
# -*- coding: utf-8-unix -*-

import datetime
import gantt
import matplotlib.pyplot as plt

# Change font default
gantt.define_font_attributes(fill='black',
                             stroke='black',
                             stroke_width=0,
                             font_family="Verdana")

# Petrus Peregrinus
p1 = gantt.Project(name='Petrus Peregrinus')
life1 = gantt.Task(name='Lifetime',
                   start=datetime.date(1240, 1, 1),
                   duration=40,
                   color="#FF8080")
t1 = gantt.Task(
    name=
    'published the "Epistala and Sigeam de Foucaucourt moletom de magnete"',
    start=datetime.date(1261, 1, 1),
    duration=8)
p1.add_task(life1)
p1.add_task(t1)

# William Gilbert
p2 = gantt.Project(name='William Gilbert')
life2 = gantt.Task(name='Lifetime',
                   start=datetime.date(1540, 1, 1),
Exemple #28
0
gantt_parser = subparsers.add_parser('gantt', help='gantt tools')
gantt_parser.add_argument('--add-dependency', action='store_true')
gantt_parser.add_argument('-f', '--fromi', type=int)
gantt_parser.add_argument('-t', '--toi', type=int)
gantt_parser.add_argument('--fromc', type=str)
gantt_parser.add_argument('--toc', type=str)
gantt_parser.set_defaults(func=parse_gantt_args)

args = parser.parse_args()
if 'func' in args:
    args.func(args)


cam = gantt.Resource('Cam')
landlord = gantt.Project(name='Landlord')
send_task = gantt.Task(name='Send lease addendum',
                  start=datetime.date(2019, 12,10),
                  duration=4,
                  resources=[cam])
sign_task = gantt.Task(
    name='Make sure lease addendum is signed',
    start=datetime.date(2019, 12, 13),
    duration=1,
    resources=[cam],
    depends_of=send_task,
)

landlord.add_task(send_task)
landlord.add_task(sign_task)
# Have to open the SVG manually for now, will have to figure this out later
Exemple #29
0
def gen_svg_for_group(group_by):
    # Create a project
    # if group_by == 'server_type_flat':
    #     p1 = gantt.Project(suppress_text=True)
    # else:
    p1 = gantt.Project()

    # Create resources
    res_names = []
    res_name2res = {}
    dag_task_id2task = {}
    col_idx = 0
    deadlines = {}
    for row in df.itertuples():
        # print(row)
        dag_id = int(row.task_dag_id)
        tid = int(row.task_tid)
        tcrit = int(row.task_crit)
        is_last = int(row.is_last)
        # Get task name
        t = "%u.%u.%s.%u" % (dag_id, tid, row.task_name, tcrit)

        server = row.type
        server_type_id = "%s (%u)" % (row.type, int(row.id))
        criticality = 'C' + str(row.task_crit)
        # Get resource name
        if group_by == 'server_type' or \
            group_by == 'server_type_flat':
            r = server_type_id  # Server type (ID).
            name = t + ', ' + criticality
        elif group_by == 'criticality' or group_by == None:
            r = criticality  # Criticality.
            name = t + ', ' + server_type_id
        else:
            raise (ValueError)
        if server not in server2col:
            assert col_idx < len(colors), 'Not enough colors!'
            server2col[server] = colors[col_idx]
            col_idx += 1
        if r not in res_names:
            res_names.append(r)
            res_name2res[r] = gantt.Resource(r)

        # DAG deadline abs time.
        if tid == 0:
            deadlines[dag_id] = int(row.dag_dtime)
        # Get start and end time of task.
        a = row.task_arrival_time
        s = row.curr_job_start_time
        e = row.curr_job_end_time
        # Get parent task IDs
        p = str(row.task_parent_ids).split(' ')
        if len(p) == 1 and p[0] == 'nan':
            p = []
        else:
            parent_dag_id = int(row.task_dag_id)
            try:
                p = [
                    dag_task_id2task[str(parent_dag_id) + '.' + parent_tid]
                    for parent_tid in p
                ]
            except:
                print("Error: corrupt row:")
                print(row)
                exit(1)
        # print(p)
        # print("%s: %d:%d" % (t, s, e))
        # arr_task = gantt.Task(fullname=name, name=t, start=a, stop=s, depends_of=p, resources=[res[r]], next_in_line=True)
        if group_by == 'server_type_flat':
            suppress_text = True
            p = []
            arr_task_opacity = 0.
        else:
            suppress_text = False
            arr_task_opacity = 0.85
        arr_task = gantt.Task(
            fullname=t,
            name=t,
            start=a,
            stop=s,
            depends_of=p,
            resources=[res_name2res[r]],
            next_in_line=True,
            suppress_text=suppress_text,
            #opacity=arr_task_opacity
        )
        exe_task = gantt.Task(fullname=name,
                              name=t,
                              start=s,
                              stop=e,
                              resources=[res_name2res[r]],
                              color=server2col[server],
                              suppress_text=suppress_text,
                              is_last=is_last)

        # Add tasks to this project
        p1.add_task(arr_task)
        p1.add_task(exe_task)
        dag_task_id2task[t] = exe_task

    # Draw
    print("Saving .svg files in: " + trace_dir + "/")
    if group_by == 'criticality':
        p1.make_svg_for_resources(filename=trace_dir + '/' + group_by +
                                  '_group.svg',
                                  start=start_ts,
                                  end=end_ts,
                                  resources=res_names.sort())
    elif group_by == 'server_type':
        p1.make_svg_for_resources(filename=trace_dir + '/' + group_by +
                                  '_group.svg',
                                  start=start_ts,
                                  end=end_ts,
                                  resources=res_names.sort())
    elif group_by == 'server_type_flat':
        p1.make_svg_for_resources(filename=trace_dir + '/' + group_by +
                                  '_group.svg',
                                  start=start_ts,
                                  end=end_ts,
                                  resources=res_names.sort(),
                                  one_line_for_tasks=True)
    elif group_by == None:
        p1.make_svg_for_tasks(filename=trace_dir + '/' + 'no_group.svg',
                              deadlines=deadlines,
                              start=start_ts,
                              end=end_ts)