####################################################################################################################################
####################################################################################################################################
#HYSPLIT4 USER's GUIDE
####################################################################################################################################
####################################################################################################################################

#The HYSPLIT_4 (Hybrid Single-Particle Lagrangian Integrated Trajectory) Model installation, configuration, and operating procedures are reviewed. Examples are given for setting up the model for trajectory and concentration simulations, graphical displays, and creating publication quality illustrations. The model requires specially preformatted meteorological data. Programs that can be used to create the model's meteorological input data are described. 

#Pre-Installation Preparation

#There are two installation programs that can be downloaded. The trial version (HYSPLIT_win{32|64}U.exe ~ 70 Mb) available to anyone and a fully functional version (HYSPLIT_win{32|64}R.exe ~ 70 Mb) that requires a user registration through the web site. Both versions identical, except the trial version will not work with forecast meteorological data files. In addition, several supplemental programs (Ghostview and Tcl/Tk) are packaged with the trial version for convenience. It is assumed that these would have already been installed when the registered version is installed on top of the trial version. 

#The self-installing executable contains only HYSPLIT related programs. No additional software is required to run a simulation if the command line interface is sufficient. To enable the model's GUI, the computer should have Tcl/Tk script language installed. 

#The most recent version can be obtained over the Internet from or an older version is packaged with some of the other programs on the HYSPLIT web site. The installation of Tcl/Tk will result in the association of
#the .tcl suffix with the Wish executable and all Hysplit GUI scripts will then show the Tk icon. The HYSPLIT GUI has been tested with Tcl/Tk version 8.5.4.

#The primary HYSPLIT graphical display programs convert the trajectory and concentration model output files to Postscript format. The Postscript files can also be viewed directly through the GUI if Ghostscript and Ghostview have been installed. See for more information on the Postscript file viewer. The HYSPLIT code and GUI have been tested with Ghostscript 8.63 and Ghostview 4.9. Installation to different default drives, directories, or other versions might require editing the main GUI script's directory pointers (edit file: /guicode/hysplit4.tcl or the directory entry in the Advanced-Configuration-Directories menu tab. 

#The third optional GUI feature is the ability to convert the Postscript output file to a different graphical formats using ImageMagick. More information on this software can be found at The HYSPLIT code and GUI have been tested with ImageMagick 6.4. Similar to Ghostscript, installation to a different default drives or directories as suggested by the installation process may require editing the main GUI script's directory pointers. Proper functioning of the conversion software with Postscript files requires the installation of Ghostscript. Although the setup script tests for the default language, it is possible that installation to non-English default windows operating systems might require additional editing of the directory pointers.

#Windows Installation (all operating systems)

#Download URL：https://www.ready.noaa.gov/HYSPLIT.php


#HYSPLIT installation to a computer running Windows is provided through a self-installing file. Executables are installed in various directories for trajectories, dispersion, display and manipulation of results, and the creation of input meteorological data files. The trajectory and dispersion model source code is not provided. However all the Fortran source code to create meteorological data files in a format that the model can read are provided in the /data2arl directory. Each subdirectory contains a @readme.txt file with more complete information about the contents of that directory.

#During the installation you will be prompted as to the directory location. It is suggested you select a simple default location (such as C:/hysplit4). The installation program installs all code and executables to your selected directory, and creates a shortcut on the desktop to /guicode/hysplit4.tcl with the "Start In" directory as your selected default. You may have one of two versions of the installation program: HYSPLIT_win{32|64}{R|U}.exe. The suffixes R and U refer to the Registered or Unregistered versions. The two versions are almost identical, except that the unregistered version does not permit calculations with current forecast meteorological data.

#HYSPLIT and all the related programs are available for either 32 bit or 64 bit operating systems. The 32 bit version can be installed on either OS, while the 64 bit programs can only be installed on a 64 bit OS. An Apple MAC version is also available (HYSPLIT_mac.dmg).

#The installation will contain several sub-directories, some of which are required for model execution, and some of which provide additional documentation and other information. For instance ...

#Bdyfiles - This directory contains an ASCII version of gridded land use, roughness length, and terrain data. The current file resolution is 360 x 180 at 1 degree. The upper left corner starts at 180W 90N. The files are read by both HYSPLIT executables, hyts_std (trajectory model) and hycs_std (concentration model), from this directory. If not found, the model uses default constant values for land use and roughness length. The data structure of these files is defined in the file ASCDATA.CFG, which should be located in either the model's startup or /bdyfiles directory. This file defines the grid system and gives an optional directory location for the landuse and roughness length files. These files may be replaced by higher resolution customized user-created files. However, regardless of their resolution, the model will only apply the data from these files at the same resolution as the input meteorological data grid. More information on the structure of these files can be found in the local @readme.txt file.

