long_lat.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. import datetime
  18. import random
  19. import geohash
  20. import pandas as pd
  21. from sqlalchemy import DateTime, Float, String
  22. from superset import db
  23. from superset.models.slice import Slice
  24. from superset.utils import core as utils
  25. from .helpers import (
  26. get_example_data,
  27. get_slice_json,
  28. merge_slice,
  29. misc_dash_slices,
  30. TBL,
  31. )
  32. def load_long_lat_data(only_metadata: bool = False, force: bool = False) -> None:
  33. """Loading lat/long data from a csv file in the repo"""
  34. tbl_name = "long_lat"
  35. database = utils.get_example_database()
  36. table_exists = database.has_table_by_name(tbl_name)
  37. if not only_metadata and (not table_exists or force):
  38. data = get_example_data("san_francisco.csv.gz", make_bytes=True)
  39. pdf = pd.read_csv(data, encoding="utf-8")
  40. start = datetime.datetime.now().replace(
  41. hour=0, minute=0, second=0, microsecond=0
  42. )
  43. pdf["datetime"] = [
  44. start + datetime.timedelta(hours=i * 24 / (len(pdf) - 1))
  45. for i in range(len(pdf))
  46. ]
  47. pdf["occupancy"] = [random.randint(1, 6) for _ in range(len(pdf))]
  48. pdf["radius_miles"] = [random.uniform(1, 3) for _ in range(len(pdf))]
  49. pdf["geohash"] = pdf[["LAT", "LON"]].apply(lambda x: geohash.encode(*x), axis=1)
  50. pdf["delimited"] = pdf["LAT"].map(str).str.cat(pdf["LON"].map(str), sep=",")
  51. pdf.to_sql( # pylint: disable=no-member
  52. tbl_name,
  53. database.get_sqla_engine(),
  54. if_exists="replace",
  55. chunksize=500,
  56. dtype={
  57. "longitude": Float(),
  58. "latitude": Float(),
  59. "number": Float(),
  60. "street": String(100),
  61. "unit": String(10),
  62. "city": String(50),
  63. "district": String(50),
  64. "region": String(50),
  65. "postcode": Float(),
  66. "id": String(100),
  67. "datetime": DateTime(),
  68. "occupancy": Float(),
  69. "radius_miles": Float(),
  70. "geohash": String(12),
  71. "delimited": String(60),
  72. },
  73. index=False,
  74. )
  75. print("Done loading table!")
  76. print("-" * 80)
  77. print("Creating table reference")
  78. obj = db.session.query(TBL).filter_by(table_name=tbl_name).first()
  79. if not obj:
  80. obj = TBL(table_name=tbl_name)
  81. obj.main_dttm_col = "datetime"
  82. obj.database = database
  83. db.session.merge(obj)
  84. db.session.commit()
  85. obj.fetch_metadata()
  86. tbl = obj
  87. slice_data = {
  88. "granularity_sqla": "day",
  89. "since": "2014-01-01",
  90. "until": "now",
  91. "viz_type": "mapbox",
  92. "all_columns_x": "LON",
  93. "all_columns_y": "LAT",
  94. "mapbox_style": "mapbox://styles/mapbox/light-v9",
  95. "all_columns": ["occupancy"],
  96. "row_limit": 500000,
  97. }
  98. print("Creating a slice")
  99. slc = Slice(
  100. slice_name="Mapbox Long/Lat",
  101. viz_type="mapbox",
  102. datasource_type="table",
  103. datasource_id=tbl.id,
  104. params=get_slice_json(slice_data),
  105. )
  106. misc_dash_slices.add(slc.slice_name)
  107. merge_slice(slc)