Exemple #1
0
def get_type_data(model):
    number = model.number
    categories = [opts.GraphCategory(name='类型')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number)
    ]
    links = []
    # 事件总数量
    set_number_node(model, categories, nodes, links)
    # 事件最多社区
    set_max_community_node('Type', model, categories, nodes, links)
    # 类型下所有大类
    maintypes = MainType.objects.filter(type=model)
    name = '大类'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    for maintype in maintypes:
        value = str(maintype)
        number = maintype.number
        if value == str(model):
            value = value + '(问题大类)'
        nodes.append(
            opts.GraphNode(name=value,
                           symbol_size=50,
                           category=index,
                           value=number))
        links.append(
            opts.GraphLink(source=str(model), target=value, value='下属大类'))

    return categories, nodes, links
Exemple #2
0
def get_district_data(model_name, model):
    categories = [opts.GraphCategory(name='区域')]
    number_d = model.number
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=80,
                       category=0,
                       value=number_d)
    ]
    links = []

    streets = Street.objects.filter(district=model)
    for street in streets:
        name_s = Street.name
        number_s = street.number
        if name_s == 'name' or name_s == 'id':
            continue
        value_s = str(street)
        categories.append(opts.GraphCategory(name='街道'))
        index_s = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_s,
                           symbol_size=60,
                           category=index_s,
                           value=number_s))
        links.append(
            opts.GraphLink(source=str(model), target=value_s, value='下属街道'))

    return categories, nodes, links
Exemple #3
0
def get_maintype_data(model):
    number = model.number
    categories = [opts.GraphCategory(name='大类')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number)
    ]
    links = []
    # 事件数量
    set_number_node(model, categories, nodes, links)
    # 所属类型
    set_type_node('MainType', model, categories, nodes, links)
    # 事件最多社区
    set_max_community_node('MainType', model, categories, nodes, links)

    subtypes = SubType.objects.filter(main_type=model)
    name = '小类'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    for subtype in subtypes:
        value = str(subtype)
        sub_number = subtype.number
        if value == str(model) or value == str(model.type):
            value = value + '(问题小类)'
        nodes.append(
            opts.GraphNode(name=value,
                           symbol_size=50,
                           category=index,
                           value=sub_number))
        links.append(
            opts.GraphLink(source=str(model), target=value, value='下属小类'))

    return categories, nodes, links
Exemple #4
0
 def _get_categories():
     try:
         _categories ={nodes[node]['color'] for node in nodes}
         categories = [opts.GraphCategory(name='level_'+str(category)) for category in _categories]
     except:
         categories = [
             opts.GraphCategory(name='c_'+ str(index)) for index in range(len(nodes))
         ]
     finally:
         return categories
Exemple #5
0
def get_street_data(model_name, model):
    categories = [opts.GraphCategory(name='街道')]
    str_number = model.number
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=80,
                       category=0,
                       value=str_number)
    ]
    links = []

    # 街道所属区域
    districts = District.objects.all()
    for district in districts:
        number_c = district.number
        name_c = district.name
        if name_c == 'name' or name_c == 'id':
            continue
        value_c = str(district)
        categories.append(opts.GraphCategory(name='区域'))
        index_c = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_c,
                           symbol_size=60,
                           category=index_c,
                           value=number_c))
        links.append(
            opts.GraphLink(source=str(model), target=value_c, value='所属区域'))


# 街道下所有社区及其数量
    communities = Community.objects.filter(street=model)
    for community in communities:
        name_c = Community.name
        number_c = community.number
        # ratio_c = str((round(number_c*100/str_number,2)))+'%'
        if name_c == 'name' or name_c == 'id':
            continue
        value_c = str(community)
        categories.append(opts.GraphCategory(name='社区'))
        index_c = len(categories) - 1
        nodes.append(
            opts.GraphNode(name=value_c,
                           symbol_size=40,
                           category=index_c,
                           value=number_c))
        links.append(
            opts.GraphLink(source=str(model), target=value_c, value='下属社区'))

    return categories, nodes, links
Exemple #6
0
def get_disposeunit_data(model_name, model):
    number_dis = str(model.number)
    categories = [opts.GraphCategory(name='执行部门')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number_dis)
    ]
    links = []

    id = DisposeUnit.objects.filter(name=str(model)).values("id")[0]['id']
    dis_model = DisposeUnit.objects.filter(id=id)[0]

    try:
        # 事件总数
        node_name = str(dis_model.number)
        print(node_name)
        cate_name = '数量'
        link_name = '事件总数'
        source_node = str(dis_model)

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 完成事件百分比
        is_achieve_count = Event.objects.filter(
            dispose_unit=id).values('achieve').annotate(
                count=Count('achieve')).values('achieve',
                                               'count').order_by('-count')
        is_achieve_count = list(is_achieve_count)
        print(is_achieve_count)
        y = is_achieve_count[0]['count']
        n = is_achieve_count[1]['count']
        percent = round(y * 100 / (y + n), 2)

        node_name = str(percent) + '%'
        cate_name = '百分比'
        link_name = '完成事件百分比'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 部门编号
        aid = dis_model.aID

        node_name = str(aid)
        cate_name = '编号'
        link_name = '部门编号'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

    except Exception as e:
        print(e)

    return categories, nodes, links
