library(tidyverse)

library(serial)

library(magrittr)

library(plotly)

library(dplyr)

library(GPSCDF)

library(geodata)

library(plot3D)

library(tibble)

library(ggplot2)

library(sf)

library(mapview)

library(ggmap)

library(PlotContour)

library(gganimate)

library(rnaturalearth)

library(rnaturalearthdata)

library(oce)

library(sf)

library(sp)

library(spData)

library(neuralnet)

library(rgdal)

library(rgeos)

library(maps)

library(tree)

library(GNSSseg)

library(scan)

library(vistime)

library(shiny)

library(ggfortify)

library(xts)

library(signal)

library(Rwave)

library(seewave)

library(tuneR)

library(tidyverse)

library(audio)

library(fftw)

library(cowplot)


listPorts()



rm(list = ls())

graphics.off()


##데이터연결

myArduino <-  serialConnection(

  name = "sketch_gps_up",

  port = "COM4",

  mode = "9600,n,8,1" ,

  buffering = "none",

  newline = TRUE,

  eof = "",

  translation = "cr",

  handshake = "none",

  buffersize = 4096

)


open(myArduino)


close(myArduino)



##데이터불러오기

stopTime <- Sys.time() +4

gpsdata <- " "

textSize <- 0



while(Sys.time() < stopTime)

{

  newText <- read.serialConnection(myArduino)

  if(0 < nchar(newText))

  {

    gpsdata <- paste(gpsdata, newText)

  }

}


cat(" \r\n\n", gpsdata, " \r\n\n")


##데이터형변환

myArduino$GPVTG<-as.numeric(myArduino$GPVTG)

myArduino$GPGGA<-as.numeric(myArduino$GPGGA)

myArduino$GPGSA<-as.numeric(myArduino$GPGSA)

myArduino$GPGSV<-as.numeric(myArduino$GPGSV)

myArduino$GPGLL<-as.numeric(myArduino$GPGLL)



comb<-stack(list(v1="GPVTG",v2="GPGGA",v3="GPGSA",v4="GPGSV",v5="GPGLL"))

comb

print(comb)

table(comb)

as.list(comb)


values<-c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL")

ind<-c("v1","v2","v3","v4","v5")

lst<-list()

lst(ind)<-values

gps_values <- cat(values,ind)



class(comb)

mode(comb)

str(comb)


##상태보기

print(myArduino)

summary(myArduino)



table(myArduino)

table(gpsdata)



##결과저장

gps_table <- write.table(cat(gpsdata), "d://filebox/csv/gps_data_1.csv",

                      sep = ",",

                      row.names = FALSE,

                      quote = FALSE,

                      append = FALSE,

                      na = "NA"

                    )


gps_table <- read.csv("d://filebox/csv/gps_data_1.csv")

gps_table




str(gps_table)

table(gps_table)



pres <- data.frame(gpsdata,Position = rep(c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),

                                             each = 12),

                   name =c("a","b"),

                   color = c('#cbb69d', '#603913', '#c69c6e'),

                   fontcolor = c("black", "white", "black"))


shinyApp(

  ui = plotOutput("gps_result"),

  server = function(input, output) {

    output$gps_result <- renderPlot({

      vistime(pres, col.event = "Position", col.group = "gpsdata")

      a    <- faithful[, 2]

      b <- seq(position, length.out = input$col + 1)

      hist(gpsdata, breaks = NULL, col = 'white', borde)

    })

  }

)







library(shiny)

shinyServer(


  function(input,output){


    datasetInput <- reactive({

      switch(input$gps_result,

             "$GPVTG"="$GPVTG",

             "$GPGGA"="$GPGGA",

             "$GPGSA"="$GPGSA",

             "$GPGSV"="$GPGSV",

             "$GPGLL"="$GPGLL")

    })


    output$summary <- renderPrint({

      gps_result <- datasetInput()

      summary(gps_result)

    })})


summary(gps_result)

gps_result


table(gps_result)

str(array(gps_result))


ggplot(data = gps_result,

       aes(x = ra, y = rb)) +

  geom_point()




gps_result_days <- xts(1:5,seq(Sys.Date(),date.length = 20,by = "days"))

gps_result_days



#####데이터저장

gps_table_sql <- read.csv("d://filebox/csv/gps_data_sql.csv")

gps_table_sql


str(gps_table_sql)

table(gps_table_sql)



gps_scan <- scan(gps_table,"d://filebox/csv/gps_data_1.csv",what=list(character(0)))

gps_scan


str(gps_scan)

table(gps_scan)


