C++项目:AI五子棋

C++项目:AI五子棋

搭建框架:项目名右键–添加–类。

设计对外接口:先在头文件中设计对外接口。

语法

  1. 类中不写public的默认private。

Labview

自定义窗口

去掉滚动条:右上角右键–VI属性–窗口外观–自定义–取消勾选显示滚动条

窗口大小:右上角右键–VI属性–窗口大小,拉动边框调到最小即可。

自定义控件制作

  1. 在前面板右击选择需要修改的控件(如布尔圆形指示灯),拉大点便于调整;
  2. 右键–制作自定义类型–打开自定义类型–点击小扳手–右键–图片项查看–以相同大小导入,每张图片逐一替换,删掉后面的背景;
  3. 最后保存即可

获取前面板上所有的控件

右键空白–应用程序控制–VI服务器引用(允许用户动态控制前面板控件、VI和LabVIEW环境的一系列函数)。

右键空白–应用程序控制–属性节点(获取或设置对象的属性),本VI-引用,属性节点选择前面板。

右键空白–应用程序控制–属性节点,前面板-引用,属性节点选择控件。

控件–创建显示控件(数组,元素为控件句柄)

获取控件高度

应用程序控制–属性节点(区域高度)

while循环遍历每个控件

先创建while循环框,终止条件false。

输入数据:控件句柄簇–右键–创建–属性节点–值;控件标签数组–右键–创建–属性节点–值。

截取控件标签前两个字符。

如果控件标签的字符串前两个字符为“石块”,位置加30。

for循环

移位寄存器:从一个迭代传输数据到下一个迭代

满足一定条件跳出循环(break):右键循环框–条件接线端当运行到里面时,把里面的True连接到停止按钮。右键框上的下方块选择未连接时使用默认。

程序执行顺序

平铺式顺序结构

通过错误簇连接

程序暂停一下接着运行

定时–等待–创建常量100ms

添加随机数

右键–数值–随机数,设置上限和下限。

U64:[0,100]

I64:[-100,100]

查看数据类型

输出端口右键创建显示控件。

常量:右键–表示法

U32:无符号32位整型

I32:有符号32位整型

强制数据类型转换

右键–数值–转换–转换为长整型

键盘信号采集

右键–互联接口–输入设备控制

初始化键盘、输入数据采集、关闭输入设备

获取键盘输入的值

输入数据采集-创建显示控件,复制一份出来,右键–转换为常量,把里面的键拉出来,其他删除即可。

获取当前文件目录

  1. 右键–文件IO–文件常量–应用程序目录
  2. 使用字符串连接选择下一级目录。若要屏幕输入可以右键创建输入控件。
  3. 右键–文件IO–创建路径,应用程序目录-基路径,连接字符串-相对路径

框架:确保程序运行一次/指定程序运行时执行

添加一个bool指示灯控件,需要运行的程序放在条件框内,里面放一个控制指示灯的属性节点值,赋值False。

程序框图外给bool指示灯赋初值False

使用的时候给bool指示灯赋初值True。

快捷方式

框太小:鼠标变成十字,按住ctrl,往外拉,循环框等量外移

**面板切换:**ctrl+E

**两面平铺:**ctrl+T

**删除断线:**ctrl+B

整理程序框图:ctrl+U

Python数据处理所需要的函数

Python数据处理所需要的函数

数据处理:pandas

读取Excel:

1
df = pd.read_excel()

导出Excel:

1
df.to_excel('路径')

筛选表格中非空的行:

1
df[(df['Europe'].notnull()) & (df['USA'].notnull())]

创建一个空数据框:

1
df = pd.DataFrame({})

去重

1
df['MakeVariant'].drop_duplicates()

重置索引

1
df.reset_index(drop=True)

列表重复

1
[1,2,3] * 3

数据框合并

1
df = pd.concat([df1, df2], axis=0)

数据分组合并求均值

1
df.groupby('列名').agg('mean')

删除数据框某一列

1
df.drop(columns='列名')

序列转列表

1
df['列名']。tolist()

数据框索引

1
2
3
4
5
6
7
8
# 行列标签(行、列、区域)
df[2:4] df[['Fruits','Price']] df[2:3,'Price':'Sales']

# loc(标签)
df.loc[:,['Fruits','Sales']]

# iloc(位置)
df.iloc[2:4,1:3] df.iloc[:,[0,2]]

深拷贝

1
df1 = df.loc['行名'].copy()

数据框条件筛选

1
num[(left > num) | (num > right) | (num < 0)]

统计个数

1
count = pd.value_counts(all_index)

重置列名

1
df.columns = ['F1', 'F2', 'F3']

统计缺失值

1
col_null = df.isnull().sum(axis=0)

缺省值判断

1
temp[~temp.isna().any(axis=1)]

矩阵处理:numpy

取对数(e为底):

1
np.log()

产生和已知数据维度相同的0矩阵:

1
np.zeros_like(data)

作图:matplotlib

多个图:

1
fig, axes = plt.subplots(3, 6)

解决图片显示不全的问题:

1
fig.tight_layout(pad=0.3, w_pad=-0.01, h_pad=0.8)

设置图片大小:

1
fig.set_size_inches(17, 9)

调整子图之间的间距:

1
plt.gcf().subplots_adjust(left=0.05,top=0.95,bottom=0.04,right=0.96)

保存svg图片:

1
plt.savefig('hist.svg')

直方图

纵轴为频率:

1
plt.hist(df, bins=50, weights=np.zeros_like(data) + 1 / len(data))  # 第一个参数是数据,第二个参数是箱子数量,第三个参数是权重

图的标题:

1
plt.title('内容', fontsize=20)

设置全局字体:

1
plt.rc('font',family='Times New Roman', size=15)

设置x轴刻度字体大小

1
plt.xticks(fontsize=ticksize)

显示中文