Exemple #7
0
def set_number_node(model, categories, nodes, links):
    value = str(getattr(model, 'number'))
    categories.append(opts.GraphCategory(name='数量'))
    index = len(categories) - 1
    nodes.append(opts.GraphNode(name=value, symbol_size=50, category=index))
    links.append(opts.GraphLink(source=str(model), target=value,
                                value='事件总数量'))

    return 0
Exemple #8
0
def get_achive_data(model_name, model):
    events = model.event.get_queryset()
    ratio = '{:.2f}%'.format(model.number / Event.objects.count() * 100)
    unit_list = {}

    for event in events:
        unit = event.dispose_unit.name
        if unit in unit_list:
            unit_list[unit] += 1
        else:
            unit_list.update({unit: 1})

    number_max = 0
    for key in unit_list:
        if unit_list[key] > number_max:
            unit = key
            number_max = unit_list[key]

    categories = [
        opts.GraphCategory(name="执行情况"),
        opts.GraphCategory(name="数量"),
        opts.GraphCategory(name="处置部门"),
        opts.GraphCategory(name="百分比"),
    ]

    nodes = [
        opts.GraphNode(name=str(model.name), symbol_size=80, category=0),
        opts.GraphNode(name=str(model.number), symbol_size=50, category=1),
        opts.GraphNode(name=unit, symbol_size=50, category=2),
        opts.GraphNode(name=ratio, symbol_size=50, category=3),
    ]

    links = [
        opts.GraphLink(source=str(model.name),
                       target=str(model.number),
                       value="事件数量"),
        opts.GraphLink(source=str(model.name),
                       target=unit,
                       value="最多 " + str(model.name) + " 处置机构"),
        opts.GraphLink(source=str(model.name), target=ratio, value="事件占比"),
    ]
    return categories, nodes, links
Exemple #9
0
def get_source_data(model_name, model):
    events = model.event.get_queryset()
    # 对应性质
    property_list = {}
    for event in events:
        proper = event.property.name
        if proper in property_list.keys():
            property_list[proper] += 1
        else:
            property_list.update({proper: 1})


# 占事件总数百分比
    ratio = '{:.2f}%'.format(model.number / Event.objects.count() * 100)
    number_max = 0
    for key in property_list:
        if property_list[key] > number_max:
            proper = key
            number_max = property_list[key]

    categories = [
        opts.GraphCategory(name="来源"),
        opts.GraphCategory(name="数量"),
        opts.GraphCategory(name="性质"),
        opts.GraphCategory(name="百分比"),
    ]
    nodes = [
        opts.GraphNode(name=str(model), symbol_size=80, category=0),
        opts.GraphNode(name=str(model.number), symbol_size=50, category=1),
        opts.GraphNode(name=proper, symbol_size=50, category=2),
        opts.GraphNode(name=ratio, symbol_size=50, category=3),
    ]

    links = [
        opts.GraphLink(source=str(model),
                       target=str(model.number),
                       value="事件总数量"),
        opts.GraphLink(source=str(model), target=proper, value="对应性质"),
        opts.GraphLink(source=str(model), target=ratio, value="占事件总数百分比"),
    ]

    return categories, nodes, links