#Data2arl - Current forecast or archive meteorological data can be obtained from the ARL ftp server: ftp://gus.arlhq.noaa.gov /pub/archives (or /forecasts). Older archive data can be ordered from the NCDC
#(National Climatic Data Center). However if you have access to your own meteorological data or data formatted as GRIB (Gridded Binary), this directory contains various example decoder programs to convert meteorological data in various formats to the format (ARL packed) that HYSPLIT can read. Sample programs include GRIB decoders for ECMWF model fields, NCAR/NCEP (National Centers for Environmental Prediction) re-analysis data, and NOAA Aviation, ETA, and Regional Spectral Model files. All the required packing and unpacking subroutines can be found in the /source subdirectories. Sample compilation scripts for Compaq Visual Fortran 6.6 are in some of the decoder directories. 

#Examples - The directory contains several example scripts and batch files that can be used to create automated simulations.

#Html - Contains all the HELP files in HTML format. These files can be displayed with any browser or interactively through the GUI. The files that are opened in the GUI depend upon the context from which HELP is invoked.

#Exec - Is the directory that contains all the executable programs. The GUI looks for all programs in this directory. When running examples from the command prompt in certain directories, the relative path should be included prior to the executable: "../exec/program.exe"

#Graphics - There are two types of graphical plotting programs provided in the ../exec directory. Publication quality graphics can be created using the postscript conversion programs, concplot and trajplot, which use a Fortran Postscript library created by Kevin Kohler4. All graphical routines use the map background file arlmap in this directory. The map background file uses a simple ASCII format and contains the world's coastal and political boundaries at relatively coarse resolution. Other higher resolution map background files are available in the /graphics/mapfiles directory or from the HYSPLIT download web page. All graphical programs search the startup directory first for arlmap before going to /graphics, therefore customized maps can be created without changing the HYSPLIT installation structure.

#Guicode - This directory contains a Tcl/Tk GUI interface source code script for HYSPLIT. The interface is used to set up the input Control file as well as run the graphical output display programs. To use the interface you must first install Tcl/Tk. The upper-level Tcl script is called hysplit4.tcl, which calls all other Tcl scripts. Executing thisscript starts the HYSPLIT GUI. The Desktop shortcut as well as the Start Menu options should point to this script. If the installation program did not properly setup the Desktop, you can manually create a shortcut to the script and edit its properties such that the "Start In" directory is /hysplit4. You should also select the HYSPLIT icon from the /icons directory.

#Working - This is the Hysplit4 root directory, which contains sample CONTROL files that can be used for initial guidance to set up more complex simulations. These should be loaded into the GUI from the approprate "Retrieve" menu tab. Examples include:
#     sample_conc - concentration simulation example from users guide

#     sample_traj - trajectory simulation example from users guide

#     The "plants.txt" file contains a sample listing of starting locations that can be opened in the GUI to select from a list of previously determined starting locations. This file can easily be customized. The "tilelist.txt" file      contains the approximate coordinates of NCEP's NAM (North America Mesoscale model) tile domains.

#Trajectory / Setup Run

#Step 1 - start the GUI menu system using \working\hysplit4.tcl or the desktop shortcut to Hysplit4. A widget will appear with the HYSPLIT graphic and three button options: Menu, Help and Exit.Click on Menu tab.

#Step 2 - The four main menus of the Hysplit4 GUI will appear: Meteorology, Trajectory, Concentration, and Advanced. An additional small widget underneath the main menu gives the current Hysplit4 version information. Do not delete this widget as it will terminate the GUI. It provides the reference frame for the model's standard output and messages. Click on the Trajectory tab.

#Step 3 - Five options appear under this item: Setup Run, Run Model, Display, Utilities, and Special Runs. Normally these are run in sequence, however any item can be selected and run if the appropriate input files were created during a previous simulation. Click on the Setup tab.

#Step 4 - Setup Run is used to enter the basic model simulation parameters: the starting time of the calculation; starting location in terms of latitude, longitude, and height; the run-time or duration of the trajectory calculation; and the names and locations of all required files. When modifications to this menu are complete, click on Save. However for this example, you will use the Retrieve option for predefined configurations, so do nothing here and go on to Step 5.

#Step 5 - The example calculation is configured by clicking on Retrieve and then entering the text: sample_traj, which is the name of the example simulation control file that was created for this demonstration. Then click on OK. After the data entry widget is closed, click on Save and the setup menu will close.

#Step 6 - Click on Run Model, which first copies the setup configuration (default_traj) saved in the previous step, to the model's input CONTROL file. The model calculation is then started. A series of messages will appear on standard output text window showing the progress of the calculation. When the simulation is completed, the trajectory end-points output file is ready to be converted for graphical display. Under some operating systems, the standard output widget will not show any output until the end of the calculation and the Trajectory menu items will be locked until the calculation completes.

