mvp.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. from mysql_db import MysqlDB
  2. from excel_util import ExcelUtil
  3. class Mvp:
  4. """
  5. ce mvp 答题数据统计
  6. 城市特例 北京市,上海市, 重庆市,天津市
  7. """
  8. age_dict = {
  9. '00-04年生': '00后',
  10. '05-09年生': '05后',
  11. '50-59年生': '50后',
  12. '60-69年生': '60后',
  13. '70-74年生': '70后',
  14. '75-79年生': '75后',
  15. '80-84年生': '80后',
  16. '85-89年生': '85后',
  17. '90-94年生': '90后',
  18. '95-99年生': '95后'
  19. }
  20. crowd = ['A', 'B', 'C', 'D', 'E', 'F']
  21. # 获取答题记录中城市列表
  22. sql_1 = 'select city from f_t_daren_score_2 group by city'
  23. # 获取父选项和父题id
  24. sql_2 = 'select a.id, a.content, b.id, b.name from bq_option a left join bq_question b on a.question_id = b.id ' \
  25. 'where a.serial_number = %s and b.serial_number = %s and a.status = b.status = 1 '
  26. # 获取答题人的年龄段集合
  27. sql_4 = 'select nld from f_t_daren_score_2 group by nld'
  28. # 根据城市,年龄段,人群分类统计答题记录数
  29. sql_5 = 'select group_type, COUNT(uuid) from f_t_daren_score_2 where (city = %s or province = %s) and nld ' \
  30. '= %s and uuid in %s group by group_type '
  31. # 根据父选项获取子选项id列表
  32. sql_6 = 'SELECT c.id, c.sub_question_id, c.content FROM bq_sub_option c WHERE c.father_id in (SELECT a.id FROM ' \
  33. 'bq_option a ' \
  34. 'LEFT JOIN bq_question b ON a.question_id = b.id WHERE a.serial_number = %s AND b.serial_number = %s ' \
  35. 'and a.status = 1 and b.status = 1) and c.status = 1 '
  36. # 根据子题id获取包含子题id的测试
  37. sql_7 = 'select group_type from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)'
  38. # 根据子选项id统计答题数
  39. sql_8 = 'SELECT count(1) FROM f_t_daren_score_2 a LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = ' \
  40. 'b.sub_question_id AND (a.score = b.score or a.score = b.sub_option_id) and a.testcase_id = ' \
  41. 'b.testcase_id WHERE b.sub_option_id in %s' \
  42. 'and (a.city = %s or a.province = %s) and a.nld = %s and a.uuid in %s'
  43. # 获取一个uuid下答题的子选项id列表
  44. sql_10 = 'select DISTINCT uuid, GROUP_CONCAT(DISTINCT b.sub_option_id) from f_t_daren_score_2 a left join ' \
  45. 'd_shangju_tiku_02 b on a.sub_question_id = b.sub_question_id and (a.score = b.score or a.score = ' \
  46. 'b.sub_option_id) where a.status = ' \
  47. 'b.status = 1 group by uuid '
  48. # 向表mvp_crowd_info插入数据
  49. sql_11 = 'insert into mvp_crowd_info(age_area, city_name, crowd_type, status) values(%s, %s, %s, 1)'
  50. # 向表mvp_crowd_info_behavior中插入数据
  51. sql_12 = 'insert into mvp_crowd_info_behavior(crowd_info_id, behavioral_interest, standard_value, status) values(' \
  52. '%s, %s, ' \
  53. '%s, 1) '
  54. # 向表mvp_crowd_info_module中插入数据
  55. sql_13 = 'insert into mvp_crowd_info_module(crowd_info_id, module_name, standard_value, status) values (%s, %s, ' \
  56. '%s, 1) '
  57. sql_14 = 'select a.id, a.age_area, a.city_name, a.crowd_type from mvp_crowd_info a where a.status = 1'
  58. def __init__(self, path=None):
  59. self.shangju_db = MysqlDB('shangju')
  60. self.marketing_db = MysqlDB('bi_report')
  61. # self.shangju_db.truncate('mvp_standard_score')
  62. self.tag_data = ExcelUtil(file_name=path).init_mvp_data()
  63. self.crowd_info = ExcelUtil(file_name=path, sheet_name='选项-人群分类对应表').init_crowd_info()
  64. self.citys = self.init_city()
  65. self.age = self.init_age()
  66. self.people_sub_option_ids = self.marketing_db.select(self.sql_10)
  67. self.crowd_contain_sub_option_ids = self.get_crowd_contain_sub_option_ids()
  68. self.module_scores = ExcelUtil(file_name='set-behavior-tag.xlsx', sheet_name='算法关系表').init_module_info()
  69. # self.scores_tag = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='行为').init_scores()
  70. # self.score_module = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='模块').init_scores()
  71. self.scores_tag = None
  72. self.score_module = None
  73. def close(self):
  74. self.shangju_db.close()
  75. self.marketing_db.close()
  76. def init_city(self):
  77. """
  78. 获取答题数据中的城市。
  79. :return:
  80. """
  81. citys = ['宁波市', '上海市', '苏州市', '无锡市', '宁波市']
  82. # citys_info = self.marketing_db.select(self.sql_1)
  83. # citys.extend([x[0] for x in citys_info if x[0] is not None])
  84. return citys
  85. def query_behavioral_info(self, city=None, age=None, crowd=None):
  86. """
  87. 查询行为兴趣信息
  88. :return:
  89. """
  90. # datas = []
  91. # for key in self.tag_data.keys():
  92. # values = self.tag_data[key]
  93. # for value in values:
  94. # question = value[0].split('-')[0]
  95. # option = value[0].split('-')[1]
  96. # corr = value[1]
  97. # data = self.shangju_db.select(self.sql_2, [option, question])
  98. # if len(data) > 0:
  99. # print([question, option, data[0][3], data[0][1], key, corr])
  100. # datas.append([question, option, data[0][3], data[0][1], key, corr])
  101. # self.shangju_db.truncate('mvp_question_classification')
  102. # self.shangju_db.add_some(self.sql_3, datas)
  103. scores_behavioral = self.city_age_crowd(city, age, crowd)
  104. # scores_module = self.module_score(crowd, city, age, scores_behavioral['score'])
  105. # result = {'行为兴趣分值': scores_behavioral['score'], '模块分值': scores_module}
  106. print('update finished!!!')
  107. return scores_behavioral
  108. def module_score(self, crowd, city, age, scores):
  109. """
  110. 模块分数计算
  111. 城市 年龄 人群分类 模块名称 分数
  112. :return:
  113. """
  114. behavioral_score = scores['用户画像-行为兴趣']
  115. modules = self.module_scores[crowd]
  116. result = []
  117. for key in modules.keys():
  118. values = modules[key]
  119. module_name = key
  120. score = 0
  121. for value in values:
  122. behavioral_name = value[0]
  123. weight = float(value[2])
  124. standard_score = [x[4] for x in behavioral_score if x[2] == behavioral_name]
  125. if len(standard_score) > 0:
  126. score += standard_score[0] * weight
  127. result.append([city, age, crowd, module_name, score])
  128. return result
  129. # def insert_data(self, scores_behavioral, scores_module):
  130. def insert(self):
  131. """
  132. 计算数据写入数据库中,供接口查看
  133. :return:
  134. """
  135. infos = []
  136. for city in ['上海市', '宁波市', '苏州市', '杭州市', ' 无锡市']:
  137. for age in ['50-59年生', '60-69年生', '70-74年生', '75-79年生', '80-84年生', '85-89年生', '90-94年生', '95-99年生', '00'
  138. '-04年生',
  139. '05-09年生']:
  140. for c_type in ['A', 'B', 'C', 'D', 'E', 'F']:
  141. age_area = self.age_dict.get(age)
  142. if age_area:
  143. infos.append([age_area, city, c_type])
  144. self.shangju_db.add_some(self.sql_11, infos)
  145. def query_data(self):
  146. ids = self.shangju_db.select(self.sql_14)
  147. return ids
  148. def shanghai_85_module_score_insert(self):
  149. """
  150. 上海市,85后模块分数计算
  151. :return:
  152. """
  153. result = []
  154. for crowd in self.crowd:
  155. modules = self.module_scores[crowd]
  156. for key in modules.keys():
  157. values = modules[key]
  158. module_name = key
  159. score = 0
  160. for value in values:
  161. behavioral_name = value[0]
  162. weight = float(value[2])
  163. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  164. standard_score = float(value[1])
  165. if standard_score is not None:
  166. score += standard_score * weight
  167. result.append(['上海市', '85后', crowd, module_name, score])
  168. return {'score': result, 'data': self.module_scores}
  169. def tag_module_score_insert(self):
  170. """
  171. 标签模块分数写入数据库
  172. :return:
  173. """
  174. ids = self.query_data()
  175. insert_data = []
  176. insert_data_1 = []
  177. for tag, module in zip(self.scores_tag, self.score_module):
  178. city = tag[0]
  179. age = tag[1]
  180. crowd = tag[2]
  181. tag_name = tag[3]
  182. tag_score = tag[4]
  183. city_2 = module[0]
  184. age_2 = module[1]
  185. crowd_2 = module[2]
  186. module_name_2 = module[3]
  187. module_score_2 = module[4]
  188. for id in ids:
  189. city_1 = id[2]
  190. age_1 = id[1]
  191. crowd_1 = id[3]
  192. id_1 = id[0]
  193. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  194. insert_data.append([id_1, tag_name, tag_score])
  195. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  196. insert_data_1.append([id_1, module_name_2, module_score_2])
  197. self.shangju_db.add_some(self.sql_12, insert_data)
  198. self.shangju_db.add_some(self.sql_13, insert_data_1)
  199. def init_age(self):
  200. """
  201. 获取答题数据中的年龄
  202. """
  203. age_info = self.marketing_db.select(self.sql_4)
  204. # print([x[0] for x in age_info])
  205. return [x[0] for x in age_info if x[0] is not None]
  206. def city_age_crowd(self, city=None, age=None, crowd=None):
  207. data_start = []
  208. result = []
  209. module_scores = []
  210. if city is not None and age is not None and crowd is not None:
  211. print('获取指定城市,年龄段,人群类型的数据...')
  212. people_uuids = self.get_people_uuid_by_type(crowd)
  213. if len(people_uuids) > 0:
  214. print('{}-{}-{}'.format(city, age, crowd))
  215. datas = self.behavior_tag_init(city, age, people_uuids)
  216. data_start.append(datas)
  217. result.extend(self.calculation_standard_score(datas, city, age, crowd))
  218. module_scores.extend(self.module_score(crowd, city, age, result))
  219. pass
  220. else:
  221. print('获取所有case的数据...')
  222. # for city in self.citys:
  223. # for city in [city]:
  224. for age in self.age:
  225. for crowd_type in self.crowd:
  226. if age == '85-89年生' and city == '上海市':
  227. print('上海市85后数据导入人工值,无需计算...')
  228. pass
  229. else:
  230. # print(' {}{}'.format(city, age))
  231. people_uuids = self.get_people_uuid_by_type(crowd_type)
  232. if len(people_uuids) > 0:
  233. print('{}-{}-{}'.format(city, age, crowd_type))
  234. datas = self.behavior_tag_init(city, age, people_uuids)
  235. data_start.append(datas)
  236. result.extend(self.calculation_standard_score(datas, city, age, crowd_type))
  237. module_scores.extend(self.module_score(crowd_type, city, age, result))
  238. # return result
  239. # data_list = []
  240. # for e in data_start:
  241. # for key in e.keys():
  242. # values = e[key]
  243. # for sub_e in values:
  244. # ele = [key]
  245. # ele.extend(sub_e)
  246. # data_list.append(ele)
  247. # pass
  248. return {'tag_score': result, 'module_score': module_scores}
  249. # return {'score': result, 'data': data_list}
  250. def behavior_tag_init(self, city, age, people_uuids):
  251. result = {}
  252. self.group_type_count = self.marketing_db.select(self.sql_5, [city, city, age, people_uuids])
  253. # 表名
  254. for key in self.tag_data:
  255. values = self.tag_data[key]
  256. result_sub = {}
  257. # 标签
  258. for key_tag_name in values.keys():
  259. questions = values[key_tag_name]
  260. elements = []
  261. for value in questions:
  262. question = value[0].split('-')[0]
  263. option = value[0].split('-')[1]
  264. corr = value[1]
  265. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  266. if fm == 0:
  267. c = 0
  268. else:
  269. c = fz / fm
  270. elements.append([question, option, corr, fz, fm, c])
  271. result_sub[key_tag_name] = elements
  272. result[key] = self.indicator_calculation_d_e(result_sub)
  273. return result
  274. def molecular_value(self, queston, option, city, age, people_uuids):
  275. # 获取当前父选项包含的子选项id和子题id列表
  276. result = self.shangju_db.select(self.sql_6, [option, queston])
  277. sub_option_ids = []
  278. group_types = []
  279. for rt in result:
  280. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  281. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  282. for g_t in grouptypes:
  283. if g_t[0] not in group_types:
  284. group_types.append(g_t[0])
  285. sub_option_ids.append(sub_option_id)
  286. # 计算子选项在答题记录中的点击数
  287. sub_options_count = 0
  288. if len(sub_option_ids) > 0:
  289. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, city, city, age, people_uuids])
  290. sub_options_count = result_1[0][0]
  291. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  292. denominator_value = 0
  293. for info in self.group_type_count:
  294. if info[0] in group_types:
  295. denominator_value += info[1]
  296. return sub_options_count, denominator_value
  297. def indicator_calculation_d_e(self, data):
  298. result = {}
  299. for key in data.keys():
  300. values = data[key]
  301. c_list = []
  302. for x in values:
  303. _x = x[5]
  304. if _x is not None and x != 0:
  305. c_list.append(_x)
  306. fm_list = [x[4] for x in values]
  307. sum_c = sum(fm_list)
  308. if len(c_list) == 0:
  309. min_c = 0
  310. else:
  311. min_c = min(c_list)
  312. elements = []
  313. for value in values:
  314. _value = []
  315. c = value[5]
  316. if sum_c == 0:
  317. d = 0
  318. else:
  319. d = c / sum_c
  320. e = c - min_c
  321. _value.extend(value)
  322. _value.append(d)
  323. _value.append(e)
  324. elements.append(_value)
  325. result[key] = elements
  326. return result
  327. def calculation_standard_score(self, datas, city, age, crowd_type):
  328. scores = {}
  329. for key_tag_type in datas.keys():
  330. tag_type_data = datas[key_tag_type]
  331. scores_sub = []
  332. for key_tag in tag_type_data.keys():
  333. key_tag_data = tag_type_data[key_tag]
  334. print(key_tag)
  335. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  336. values = [x[5] for x in key_tag_data]
  337. min_c = min(values)
  338. f = min_c
  339. for value in key_tag_data:
  340. print(' {}'.format(value))
  341. if value[2] is not None and value[7] is not None:
  342. f += float(value[2] * value[7])
  343. print(' 标准分:{}'.format(f))
  344. scores_sub.append([city, age, key_tag, crowd_type, f])
  345. scores[key_tag_type] = scores_sub
  346. # self.shangju_db.add_some(self.sql_9, scores)
  347. return scores
  348. def get_crowd_people(self):
  349. result = {}
  350. for type in self.crowd:
  351. uuids = self.get_people_uuid_by_type(type)
  352. result[type] = len(uuids)
  353. return result
  354. def get_people_uuid_by_type(self, type):
  355. uuids = []
  356. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  357. for people in self.people_sub_option_ids:
  358. uuid = people[0]
  359. sub_option_ids = list(map(int, str(people[1]).split(',')))
  360. # list(set(a).intersection(set(b)))
  361. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  362. uuids.append(uuid)
  363. return uuids
  364. def get_crowd_contain_sub_option_ids(self):
  365. """
  366. 获取ABCDEF人群包含的子选项id
  367. :return:
  368. """
  369. infos = {}
  370. for key in self.crowd_info.keys():
  371. values = self.crowd_info[key]
  372. sub_option_ids = []
  373. for value in values:
  374. if value is not None:
  375. vals = str(value).split('-')
  376. option, question = vals[1], vals[0]
  377. query_result = self.shangju_db.select(self.sql_6, [option, question])
  378. for qr in query_result:
  379. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  380. sub_option_ids.append(int(sub_option_id))
  381. infos[key] = sub_option_ids
  382. print(infos)
  383. return infos