1
2
plt.rcParams['font.sans-serif']=['SimHei']   #这两行用来显示汉字
plt.rcParams['axes.unicode_minus'] = False

VScode安装教程

VScode安装教程

下载

下载网址:Download Visual Studio Code - Mac, Linux, Windows

按电脑系统选择下载,选择System Installer里的下载,因为User Installer无法选择安装目录,只能装C盘。(windows一般选择x64吧),点击Download下载。

1679401878081

安装

解压缩下载的压缩包,双击Code.exe文件。

在D盘(不是C盘即可)下新建文件夹,命名VScode,选择安装在这里。

img

img

选择附加任务:
①将“通过code打开“操作添加到windows资源管理器文件上下文菜单
②将"通过code打开”操作添加到windows:资源管理器目录上下文菜单
说明:①②勾选上,可以对文件,目录点击鼠标右键,选择使用VScod打开。
③将code注册为受支持的文件类型的编辑器
说明:默认使用VScode打开诸如txt,py等文本类型的文件,一般建议不勾选。
④添加到PATH(重启后生效)
说明:这步聚默认的,勾选上,不用配置环境变量,可以直接使用。

img

img

安装插件

点击左侧工具栏扩展按钮(四个方块)输入chinese,选择Chinese (Simplified) Language,点击install。如果没有变成中文,重新启动软件即可。

点击左侧工具栏扩展按钮(四个方块)输入open in,选择open in browser,点击install。

Echarts-开始做图

Echarts

本文将采用以下示例:

基本柱形图:Examples - Apache ECharts

坐标轴刻度与标签对齐:Examples - Apache ECharts

条形图:Examples - Apache ECharts

南丁格尔玫瑰图:Examples - Apache ECharts

折线图:Examples - Apache ECharts

旭日图:Examples - Apache ECharts

桑吉图:Examples - Apache ECharts

选取模板

选取官方示例中的基础柱状图作为示例,链接如下:Examples - Apache ECharts

选择完整代码,除去第一行粘贴入框架中option部分。

数据准备

学院
物电 140 60
数科 80 50
经管 100 130
环境 90 80
生科 80 85
音乐 30 50
体育 80 40
文学 60 40
法学 100 120

首先,把数据粘贴到Echarts官方给出的“表格工具”中,链接如下:Spreadsheet Tool - Apache ECharts

删除第一行数据。

在右侧选项栏中可以对数据格式进行调整,调节数据格式与官方示例中的数据格式一致即可。

把数据粘贴到代码对应位置。

在浏览器中打开即可。

坐标轴刻度与标签对齐

打开示例:Examples - Apache ECharts

找到对应代码:

1
2
3
axisTick: {
alignWithLabel: true
}

代码注释:

tooltip:设置提示框

设置提示框

1
2
3
tooltip: {
trigger: 'axis'
},

降序排列

打开示例:Examples - Apache ECharts

由于数据格式改变,我们重新转换格式,方法同上,选择“每两列转换成一个二维数组”。

再加上上面的语句。

条形图

把xaxis和yaxis名字换一下就行。

极坐标

打开示例:Examples - Apache ECharts

在表格工具中选择“每一列转换为一个一维数组”

直接修改data中的数据即可。

南丁格尔玫瑰图

官方示例:Examples - Apache ECharts

这里可以直接修改数据。

1
2
3
4
5
6
7
8
9
[
{ value: 4400, name: '亚洲' , itemStyle: {color: '#DF2F2F'}},
{ value: 3000, name: '非洲' , itemStyle: {color: '#DB6D23'}},
{ value: 2400, name: '北美洲' , itemStyle: {color: '#F3A502'}},
{ value: 1800, name: '南美洲' , itemStyle: {color: '#6AA006'}},
{ value: 1400, name: '南极洲' , itemStyle: {color: '#14539A'}},
{ value: 1000, name: '欧洲' , itemStyle: {color: '#87409C'}},
{ value: 900, name: '大洋洲' , itemStyle: {color: '#7F3912'}}
]

修改颜色:

1
2
3
data: [
{ value: 40, name: 'rose 1' , itemStyle: {color: '#516b91'}}
]

缺点:数据处理不太方便,除非掌握js语言,建议外部处理好数据后在这里画图比较方便。

气泡图

emphasis.focus:series(高亮当前序列),self(高亮当前值)

旭日图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var data = [{ 'name': '化学化工学院', 'children': [{ 'name': '化学', 'value': 11 }, { 'name': '应用化学', 'value': 7 }, { 'name': '材料化学', 'value': 6 }, { 'name': '化学类', 'value': 2 }] }, { 'name': '物理电子工程学院', 'children': [{ 'name': '电子信息科学与技术', 'value': 8 }, { 'name': '物理学(国家基地)', 'value': 5 }, { 'name': '光电信息科学与工程', 'value': 4 }] }, { 'name': '初民学院', 'children': [{ 'name': '大数据金融试验班', 'value': 2 }, { 'name': '生化试验班', 'value': 2 }, { 'name': '金融学', 'value': 1 }, { 'name': '生物科学', 'value': 1 }] }, { 'name': '数学科学学院', 'children': [{ 'name': '数学类', 'value': 5 }, { 'name': '数学与应用数学', 'value': 1 }] }, { 'name': '音乐学院', 'children': [{ 'name': '舞蹈编导', 'value': 4 }, { 'name': '音乐表演', 'value': 1 }] }, { 'name': '计算机与信息技术学院', 'children': [{ 'name': '数据科学与大数据技术', 'value': 3 }] }, { 'name': '生命科学学院', 'children': [{ 'name': '生物科学类', 'value': 2 }] }, { 'name': '体育学院', 'children': [{ 'name': '运动训练', 'value': 2 }] }, { 'name': '历史文化学院', 'children': [{ 'name': '考古学', 'value': 1 }] }, { 'name': '美术学院', 'children': [{ 'name': '环境设计', 'value': 1 }] }, { 'name': '文学院', 'children': [{ 'name': '汉语言文学', 'value': 1 }] }, { 'name': '哲学社会学学院', 'children': [{ 'name': '哲学类', 'value': 1 }] }]

