mvp.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. from mysql_db import MysqlDB
  2. from excel_util import ExcelUtil
  3. import time
  4. class Mvp:
  5. """
  6. ce mvp 答题数据统计
  7. 城市特例 北京市,上海市, 重庆市,天津市
  8. """
  9. age_dict = {
  10. '00-04年生': '00后',
  11. '05-09年生': '05后',
  12. '50-59年生': '50后',
  13. '60-69年生': '60后',
  14. '70-74年生': '70后',
  15. '75-79年生': '75后',
  16. '80-84年生': '80后',
  17. '85-89年生': '85后',
  18. '90-94年生': '90后',
  19. '95-99年生': '95后'
  20. }
  21. tag_table = {
  22. '用户画像-审美偏好': ['mvp_crowd_info_aesthetic_preference', 'aesthetic_preference'],
  23. '用户画像-行为兴趣': ['mvp_crowd_info_behavior', 'behavioral_interest'],
  24. '用户画像-观念': ['mvp_crowd_info_consumer_concept', ''],
  25. '用户画像-消费特征': ['mvp_crowd_info_consumer_structure', ''],
  26. '空间需求图谱-功能关联': ['mvp_crowd_info_functional_module', ''],
  27. '性别比例': ['mvp_crowd_info_gender_rate', ''],
  28. '用户画像-生活方式': ['mvp_crowd_info_life_style', ''],
  29. '人群占比': ['mvp_crowd_info_rate', ''],
  30. '用户画像-社交模式': ['mvp_crowd_info_social_mode', ''],
  31. '用户画像-行业': ['mvp_crowd_info_trade', ''],
  32. '用户画像-出行方式': ['mvp_crowd_info_trip_mode', ''],
  33. '空间需求图谱-基础模块分值': ['mvp_innovate_space_base_module', ''],
  34. '空间需求图谱-色相': ['mvp_innovate_space_color_prefer', 'color'],
  35. '空间需求图谱-精装关注点': ['mvp_innovate_space_hardcover_focus', 'hardcover_focus'],
  36. '空间需求图谱-色调': ['mvp_innovate_space_hue_prefer', 'hue'],
  37. '空间需求图谱-单品偏好': ['mvp_innovate_space_item_preference', 'item_preference'],
  38. '空间需求图谱-材质': ['mvp_innovate_space_material_prefer', 'material'],
  39. '空间需求图谱-空间特性偏好': ['mvp_innovate_space_space_prefer', 'space_preference'],
  40. '空间需求图谱-空间拓普图': ['mvp_innovate_space_space_top', ''],
  41. '模块分数': ['mvp_crowd_info_module', 'module_name']
  42. }
  43. base_insert_sql = 'insert into {}(crowd_info_id, {}, standard_value, status) values(%s, %s, %s, '\
  44. '1) '
  45. def get_table_name(self, name):
  46. """
  47. 获取表名
  48. :param name:
  49. :return:
  50. """
  51. params = self.tag_table.get(name)
  52. if params:
  53. return self.tag_table.get(name)[0]
  54. def get_insert_sql(self, tag_type_name):
  55. """
  56. 根据标签分类名称获取相应表的插入sql
  57. :param tag_type_name:
  58. :return:
  59. """
  60. params = self.tag_table.get(tag_type_name)
  61. if params:
  62. return self.base_insert_sql.format(params[0], [1])
  63. crowd = ['A', 'B', 'C', 'D', 'E', 'F']
  64. # 获取答题记录中城市列表
  65. sql_1 = 'select city from f_t_daren_score_2 group by city'
  66. # 获取父选项和父题id
  67. 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 ' \
  68. 'where a.serial_number = %s and b.serial_number = %s and a.status = b.status = 1 '
  69. # 获取答题人的年龄段集合
  70. sql_4 = 'select nld from f_t_daren_score_2 group by nld'
  71. # 根据城市,年龄段,人群分类统计答题记录数
  72. sql_5 = 'select group_type, COUNT(uuid) from f_t_daren_score_2 where (city = %s or province = %s) and nld ' \
  73. '= %s and uuid in %s group by group_type '
  74. # 根据父选项获取子选项id列表
  75. 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 ' \
  76. 'bq_option a ' \
  77. 'LEFT JOIN bq_question b ON a.question_id = b.id WHERE a.serial_number = %s AND b.serial_number = %s ' \
  78. 'and a.status = 1 and b.status = 1) and c.status = 1 '
  79. # 根据子题id获取包含子题id的测试
  80. sql_7 = 'select group_type from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)'
  81. # 根据子选项id统计答题数
  82. sql_8 = 'SELECT count(1) FROM f_t_daren_score_2 a LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = ' \
  83. 'b.sub_question_id AND (a.score = b.score or a.score = b.sub_option_id) and a.testcase_id = ' \
  84. 'b.testcase_id WHERE b.sub_option_id in %s' \
  85. 'and (a.city = %s or a.province = %s) and a.nld = %s and a.uuid in %s'
  86. # 获取一个uuid下答题的子选项id列表
  87. sql_10 = 'select DISTINCT uuid, GROUP_CONCAT(DISTINCT b.sub_option_id) from f_t_daren_score_2 a left join ' \
  88. 'd_shangju_tiku_02 b on a.sub_question_id = b.sub_question_id and (a.score = b.score or a.score = ' \
  89. 'b.sub_option_id) where a.status = ' \
  90. 'b.status = 1 group by uuid '
  91. # 向表mvp_crowd_info插入数据
  92. sql_11 = 'insert into mvp_crowd_info(age_area, city_name, crowd_type, status) values(%s, %s, %s, 1)'
  93. # 向表mvp_crowd_info_behavior中插入数据
  94. sql_12 = 'insert into mvp_crowd_info_behavior(crowd_info_id, behavioral_interest, standard_value, status) values(' \
  95. '%s, %s, ' \
  96. '%s, 1) '
  97. # 向表mvp_crowd_info_module中插入数据
  98. sql_13 = 'insert into mvp_crowd_info_module(crowd_info_id, module_name, standard_value, status) values (%s, %s, ' \
  99. '%s, 1) '
  100. sql_14 = 'select a.id, a.age_area, a.city_name, a.crowd_type from mvp_crowd_info a where a.status = 1'
  101. def __init__(self, path=None):
  102. self.shangju_db = MysqlDB('shangju')
  103. self.marketing_db = MysqlDB('bi_report')
  104. # self.shangju_db.truncate('mvp_standard_score')
  105. self.tag_data = ExcelUtil(file_name=path).init_mvp_data()
  106. self.crowd_info = ExcelUtil(file_name=path, sheet_name='选项-人群分类对应表').init_crowd_info()
  107. self.citys = self.init_city()
  108. self.age = self.init_age()
  109. self.people_sub_option_ids = self.marketing_db.select(self.sql_10)
  110. self.crowd_contain_sub_option_ids = self.get_crowd_contain_sub_option_ids()
  111. self.module_scores = ExcelUtil(file_name='set-behavior-tag.xlsx', sheet_name='算法关系表').init_module_info()
  112. # self.scores_tag = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='行为').init_scores()
  113. # self.score_module = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='模块').init_scores()
  114. self.scores_tag = None
  115. self.score_module = None
  116. def close(self):
  117. self.shangju_db.close()
  118. self.marketing_db.close()
  119. def init_city(self):
  120. """
  121. 获取答题数据中的城市。
  122. :return:
  123. """
  124. citys = ['宁波市', '上海市', '苏州市', '无锡市', '宁波市']
  125. # citys_info = self.marketing_db.select(self.sql_1)
  126. # citys.extend([x[0] for x in citys_info if x[0] is not None])
  127. return citys
  128. def query_behavioral_info(self, city=None, age=None, crowd=None):
  129. """
  130. 查询行为兴趣信息
  131. :return:
  132. """
  133. # datas = []
  134. # for key in self.tag_data.keys():
  135. # values = self.tag_data[key]
  136. # for value in values:
  137. # question = value[0].split('-')[0]
  138. # option = value[0].split('-')[1]
  139. # corr = value[1]
  140. # data = self.shangju_db.select(self.sql_2, [option, question])
  141. # if len(data) > 0:
  142. # print([question, option, data[0][3], data[0][1], key, corr])
  143. # datas.append([question, option, data[0][3], data[0][1], key, corr])
  144. # self.shangju_db.truncate('mvp_question_classification')
  145. # self.shangju_db.add_some(self.sql_3, datas)
  146. scores_behavioral = self.city_age_crowd(city, age, crowd)
  147. # scores_module = self.module_score(crowd, city, age, scores_behavioral['score'])
  148. # result = {'行为兴趣分值': scores_behavioral['score'], '模块分值': scores_module}
  149. print('update finished!!!')
  150. return scores_behavioral
  151. def update_data(self):
  152. """
  153. 定时更新分值
  154. :return:
  155. """
  156. citys = ['上海市', '杭州市', '苏州市', '无锡市', '宁波市']
  157. for city in citys:
  158. result = self.city_age_crowd(city)
  159. self.insert_score_to_db(result)
  160. print('{}数据更新完成...'.format(citys))
  161. print('{}数据关系完成...'.format(time.time()))
  162. def insert_score_to_db(self, scores):
  163. """
  164. 行为、模块分数写入数据库
  165. :return:
  166. """
  167. ids = self.query_data()
  168. behavior_score = scores['behavior_score']
  169. module_score = scores['module_score']
  170. module_insert_sql = self.get_insert_sql('模块分数')
  171. if module_insert_sql:
  172. module_insert_data = []
  173. for module in module_score:
  174. city_2 = module[0]
  175. age_2 = module[1]
  176. crowd_2 = module[2]
  177. module_name_2 = module[3]
  178. module_score_2 = module[4]
  179. for id in ids:
  180. city_1 = id[2]
  181. age_1 = id[1]
  182. crowd_1 = id[3]
  183. id_1 = id[0]
  184. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  185. module_insert_data.append([id_1, module_name_2, module_score_2])
  186. # 先清空之前的数据
  187. table_name = self.get_table_name('模块分数')
  188. if table_name:
  189. self.shangju_db.truncate(table_name)
  190. self.shangju_db.add_some(module_insert_sql, module_insert_data)
  191. print('模块分数更新完成...')
  192. for b_score in behavior_score:
  193. for key in b_score.keys():
  194. insert_sql = self.get_insert_sql(key)
  195. if insert_sql:
  196. insert_data = []
  197. score = b_score[key]
  198. for data in score:
  199. city = data[0]
  200. age = data[1]
  201. tag_name = data[2]
  202. crowd = data[3]
  203. tag_score = data[4]
  204. for id in ids:
  205. city_1 = id[2]
  206. age_1 = id[1]
  207. crowd_1 = id[3]
  208. id_1 = id[0]
  209. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  210. insert_data.append([id_1, tag_name, tag_score])
  211. if len(insert_data) > 0:
  212. table_name = self.get_table_name(key)
  213. if table_name:
  214. self.shangju_db.truncate(table_name)
  215. self.shangju_db.add_some(insert_sql, insert_data)
  216. else:
  217. print('未找到对应的表,数据无法插入...')
  218. print('行为分数更新完成...')
  219. def module_score(self, crowd, city, age, scores):
  220. """
  221. 模块分数计算
  222. 城市 年龄 人群分类 模块名称 分数
  223. :return:
  224. """
  225. import json
  226. print(json.dumps(scores, ensure_ascii=False))
  227. modules = self.module_scores[crowd]
  228. result = []
  229. for key in modules.keys():
  230. values = modules[key]
  231. module_name = key
  232. score = 0
  233. for value in values:
  234. behavioral_name = value[0]
  235. weight = float(value[2])
  236. standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  237. if len(standard_score) > 0:
  238. score += standard_score[0] * weight
  239. result.append([city, age, crowd, module_name, score])
  240. return result
  241. # def insert_data(self, scores_behavioral, scores_module):
  242. def insert(self):
  243. """
  244. 计算数据写入数据库中,供接口查看
  245. :return:
  246. """
  247. infos = []
  248. for city in ['上海市', '宁波市', '苏州市', '杭州市', ' 无锡市']:
  249. for age in ['50-59年生', '60-69年生', '70-74年生', '75-79年生', '80-84年生', '85-89年生', '90-94年生', '95-99年生', '00'
  250. '-04年生',
  251. '05-09年生', '10-14年生', '15-19年生']:
  252. for c_type in ['A', 'B', 'C', 'D', 'E', 'F']:
  253. age_area = self.age_dict.get(age)
  254. if age_area:
  255. infos.append([age_area, city, c_type])
  256. self.shangju_db.add_some(self.sql_11, infos)
  257. def query_data(self):
  258. ids = self.shangju_db.select(self.sql_14)
  259. return ids
  260. def shanghai_85_module_score_insert(self):
  261. """
  262. 上海市,85后模块分数计算
  263. :return:
  264. """
  265. result = []
  266. for crowd in self.crowd:
  267. modules = self.module_scores[crowd]
  268. for key in modules.keys():
  269. values = modules[key]
  270. module_name = key
  271. score = 0
  272. for value in values:
  273. behavioral_name = value[0]
  274. weight = float(value[2])
  275. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  276. standard_score = float(value[1])
  277. if standard_score is not None:
  278. score += standard_score * weight
  279. result.append(['上海市', '85后', crowd, module_name, score])
  280. return {'score': result, 'data': self.module_scores}
  281. def tag_module_score_insert(self):
  282. """
  283. 标签模块分数写入数据库
  284. :return:
  285. """
  286. ids = self.query_data()
  287. insert_data = []
  288. insert_data_1 = []
  289. for tag, module in zip(self.scores_tag, self.score_module):
  290. city = tag[0]
  291. age = tag[1]
  292. crowd = tag[2]
  293. tag_name = tag[3]
  294. tag_score = tag[4]
  295. city_2 = module[0]
  296. age_2 = module[1]
  297. crowd_2 = module[2]
  298. module_name_2 = module[3]
  299. module_score_2 = module[4]
  300. for id in ids:
  301. city_1 = id[2]
  302. age_1 = id[1]
  303. crowd_1 = id[3]
  304. id_1 = id[0]
  305. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  306. insert_data.append([id_1, tag_name, tag_score])
  307. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  308. insert_data_1.append([id_1, module_name_2, module_score_2])
  309. self.shangju_db.add_some(self.sql_12, insert_data)
  310. self.shangju_db.add_some(self.sql_13, insert_data_1)
  311. def init_age(self):
  312. """
  313. 获取答题数据中的年龄
  314. """
  315. age_info = self.marketing_db.select(self.sql_4)
  316. # print([x[0] for x in age_info])
  317. return [x[0] for x in age_info if x[0] is not None]
  318. def city_age_crowd(self, city=None, age=None, crowd=None):
  319. data_start = []
  320. result = []
  321. module_scores = []
  322. if city is not None and age is not None and crowd is not None:
  323. print('获取指定城市,年龄段,人群类型的数据...')
  324. people_uuids = self.get_people_uuid_by_type(crowd)
  325. behavior_data = None
  326. if len(people_uuids) > 0:
  327. print('{}-{}-{}'.format(city, age, crowd))
  328. datas = self.behavior_tag_init(city, age, people_uuids)
  329. data_start.append(datas)
  330. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd)
  331. result.append(all_data)
  332. behavior_data = behavior_data_1
  333. if behavior_data:
  334. module_scores.extend(self.module_score(crowd, city, age, behavior_data))
  335. else:
  336. print('获取所有case的数据...')
  337. # for city in self.citys:
  338. # for city in [city]:
  339. for age in self.age:
  340. for crowd_type in self.crowd:
  341. if age == '85-89年生' and city == '上海市':
  342. print('上海市85后数据导入人工值,无需计算...')
  343. pass
  344. else:
  345. # print(' {}{}'.format(city, age))
  346. people_uuids = self.get_people_uuid_by_type(crowd_type)
  347. behavior_data = None
  348. if len(people_uuids) > 0:
  349. print('{}-{}-{}'.format(city, age, crowd_type))
  350. datas = self.behavior_tag_init(city, age, people_uuids)
  351. data_start.append(datas)
  352. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd_type)
  353. result.append(all_data)
  354. behavior_data = behavior_data_1
  355. if behavior_data:
  356. module_scores.extend(self.module_score(crowd_type, city, age, behavior_data))
  357. # return result
  358. # data_list = []
  359. # for e in data_start:
  360. # for key in e.keys():
  361. # values = e[key]
  362. # for sub_e in values:
  363. # ele = [key]
  364. # ele.extend(sub_e)
  365. # data_list.append(ele)
  366. # pass
  367. return {'behavior_score': result, 'module_score': module_scores}
  368. # return {'score': result, 'data': data_list}
  369. def behavior_tag_init(self, city, age, people_uuids):
  370. result = {}
  371. self.group_type_count = self.marketing_db.select(self.sql_5, [city, city, age, people_uuids])
  372. # 表名
  373. for key in self.tag_data:
  374. values = self.tag_data[key]
  375. result_sub = {}
  376. # 标签
  377. for key_tag_name in values.keys():
  378. questions = values[key_tag_name]
  379. elements = []
  380. for value in questions:
  381. question = value[0].split('-')[0]
  382. option = value[0].split('-')[1]
  383. corr = value[1]
  384. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  385. if fm == 0:
  386. c = 0
  387. else:
  388. c = fz / fm
  389. elements.append([question, option, corr, fz, fm, c])
  390. result_sub[key_tag_name] = elements
  391. result[key] = self.indicator_calculation_d_e(result_sub)
  392. return result
  393. def molecular_value(self, queston, option, city, age, people_uuids):
  394. # 获取当前父选项包含的子选项id和子题id列表
  395. result = self.shangju_db.select(self.sql_6, [option, queston])
  396. sub_option_ids = []
  397. group_types = []
  398. for rt in result:
  399. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  400. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  401. for g_t in grouptypes:
  402. if g_t[0] not in group_types:
  403. group_types.append(g_t[0])
  404. sub_option_ids.append(sub_option_id)
  405. # 计算子选项在答题记录中的点击数
  406. sub_options_count = 0
  407. if len(sub_option_ids) > 0:
  408. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, city, city, age, people_uuids])
  409. sub_options_count = result_1[0][0]
  410. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  411. denominator_value = 0
  412. for info in self.group_type_count:
  413. if info[0] in group_types:
  414. denominator_value += info[1]
  415. return sub_options_count, denominator_value
  416. def indicator_calculation_d_e(self, data):
  417. result = {}
  418. for key in data.keys():
  419. values = data[key]
  420. c_list = []
  421. for x in values:
  422. _x = x[5]
  423. if _x is not None and x != 0:
  424. c_list.append(_x)
  425. fm_list = [x[4] for x in values]
  426. sum_c = sum(fm_list)
  427. if len(c_list) == 0:
  428. min_c = 0
  429. else:
  430. min_c = min(c_list)
  431. elements = []
  432. for value in values:
  433. _value = []
  434. c = value[5]
  435. if sum_c == 0:
  436. d = 0
  437. else:
  438. d = c / sum_c
  439. e = c - min_c
  440. _value.extend(value)
  441. _value.append(d)
  442. _value.append(e)
  443. elements.append(_value)
  444. result[key] = elements
  445. return result
  446. def calculation_standard_score(self, datas, city, age, crowd_type):
  447. scores = {}
  448. for key_tag_type in datas.keys():
  449. print(key_tag_type)
  450. tag_type_data = datas[key_tag_type]
  451. scores_sub = []
  452. for key_tag in tag_type_data.keys():
  453. key_tag_data = tag_type_data[key_tag]
  454. print(key_tag)
  455. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  456. values = [x[5] for x in key_tag_data]
  457. min_c = min(values)
  458. f = min_c
  459. for value in key_tag_data:
  460. print(' {}'.format(value))
  461. if value[2] is not None and value[7] is not None:
  462. f += float(value[2] * value[7])
  463. print(' 标准分:{}'.format(f))
  464. scores_sub.append([city, age, key_tag, crowd_type, f])
  465. scores[key_tag_type] = scores_sub
  466. # self.shangju_db.add_some(self.sql_9, scores)
  467. return scores, scores['用户画像-行为兴趣']
  468. def get_crowd_people(self):
  469. result = {}
  470. for type in self.crowd:
  471. uuids = self.get_people_uuid_by_type(type)
  472. result[type] = len(uuids)
  473. return result
  474. def get_people_uuid_by_type(self, type):
  475. uuids = []
  476. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  477. for people in self.people_sub_option_ids:
  478. uuid = people[0]
  479. sub_option_ids = list(map(int, str(people[1]).split(',')))
  480. # list(set(a).intersection(set(b)))
  481. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  482. uuids.append(uuid)
  483. return uuids
  484. def get_crowd_contain_sub_option_ids(self):
  485. """
  486. 获取ABCDEF人群包含的子选项id
  487. :return:
  488. """
  489. infos = {}
  490. for key in self.crowd_info.keys():
  491. values = self.crowd_info[key]
  492. sub_option_ids = []
  493. for value in values:
  494. if value is not None:
  495. vals = str(value).split('-')
  496. option, question = vals[1], vals[0]
  497. query_result = self.shangju_db.select(self.sql_6, [option, question])
  498. for qr in query_result:
  499. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  500. sub_option_ids.append(int(sub_option_id))
  501. infos[key] = sub_option_ids
  502. print(infos)
  503. return infos
  504. if __name__ == '__main__':
  505. print('{}哈{}ha%s'.format('1', '2'))