Exemple #10
0
def set_max_community_node(model_name, model, categories, nodes, links):
    max_num = 0
    communities = Community.objects.all()
    if model_name == 'MainType':
        subtypes = SubType.objects.filter(main_type=model)
        for community in communities:
            events = Event.objects.filter(sub_type__in=subtypes,
                                          community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    if model_name == 'SubType':
        for community in communities:
            events = Event.objects.filter(sub_type=model, community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    if model_name == 'Type':
        maintypes = MainType.objects.filter(type=model)
        subtypes = SubType.objects.filter(main_type__in=maintypes)
        for community in communities:
            events = Event.objects.filter(sub_type__in=subtypes,
                                          community=community)
            now_num = len(events)
            if now_num > max_num:
                max_num = now_num
                max_community = community
    name = '社区'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    value = str(max_community)
    nodes.append(
        opts.GraphNode(name=value,
                       value=str(max_num),
                       symbol_size=50,
                       category=index))
    links.append(
        opts.GraphLink(source=str(model), target=value, value='发生最多的社区'))
Exemple #11
0
def create_node(source_node,
                categories,
                cate_name,
                nodes,
                node_name,
                links,
                link_name,
                node_value='-'):
    categories.append(opts.GraphCategory(cate_name))
    print(cate_name)
    length = len(categories) - 1
    nodes.append(
        opts.GraphNode(name=node_name,
                       value=node_value,
                       symbol_size=50,
                       category=length))
    print(node_name)
    links.append(
        opts.GraphLink(source=source_node, target=node_name, value=link_name))
    print(link_name)

    return 0
Exemple #12
0
def set_type_node(model_name, model, categories, nodes, links):
    if model_name == 'SubType':
        sub_model = model
        model = model.main_type

    thetype = model.type
    type_number = model.type.number
    name = '类型'
    categories.append(opts.GraphCategory(name=name))
    index = len(categories) - 1
    value = str(thetype)
    if (model_name == 'SubType'
            and value == str(sub_model)) or value == str(model):
        value = value + '(问题类型)'
    nodes.append(
        opts.GraphNode(name=value,
                       symbol_size=50,
                       category=index,
                       value=type_number))
    links.append(opts.GraphLink(source=str(model), target=value, value='类型'))

    return 0
Exemple #13
0
def get_subtype_data(model_name, model):
    categories = [opts.GraphCategory(name='小类')]
    number = model.number
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=number)
    ]
    links = []

    id = SubType.objects.filter(name=str(model)).values("id")[0]['id']
    sub_model = SubType.objects.filter(id=id)[0]

    try:
        # 小类所属大类
        node_name = str(sub_model.main_type)
        print(node_name)
        cate_name = '大类'
        link_name = '所属大类'
        source_node = str(model)
        maintype_number = sub_model.main_type.number

        create_node(source_node,
                    categories,
                    cate_name,
                    nodes,
                    node_name,
                    links,
                    link_name,
                    node_value=maintype_number)

        # 小类发生最多的社区名
        coms = Event.objects.filter(
            sub_type_id=id).values('community').annotate(
                count=Count('community')).values('community',
                                                 'count').order_by('-count')
        coms = list(coms)
        com = coms[0]
        com_name = Community.objects.get(id=com['community']).name
        print(com_name)

        node_name = com_name
        cate_name = '社区'
        link_name = '小类发生最多社区'
        source_node = str(model)

        create_node(source_node,
                    categories,
                    cate_name,
                    nodes,
                    node_name,
                    links,
                    link_name,
                    node_value=str(com['count']))

        # 小类编号
        sub_model = SubType.objects.filter(id=id)[0]
        aid = sub_model.aID

        node_name = str(aid)
        cate_name = '编号'
        link_name = '小类编号'
        source_node = str(model)

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 小类事件总数
        node_name = str(sub_model.number)
        print(node_name)
        cate_name = '数量'
        link_name = '事件总数'
        source_node = str(model)

        create_node(source_node,
                    categories,
                    cate_name,
                    nodes,
                    node_name,
                    links,
                    link_name,
                    node_value=node_name)

    except Exception as e:
        print(e)

    return categories, nodes, links
Exemple #14
0
def echarts_Location(graph,
                     h,
                     x,
                     y,
                     symbol_size=5,
                     line_width=1,
                     width="1400px",
                     height="800px",
                     path='locationExample.html',
                     title='Location_Graph',
                     subtitle='',
                     showName=True,
                     font_size=15,
                     edge_symbol_size=10,
                     pageLayout=Page.SimplePageLayout,
                     show_node_value=True,
                     show_edge_value=True,
                     render=True):
    """
        A method to render a network in location layout.

        Parameter(s):
        -------------
        graph : TemporalDiGraph
            An object which represents a temporal, directed graph consisting of nodes and temporal arcs.
        h : int
            The threshold of temporal reachability. Nodes will be assigned different color based on this value.
        x : String
            The name of the x coordinates of the nodes.
            For example, in the network of London subway stations, the name of x coordinate can be 'lon' or 'lat'.
        y : String
            The name of the y coordinates of the nodes.
            For example, in the network of London subway stations, the name of x coordinate can be 'lon' or 'lat'.
        symbol_size : int
            The size of the nodes.
        line_width : int
            The width of the edges.
        width: String
            The width of the image.
            Default value: 1200px
        height: String
            The height of the image.
            Decault value: 600px
        path : String
            The path of the rendered image.
            Default value: forceExample.html
        title : String
            The title of the rendered image.
            Default value: Location_Graph
        subtitle : String
            The subtitle of the rendered image.
            Default value: ''
        showName : boolean
            Whether to show the name of nodes.
            Default value: True
        font_size : int
            The font size of the value on the nodes.
            Default value: 10
        edge_symbol_size : int
            The size of the symbol on the edges.
            Default value: 10
        pageLayout : PageLayoutOpts
            There are two kinds of page layout: Page.DraggablePageLayout and Page.SimplePageLayout.
            In Page.SimplePageLayout, the width and height of the image border is stable.
            While in Page.DraggablePageLayout, the image border can be changed.
            Default value: Page.SimplePageLayout
        show_node_value : boolean
            Whether to show the reachability of nodes.
            Default value: True
        show_edge_value : boolean
            Whether to show the start time and end time of edges.
            Default value: False
        render : boolean
            Whether to generate the html file directly.
            Default value: True

        Returns:
        --------
        c : Graph
            basic charts object in pyecharts package
    """

    # initialize nodes list
    nodes = []
    if show_node_value:
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=0,
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   label_opts=opts.LabelOpts(
                                       is_show=showName, font_size=font_size),
                                   value=reachability))
            else:
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=1,
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   label_opts=opts.LabelOpts(
                                       is_show=showName, font_size=font_size),
                                   value=reachability))
    else:
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=0,
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   label_opts=opts.LabelOpts(
                                       is_show=showName, font_size=font_size)))
            else:
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=1,
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   label_opts=opts.LabelOpts(
                                       is_show=showName, font_size=font_size)))

    # initialize links list
    links = []
    if show_edge_value:
        # initialize value list of edges
        edge_value = []
        # 1. compare all edge labels with unique edge labels to find which edges are duplicated
        # 2. edge value of duplicate edges will be added to the same list and shown together
        for i in range(len(graph.edges.labels())):
            for j in range(len(graph.edges.ulabels())):
                if graph.edges.labels()[i] == graph.edges.ulabels()[j]:
                    if j < len(edge_value):
                        edge_value[j].append(
                            '{start time: ' +
                            str(graph.edges.start_times()[i]) +
                            ', end time: ' + str(graph.edges.end_times()[i]) +
                            '}')
                    else:
                        tmp_edge_value = []
                        tmp_edge_value.append(
                            '{start time: ' +
                            str(graph.edges.start_times()[i]) +
                            ', end time: ' + str(graph.edges.end_times()[i]) +
                            '}')
                        edge_value.append(tmp_edge_value)
            # print the rate of progress
            print('rate of progress: {}%'.format(
                (i + 1) / len(graph.edges.labels()) * 100))

        for i in range(len(graph.edges.ulabels())):
            tmp = graph.edges.ulabels()[i].split('-')

            links.append(
                opts.GraphLink(source=tmp[0],
                               target=tmp[1],
                               value=edge_value[i]))

    else:
        for i in range(len(graph.edges.ulabels())):
            tmp = graph.edges.ulabels()[i].split('-')

            links.append(opts.GraphLink(source=tmp[0], target=tmp[1]))

    # initialize categories list
    categories = [
        opts.GraphCategory(
            name='nodes with reachability more than {}'.format(h)),
        opts.GraphCategory(
            name='nodes with reachability less than or equal to {}'.format(h))
    ]

    # generate an html file of the graph
    c = (Graph(init_opts=opts.InitOpts(width=width, height=height)).add(
        "",
        nodes=nodes,
        links=links,
        categories=categories,
        layout="none",
        symbol_size=symbol_size,
        linestyle_opts=opts.LineStyleOpts(is_show=True,
                                          curve=0.1,
                                          width=line_width),
        label_opts=opts.LabelOpts(position="right"),
        edge_symbol=['circle', 'arrow'],
        edge_symbol_size=symbol_size).set_global_opts(
            title_opts=opts.TitleOpts(
                title=title,
                subtitle=subtitle,
                title_textstyle_opts=opts.TextStyleOpts(font_size=40),
                subtitle_textstyle_opts=opts.TextStyleOpts(font_size=20)),
            legend_opts=opts.LegendOpts(
                orient="vertical",
                pos_left="2%",
                pos_top="20%",
                textstyle_opts=opts.TextStyleOpts(font_size=20)),
        ))

    if render:
        page = Page(layout=pageLayout)
        page.add(c)
        page.render(path)

    return c