#Step 7 - Selecting Display will run a special program that converts the text file of trajectory end-point positions into a high quality Postscript file (trajplot.ps) suitable for printing. The conversion widget provides options for the frequency of the labels on the trajectory, a variable zoom factor, and color or black and white graphics options. If the Postscript viewer (Ghostscript) has been installed and associated with the .ps file suffix, then it will be invoked by the GUI. 


#In order to make the result visulized, we use R to plot.

#The plotting code is as follows：

library(ggplot2)
library(sp)
library(sf)
library(tmap)
library(tmaptools)
library(rgdal)
library(legendMap)
library(maptools)
library(viridis)
library(ggpointdensity)
library(ggspatial)
library(RColorBrewer)
library(stringr)
library(tidyverse)
library(tidyr)
library(lubridate)
library(patchwork)
library(readr)
library(grid)
library(showtext)
showtext_auto(enable = TRUE)
font_add('times', 'times.ttf')
font_add('arial','arial.ttf') 
setwd("D:") # The path where the trajectory output results are saved
filename <- list.files(pattern = 'XX') # prefix for output files


data <- data.frame()

df <- data.frame()
for (i in 1:length(filename)) {
  df <- read.table(file = filename[i],fill = T,
                   col.names =c('a','b','year','month','day','hour','c','d','time_step','lat','long','g','i'))
  df <- na.omit(df)
  df$start_date <- ymd_h(str_sub(filename[i],5))
  data <- rbind(data,df)
  
}


bou2_4p=readOGR("D:/mapdata/chinamap/bou2_4m/bou2_4p.shp") # Vector map of China
china <- readOGR("D:/mapdata/chinamap/bou2_4m/bou2_4p.shp") #,delete_null_obj=TRUE)

china <- sp2tmap(china)
chinab <- readOGR("D:/mapdata/chinamap/bou1_4m/bou1_4l.shp") #,delete_null_obj=TRUE)
chinab <- fortify(chinab, region='id')
asia <- readOGR('D:/mapdata/Asia/Asia_country.shp')
province_city <- read.csv("D:/mapdata/chinamap/china_cities_EG.csv") 
raw= read.csv(province_city, encoding = 'utf-8')
iconv ( raw, 'utf-8', 'gbk')

p <- ggplot(data,aes(x=long,y=lat))
p <- p + xlab("")+ylab("")
p <- p + geom_polygon(data=asia,aes(group=group,x=long,y=lat),colour="gray",linetype=1,size=0.3,fill='white')
p <- p + geom_polygon(data=bou2_4p,aes(group=group,x=long,y=lat),colour="gray",linetype=1,size=0.3,fill='white')
p <- p + geom_path(data=chinab,aes(group=id,x=long,y=lat),colour="black",linetype=1,size=0.2)

#p <- p + geom_point()


p <- p + coord_map("albers", lat=18, lat=53,xlim = c(82,126), ylim=c(17,52))
#p <- p+coord_map("albers",lon=105,lon=125,xlim = c(90,140), ylim=c(15,55))

p <- p+theme_bw() 
p <- p+theme(panel.spacing=unit(0.0,"cm"))
p <- p+theme(panel.background = element_rect(fill = "gray90",  colour =NA),
             panel.grid.major = element_line(size = 0.25, linetype = 'solid',colour = "white"), 
             panel.grid.minor = element_line(size = 0.1, linetype = 'solid', colour = "white"))


p 
pp<- p + geom_point(alpha=0.2)

p1 <- p + stat_density2d(aes(fill=..level..),bins=100,geom='polygon',contour_var = 'ndensity',alpha=0.2,n=1000)+
  scale_fill_distiller(palette = 'Spectral') + geom_text(aes(x =jd,y =wd,label = Egname), data =province_city,size=1.8)+
  theme(
    panel.grid = element_blank(),
    panel.background = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank()) +
  annotation_north_arrow(location="tl",style = north_arrow_nautical)+
  scale_bar(lon =100.8,lat = 15.7,distance_lon =350,
            distance_lat =70,distance_legend =140,dist_unit ="km",orientation=F) 
  
p1

#Add South China Sea
p2 <-p + geom_polygon(data=bou2_4p,aes(x=long,y=lat,group=group),color="grey40",fill="white")+ 
  geom_line(data=chinab,aes(x=long,y=lat,group=group),color="black",size=0.3)+ 
  coord_cartesian(xlim=c(105,125),ylim=c(3,30))+ 
  theme(
    aspect.ratio = 1.25, 
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    panel.background = element_blank(),
    panel.border = element_rect(fill=NA,color="grey20",linetype=1,size=0.8),
    plot.margin=unit(c(0,0,0,0),"mm"))




vie <- viewport(width=0.40,height=0.25,x=0.13,y=0.155) 

print(p2,vp=vie) 













