world_bank.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """Loads datasets, dashboards and slices in a new superset instance"""
  18. import json
  19. import os
  20. import textwrap
  21. import pandas as pd
  22. from sqlalchemy import DateTime, String
  23. from sqlalchemy.sql import column
  24. from superset import db
  25. from superset.connectors.sqla.models import SqlMetric
  26. from superset.models.dashboard import Dashboard
  27. from superset.models.slice import Slice
  28. from superset.utils import core as utils
  29. from .helpers import (
  30. config,
  31. EXAMPLES_FOLDER,
  32. get_example_data,
  33. get_slice_json,
  34. merge_slice,
  35. misc_dash_slices,
  36. TBL,
  37. update_slice_ids,
  38. )
  39. def load_world_bank_health_n_pop(
  40. only_metadata=False, force=False
  41. ): # pylint: disable=too-many-locals
  42. """Loads the world bank health dataset, slices and a dashboard"""
  43. tbl_name = "wb_health_population"
  44. database = utils.get_example_database()
  45. table_exists = database.has_table_by_name(tbl_name)
  46. if not only_metadata and (not table_exists or force):
  47. data = get_example_data("countries.json.gz")
  48. pdf = pd.read_json(data)
  49. pdf.columns = [col.replace(".", "_") for col in pdf.columns]
  50. pdf.year = pd.to_datetime(pdf.year)
  51. pdf.to_sql(
  52. tbl_name,
  53. database.get_sqla_engine(),
  54. if_exists="replace",
  55. chunksize=50,
  56. dtype={
  57. "year": DateTime(),
  58. "country_code": String(3),
  59. "country_name": String(255),
  60. "region": String(255),
  61. },
  62. index=False,
  63. )
  64. print("Creating table [wb_health_population] reference")
  65. tbl = db.session.query(TBL).filter_by(table_name=tbl_name).first()
  66. if not tbl:
  67. tbl = TBL(table_name=tbl_name)
  68. tbl.description = utils.readfile(os.path.join(EXAMPLES_FOLDER, "countries.md"))
  69. tbl.main_dttm_col = "year"
  70. tbl.database = database
  71. tbl.filter_select_enabled = True
  72. metrics = [
  73. "sum__SP_POP_TOTL",
  74. "sum__SH_DYN_AIDS",
  75. "sum__SH_DYN_AIDS",
  76. "sum__SP_RUR_TOTL_ZS",
  77. "sum__SP_DYN_LE00_IN",
  78. "sum__SP_RUR_TOTL",
  79. ]
  80. for metric in metrics:
  81. if not any(col.metric_name == metric for col in tbl.metrics):
  82. aggr_func = metric[:3]
  83. col = str(column(metric[5:]).compile(db.engine))
  84. tbl.metrics.append(
  85. SqlMetric(metric_name=metric, expression=f"{aggr_func}({col})")
  86. )
  87. db.session.merge(tbl)
  88. db.session.commit()
  89. tbl.fetch_metadata()
  90. defaults = {
  91. "compare_lag": "10",
  92. "compare_suffix": "o10Y",
  93. "limit": "25",
  94. "granularity_sqla": "year",
  95. "groupby": [],
  96. "metric": "sum__SP_POP_TOTL",
  97. "metrics": ["sum__SP_POP_TOTL"],
  98. "row_limit": config["ROW_LIMIT"],
  99. "since": "2014-01-01",
  100. "until": "2014-01-02",
  101. "time_range": "2014-01-01 : 2014-01-02",
  102. "markup_type": "markdown",
  103. "country_fieldtype": "cca3",
  104. "secondary_metric": {
  105. "aggregate": "SUM",
  106. "column": {
  107. "column_name": "SP_RUR_TOTL",
  108. "optionName": "_col_SP_RUR_TOTL",
  109. "type": "DOUBLE",
  110. },
  111. "expressionType": "SIMPLE",
  112. "hasCustomLabel": True,
  113. "label": "Rural Population",
  114. },
  115. "entity": "country_code",
  116. "show_bubbles": True,
  117. }
  118. print("Creating slices")
  119. slices = [
  120. Slice(
  121. slice_name="Region Filter",
  122. viz_type="filter_box",
  123. datasource_type="table",
  124. datasource_id=tbl.id,
  125. params=get_slice_json(
  126. defaults,
  127. viz_type="filter_box",
  128. date_filter=False,
  129. filter_configs=[
  130. {
  131. "asc": False,
  132. "clearable": True,
  133. "column": "region",
  134. "key": "2s98dfu",
  135. "metric": "sum__SP_POP_TOTL",
  136. "multiple": True,
  137. },
  138. {
  139. "asc": False,
  140. "clearable": True,
  141. "key": "li3j2lk",
  142. "column": "country_name",
  143. "metric": "sum__SP_POP_TOTL",
  144. "multiple": True,
  145. },
  146. ],
  147. ),
  148. ),
  149. Slice(
  150. slice_name="World's Population",
  151. viz_type="big_number",
  152. datasource_type="table",
  153. datasource_id=tbl.id,
  154. params=get_slice_json(
  155. defaults,
  156. since="2000",
  157. viz_type="big_number",
  158. compare_lag="10",
  159. metric="sum__SP_POP_TOTL",
  160. compare_suffix="over 10Y",
  161. ),
  162. ),
  163. Slice(
  164. slice_name="Most Populated Countries",
  165. viz_type="table",
  166. datasource_type="table",
  167. datasource_id=tbl.id,
  168. params=get_slice_json(
  169. defaults,
  170. viz_type="table",
  171. metrics=["sum__SP_POP_TOTL"],
  172. groupby=["country_name"],
  173. ),
  174. ),
  175. Slice(
  176. slice_name="Growth Rate",
  177. viz_type="line",
  178. datasource_type="table",
  179. datasource_id=tbl.id,
  180. params=get_slice_json(
  181. defaults,
  182. viz_type="line",
  183. since="1960-01-01",
  184. metrics=["sum__SP_POP_TOTL"],
  185. num_period_compare="10",
  186. groupby=["country_name"],
  187. ),
  188. ),
  189. Slice(
  190. slice_name="% Rural",
  191. viz_type="world_map",
  192. datasource_type="table",
  193. datasource_id=tbl.id,
  194. params=get_slice_json(
  195. defaults,
  196. viz_type="world_map",
  197. metric="sum__SP_RUR_TOTL_ZS",
  198. num_period_compare="10",
  199. ),
  200. ),
  201. Slice(
  202. slice_name="Life Expectancy VS Rural %",
  203. viz_type="bubble",
  204. datasource_type="table",
  205. datasource_id=tbl.id,
  206. params=get_slice_json(
  207. defaults,
  208. viz_type="bubble",
  209. since="2011-01-01",
  210. until="2011-01-02",
  211. series="region",
  212. limit=0,
  213. entity="country_name",
  214. x="sum__SP_RUR_TOTL_ZS",
  215. y="sum__SP_DYN_LE00_IN",
  216. size="sum__SP_POP_TOTL",
  217. max_bubble_size="50",
  218. adhoc_filters=[
  219. {
  220. "clause": "WHERE",
  221. "expressionType": "SIMPLE",
  222. "filterOptionName": "2745eae5",
  223. "comparator": [
  224. "TCA",
  225. "MNP",
  226. "DMA",
  227. "MHL",
  228. "MCO",
  229. "SXM",
  230. "CYM",
  231. "TUV",
  232. "IMY",
  233. "KNA",
  234. "ASM",
  235. "ADO",
  236. "AMA",
  237. "PLW",
  238. ],
  239. "operator": "not in",
  240. "subject": "country_code",
  241. }
  242. ],
  243. ),
  244. ),
  245. Slice(
  246. slice_name="Rural Breakdown",
  247. viz_type="sunburst",
  248. datasource_type="table",
  249. datasource_id=tbl.id,
  250. params=get_slice_json(
  251. defaults,
  252. viz_type="sunburst",
  253. groupby=["region", "country_name"],
  254. since="2011-01-01",
  255. until="2011-01-01",
  256. ),
  257. ),
  258. Slice(
  259. slice_name="World's Pop Growth",
  260. viz_type="area",
  261. datasource_type="table",
  262. datasource_id=tbl.id,
  263. params=get_slice_json(
  264. defaults,
  265. since="1960-01-01",
  266. until="now",
  267. viz_type="area",
  268. groupby=["region"],
  269. ),
  270. ),
  271. Slice(
  272. slice_name="Box plot",
  273. viz_type="box_plot",
  274. datasource_type="table",
  275. datasource_id=tbl.id,
  276. params=get_slice_json(
  277. defaults,
  278. since="1960-01-01",
  279. until="now",
  280. whisker_options="Min/max (no outliers)",
  281. x_ticks_layout="staggered",
  282. viz_type="box_plot",
  283. groupby=["region"],
  284. ),
  285. ),
  286. Slice(
  287. slice_name="Treemap",
  288. viz_type="treemap",
  289. datasource_type="table",
  290. datasource_id=tbl.id,
  291. params=get_slice_json(
  292. defaults,
  293. since="1960-01-01",
  294. until="now",
  295. viz_type="treemap",
  296. metrics=["sum__SP_POP_TOTL"],
  297. groupby=["region", "country_code"],
  298. ),
  299. ),
  300. Slice(
  301. slice_name="Parallel Coordinates",
  302. viz_type="para",
  303. datasource_type="table",
  304. datasource_id=tbl.id,
  305. params=get_slice_json(
  306. defaults,
  307. since="2011-01-01",
  308. until="2011-01-01",
  309. viz_type="para",
  310. limit=100,
  311. metrics=["sum__SP_POP_TOTL", "sum__SP_RUR_TOTL_ZS", "sum__SH_DYN_AIDS"],
  312. secondary_metric="sum__SP_POP_TOTL",
  313. series="country_name",
  314. ),
  315. ),
  316. ]
  317. misc_dash_slices.add(slices[-1].slice_name)
  318. for slc in slices:
  319. merge_slice(slc)
  320. print("Creating a World's Health Bank dashboard")
  321. dash_name = "World Bank's Data"
  322. slug = "world_health"
  323. dash = db.session.query(Dashboard).filter_by(slug=slug).first()
  324. if not dash:
  325. dash = Dashboard()
  326. dash.published = True
  327. js = textwrap.dedent(
  328. """\
  329. {
  330. "CHART-36bfc934": {
  331. "children": [],
  332. "id": "CHART-36bfc934",
  333. "meta": {
  334. "chartId": 40,
  335. "height": 25,
  336. "sliceName": "Region Filter",
  337. "width": 2
  338. },
  339. "type": "CHART"
  340. },
  341. "CHART-37982887": {
  342. "children": [],
  343. "id": "CHART-37982887",
  344. "meta": {
  345. "chartId": 41,
  346. "height": 25,
  347. "sliceName": "World's Population",
  348. "width": 2
  349. },
  350. "type": "CHART"
  351. },
  352. "CHART-17e0f8d8": {
  353. "children": [],
  354. "id": "CHART-17e0f8d8",
  355. "meta": {
  356. "chartId": 42,
  357. "height": 92,
  358. "sliceName": "Most Populated Countries",
  359. "width": 3
  360. },
  361. "type": "CHART"
  362. },
  363. "CHART-2ee52f30": {
  364. "children": [],
  365. "id": "CHART-2ee52f30",
  366. "meta": {
  367. "chartId": 43,
  368. "height": 38,
  369. "sliceName": "Growth Rate",
  370. "width": 6
  371. },
  372. "type": "CHART"
  373. },
  374. "CHART-2d5b6871": {
  375. "children": [],
  376. "id": "CHART-2d5b6871",
  377. "meta": {
  378. "chartId": 44,
  379. "height": 52,
  380. "sliceName": "% Rural",
  381. "width": 7
  382. },
  383. "type": "CHART"
  384. },
  385. "CHART-0fd0d252": {
  386. "children": [],
  387. "id": "CHART-0fd0d252",
  388. "meta": {
  389. "chartId": 45,
  390. "height": 50,
  391. "sliceName": "Life Expectancy VS Rural %",
  392. "width": 8
  393. },
  394. "type": "CHART"
  395. },
  396. "CHART-97f4cb48": {
  397. "children": [],
  398. "id": "CHART-97f4cb48",
  399. "meta": {
  400. "chartId": 46,
  401. "height": 38,
  402. "sliceName": "Rural Breakdown",
  403. "width": 3
  404. },
  405. "type": "CHART"
  406. },
  407. "CHART-b5e05d6f": {
  408. "children": [],
  409. "id": "CHART-b5e05d6f",
  410. "meta": {
  411. "chartId": 47,
  412. "height": 50,
  413. "sliceName": "World's Pop Growth",
  414. "width": 4
  415. },
  416. "type": "CHART"
  417. },
  418. "CHART-e76e9f5f": {
  419. "children": [],
  420. "id": "CHART-e76e9f5f",
  421. "meta": {
  422. "chartId": 48,
  423. "height": 50,
  424. "sliceName": "Box plot",
  425. "width": 4
  426. },
  427. "type": "CHART"
  428. },
  429. "CHART-a4808bba": {
  430. "children": [],
  431. "id": "CHART-a4808bba",
  432. "meta": {
  433. "chartId": 49,
  434. "height": 50,
  435. "sliceName": "Treemap",
  436. "width": 8
  437. },
  438. "type": "CHART"
  439. },
  440. "COLUMN-071bbbad": {
  441. "children": [
  442. "ROW-1e064e3c",
  443. "ROW-afdefba9"
  444. ],
  445. "id": "COLUMN-071bbbad",
  446. "meta": {
  447. "background": "BACKGROUND_TRANSPARENT",
  448. "width": 9
  449. },
  450. "type": "COLUMN"
  451. },
  452. "COLUMN-fe3914b8": {
  453. "children": [
  454. "CHART-36bfc934",
  455. "CHART-37982887"
  456. ],
  457. "id": "COLUMN-fe3914b8",
  458. "meta": {
  459. "background": "BACKGROUND_TRANSPARENT",
  460. "width": 2
  461. },
  462. "type": "COLUMN"
  463. },
  464. "GRID_ID": {
  465. "children": [
  466. "ROW-46632bc2",
  467. "ROW-3fa26c5d",
  468. "ROW-812b3f13"
  469. ],
  470. "id": "GRID_ID",
  471. "type": "GRID"
  472. },
  473. "HEADER_ID": {
  474. "id": "HEADER_ID",
  475. "meta": {
  476. "text": "World's Bank Data"
  477. },
  478. "type": "HEADER"
  479. },
  480. "ROOT_ID": {
  481. "children": [
  482. "GRID_ID"
  483. ],
  484. "id": "ROOT_ID",
  485. "type": "ROOT"
  486. },
  487. "ROW-1e064e3c": {
  488. "children": [
  489. "COLUMN-fe3914b8",
  490. "CHART-2d5b6871"
  491. ],
  492. "id": "ROW-1e064e3c",
  493. "meta": {
  494. "background": "BACKGROUND_TRANSPARENT"
  495. },
  496. "type": "ROW"
  497. },
  498. "ROW-3fa26c5d": {
  499. "children": [
  500. "CHART-b5e05d6f",
  501. "CHART-0fd0d252"
  502. ],
  503. "id": "ROW-3fa26c5d",
  504. "meta": {
  505. "background": "BACKGROUND_TRANSPARENT"
  506. },
  507. "type": "ROW"
  508. },
  509. "ROW-46632bc2": {
  510. "children": [
  511. "COLUMN-071bbbad",
  512. "CHART-17e0f8d8"
  513. ],
  514. "id": "ROW-46632bc2",
  515. "meta": {
  516. "background": "BACKGROUND_TRANSPARENT"
  517. },
  518. "type": "ROW"
  519. },
  520. "ROW-812b3f13": {
  521. "children": [
  522. "CHART-a4808bba",
  523. "CHART-e76e9f5f"
  524. ],
  525. "id": "ROW-812b3f13",
  526. "meta": {
  527. "background": "BACKGROUND_TRANSPARENT"
  528. },
  529. "type": "ROW"
  530. },
  531. "ROW-afdefba9": {
  532. "children": [
  533. "CHART-2ee52f30",
  534. "CHART-97f4cb48"
  535. ],
  536. "id": "ROW-afdefba9",
  537. "meta": {
  538. "background": "BACKGROUND_TRANSPARENT"
  539. },
  540. "type": "ROW"
  541. },
  542. "DASHBOARD_VERSION_KEY": "v2"
  543. }
  544. """
  545. )
  546. pos = json.loads(js)
  547. update_slice_ids(pos, slices)
  548. dash.dashboard_title = dash_name
  549. dash.position_json = json.dumps(pos, indent=4)
  550. dash.slug = slug
  551. dash.slices = slices[:-1]
  552. db.session.merge(dash)
  553. db.session.commit()