Exemple #15
0
def echarts_Timeline(graph,
                     h,
                     x='',
                     y='',
                     symbol_size=20,
                     line_width=1,
                     repulsion=500,
                     is_draggable=True,
                     width="800px",
                     height="500px",
                     path='timelineExample.html',
                     title='Timeline_graph',
                     subtitle='',
                     pageLayout=Page.DraggablePageLayout,
                     layout="circular",
                     show_node_value=True,
                     render=True):
    """
        A method to render a network with timeline.

        Parameter(s):
        -------------
        graph : TemporalDiGraph
            An object which represents a temporal, directed graph consisting of nodes and temporal arcs.
        h : int
            The threshold of temporal reachability. Nodes will be assigned different color based on this value.
        x : String
            The name of the x coordinates of the nodes.
            For example, in the network of London subway stations, the name of x coordinate can be 'lon' or 'lat'.
        y : String
            The name of the y coordinates of the nodes.
            For example, in the network of London subway stations, the name of x coordinate can be 'lon' or 'lat'.
        symbol_size : int
            The size of the nodes.
        line_width : int
            The width of the edges.
        repulsion : int
            The repulsion between nodes.
        is_draggable : boolean
            Whether the nodes are moveable.
        width: String
            The width of the image.
            Default value: 800px
        height: String
            The height of the image.
            Decault value: 500px
        path : String
            The path of the rendered image.
            Default value: circleExample.html
        title : String
            The title of the rendered image.
            Default value: Circle_Graph
        subtitle : String
            The subtitle of the rendered image.
            Default value: ''
        pageLayout : PageLayoutOpts
            There are two kinds of page layout: Page.DraggablePageLayout and Page.SimplePageLayout.
            In Page.SimplePageLayout, the width and height of the image border is stable.
            While in Page.DraggablePageLayout, the image border can be changed.
            Default value: Page.DraggablePageLayout
        layout : String
            There are three kinds of image layout: circular, force and none
            If the layout is none, you have to provide the x-coordinate and y-coordinate of nodes.
        show_node_value : boolean
            Whether show the reachability of nodes.
            Default value: True
        render : boolean
            Whether generate the html file directly.
            Default value: True

        Returns:
        --------
        c : Graph
            basic charts object in pyecharts package
    """

    # initialize nodes list
    nodes = []
    if layout == 'none':
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                # nodes with reachability more than h will be assigned category 0
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   category=0,
                                   value=reachability))
            else:
                # nodes with reachability less than or equal to h will be assigned category 1
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   x=graph.nodes.aslist()[i].data[x],
                                   y=graph.nodes.aslist()[i].data[y],
                                   category=1,
                                   value=reachability))
    else:
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                # nodes with reachability more than h will be assigned category 0
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=0,
                                   value=reachability))
            else:
                # nodes with reachability less than or equal to h will be assigned category 1
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=1,
                                   value=reachability))

    # initialize links list
    links = []
    for i in graph.edges.timespan():
        tmpLinks = []
        for j in range(len(graph.edges.labels())):

            if graph.edges.start_times()[j] == i:
                tmp = graph.edges.labels()[j].split('-')
                edgeval = '{start time: ' + str(
                    graph.edges.start_times()[j]) + ', end time: ' + str(
                        graph.edges.end_times()[j]) + '}'
                tmpLinks.append(
                    opts.GraphLink(source=tmp[0], target=tmp[1],
                                   value=edgeval))
        links.append(tmpLinks)

    # initialize categories list
    categories = [
        opts.GraphCategory(
            name='nodes with reachability more than {}'.format(h)),
        opts.GraphCategory(
            name='nodes with reachability less than or equal to {}'.format(h))
    ]

    tl = Timeline()
    for i in graph.edges.timespan():
        c = (Graph(init_opts=opts.InitOpts(width=width, height=height)).add(
            "",
            nodes=nodes,
            links=links[i - graph.edges.start_times()[0]],
            categories=categories,
            layout=layout,
            is_draggable=is_draggable,
            is_rotate_label=True,
            symbol_size=symbol_size,
            linestyle_opts=opts.LineStyleOpts(is_show=True,
                                              curve=0.1,
                                              color="source",
                                              width=line_width),
            label_opts=opts.LabelOpts(position="right"),
            edge_symbol=['circle', 'arrow'],
            edge_symbol_size=10).set_global_opts(
                title_opts=opts.TitleOpts(
                    title=title,
                    subtitle=subtitle,
                    title_textstyle_opts=opts.TextStyleOpts(font_size=40),
                    subtitle_textstyle_opts=opts.TextStyleOpts(font_size=20)),
                legend_opts=opts.LegendOpts(
                    orient="vertical",
                    pos_left="2%",
                    pos_top="20%",
                    textstyle_opts=opts.TextStyleOpts(font_size=20)),
            ))
        tl.add(c, "{}".format(i))

    # if render is True, generate an html file
    if render:
        page = Page(layout=pageLayout)
        page.add(tl)
        page.render(path)

    return c