option = {
title: {
text: '山西大学学院专业分布图',
subtext: '来源:山西大学',
},
tooltip: {},
series: {
type: 'sunburst',
data: data,
radius: [0, '95%'],
sort: 'desc',
emphasis: {
focus: 'descendant'
},
levels: [
{},
{
r0: '15%',
r: '50%',
itemStyle: {
borderWidth: 2
},
label: {
fontSize: 10,
rotate: 'radial'
}
},
{
r0: '50%',
r: '95%',
label: {
align: 'right'
}
}
]
}
};

桑吉图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var nodes = [
{ 'name': '建筑电气与智能化', 'itemStyle': { 'color': '#FFFFD9' } },
{ 'name': '能源与动力工程', 'itemStyle': { 'color': '#F4FBC2' } },
{ 'name': '环境科学与工程类', 'itemStyle': { 'color': '#D1EDB3' } },
{ 'name': '建筑环境与能源应用工程', 'itemStyle': { 'color': '#E7F5B1' } },
{ 'name': '机械电子工程', 'itemStyle': { 'color': '#D1EDB3' } },
{ 'name': '生物科学类', 'itemStyle': { 'color': '#89D1BA' } },
{ 'name': '工商管理类', 'itemStyle': { 'color': '#41B6C4' } },
{ 'name': '化学类', 'itemStyle': { 'color': '#64C3BE' } },
{ 'name': '电气工程及其自动化', 'itemStyle': { 'color': '#2CA0C1' }, 'label': { 'color': 'white' } },
{ 'name': '计算机科学与技术', 'itemStyle': { 'color': '#206CAE' }, 'label': { 'color': 'white' } },
{ 'name': '电子信息工程', 'itemStyle': { 'color': '#1D89BC' }, 'label': { 'color': 'white' } },
{ 'name': '数据科学与大数据技术', 'itemStyle': { 'color': '#2252A2' }, 'label': { 'color': 'white' } },
{ 'name': '经济学类', 'itemStyle': { 'color': '#243A96' }, 'label': { 'color': 'white' } },
{ 'name': '成绩优秀', 'itemStyle': { 'color': '#182A7A' }, 'label': { 'color': 'white' } },
{ 'name': '其他情况', 'itemStyle': { 'color': '#081D58' }, 'label': { 'color': 'white' } },
]

var links = [
{ 'source': '生物科学类', 'target': '计算机科学与技术', 'value': 5 },
{ 'source': '能源与动力工程', 'target': '电子信息工程', 'value': 3 },
{ 'source': '能源与动力工程', 'target': '电气工程及其自动化', 'value': 6 },
{ 'source': '建筑环境与能源应用工程', 'target': '电子信息工程', 'value': 3 },
{ 'source': '建筑环境与能源应用工程', 'target': '电气工程及其自动化', 'value': 3 },
{ 'source': '建筑电气与智能化', 'target': '电气工程及其自动化', 'value': 24 },
{ 'source': '机械电子工程', 'target': '电气工程及其自动化', 'value': 5 },
{ 'source': '环境科学与工程类', 'target': '数据科学与大数据技术', 'value': 3 },
{ 'source': '环境科学与工程类', 'target': '计算机科学与技术', 'value': 2 },
{ 'source': '化学类', 'target': '计算机科学与技术', 'value': 3 },
{ 'source': '工商管理类', 'target': '经济学类', 'value': 3 },
{ 'source': '计算机科学与技术', 'target': '成绩优秀', 'value': 10 },
{ 'source': '电子信息工程', 'target': '成绩优秀', 'value': 6 },
{ 'source': '电气工程及其自动化', 'target': '成绩优秀', 'value': 34 },
{ 'source': '电气工程及其自动化', 'target': '其他情况', 'value': 4 },
{ 'source': '数据科学与大数据技术', 'target': '成绩优秀', 'value': 3 },
{ 'source': '经济学类', 'target': '成绩优秀', 'value': 3 }
]

option = {
title: {
text: '山西大学转专业示意图'
},
tooltip: {
trigger: 'item',
triggerOn: 'mousemove'
},
series: [
{
type: 'sankey',
data: nodes,
links: links,
emphasis: {
focus: 'adjacency'
},
nodeWidth: 145,
nodeGap: 0,
top: '8%',
right: '5%',
label: {
position: 'inside'
},
levels: [
{
depth: 0,
lineStyle: {
color: 'source',
opacity: 0.6
}
},
{
depth: 1,
lineStyle: {
color: 'source',
opacity: 0.6
}
}
],
lineStyle: {
curveness: 0.5
}
}
]
}

北京AQI

1
2
3
4
5
xAxis: {
data: data.map(function (item) {
return item[0];
})
}

该代码使用了JavaScript数组的map方法,该方法遍历数组中的每个元素(选择data中的第一个元素)并执行操作(此处是返回第一个值)。传入的参数是一个函数。

1680013342536

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>ECharts</title>
<!-- 引入刚刚下载的 ECharts 文件 -->
<script src="echarts.js"></script>
</head>

<body>
<!-- 为 ECharts 准备一个定义了宽高的 DOM -->
<div id="main" style="width: 800px;height:600px;"></div>
<script type="text/javascript">

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