gps_scan<-data.frame(vals = 1:5)

gps_scan %>% mutate(new_vals=case_when(vals <= 1 ~ "$GPVTG",

                             vals <= 2 ~ "$GPGGA",

                             TRUE ~ "$GPGSA,$GPGSV,$GPGLL"))


date <- format(Sys.Date(),"%m-%d-%y")

xts(gps_scan,seq(Sys.Date("date")))


r1<-data.frame(a = "$GPVTG",b = "N*30")

r2<-data.frame(a = "$GPGGA",b = "0,00,99.99,,,,,,*48")

r3<-data.frame(a = "$GPGSA",b = "A,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30")

r4<-data.frame(a = "$GPGSV",b = "1,1,00*79")

r5<-data.frame(a = "$GPGLL",b = ",,,,,,V,N*64")


gps_result <- rbind(r1,r2,r3,r4,r5)

gps_result

arrange(gps_result,r1,r2,r3,r4,r5)


gps_result <- data.frame(ra=c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),

                         rb=c("N*30","0,00,99.99,,,,,,*48",

                              "A,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30","1,1,00*79",",,,,,,V,N*64"))


summary(table(gps_result))


gps_sheet<-table(array(data.frame(arrange(gps_result))))

gps_sheet


locations <-data(world)


gt <- outer(gps_scan,gps_result,paste,sep=",")

gt



table(array(data.frame(gt)))








fnx <- function(x, fn) sin(2 * pi * fn * x) * exp(-fn * abs(x))

ffs <- 1000

tp <- seq(gps_scan)

pp <- fnx(gps_scan, 30)

fs <- 2e3

t <- seq(0, 1.2, 1 / fs)

d <- seq(0,1.5, 1/3)

dd <- cbind(d, 4^-d)

z <- pulstran(t, dd, pp, ffs)

plot(t, z, type = "l", xlab = "", ylab = "",

     main = "gps")




data_wave <- read.csv("d://filebox/csv/gps_data_sql.csv")


summary(data_wave)





#############시그날 그래프

t <- seq(0, 3*pi, length.out = 100)


df = data.frame(x = gps_result$rb,1:10,

                y = gps_result$ra,sample(c(1,10), 10, replace = TRUE))

summary(df)


y = gps_result$ra

x =gps_result$rb


theme_set(theme_light())

wvfm <- ggplot(df,mapping = aes(x = seq_len(length(y)), y = y))+

  geom_step()+

  geom_line(color = 'blue')+


  labs(x = "Signal", y = "GPS_Proceed")+

  theme(plot.title = element_text(hjust = 0.5))


ggplotly(wvfm)




##################




which(is.na(gps_result$ra))


GNSSseg(

  gps_result,

  lyear = 365.25,

  lmin = 1,

  Kmax = 30,

  selection.K = "BM_BJ",

  S = 0.75,

  f = TRUE,

  selection.f = TRUE,

  threshold = 0.001,

  tol = 1e-04

)



gps_scan <- scan(gpsdata,"d://filebox/csv/gps_data_1.csv",what=list(character(0)))

gps_scan

lyear=365.25

Kmax=4

lmin=1

result=GNSSseg(gps_scan,lyear,Kmax=Kmax,selection.K="none")

plot_GNSS(gps_result$ra)


runif(gps_result)



flightplot(gps_result)

#######


library(keras)

install_keras()


gpsdata0 <- as.matrix(gps_result)

dimnames(gpsdata0) <- NULL


gpsdata0 <- normalize(gpsdata0[,1:3])



gpsdata_mat <- cbind(gpsdata0, comb[,1])

head(gpsdata_mat)



set.seed(1000)

test_gps = sample(1:nrow(gpsdata_mat),nrow(gpsdata_mat)+0.25)

test_gps



data <- matrix(runif(1000*100), nrow = 1000, ncol = 100)

labels <- matrix(round(runif(1000, min = 0, max = 1)), nrow = 1000, ncol = 1)



model %>% fit(data, labels, epochs=10, batch_size=32)


model <- keras_model_sequential()

model %>%

  layer_lstm(units = 32, return_sequences = TRUE, input_shape = c(timesteps, data_dim)) %>%

  layer_lstm(units = 32, return_sequences = TRUE) %>%

  layer_lstm(units = 32) %>% # return a single vector dimension 32

  layer_dense(units = 10, activation = 'softmax') %>%

  compile(

    loss = 'categorical_crossentropy',

    optimizer = 'rmsprop',

    metrics = c('accuracy')

  )


# generate dummy training data