Exemple #16
0
def graph_with_opts() -> Graph:
    g = []
    layer_sizes = [2, 2, 1]
    pos = negmas_draw.negmas_layout(g, layer_sizes)
    nodes = [
        opts.GraphNode(name="n1",
                       x=pos[0][0],
                       y=pos[0][1],
                       symbol_size=10,
                       category='c1'),
        opts.GraphNode(name="n2",
                       x=pos[1][0],
                       y=pos[1][1],
                       symbol_size=20,
                       category='c2'),
        opts.GraphNode(name="n3",
                       x=pos[2][0],
                       y=pos[2][1],
                       symbol_size=30,
                       category='c3'),
        opts.GraphNode(name="n4",
                       x=pos[3][0],
                       y=pos[3][1],
                       symbol_size=40,
                       category='c1'),
        opts.GraphNode(name="n5",
                       x=pos[4][0],
                       y=pos[4][1],
                       symbol_size=50,
                       category='c1'),
    ]

    linestyleopts = [
        opts.LineStyleOpts(width=5),
    ]

    links = [
        opts.GraphLink(source="n1", target="n2"),
        opts.GraphLink(source="n2", target="n3"),
        opts.GraphLink(source="n3", target="n4"),
        opts.GraphLink(source="n4", target="n5"),
        opts.GraphLink(source="n5", target="n1"),
    ]

    categories = [
        opts.GraphCategory(name='c1'),
        opts.GraphCategory(name='c2'),
        opts.GraphCategory(name='c3'),
        opts.GraphCategory(name='c4'),
        opts.GraphCategory(name='c5'),
    ]

    c = (Graph().add("",
                     nodes,
                     links,
                     categories,
                     edge_symbol=['', 'arrow'],
                     edge_symbol_size=10,
                     layout='none',
                     repulsion=4000,
                     emphasis_itemstyle_opts=linestyleopts[0]).set_global_opts(
                         title_opts=opts.TitleOpts(title="")))
    return c