option = {
title: {
text: 'Beijing AQI',
left: '1%'
},
tooltip: {
trigger: 'axis'
},
grid: {
left: '5%',
right: '15%',
bottom: '10%'
},
xAxis: {
data: ['2020/1/1', '2020/1/2', '2020/1/3']
},
yAxis: {},
toolbox: {
right: 10,
feature: {
dataZoom: {
yAxisIndex: 'none'
},
restore: {},
saveAsImage: {}
}
},
dataZoom: [
{
startValue: '2014-06-01'
},
{
type: 'inside'
}
],
visualMap: {
top: 50,
right: 10,
pieces: [
{
gt: 0,
lte: 50,
color: '#93CE07'
},
{
gt: 50,
lte: 100,
color: '#FBDB0F'
},
{
gt: 100,
lte: 150,
color: '#FC7D02'
},
{
gt: 150,
lte: 200,
color: '#FD0100'
},
{
gt: 200,
lte: 300,
color: '#AA069F'
},
{
gt: 300,
color: '#AC3B2A'
}
],
outOfRange: {
color: '#999'
}
},
series: {
name: 'Beijing AQI',
type: 'line',
data: [110, 158, 216],
markLine: {
silent: true,
lineStyle: {
color: '#333'
},
data: [
{
yAxis: 50
},
{
yAxis: 100
},
{
yAxis: 150
},
{
yAxis: 200
},
{
yAxis: 250
}
]
// markLine: {
// data: [
// [
// { coord: [2, 100] },
// { coord: [3, 200] }
// ],
// [
// {},
// {}
// ]
// ]
// }
}
}
}
option && myChart.setOption(option);
</script>
</body>

</html>

Echarts-准备工作

下载echarts

  1. 下载echarts.js文件。
  2. 新建文件夹,导入echarts.js文件,新建index.html文件。

Echarts框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
<!-- 引入刚刚下载的 ECharts 文件 -->
<script src="echarts.js"></script>
</head>
<body>
<!-- 为 ECharts 准备一个定义了宽高的 DOM -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>

主题工具

  1. 使用默认主题:主题下载 - Apache ECharts

    注意:使用时先引入主题,再在echarts.init(dom, ‘主题名字’)

  2. 自定义主题:主题编辑器 - Apache ECharts

    设置好后,点击下载。使用时先引入主题,再在echarts.init(dom, ‘主题名字’)

方案一:简单粗暴

  1. 处理数据。把excel数据在Spreadsheet Tool - Apache ECharts网站处理得到所需格式的数据。(缺点:数据必须完美,得在别的软件处理好)
  2. 下载图片。(仅png)

方案二:摘代码块

最好还是外面处理好数据吧

Pyecharts-桑基图

桑基图

导入需要的包

1
2
3
4
import pandas as pd
from pyecharts.charts import Sankey
from pyecharts import options as opts
import os

导入数据

1
df: pd.DataFrame = pd.read_excel(r'山西大学2021年本科生转专业情况.xlsx')

节点处理

1
2
3
4
5
nodes = list(set(df['转出专业'].tolist() + df['转入专业'].tolist() + df['类型'].tolist()))
node_list = []
for i in range(len(nodes)):
dict = {'name': nodes[i]}
node_list.append(dict)

连线数据处理

第一层

1
2
3
4
5
6
df1: pd.DataFrame = df[['转出专业', '转入专业']]
df1['次数'] = ''
for i in range(len(df1)):
df1.loc[i, '次数'] = df1[(df1['转出专业'] == df1.loc[i, '转出专业']) & (df1['转入专业'] == df1.loc[i, '转入专业'])].shape[0]
df1 = df1.drop_duplicates()
df1.columns = ['source', 'target', 'value']

第二层

1
2
3
4
5
6
df2: pd.DataFrame = df[['转入专业', '类型']]
df2['次数'] = ''
for i in range(len(df2)):
df2.loc[i, '次数'] = df2[(df2['转入专业'] == df2.loc[i, '转入专业']) & (df2['类型'] == df2.loc[i, '类型'])].shape[0]
df2 = df2.drop_duplicates()
df2.columns = ['source', 'target', 'value']

拼接两个数据

1
2
3
4
5
6
7
8
link_df = pd.concat([df1, df2])

link_list = []
for i in range(len(link_df)):
dict = {'source': link_df.iloc[i, 0],
'target': link_df.iloc[i, 1],
'value': int(link_df.iloc[i, 2])}
link_list.append(dict)

作图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sankey = (Sankey(init_opts=opts.InitOpts(bg_color='white'))
.add("",
nodes=node_list,
links=link_list,
pos_left="7%",
node_width=135,
node_gap=0,
layout_iterations=1000,
is_draggable=False,
focus_node_adjacency=True,
linestyle_opt=opts.LineStyleOpts(opacity=0.7, curve=0.5, color="source"),
label_opts=opts.LabelOpts(font_size=12, position='inside')
)
.set_global_opts(title_opts=opts.TitleOpts(title="转专业-桑基图"))
)

sankey.render("sankey.html")
os.system("sankey.html")

修改颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
node_list = [
{'name': '建筑电气与智能化', 'itemStyle': {'color': '#FFFFD9'}},
{'name': '能源与动力工程', 'itemStyle': {'color': '#F4FBC2'}},
{'name': '环境科学与工程类', 'itemStyle': {'color': '#D1EDB3'}},
{'name': '建筑环境与能源应用工程', 'itemStyle': {'color': '#E7F5B1'}},
{'name': '机械电子工程', 'itemStyle': {'color': '#D1EDB3'}},
{'name': '生物科学类', 'itemStyle': {'color': '#89D1BA'}},
{'name': '工商管理类', 'itemStyle': {'color': '#41B6C4'}},
{'name': '化学类', 'itemStyle': {'color': '#64C3BE'}},
{'name': '电气工程及其自动化', 'itemStyle': {'color': '#2CA0C1'}, 'label': {'color': 'white'}},
{'name': '计算机科学与技术', 'itemStyle': {'color': '#206CAE'}, 'label': {'color': 'white'}},
{'name': '电子信息工程', 'itemStyle': {'color': '#1D89BC'}, 'label': {'color': 'white'}},
{'name': '数据科学与大数据技术', 'itemStyle': {'color': '#2252A2'}, 'label': {'color': 'white'}},
{'name': '经济学类', 'itemStyle': {'color': '#243A96'}, 'label': {'color': 'white'}},
{'name': '成绩优秀', 'itemStyle': {'color': '#182A7A'}, 'label': {'color': 'white'}},
{'name': '其他情况', 'itemStyle': {'color': '#081D58'}, 'label': {'color': 'white'}},
]

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pandas as pd
from pyecharts.charts import Sankey
from pyecharts import options as opts
import os