x_train <- array(runif(1000 * timesteps * data_dim), dim = c(1000, timesteps, data_dim))

y_train <- matrix(runif(1000 * num_classes), nrow = 1000, ncol = num_classes)


# generate dummy validation data

x_val <- array(runif(100 * timesteps * data_dim), dim = c(100, timesteps, data_dim))

y_val <- matrix(runif(100 * num_classes), nrow = 100, ncol = num_classes)


# train

model %>% fit(

  x_train, y_train, batch_size = 64, epochs = 5, validation_data = list(x_val, y_val)

)




gpsdata0 <- keras_model_sequential()

gpsdata0 %>%

  layer_dense(units = 16, input_shape = c(12)) %>%

  layer_activation('sigmoid') %>%

  layer_dense(units = 6) %>%

  layer_activation('softmax')


gpsdata0 %>% compile(

  optimizer = 'rmsprop',

  loss = 'categorical_crossentropy',

  metrics = c('accuracy')

)


gpsdata0 <- keras_model_sequential(input_shape = c(12)) %>%

  layer_dense(units = 32) %>%

  layer_activation('sigmoid') %>%

  layer_dense(units = 10) %>%

  layer_activation('softmax')


gpsdata0 %>% fit(

  train.data,

  labels,

  epochs = 100,

  batch_size = 5,

  validation_split = 0.5

)



gpsdata0

history(gpsdata0$compiled_loss)

plot(gpsdata0)


class <- gpsdata0 %>% predict_classes(labels, batch_size = 128)


# 혼동행렬

table(gpsdata0, class)


score <- gpsdata0 %>% evaluate(test.data, gpsdata.testtarget, batch_size = 128)

print(score)








seoul <- ne_countries(scale = "medium", returnclass = "sf")


gps_sheet.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = gps_sheet, aes(x = x, y = 0, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_sheet%>%slice(seq(3,20,25)),

                           aes(x = x, y = 0, label = x ))+

  #transition_states( state_length = 0, transition_length = 2) +

  transition_time(POSIXCT)+

  ease_aes("sine-in-out")+enter_fade() +

  exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(gps_scan.animate,width=1020, height=880, res=35)

animate(gis_table.animate, width = 1020, height = 880, fps = 25, duration = 15, rewind = FALSE)





gps_line <- readLines("d://filebox/csv/gps_data.csv",n=21)

gps_line


str(gps_line)

table(gps_line)

summary(table(gps_line))



gps_scan <- scan("d://filebox/csv/gps_data.csv",what=list(character(0)))%>%mutate(x=108)

gps_scan


str(gps_scan)

table(gps_scan)