Exemple #17
0
def echarts_Circular(graph,
                     h,
                     symbol_size=20,
                     line_width=1,
                     width="800px",
                     height="500px",
                     curve_list=[0.1, 0.3],
                     path='circleExample.html',
                     title='Circle_Graph',
                     subtitle='',
                     pageLayout=Page.DraggablePageLayout,
                     show_node_value=True,
                     show_edge_value=True,
                     render=True):
    """
        A method to render a network in circular layout.

        Parameter(s):
        -------------
        graph : TemporalDiGraph
            An object which represents a temporal, directed graph consisting of nodes and temporal arcs.
        h : int
            The threshold of temporal reachability. Nodes will be assigned different color based on this value.
        symbol_size : int
            The size of the nodes.
        line_width : int
            The width of the edges.
        width: String
            The width of the image.
            Default value: 800px
        height: String
            The height of the image.
            Decault value: 500px
        curve_list : list
            A list contains one or two values which represent the curvature of edges.
            If you give two values in this list, then duplicate edges (a->b, b->a) will be rendered using different curvature.
            Otherwise, duplicate edges will be rendered using the same curvature.
            Decault value: [0.1, 0.3]
        path : String
            The path of the rendered image.
            Default value: circleExample.html
        title : String
            The title of the rendered image.
            Default value: Circle_Graph
        subtitle : String
            The subtitle of the rendered image.
            Default value: ''
        pageLayout : PageLayoutOpts
            There are two kinds of page layout: Page.DraggablePageLayout and Page.SimplePageLayout.
            In Page.SimplePageLayout, the width and height of the image border is stable.
            While in Page.DraggablePageLayout, the image border can be changed.
            Default value: Page.DraggablePageLayout
        show_node_value : boolean
            Whether show the reachability of nodes.
            Default value: True
        show_edge_value : boolean
            Whether show the start time and end time of edges.
            Default value: True
        render : boolean
            Whether generate the html file directly.
            Default value: True

        Returns:
        --------
        c : Graph
            basic charts object in pyecharts package
    """

    # initialize nodes list
    nodes = []
    if show_node_value:
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                # nodes with reachability more than h will be assigned category 0
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=0,
                                   value=reachability))
            else:
                # nodes with reachability less than or equal to h will be assigned category 1
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i],
                                   category=1,
                                   value=reachability))
    else:
        for i in range(len(graph.nodes.aslist())):
            # calculate reachability for each nodes
            reachability = ot.calculate_reachability(graph,
                                                     graph.nodes.labels()[i])
            if reachability > h:
                # nodes with reachability more than h will be assigned category 0
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i], category=0))
            else:
                # nodes with reachability less than or equal to h will be assigned category 1
                nodes.append(
                    opts.GraphNode(name=graph.nodes.labels()[i], category=1))

    # initialize links list
    links = []
    # used to check duplicate edges
    edge_list = []
    # accumulate the appearance times of each edge
    accumulator = np.zeros(len(graph.edges.labels()))
    if show_edge_value:
        # initialize value list of edges
        edge_value = []
        # 1. compare all edge labels with unique edge labels to find which edges are duplicated
        # 2. edge value of duplicate edges will be added to the same list and shown together
        for i in range(len(graph.edges.labels())):
            for j in range(len(graph.edges.ulabels())):
                if graph.edges.labels()[i] == graph.edges.ulabels()[j]:
                    if j < len(edge_value):
                        edge_value[j].append(
                            '{start time: ' +
                            str(graph.edges.start_times()[i]) +
                            ', end time: ' + str(graph.edges.end_times()[i]) +
                            '}')
                    else:
                        tmp_edge_value = []
                        tmp_edge_value.append(
                            '{start time: ' +
                            str(graph.edges.start_times()[i]) +
                            ', end time: ' + str(graph.edges.end_times()[i]) +
                            '}')
                        edge_value.append(tmp_edge_value)
            # print the rate of progress
            print('rate of progress: {}%'.format(
                (i + 1) / len(graph.edges.labels()) * 100))

        # check duplicate edges
        # 1. get nodes' name by spliting the edge labels
        # 2. transform them to set and compare them with elements in 'edge_list'
        # 3. if they are not duplicated, add them to 'edge_list'
        for i in range(len(graph.edges.ulabels())):
            tmp = graph.edges.ulabels()[i].split('-')

            flag = True
            for j in np.arange(0, len(edge_list)):
                if set(tmp) == set(edge_list[j]):
                    accumulator[i] = 1
                    flag = False
                    break

            if flag:
                edge_list.append(tmp)

            # add links
            # duplicate edges with different direction will be rendered based on their corresponding curvature
            # duplicate edges with the same direction will be rendered only once
            links.append(
                opts.GraphLink(source=tmp[0],
                               target=tmp[1],
                               value=edge_value[i],
                               linestyle_opts=opts.LineStyleOpts(
                                   curve=curve_list[int(accumulator[i]) %
                                                    len(curve_list)])))
    else:
        # check duplicate edges
        for i in range(len(graph.edges.ulabels())):
            tmp = graph.edges.labels()[i].split('-')

            flag = True
            for j in np.arange(0, len(edge_list)):
                if set(tmp) == set(edge_list[j]):
                    accumulator[i] = 1
                    flag = False
                    break

            if flag:
                edge_list.append(tmp)

            links.append(
                opts.GraphLink(source=tmp[0],
                               target=tmp[1],
                               linestyle_opts=opts.LineStyleOpts(
                                   curve=curve_list[int(accumulator[i]) %
                                                    len(curve_list)])))

    # initialize categories list
    categories = [
        opts.GraphCategory(
            name='nodes with reachability more than {}'.format(h)),
        opts.GraphCategory(
            name='nodes with reachability less than or equal to {}'.format(h))
    ]

    # generate an html file of the graph
    c = (Graph(init_opts=opts.InitOpts(width=width, height=height)).add(
        "",
        nodes=nodes,
        links=links,
        categories=categories,
        layout="circular",
        is_rotate_label=True,
        symbol_size=symbol_size,
        linestyle_opts=opts.LineStyleOpts(color="source", width=line_width),
        label_opts=opts.LabelOpts(position="right"),
        edge_symbol=['circle', 'arrow'],
        edge_symbol_size=10).set_global_opts(
            title_opts=opts.TitleOpts(
                title=title,
                subtitle=subtitle,
                title_textstyle_opts=opts.TextStyleOpts(font_size=40),
                subtitle_textstyle_opts=opts.TextStyleOpts(font_size=20)),
            legend_opts=opts.LegendOpts(
                orient="vertical",
                pos_left="2%",
                pos_top="20%",
                textstyle_opts=opts.TextStyleOpts(font_size=20)),
        ))

    # if render is True, generate an html file
    if render:
        page = Page(layout=pageLayout)
        page.add(c)
        page.render(path)

    return c
