less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

226 líneas
6.8 KiB

  1. import json
  2. import sys
  3. import subprocess
  4. from tqdm import tqdm
  5. config = json.load(open(sys.argv[1]))
  6. if config["mode"] == "points" or config["mode"] == "bounding-boxes":
  7. results = []
  8. for item in config["items"]:
  9. if config["mode"] == "bounding-boxes":
  10. lon0 = item["corner0"][0]
  11. lat0 = item["corner0"][1]
  12. lon1 = item["corner1"][0]
  13. lat1 = item["corner1"][1]
  14. center_lat = (lat0 + lat1) / 2
  15. center_lon = (lon0 + lon1) / 2
  16. elif config["mode"] == "points":
  17. lon0 = -180
  18. lat0 = -90
  19. lon1 = 180
  20. lat1 = 90
  21. center_lat = item["lat"]
  22. center_lon = item["lon"]
  23. path = "../../" + config["directory"] + "/" + item["name"] + ".svg"
  24. CMD = """\
  25. mapshaper -i "{7}" \
  26. -rectangle bbox={0},{1},{2},{3} name=rect \
  27. -clip rect target="{8}" \
  28. -proj crs="+proj=ortho +lon_0={4} +lat_0={5}" target="{8}",rect \
  29. -info target="{8}" \
  30. -o "{6}" target="{8}"
  31. """
  32. file = config["shapefile"]
  33. if "file" in item:
  34. file = item["file"]
  35. try:
  36. prepared = CMD.format(lon0, lat0, lon1, lat1, center_lon, center_lat, path, file, item["name"])
  37. result = subprocess.check_output(
  38. prepared,
  39. shell=True,
  40. stderr=subprocess.STDOUT
  41. )
  42. for line in result.decode("utf-8").split("\n"):
  43. if "Bounds:" in line:
  44. data = [float(x) for x in line[8:].strip().split(",")]
  45. height = data[3] - data[1]
  46. results.append([item["name"], height])
  47. except Exception as e:
  48. print(e.output)
  49. print(result.decode("utf-8"))
  50. print(json.dumps(results))
  51. elif config["mode"] == "filter":
  52. results = []
  53. CMD = (
  54. f"""mapshaper -i {config["shapefile"]} """
  55. f"""-filter "{config["base-filter"]}" """
  56. f"""-o temp.shp"""
  57. )
  58. result = subprocess.check_output(
  59. CMD,
  60. shell=True,
  61. stderr=subprocess.STDOUT
  62. )
  63. for item in config["items"]:
  64. CMD = (
  65. f"""mapshaper -i temp.shp """
  66. f"""-filter "{config["base-filter"]}" """
  67. f"""-filter "{item["filter"]}" """
  68. f"""-simplify interval=1000 """
  69. f"""-info """
  70. )
  71. result = subprocess.check_output(
  72. CMD,
  73. shell=True,
  74. stderr=subprocess.STDOUT
  75. )
  76. found = False
  77. for line in result.decode("utf-8").split("\n"):
  78. if "Bounds:" in line:
  79. coords = list(map(float, line[7:].strip().split(",")))
  80. lat = coords[1] + coords[3]
  81. lat /= 2
  82. lon = coords[0] + coords[2]
  83. lon /= 2
  84. found = True
  85. break
  86. if not found:
  87. print("Did not find ", item["name"])
  88. continue
  89. CMD = (
  90. f"""mapshaper -i temp.shp """
  91. f"""-filter "{config["base-filter"]}" """
  92. f"""-filter "{item["filter"]}" """
  93. f"""-simplify interval={config["simplify-size"]} """
  94. f"""-proj "+proj=ortho +lat_0={lat} +lon_0={lon}" """
  95. f"""-info """
  96. f"""-style stroke-width={config["stroke-width"]} """
  97. f"""-o "../../{config["directory"]}/{item["name"]}.svg" margin={config["stroke-width"]/2} height=1000 """
  98. )
  99. try:
  100. result = subprocess.check_output(
  101. CMD,
  102. shell=True,
  103. stderr=subprocess.STDOUT
  104. )
  105. except subprocess.CalledProcessError as exc:
  106. print(exc.output.decode("utf-8"))
  107. continue
  108. print(result.decode("utf-8"))
  109. for line in result.decode("utf-8").split("\n"):
  110. if "Bounds:" in line:
  111. coords = list(map(float, line[7:].strip().split(",")))
  112. print(coords)
  113. height = coords[3] - coords[1]
  114. height *= 1000 / (1000 - config["stroke-width"]) # accounts for the margin
  115. results.append([item["name"], height])
  116. print(results)
  117. elif config["mode"] == "forms":
  118. results = []
  119. CMD = (
  120. f"""mapshaper -i {config["shapefile"]} """
  121. f"""-filter "{config["base-filter"]}" """
  122. f"""-o temp.shp"""
  123. )
  124. result = subprocess.check_output(
  125. CMD,
  126. shell=True,
  127. stderr=subprocess.STDOUT
  128. )
  129. CMD = (
  130. f"""mapshaper -i temp.shp """
  131. f"""encoding=utf-8 """
  132. f"""-each "console.log(JSON.stringify({{id: this.id, name: {config["name-key"]}, key: {config["form-key"]} }}))" """
  133. f"""-split """
  134. f"""-o tmp/ format=topojson singles target=* """
  135. )
  136. try:
  137. result = subprocess.check_output(
  138. CMD,
  139. shell=True
  140. )
  141. except subprocess.CalledProcessError as e:
  142. print(e.output)
  143. entities = []
  144. for line in result.decode("utf-8").split("\n"):
  145. if len(line) > 0:
  146. print(line)
  147. entities.append(json.loads(line))
  148. for item in tqdm(entities):
  149. CMD = (
  150. f"""mapshaper -i tmp/temp-{item["id"] + 1}.json """
  151. f"""encoding=utf-8 """
  152. f"""-each "console.log(this.centroidX, this.centroidY)" """
  153. )
  154. result = subprocess.check_output(
  155. CMD,
  156. shell=True,
  157. stderr=subprocess.STDOUT
  158. )
  159. output = result.decode("utf-8")
  160. parts = output.split(" ")
  161. lon = float(parts[0])
  162. lat = float(parts[1])
  163. CMD = (
  164. f"""mapshaper -i tmp/temp-{item["id"] + 1}.json """
  165. f"""encoding=utf-8 """
  166. f"""-simplify interval={config["simplify-size"]} """
  167. f"""-proj "+proj=ortho +lat_0={lat} +lon_0={lon}" """
  168. f"""-info """
  169. f"""-style stroke-width={config["stroke-width"]} """
  170. f"""-o "../../{config["directory"]}/{item["key"]}/{item["name"]}.svg" margin={config["stroke-width"]/2} height=1000 """
  171. )
  172. try:
  173. result = subprocess.check_output(
  174. CMD,
  175. shell=True,
  176. stderr=subprocess.STDOUT
  177. )
  178. except subprocess.CalledProcessError as exc:
  179. print(exc.output.decode("utf-8"))
  180. continue
  181. for line in result.decode("utf-8").split("\n"):
  182. if "Bounds:" in line:
  183. coords = list(map(float, line[7:].strip().split(",")))
  184. height = coords[3] - coords[1]
  185. height *= 1000 / (1000 - config["stroke-width"]) # accounts for the margin
  186. results.append({"name": item["name"], "form": item["key"], "height": round(height)})
  187. print(results)