ftable(tapply(gps_scan,list("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),mean))






library(XLConnect)

writeWorksheetToFile("d://filebox/csv/gps_data_xl.xlsx", gpsdata, sheet="gps data")


library(readxl)

gps_xl <- read_xlsx("d://filebox/csv/gps_data_xl.xlsx")

gps_xl


seoul <- ne_countries(scale = "medium", returnclass = "sf")


gps_scan.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = gps_scan, aes(x = x, y = 0, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_scan%>%slice(seq(3,108,25)),

                           aes(x = x, y = 0, label = x))+

  #transition_states( state_length = 0, transition_length = 2) +

  transition_time(POSIXct)+

  #seq.default(length.out = 2)+

  ease_aes("sine-in-out")+

  enter_fade() + exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(gps_scan.animate,width=1020, height=880, res=35)


##데이터상태보기

for(gpsdata in 1:2){

  cat("\n",paste0(gpsdata,gps_scan))

}


str(gps_scan)

summary(gps_scan)


plot(gps_scan)


##

for(i in 1:2) {

array(comb)


  cat( "/n",paste0(i,comb))

  print(i)

  extent = "COM4"

  break()

}



str(comb)

summary(comb)

table(comb)

plot(comb)


summary(table(comb))

plot(values~ind,comb)



basemap <- get_openstreetmap("seoul", zoom = 12)

ggmap(basemap)








df<- ggplot(data=gps_line)+

  geom_sf(map(database = "world"))+

  coord_sf(xlim=Long, ylim=Lat, expand = "device")+

  geom_point(data = gps_line, aes(x = values, y = ind, colour = bathy))+

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_line,

                           aes(x = values, y = ind))+

  transition_time(gps_line)+

  ease_aes("sine-in-out")+

  shadow_mark()

df



seoul <- ne_countries(scale = "medium", returnclass = "sf")


df.animate(comb+

             #geom_point(aes(c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL")))+

             geom_point(gps_line)+

             add_segments(x=x,y=y))+

  #add_markers(x = ~x,y = ~y,z = ~z)+

  addNode(plot(myArduino),n)





df.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = df, aes(x = lon, y = lat, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = df%>%slice(6),

                           aes(x = x, y = y, label = c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL" )))+

  #transition_states( state_length.out = gps_table, transition_rane = 2) +

  transition_time(c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL"))+

  ease_aes("sine-in-out")+enter_fade() +

  exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(df.animate,width=1020, height=880, res=35)

animate(df.animate, width = 1020, height = 880, fps = 25, duration = 15, rewind = FALSE)


#####

z <- Sys.time()

unclass(z)

floor(unclass(z)/86400)

(now <- as.POSIXlt(Sys.time()))

unlist(unclass(now))

now$year + 1900

months(now); weekdays(now)


z <- 1472562988


as.POSIXct(z, origin = "1960-01-01")

as.POSIXct(z, origin = "1960-01-01", tz = "GMT")


#z <- c(10485849600, 10477641600, 10561104000, 10562745600)

#as.Date(as.POSIXct(z, origin = "1582-10-14", tz = "GMT"))


z <- 1579598122120

op <- options(digits.secs = 3)


as.POSIXct((z+0.1)/1000, origin = "1960-01-01")

options(op)


z <- 7.343736909722223e5

as.POSIXct((z - 719529)*86400, origin = "1970-01-01", tz = "UTC")


as.POSIXlt(Sys.time(), "GMT")

as.POSIXlt(Sys.time(), "EST" )


cols <- c("code", "coordinates", "TZ", "comments")

tmp <- read.delim(file.path(R.home("share"), "zoneinfo", "zone.tab"),

                  header = FALSE, comment.char = "#", col.names = cols)

if(interactive())

  View(tmp)




################


library(ggmap)

library(tidyverse)


map_data <- read.table("d://filebox/csv/gps_data.csv")



map.view <- map_data %>%

  filter(127.26 <= lon & lon <= 127.20,

         36.85 <= lat & lat <= 36.91)



qmplot(x=lon, y=lat, data = map_data)

seoul <- get_map("seoul", color="bw",zoom=18)

ggmap(seoul)

ggmap(world) +

  geom_point(data=gps_line,aes(x=long,y=lat,color=n.trips),size=3,alpha=0.75)+

  scale_colour_gradient(high="red",low='green')+

  theme(axis.ticks = element_blank(),axis.text = element_blank())+

  xlab('')+ylab('')



##########example

library(lubridate)

library(forcats)

## Pick coordinates that approximates dropoffs near the Met

lat <- c(36.7785,36.780)

lon <- c(126.963,126.9615)


taxi <- read.csv('c://.csv') %>%

  mutate(weekday.pickup = wday(tpep_pickup_datetime,label=TRUE,abbr=TRUE),

         weekday.dropoff = wday(tpep_dropoff_datetime,label=TRUE,abbr=TRUE),

         hour.trip.start = factor(hour(tpep_pickup_datetime)),                                 # hour of day

         hour.trip.end = factor(hour(tpep_dropoff_datetime)),                                  # hour of day

         day = factor(mday(tpep_dropoff_datetime)),                                             # day of month

         trip.duration = as.numeric(difftime(tpep_dropoff_datetime,tpep_pickup_datetime,units="mins")),   # trip duration in minutes

         trip.speed = ifelse(trip.duration > 1, trip_distance/(trip.duration/60), NA),          # trip speed in miles/hour

         payment_type_label = fct_recode(factor(payment_type),

                                         "Credit Card"="1",

                                         "Cash"="2",

                                         "No Charge"="3",

                                         "Other"="4")) %>%

  filter(day %in% c(1:28))



## Filter data for drop-offs near the Met

seoul <- taxi %>%

  filter(dropoff_longitude > lon[1] & dropoff_longitude < lon[2],

         dropoff_latitude > lat[1] & dropoff_latitude < lat[2])


ggmap(seoul) +

  geom_point(data=gps_line,

             aes(x=dropoff_longitude,y=dropoff_latitude),size=.03,alpha=0.3,color="red")

######




df <- read.csv("d://filebox/csv/gps_data.csv") %>% mutate(df = 1:1)

df


table(df)

str(df)

summary(df)









plot(gps_line,

     type = "l", col = "blue", lwd = 3)


df <- neuralnet %>% cat(gps_table)

df


###

gpx_parsed <- htmlTreeParse(file = 'd://filebox/csv/gps_data.csv', useInternalNodes = TRUE)

gpx_parsed

dygraphs::dyPlotter(gps_data,pathSApply(doc = gpx_parsed,path = "/gps_data.csv", fun = xmlAttrs))




ggplot(df, aes(x = Lon, y = Lat)) +

  coord_quickmap() +

  geom_point()



#####

library(here)

library(XML)

library(lubridate)

library(Rwave)

library(rwavelet)

library(mathml)

library(zoo)


path_tmp <- paste0("d://filebox/csv/gps_data.csv")

parsed <- htmlTreeParse(file = "d://filebox/csv/gps_data.csv", useInternalNodes = TRUE)

parsed



coords <- xpathSApply(parsed, path = "//trkpt/Lat", xmlAttrs)

coords <- xpathSApply(parsed, path = "//trkpt/Lon", xmlAttrs)

#elev   <- xpathSApply(parsed, path = "//trkpt/ele", xmlValue)

#tser <- xpathSApply(parsed, path = "//trkpt/time", xmlValue)


A ="2023-01-01"

B ="2023-04-07"

zooser <- zoo(x=tser$time, order.by=as.POSIXct(tser$pTime, origin="2023-01-01"))

window(zooser, start=A, end=B)


#

path_tmp <- data.frame(parsed,

                    # ts_POSIXct = ymd_hms(tser$time, tz = "EST"),

                     lat = as.numeric(coords[latitude,]),

                     lon = as.numeric(coords[longitude,])

                    # elev = as.numeric(ele)

)

head(path_tmp)

plot(path_tmp)

#ts_POSIXct



#####

ggplot(gps_line,aes(x=Lat,y=Long))+

  geom_segment(aes(x=0,y=Date,xend=Lat,yend=Long))+

  geom_point()







#############

bbox <- make_bbox(range(gps_data$Longitude), range(gps_data$Longitude))

dat_df_map <- get_map(center = c(mean(range(gps_data$Longitude)), mean(range(gps_data$Longitude))), zoom = 15)


dat_df_dist_marks <-

  dat_df %>%

  mutate(dist_m_cumsum = cumsum(dist_to_lead_m)) %>%

  mutate(dist_m_cumsum_km_floor = floor(dist_m_cumsum / 1000)) %>%

  group_by(dist_m_cumsum_km_floor) %>%

  filter(row_number() == 1, dist_m_cumsum_km_floor > 0)


# generate plot

plt_path_fancy <-

  ggmap(dat_df_map) +

  geom_point(data = gps_data, aes(lon, lat, col = elev),

             size = 1, alpha = 0.5) +

  geom_path(data = dat_df, aes(lon, lat),

            size = 0.3) +

  geom_label(data = dat_df_dist_marks, aes(lon, lat, label = dist_m_cumsum_km_floor),

             size = 3) +

  labs(x = "Longitude",

       y = "Latitude",

       color = "Elev. [m]",

       title = "Track of one Marta's run on 2022-01-01")

plt_path_fancy




############


library(leaflet)

leaflet() %>%

  addTiles(group = "OSM") %>%

  add_trace(gps_line, weight = 1, fillColor = "grey", color = "black",

            opacity = 1, fillOpacity = 0.6)%>%

  add_markers(x = ~Longitude,y = ~Latitude, popup = gps_table)





##


##

library(maps)

data(world.cities)

library(rbokeh)

caps <- dplyr::filter("d://filebox/csv/gps_data.csv", x == 1)

caps <- prettyNum(gps_data$gps_line, big.mark = ",")

plot <- suppressWarnings(figure(width = 800, height = 450, padding_factor = 0) %>%

                           ly_map("world", col = "gray") %>%

                           ly_points(lon, lat, data = caps, size = 5,

                                     hover = c(gps_line,x)))


widgetframe::frameWidget(plot,width=1000,height=600)







isOpen(myArduino)



write.serialConnection(myArduino)

read.serialConnection(myArduino)


summary(myArduino)







write.serialConnection(myArduino, rawToChar(as.raw(15)) ) # 0x0F

write.serialConnection(myArduino, c(15,20) ) # 0x0F, 0x14

write.serialConnection(myArduino, c(0x6F,0x6C) )



tran <- read.serialConnection(myArduino)

print(tran)



close(myArduino)



##

library(DiagrammeR)

mermaid(str(gpsdata))



library()

vec <- rnorm(1200)

mat <- matrix(vec, nrow=30, ncol=40)

whitenoise <- im(mat)

whitenoise <- im(mat, xrange=c(0,1), yrange=c(0,1))

whitenoise <- im(mat, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))

whitenoise <- im(vec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))

plot(whitenoise)



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기