Exemple #18
0
def get_community_data(model_name, model):
    com_number = model.number
    categories = [opts.GraphCategory(name='社区')]
    nodes = [
        opts.GraphNode(name=str(model),
                       symbol_size=100,
                       category=0,
                       value=com_number)
    ]
    links = []

    id = Community.objects.filter(name=str(model)).values("id")[0]['id']
    com_model = Community.objects.filter(id=id)[0]

    try:
        # 社区所属街道
        str_number = com_model.street.number
        node_name = str(com_model.street)
        print(node_name)
        cate_name = '街道'
        link_name = '所属街道'
        source_node = str(com_model)

        create_node(source_node,
                    categories,
                    cate_name,
                    nodes,
                    node_name,
                    links,
                    link_name,
                    node_value=str_number)

        # 编号
        aid = com_model.aID
        node_name = str(aid)
        cate_name = '编号'
        link_name = '社区编号'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 事件最多类型
        type_count = Event.objects.filter(
            community=id).values('type').annotate(count=Count('type')).values(
                'type', 'count').order_by('-count')
        type_count = list(type_count)

        tid = type_count[0]['type']
        t = Type.objects.filter(id=tid)[0]
        c = type_count[0]['count']

        node_name = str(t)
        cate_name = '类型'
        link_name = '事件最多类型'

        create_node(source_node,
                    categories,
                    cate_name,
                    nodes,
                    node_name,
                    links,
                    link_name,
                    node_value=str(c))

        # 社区事件总数
        node_name = str(com_model.number)
        # print(node_name)
        cate_name = '数量'
        link_name = '事件总数'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)

        # 事件占街道百分比
        strt = com_model.street

        x = com_model.number
        y = strt.number
        percentage = round(x * 100 / y, 2)

        cate_name = '百分比'
        node_name = str(percentage) + '%'
        link_name = '事件占街道百分比'

        create_node(source_node, categories, cate_name, nodes, node_name,
                    links, link_name)
    except Exception as e:
        print(e)

    return categories, nodes, links
Exemple #19
0
def get_property_data(model_name, model):
    events = model.event.get_queryset()
    intime_number = 0
    intime_to_number = 0
    overtime_number = 0
    community_list = {}
    for event in events:
        achieve = event.achieve.name
        community = event.community.name
        if community in community_list.keys():
            community_list[community] += 1
        else:
            community_list.update({community: 1})
        if achieve == "执行中":
            intime_to_number += 1
        elif achieve == '按期办结':
            overtime_number += 1
        elif achieve == "逾期办结":
            intime_number += 1

    number_max = 0
    for key in community_list:
        if community_list[key] > number_max:
            community = key
            number_max = community_list[key]

    community_model = Community.objects.get(name=community)
    street = community_model.street
    district = street.district

    categories = [
        opts.GraphCategory(name="事件性质"),
        opts.GraphCategory(name="事件数量"),
        opts.GraphCategory(name="百分比"),
        opts.GraphCategory(name="百分比"),
        # opts.GraphCategory(name="逾期办结"),
        opts.GraphCategory(name="社区"),
        opts.GraphCategory(name="街道"),
        opts.GraphCategory(name="区域"),
    ]
    nodes = [
        opts.GraphNode(name=str(model), symbol_size=80, category=0),
        opts.GraphNode(name=str(model.number), symbol_size=50, category=1),
        opts.GraphNode(name=str(
            (round(intime_to_number * 100 / model.number, 2))) + '%',
                       symbol_size=50,
                       category=2),
        opts.GraphNode(name=str(
            (round(intime_number * 100 / model.number, 2))) + '%',
                       symbol_size=50,
                       category=3),
        # opts.GraphNode(name=str(overtime_number), symbol_size=50, category=4),
        opts.GraphNode(name=community, symbol_size=50, category=5),
        opts.GraphNode(name=street.name, symbol_size=40, category=6),
        opts.GraphNode(name=district.name, symbol_size=30, category=7),
    ]
    links = [
        opts.GraphLink(source=str(model),
                       target=str(model.number),
                       value='事件总数'),
        opts.GraphLink(source=str(model),
                       target=str(
                           (round(intime_to_number * 100 / model.number, 2))) +
                       '%',
                       value='执行中事件百分比'),
        opts.GraphLink(
            source=str(model),
            target=str((round(intime_number * 100 / model.number, 2))) + '%',
            value='按期办结百分比'),
        # opts.GraphLink(source=str(model), target=str(overtime_number), value=50),
        opts.GraphLink(source=str(model),
                       target=community,
                       value=str(model) + "下最多社区"),
        opts.GraphLink(source=community, target=street.name, value="对应街道"),
        opts.GraphLink(source=street.name, target=district.name, value="对应区域"),
    ]

    return categories, nodes, links