df: pd.DataFrame = pd.read_excel(r'山西大学2021年本科生转专业情况.xlsx')

# -------------------------------处理节点--------------------------------------
nodes = list(set(df['转出专业'].tolist() + df['转入专业'].tolist() + df['类型'].tolist()))
node_list = []
for i in range(len(nodes)):
dict = {'name': nodes[i]}
node_list.append(dict)
# print(node_list)

node_list = [
{'name': '建筑电气与智能化', 'itemStyle': {'color': '#FFFFD9'}},
{'name': '能源与动力工程', 'itemStyle': {'color': '#F4FBC2'}},
{'name': '环境科学与工程类', 'itemStyle': {'color': '#D1EDB3'}},
{'name': '建筑环境与能源应用工程', 'itemStyle': {'color': '#E7F5B1'}},
{'name': '机械电子工程', 'itemStyle': {'color': '#D1EDB3'}},
{'name': '生物科学类', 'itemStyle': {'color': '#89D1BA'}},
{'name': '工商管理类', 'itemStyle': {'color': '#41B6C4'}},
{'name': '化学类', 'itemStyle': {'color': '#64C3BE'}},
{'name': '电气工程及其自动化', 'itemStyle': {'color': '#2CA0C1'}, 'label': {'color': 'white'}},
{'name': '计算机科学与技术', 'itemStyle': {'color': '#206CAE'}, 'label': {'color': 'white'}},
{'name': '电子信息工程', 'itemStyle': {'color': '#1D89BC'}, 'label': {'color': 'white'}},
{'name': '数据科学与大数据技术', 'itemStyle': {'color': '#2252A2'}, 'label': {'color': 'white'}},
{'name': '经济学类', 'itemStyle': {'color': '#243A96'}, 'label': {'color': 'white'}},
{'name': '成绩优秀', 'itemStyle': {'color': '#182A7A'}, 'label': {'color': 'white'}},
{'name': '其他情况', 'itemStyle': {'color': '#081D58'}, 'label': {'color': 'white'}},
]

# -------------------------------处理连线--------------------------------------
df1: pd.DataFrame = df[['转出专业', '转入专业']]
df1['次数'] = ''
for i in range(len(df1)):
df1.loc[i, '次数'] = df1[(df1['转出专业'] == df1.loc[i, '转出专业']) & (df1['转入专业'] == df1.loc[i, '转入专业'])].shape[0]
df1 = df1.drop_duplicates()
df1.columns = ['source', 'target', 'value']
# print(df1)

df2: pd.DataFrame = df[['转入专业', '类型']]
df2['次数'] = ''
for i in range(len(df2)):
df2.loc[i, '次数'] = df2[(df2['转入专业'] == df2.loc[i, '转入专业']) & (df2['类型'] == df2.loc[i, '类型'])].shape[0]
df2 = df2.drop_duplicates()
df2.columns = ['source', 'target', 'value']

link_df = pd.concat([df1, df2])

link_list = []
for i in range(len(link_df)):
dict = {'source': link_df.iloc[i, 0],
'target': link_df.iloc[i, 1],
'value': int(link_df.iloc[i, 2])}
link_list.append(dict)
# print(link_list)

# -------------------------------画图--------------------------------------
sankey = (Sankey(init_opts=opts.InitOpts(bg_color='white'))
.add("",
nodes=node_list,
links=link_list,
pos_left="7%",
node_width=135,
node_gap=0,
layout_iterations=1000,
is_draggable=False,
focus_node_adjacency=True,
linestyle_opt=opts.LineStyleOpts(opacity=0.7, curve=0.5, color="source"),
label_opts=opts.LabelOpts(font_size=12, position='inside')
)
.set_global_opts(title_opts=opts.TitleOpts(title="转专业-桑基图"))
)

sankey.render("sankey.html")
os.system("sankey.html")

大功告成!

量子随机数生成器

后处理

**背景:**由于器件的缺陷(噪声、精度等),可能对实际系统产生的随机数的随机性有影响。

**目的:**使实际系统产生的随机数的随机性更好。

不后处理也行,代价是随机数产生速率更低。

方法一:冯·诺依曼法

原始数据进行如下改造:

  1. 连续出现 10 的,记为 1
  2. 连续出现 01 的,记为 0
  3. 出现 00 11 的,舍弃。

**优势:**消除原始数据的偏置。新序列中,保证$$P(01)=P(10)$$

**劣势:**速率损失大。

均匀分布时:$$P(01)=P(10)=P(00)=P(11)$$,输入长度和输出长度之比为$$1/4$$;

**一般情况:**输入长度和输出长度之比为$$(1/4-e(n)^2)$$,$$e(n)$$为原始数据的偏置。

方法二:逻辑异或操作

过程:

  1. 第一种XOR方法:$$A_1\oplus A_2, A_3\oplus A_4, \cdots$$

    输入输出比:$$1/2$$

  2. 第二种XOR方法:$$A_1\oplus A_2, A_2\oplus A_2, \cdots$$

    输入输出比:$$1$$

作用:

  1. 改善统计分布。经过一次异或操作,可以将任意统计分布转换为对称统计分布。多次异或下,统计分布非常接近均匀分布。
  2. 可以将输出值偏置和自相关系数降低。4

**优势:**较高的输入输出比。

**劣势:**重复次数多,引入经典信息多,对于一阶自相关系数高的序列,输出序列相关性高。

**适用范围:**采样速率低。

方法三:m-LSB操作

**过程:**保留每次采样信号$m$比特最低有效位。

比方说,我们使用8比特$(n=8)$数模转换器,通过对随机源熵评估得到信息熵为$m=5$,即把每一个采样信号的最高3位舍弃,仅保留最低5位,将这些重新组合得到新输出序列。

m取值越小,输出序列越接近均匀分布。

python:多层嵌套的树状json数据和excel数据的转换

问题

目标:实现多层嵌套的树状json数据和excel数据的转换

工具:python

json数据转化结果
  
  data = [
    {
        "name": "Flora",
        "itemStyle": {"color": "#da0d68"},
        "children": [
            {"name": "Black Tea", "value": 1, "itemStyle": {"color": "#975e6d"}},
            {
                "name": "Floral",
                "itemStyle": {"color": "#e0719c"},
                "children": [
                    {
                        "name": "Chamomile",
                        "value": 1,
                        "itemStyle": {"color": "#f99e1c"},
                    },
                    {"name": "Rose", "value": 1, "itemStyle": {"color": "#ef5a78"}},
                    {"name": "Jasmine", "value": 1, "itemStyle": {"color": "#f7f1bd"}},
                ],
            },
        ],
    },
    {
        "name": "Fruity",
        "itemStyle": {"color": "#da1d23"},
        "children": [
            {
                "name": "Berry",
                "itemStyle": {"color": "#dd4c51"},
                "children": [
                    {
                        "name": "Blackberry",
                        "value": 1,
                        "itemStyle": {"color": "#3e0317"},
                    },
                    {
                        "name": "Raspberry",
                        "value": 1,
                        "itemStyle": {"color": "#e62969"},
                    },
                    {
                        "name": "Blueberry",
                        "value": 1,
                        "itemStyle": {"color": "#6569b0"},
                    },
                    {
                        "name": "Strawberry",
                        "value": 1,
                        "itemStyle": {"color": "#ef2d36"},
                    },
                ],
            },
            {
                "name": "Dried Fruit",
                "itemStyle": {"color": "#c94a44"},
                "children": [
                    {"name": "Raisin", "value": 1, "itemStyle": {"color": "#b53b54"}},
                    {"name": "Prune", "value": 1, "itemStyle": {"color": "#a5446f"}},
                ],
            },
            {
                "name": "Other Fruit",
                "itemStyle": {"color": "#dd4c51"},
                "children": [
                    {"name": "Coconut", "value": 1, "itemStyle": {"color": "#f2684b"}},
                    {"name": "Cherry", "value": 1, "itemStyle": {"color": "#e73451"}},
                    {
                        "name": "Pomegranate",
                        "value": 1,
                        "itemStyle": {"color": "#e65656"},
                    },
                    {
                        "name": "Pineapple",
                        "value": 1,
                        "itemStyle": {"color": "#f89a1c"},
                    },
                    {"name": "Grape", "value": 1, "itemStyle": {"color": "#aeb92c"}},
                    {"name": "Apple", "value": 1, "itemStyle": {"color": "#4eb849"}},
                    {"name": "Peach", "value": 1, "itemStyle": {"color": "#f68a5c"}},
                    {"name": "Pear", "value": 1, "itemStyle": {"color": "#baa635"}},
                ],
            },
            {
                "name": "Citrus Fruit",
                "itemStyle": {"color": "#f7a128"},
                "children": [
                    {
                        "name": "Grapefruit",
                        "value": 1,
                        "itemStyle": {"color": "#f26355"},
                    },
                    {"name": "Orange", "value": 1, "itemStyle": {"color": "#e2631e"}},
                    {"name": "Lemon", "value": 1, "itemStyle": {"color": "#fde404"}},
                    {"name": "Lime", "value": 1, "itemStyle": {"color": "#7eb138"}},
                ],
            },
        ],
    },
    {
        "name": "Sour/\nFermented",
        "itemStyle": {"color": "#ebb40f"},
        "children": [
            {
                "name": "Sour",
                "itemStyle": {"color": "#e1c315"},
                "children": [
                    {
                        "name": "Sour Aromatics",
                        "value": 1,
                        "itemStyle": {"color": "#9ea718"},
                    },
                    {
                        "name": "Acetic Acid",
                        "value": 1,
                        "itemStyle": {"color": "#94a76f"},
                    },
                    {
                        "name": "Butyric Acid",
                        "value": 1,
                        "itemStyle": {"color": "#d0b24f"},
                    },
                    {
                        "name": "Isovaleric Acid",
                        "value": 1,
                        "itemStyle": {"color": "#8eb646"},
                    },
                    {
                        "name": "Citric Acid",
                        "value": 1,
                        "itemStyle": {"color": "#faef07"},
                    },
                    {
                        "name": "Malic Acid",
                        "value": 1,
                        "itemStyle": {"color": "#c1ba07"},
                    },
                ],
            },
            {
                "name": "Alcohol/\nFremented",
                "itemStyle": {"color": "#b09733"},
                "children": [
                    {"name": "Winey", "value": 1, "itemStyle": {"color": "#8f1c53"}},
                    {"name": "Whiskey", "value": 1, "itemStyle": {"color": "#b34039"}},
                    {
                        "name": "Fremented",
                        "value": 1,
                        "itemStyle": {"color": "#ba9232"},
                    },
                    {"name": "Overripe", "value": 1, "itemStyle": {"color": "#8b6439"}},
                ],
            },
        ],
    },
    {
        "name": "Green/\nVegetative",
        "itemStyle": {"color": "#187a2f"},
        "children": [
            {"name": "Olive Oil", "value": 1, "itemStyle": {"color": "#a2b029"}},
            {"name": "Raw", "value": 1, "itemStyle": {"color": "#718933"}},
            {
                "name": "Green/\nVegetative",
                "itemStyle": {"color": "#3aa255"},
                "children": [
                    {
                        "name": "Under-ripe",
                        "value": 1,
                        "itemStyle": {"color": "#a2bb2b"},
                    },
                    {"name": "Peapod", "value": 1, "itemStyle": {"color": "#62aa3c"}},
                    {"name": "Fresh", "value": 1, "itemStyle": {"color": "#03a653"}},
                    {
                        "name": "Dark Green",
                        "value": 1,
                        "itemStyle": {"color": "#038549"},
                    },
                    {
                        "name": "Vegetative",
                        "value": 1,
                        "itemStyle": {"color": "#28b44b"},
                    },
                    {"name": "Hay-like", "value": 1, "itemStyle": {"color": "#a3a830"}},
                    {
                        "name": "Herb-like",
                        "value": 1,
                        "itemStyle": {"color": "#7ac141"},
                    },
                ],
            },
            {"name": "Beany", "value": 1, "itemStyle": {"color": "#5e9a80"}},
        ],
    },
    {
        "name": "Other",
        "itemStyle": {"color": "#0aa3b5"},
        "children": [
            {
                "name": "Papery/Musty",
                "itemStyle": {"color": "#9db2b7"},
                "children": [
                    {"name": "Stale", "value": 1, "itemStyle": {"color": "#8b8c90"}},
                    {
                        "name": "Cardboard",
                        "value": 1,
                        "itemStyle": {"color": "#beb276"},
                    },
                    {"name": "Papery", "value": 1, "itemStyle": {"color": "#fefef4"}},
                    {"name": "Woody", "value": 1, "itemStyle": {"color": "#744e03"}},
                    {
                        "name": "Moldy/Damp",
                        "value": 1,
                        "itemStyle": {"color": "#a3a36f"},
                    },
                    {
                        "name": "Musty/Dusty",
                        "value": 1,
                        "itemStyle": {"color": "#c9b583"},
                    },
                    {
                        "name": "Musty/Earthy",
                        "value": 1,
                        "itemStyle": {"color": "#978847"},
                    },
                    {"name": "Animalic", "value": 1, "itemStyle": {"color": "#9d977f"}},
                    {
                        "name": "Meaty Brothy",
                        "value": 1,
                        "itemStyle": {"color": "#cc7b6a"},
                    },
                    {"name": "Phenolic", "value": 1, "itemStyle": {"color": "#db646a"}},
                ],
            },
            {
                "name": "Chemical",
                "itemStyle": {"color": "#76c0cb"},
                "children": [
                    {"name": "Bitter", "value": 1, "itemStyle": {"color": "#80a89d"}},
                    {"name": "Salty", "value": 1, "itemStyle": {"color": "#def2fd"}},
                    {
                        "name": "Medicinal",
                        "value": 1,
                        "itemStyle": {"color": "#7a9bae"},
                    },
                    {
                        "name": "Petroleum",
                        "value": 1,
                        "itemStyle": {"color": "#039fb8"},
                    },
                    {"name": "Skunky", "value": 1, "itemStyle": {"color": "#5e777b"}},
                    {"name": "Rubber", "value": 1, "itemStyle": {"color": "#120c0c"}},
                ],
            },
        ],
    },
    {
        "name": "Roasted",
        "itemStyle": {"color": "#c94930"},
        "children": [
            {"name": "Pipe Tobacco", "value": 1, "itemStyle": {"color": "#caa465"}},
            {"name": "Tobacco", "value": 1, "itemStyle": {"color": "#dfbd7e"}},
            {
                "name": "Burnt",
                "itemStyle": {"color": "#be8663"},
                "children": [
                    {"name": "Acrid", "value": 1, "itemStyle": {"color": "#b9a449"}},
                    {"name": "Ashy", "value": 1, "itemStyle": {"color": "#899893"}},
                    {"name": "Smoky", "value": 1, "itemStyle": {"color": "#a1743b"}},
                    {
                        "name": "Brown, Roast",
                        "value": 1,
                        "itemStyle": {"color": "#894810"},
                    },
                ],
            },
            {
                "name": "Cereal",
                "itemStyle": {"color": "#ddaf61"},
                "children": [
                    {"name": "Grain", "value": 1, "itemStyle": {"color": "#b7906f"}},
                    {"name": "Malt", "value": 1, "itemStyle": {"color": "#eb9d5f"}},
                ],
            },
        ],
    },
    {
        "name": "Spices",
        "itemStyle": {"color": "#ad213e"},
        "children": [
            {"name": "Pungent", "value": 1, "itemStyle": {"color": "#794752"}},
            {"name": "Pepper", "value": 1, "itemStyle": {"color": "#cc3d41"}},
            {
                "name": "Brown Spice",
                "itemStyle": {"color": "#b14d57"},
                "children": [
                    {"name": "Anise", "value": 1, "itemStyle": {"color": "#c78936"}},
                    {"name": "Nutmeg", "value": 1, "itemStyle": {"color": "#8c292c"}},
                    {"name": "Cinnamon", "value": 1, "itemStyle": {"color": "#e5762e"}},
                    {"name": "Clove", "value": 1, "itemStyle": {"color": "#a16c5a"}},
                ],
            },
        ],
    },
    {
        "name": "Nutty/\nCocoa",
        "itemStyle": {"color": "#a87b64"},
        "children": [
            {
                "name": "Nutty",
                "itemStyle": {"color": "#c78869"},
                "children": [
                    {"name": "Peanuts", "value": 1, "itemStyle": {"color": "#d4ad12"}},
                    {"name": "Hazelnut", "value": 1, "itemStyle": {"color": "#9d5433"}},
                    {"name": "Almond", "value": 1, "itemStyle": {"color": "#c89f83"}},
                ],
            },
            {
                "name": "Cocoa",
                "itemStyle": {"color": "#bb764c"},
                "children": [
                    {
                        "name": "Chocolate",
                        "value": 1,
                        "itemStyle": {"color": "#692a19"},
                    },
                    {
                        "name": "Dark Chocolate",
                        "value": 1,
                        "itemStyle": {"color": "#470604"},
                    },
                ],
            },
        ],
    },
    {
        "name": "Sweet",
        "itemStyle": {"color": "#e65832"},
        "children": [
            {
                "name": "Brown Sugar",
                "itemStyle": {"color": "#d45a59"},
                "children": [
                    {"name": "Molasses", "value": 1, "itemStyle": {"color": "#310d0f"}},
                    {
                        "name": "Maple Syrup",
                        "value": 1,
                        "itemStyle": {"color": "#ae341f"},
                    },
                    {
                        "name": "Caramelized",
                        "value": 1,
                        "itemStyle": {"color": "#d78823"},
                    },
                    {"name": "Honey", "value": 1, "itemStyle": {"color": "#da5c1f"}},
                ],
            },
            {"name": "Vanilla", "value": 1, "itemStyle": {"color": "#f89a80"}},
            {"name": "Vanillin", "value": 1, "itemStyle": {"color": "#f37674"}},
            {"name": "Overall Sweet", "value": 1, "itemStyle": {"color": "#e75b68"}},
            {"name": "Sweet Aromatics", "value": 1, "itemStyle": {"color": "#d0545f"}},
        ],
    },
	]
  