Exemple #20
0
def pre_graph_data(df):
    #筛选数据&去除全为空值的行
    volunteer_cols = [
        'volunteer_1', 'volunteer_2', 'volunteer_3', 'volunteer_4',
        'volunteer_5'
    ]
    graph_data = df[['school'] + volunteer_cols]
    notna_idx = graph_data[volunteer_cols].dropna(how='all').index
    graph_data = graph_data.loc[notna_idx]

    #高中名称添加(高)
    def add_high_school(x):
        try:
            return (x + '(高)')
        except:
            return x

    graph_data[volunteer_cols] = graph_data[volunteer_cols].applymap(
        add_high_school)

    nodes = []
    #初中学校
    for school_name in graph_data['school'].unique():
        count = (graph_data['school'] == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='初中'))

    #第一批次学校
    first_batch = (graph_data['volunteer_1'].append(
        graph_data['volunteer_2'])).dropna()
    for school_name in first_batch.unique():
        count = (first_batch == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='第一批次'))

    #第二批次学校
    second_batch = (graph_data['volunteer_3'].append(
        graph_data['volunteer_4']).append(graph_data['volunteer_5'])).dropna()
    for school_name in second_batch.unique():
        count = (second_batch == school_name).sum()
        nodes.append(
            opts.GraphNode(name=school_name,
                           symbol_size=int(count),
                           value=int(count),
                           category='第二批次'))

    def data2links(pivot_data, color):
        '''
        将分志愿计数的dataframe处理成links
        '''
        links = []
        for idx in pivot_data.index:
            for col in pivot_data.columns:
                if not np.isnan(pivot_data.loc[idx, col]):
                    links.append(
                        opts.GraphLink(source=idx,
                                       target=col,
                                       value=int(pivot_data.loc[idx, col]),
                                       linestyle_opts=opts.LineStyleOpts(
                                           width=int(pivot_data.loc[idx, col]),
                                           color=color,
                                           curve=0.2)))
        return links

    #各志愿对应的线条颜色
    colors = ['#FF8947', '#41E89D', '#FF8947', '#41E89D', '#557EFF']
    links = []
    for volunteer, color in list(zip(volunteer_cols, colors)):
        pivot_data = graph_data.pivot_table(index='school',
                                            columns=volunteer,
                                            aggfunc='size')
        link = data2links(pivot_data, color)
        links += link
    #Categories
    categories = [
        opts.GraphCategory(name='初中'),
        opts.GraphCategory(name='第一批次'),
        opts.GraphCategory(name='第二批次')
    ]
    return nodes, links, categories
Exemple #21
0
def get_graph(request):
    # data_num = request.GET.get('data_num')
    data_all = [[
        "2020/11/29", "福田区 香景大厦", "深圳市城市管理和综合执法局", "投诉", "晚上城市作业车在楼下作业"
    ], ["2020/11/23", " ", "市场监督局", "感谢", "投诉积极响应"],
                ["2020/11/24", "皇岗口岸附近", " ", "投诉", "施工扰民", "噪音超标"],
                ["2020/11/21", "三联山咀头小区", "深圳人居委", "投诉", "施工 没有降噪措施"],
                ["2020/11/21", " ", "深圳交委", "投诉", "宜停车 钓鱼执法"]]

    data = data_all

    cate = ["时间", "地点", "部门", "性质", "事件"]

    link_value = ["发生时间", "发生地点", "责任部门", "事件性质", "事件本身"]

    categories_all = []
    nodes_all = []
    links_all = []
    nodes_name = []

    node_index = 0

    for record in data:
        categories = []
        nodes = []
        links = []
        for c in cate:
            print("cate:" + c + "\n")
            categories.append(opts.GraphCategory(name=c))

        for anode, i in zip(record, range(0, len(cate))):
            print("node:" + anode + "\n")
            if anode == " ":
                pass
            else:
                if is_node_exist(nodes_name, anode) == -1:
                    nodes.append(
                        opts.GraphNode(name=anode, symbol_size=80, category=i))
                    nodes_name.append(anode)
                    node_index += len(nodes_name) - 1
                else:
                    node_index = is_node_exist(nodes_name, anode)

        for anode, i in zip(record, range(0, len(link_value) - 1)):
            print("link:" + record[4] + "->" + link_value[i] + "->" +
                  record[i] + "\n")
            if anode == record[4]:
                pass
            else:
                links.append(
                    opts.GraphLink(source=record[4],
                                   target=anode,
                                   value=link_value[i]))

        categories_all = categories_all + categories
        nodes_all = nodes_all + nodes
        links_all = links_all + links

    page = "graph"
    kgraph = to_graph(categories_all, nodes_all, links_all)

    context = {
        'graph': kgraph,
        "page": page,
        'cur_page': "kgraph",
    }
    return render(request, 'tograph/tograph.html', context)