excel数据转化结果

name1 color1 name2 color2 name3 color3
Flora #da0d68 Black Tea #975e6d 0 0
Flora #da0d68 Floral #e0719c Chamomile #f99e1c
Flora #da0d68 Floral #e0719c Rose #ef5a78
Flora #da0d68 Floral #e0719c Jasmine #f7f1bd
Fruity #da1d23 Berry #dd4c51 Blackberry #3e0317
Fruity #da1d23 Berry #dd4c51 Raspberry #e62969
Fruity #da1d23 Berry #dd4c51 Blueberry #6569b0
Fruity #da1d23 Berry #dd4c51 Strawberry #ef2d36
Fruity #da1d23 Dried Fruit #c94a44 Raisin #b53b54
Fruity #da1d23 Dried Fruit #c94a44 Prune #a5446f
Fruity #da1d23 Other Fruit #dd4c51 Coconut #f2684b
Fruity #da1d23 Other Fruit #dd4c51 Cherry #e73451
Fruity #da1d23 Other Fruit #dd4c51 Pomegranate #e65656

tips: excel数据仅展示部分

Part1: 多层嵌套json数据→excel数据

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd

df = pd.DataFrame()
for i in data:
x = pd.json_normalize(i,
record_path=['children', 'children'],
meta=[['children', 'name'], ['children', 'itemStyle', 'color'], "itemStyle", "name"],
record_prefix='children->',
meta_prefix='father->',
sep='->',
errors='ignore')
df = pd.concat([df, x],axis=0)
df.to_csv('1.csv')

1、json_normalize用法:

  • **第一个参数:**转换的json数据

  • **record_path:**搜索路径。如果不设置这个参数,默认将json第一层数据转为dataframe,内层数据将还是字典格式。如果要找到children里的数据,则需设定路径,格式为:每一层的名字组成的列表。这里名字需为json数据中每一层的列表名。此例中,我们有3层数据,要找到做内层的children,需要设置为[‘children’, ‘children’]。

    这里可能会报这样的错误:KeyError: ‘children’

    是因为有的数据有一个children,有的数据有children的children,所以他无法识别只有一个children数据的路径,所以这里我们需要手动检查一下数据,把只有一个children的数据加一个空的children参数**, ‘children’: [{‘name’: 0}]**,这样就没问题啦。

  • **meta:**添加额外列。如果我们成功取到最内层的children数据,我们还想再补充上它的上一级中的参数,就可使用这个参数。**格式:**还是按照搜索路径的方式,依次添加在列表中。最外层的数据不需要列表,直接写名字就行。

  • **record_prefix’和meta_prefix:**当不同级别数据中有重名时使用,否则报错。

  • **errors:**忽略缺少key的情况。数据中,有的children的key有,有的children的key没有,这样就会报错。写上就可以忽略这些错误正常执行。

2、处理完每一组数据,把数据追加到上一次循环好的dataframe中。

3、最后输出csv格式数据。

Part2: excel数据→多层嵌套json数据

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import pandas as pd

df = pd.read_csv("旭日图数据.csv")

data = []
for first in df["name1"].unique():
first_dict = {}
first_dict["name"] = first
first_dict["itemStyle"] = {"color": df[df["name1"] == first]["color1"].unique()[0]}
first_list = []
first_data = df[df["name1"] == first]

for second in first_data["name2"].unique():
second_dict = {}
second_dict["name"] = second
second_dict["itemStyle"] = {"color": first_data[first_data["name2"] == second]["color2"].unique()[0]}

if (first_data[first_data["name2"] == second]["name3"].unique()[0] == '0'):
second_dict["value"] = 1
else:
second_list = []
second_data = first_data[first_data["name2"] == second]

for third in second_data["name3"].unique():
third_dict = {}
third_dict["name"] = third
third_dict["itemStyle"] = {"color": second_data[second_data["name3"] == third]["color3"].unique()[0]}
third_dict["value"] = 1
second_list.append(third_dict)
second_dict["children"] = second_list

first_list.append(second_dict)
first_dict["children"] = first_list

data.append(first_dict)

**第一层循环:**先取出name1的数据,unique()一下(去掉重复),遍历每个名字。

​ 创建一个字典,里面存放“名字”和“颜色”,

​ 再创建一个列表,用来存放“children”,

​ 筛选出name1的数据,用于下一级循环

第二层循环:(思路和第一层一样)

​ 这里强调的是由于有的数据只有一个children,有的有两个,所以这里判断一下,如果name3为0,即没有第三层,则赋value=1,否则进行第三层循环

第三层循环:(思路和第一层一样)

​ 遍历完之后就要把数据合一起了(本层的数据加到上一层的列表中,上一层的列表赋值到上一层的字典中)

  • Copyrights © 2022-2023 发现美的眼睛
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信