diff --git a/controllers/freezing_dates_controller_test.go b/controllers/freezing_dates_controller_test.go deleted file mode 100644 index 724e83be3005594defd19f5aacc9163a1101c661..0000000000000000000000000000000000000000 --- a/controllers/freezing_dates_controller_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package controllers - -import ( - "testing" - - "github.com/gofiber/fiber/v2" - "github.com/stretchr/testify/assert" - DawnTest "github.com/tgs266/dawn-go-common/testing" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/services" -) - -func mockGetFreezingDate(request models.FreezingDateRequest) models.FreezingDateResponse { - dateCounts := make(map[string]*models.SingleFreezingDate) - dateCounts["one"] = &models.SingleFreezingDate{ - Count: 1, - Years: []int{2021}, - } - return models.FreezingDateResponse{ - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - FirstDateCounts: dateCounts, - LastDateCounts: dateCounts, - } -} - -func TestGetFreezingDates(t *testing.T) { - mock := DawnTest.CreateMock(services.GetFreezingDate, mockGetFreezingDate) - defer mock.Unpatch() - app := fiber.New() - app.Get("/test", GetFreezingDates) - var data models.FreezingDateResponse - - params := make(map[string]string) - params["latitude"] = "12.0" - params["longitude"] = "12.0" - params["freezing_temp"] = "28" - - statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - - DawnTest.StatusCodeEqual(t, 200, statusCode) - assert.Equal(t, 2021, data.FirstDateCounts["one"].Years[0], "should match") - assert.Equal(t, 1, data.FirstDateCounts["one"].Count, "should match") -} diff --git a/controllers/gdd_controller_test.go b/controllers/gdd_controller_test.go deleted file mode 100644 index fea85758b653a001ac03929bec3987898690ee7b..0000000000000000000000000000000000000000 --- a/controllers/gdd_controller_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package controllers - -import ( - "testing" - "time" - - "github.com/gofiber/fiber/v2" - "github.com/stretchr/testify/assert" - "github.com/tgs266/dawn-go-common/common" - DawnTest "github.com/tgs266/dawn-go-common/testing" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/services" -) - -func mockGetGddValues(ctx common.DawnCtx, request models.GddRequest) models.GddResponse { - return models.GddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - LastDate: time.Date(2021, time.January, 4, 0, 0, 0, 0, time.Now().Location()), - } -} - -func mockGetNormalValues(request models.GddRequest) models.GddResponse { - return models.GddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - LastDate: time.Date(2021, time.January, 4, 0, 0, 0, 0, time.Now().Location()), - } -} - -func TestGetDailyGdd(t *testing.T) { - mock := DawnTest.CreateMock(services.GetGddValues, mockGetGddValues) - defer mock.Unpatch() - app := fiber.New() - app.Get("/test", GetDailyGdd) - var data models.GddResponse - - params := make(map[string]string) - params["year"] = "2021" - params["product"] = "corn" - params["latitude"] = "12.0" - params["longitude"] = "12.0" - params["accumulate"] = "false" - - statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - - DawnTest.StatusCodeEqual(t, 200, statusCode) - assert.Equal(t, "corn", data.Product, "should match") - assert.Equal(t, 4.0, data.GddValues[3], "should match") -} - -func TestGetNormalGdd(t *testing.T) { - mock := DawnTest.CreateMock(services.GetNormalValues, mockGetNormalValues) - defer mock.Unpatch() - app := fiber.New() - app.Get("/test", GetNormalGdd) - var data models.GddResponse - - params := make(map[string]string) - params["product"] = "corn" - params["latitude"] = "12.0" - params["longitude"] = "12.0" - params["accumulate"] = "false" - - statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - - DawnTest.StatusCodeEqual(t, 200, statusCode) - assert.Equal(t, "corn", data.Product, "should match") - assert.Equal(t, 4.0, data.GddValues[3], "should match") -} diff --git a/controllers/misc_controller_test.go b/controllers/misc_controller_test.go deleted file mode 100644 index c1da7d05a91018d29ab5fd9f4aa70ac01c9e7027..0000000000000000000000000000000000000000 --- a/controllers/misc_controller_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package controllers - -import ( - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence/entities" -) - -func mockFindAnalogYear(location entities.Location) models.AnalogResponse { - return models.AnalogResponse{ - ClosestLatitude: 4.0, - ClosestLongitude: 4.0, - AnalogYear: 2001, - } -} - -func mockGetConfidenceInterval(request models.ConfidenceIntervalRequest) models.ConfidenceIntervalResposne { - return models.ConfidenceIntervalResposne{ - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - LowerBound: []float64{1.0, 1.0, 2.0, 2.0}, - UpperBound: []float64{5.0, 5.0, 10.0, 10.0}, - } -} - -// func TestGetAnalogYear(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.FindAnalogYear, mockFindAnalogYear) -// defer mock.Unpatch() -// app := fiber.New() -// app.Get("/test", GetAnalogYear) -// var data models.AnalogResponse - -// params := make(map[string]string) -// params["latitude"] = "12.0" -// params["longitude"] = "12.0" - -// statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - -// DawnTest.StatusCodeEqual(t, 200, statusCode) -// assert.Equal(t, 2001, data.AnalogYear, "should match") -// } - -// func TestGetConfidenceInterval(t *testing.T) { -// mock := DawnTest.CreateMock(services.GetConfidenceInterval, mockGetConfidenceInterval) -// defer mock.Unpatch() -// app := fiber.New() -// app.Get("/test", GetConfidenceInterval) -// var data models.ConfidenceIntervalResposne - -// params := make(map[string]string) -// params["product"] = "corn" -// params["latitude"] = "12.0" -// params["longitude"] = "12.0" -// params["interval"] = "95" - -// statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - -// DawnTest.StatusCodeEqual(t, 200, statusCode) -// assert.Equal(t, 1.0, data.LowerBound[1], "should match") -// assert.Equal(t, 10.0, data.UpperBound[2], "should match") -// } diff --git a/controllers/nomads_controller_test.go b/controllers/nomads_controller_test.go deleted file mode 100644 index 60c10d609ae4580b0d1ce5b1aee6c76070e8a977..0000000000000000000000000000000000000000 --- a/controllers/nomads_controller_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package controllers - -import ( - "testing" - "time" - - "github.com/gofiber/fiber/v2" - "github.com/stretchr/testify/assert" - DawnTest "github.com/tgs266/dawn-go-common/testing" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/services" -) - -func mockGetGefsGddValues(request models.GddRequest) models.GefsGddResponse { - return models.GefsGddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - UpperBound: []float64{1.0, 2.0, 3.0, 4.0}, - LowerBound: []float64{1.0, 2.0, 3.0, 4.0}, - FirstDate: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.Now().Location()), - LastDate: time.Date(2021, time.January, 4, 0, 0, 0, 0, time.Now().Location()), - } -} - -func mockGetCfsGddValues(request models.GddRequest) models.CfsGddResponse { - return models.CfsGddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - UpperBound: []float64{1.0, 2.0, 3.0, 4.0}, - LowerBound: []float64{1.0, 2.0, 3.0, 4.0}, - FirstDate: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.Now().Location()), - } -} - -func TestGetGefsGDD(t *testing.T) { - mock := DawnTest.CreateMock(services.GetGefsGddValues, mockGetGefsGddValues) - defer mock.Unpatch() - app := fiber.New() - app.Get("/test", GetGefsGDD) - var data models.GddResponse - - params := make(map[string]string) - params["year"] = "2021" - params["product"] = "corn" - params["latitude"] = "12.0" - params["longitude"] = "12.0" - params["accumulate"] = "false" - - statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - - DawnTest.StatusCodeEqual(t, 200, statusCode) - assert.Equal(t, "corn", data.Product, "should match") - assert.Equal(t, 4.0, data.GddValues[3], "should match") -} - -func TestGetCfsGDD(t *testing.T) { - mock := DawnTest.CreateMock(services.GetCfsGddValues, mockGetCfsGddValues) - defer mock.Unpatch() - app := fiber.New() - app.Get("/test", GetCfsGDD) - var data models.GddResponse - - params := make(map[string]string) - params["year"] = "2021" - params["product"] = "corn" - params["latitude"] = "12.0" - params["longitude"] = "12.0" - params["accumulate"] = "false" - - statusCode := DawnTest.TestGetRequestParams(app, "/test", params, "token", &data) - - DawnTest.StatusCodeEqual(t, 200, statusCode) - assert.Equal(t, "corn", data.Product, "should match") - assert.Equal(t, 4.0, data.GddValues[3], "should match") -} diff --git a/controllers/seed_controllers.go b/controllers/seed_controllers.go deleted file mode 100644 index ac8562d8f8aa0a52d2c5949ff545da3d2167817e..0000000000000000000000000000000000000000 --- a/controllers/seed_controllers.go +++ /dev/null @@ -1,38 +0,0 @@ -package controllers - -// import ( -// "github.com/tgs266/dawn-go-common/common" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/services" - -// "github.com/gofiber/fiber/v2" -// ) - -// func GetSeedList(c *fiber.Ctx) error { -// request := models.SeedListRequest{Product: c.Query("product")} -// return c.Status(fiber.StatusOK).JSON( -// services.GetSeedList(c, request), -// ) -// } - -// // GetCornSeedMaturityDate godoc -// // @Summary Get estimated maturity date from given gdd (uses CFS data if current GDUs are less than the crop maturity) -// // @Tags GDD Maturity Data -// // @Description Get estimated maturity date from given gdd -// // @Accept json -// // @Produce json -// // @Success 200 {object} models.CornMaturityResponse -// // @Failure 400 {object} errors.StandardError -// // @Param latitude query number true "Latitude to search for" -// // @Param longitude query number true "Longitude to search for" -// // @Param gdds query number true "number of gdds given" -// // @Param month query number true "month planted" -// // @Param date query number true "date planted" -// // @Router /gdd/maturity/corn [get] -// func GetCornSeedMaturityDate(c *fiber.Ctx) error { -// ctx := common.DawnCtx{FiberCtx: c} -// request := models.BuildCornMaturityRequest(c) -// return c.Status(fiber.StatusOK).JSON( -// services.GetCornMaturityDate(ctx, request), -// ) -// } diff --git a/go.mod b/go.mod index 18f8bcc6e66577a16646ef71f65405f211b15973..383f05f15d1644dccca08e8c6bfcd6abafc04994 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/spf13/viper v1.9.0 github.com/stretchr/testify v1.7.0 github.com/swaggo/swag v1.8.6 - github.com/tgs266/dawn-go-common v0.0.0-20221205185728-2a3bf79effee + github.com/tgs266/dawn-go-common v0.0.0-20221206030504-5f380b46dded go.mongodb.org/mongo-driver v1.7.3 gonum.org/v1/gonum v0.9.3 ) diff --git a/go.sum b/go.sum index 839324e1815920f5c5ee012686fc3e03fa0596ef..16ca9c58211790552145b66c5cbd541be1dade81 100644 --- a/go.sum +++ b/go.sum @@ -458,6 +458,8 @@ github.com/swaggo/swag v1.8.6 h1:2rgOaLbonWu1PLP6G+/rYjSvPg0jQE0HtrEKuE380eg= github.com/swaggo/swag v1.8.6/go.mod h1:jMLeXOOmYyjk8PvHTsXBdrubsNd9gUJTTCzL5iBnseg= github.com/tgs266/dawn-go-common v0.0.0-20221205185728-2a3bf79effee h1:xj6dQOrNY04WjPHxd4O8Z06bs6AxSosoiaEZMrHpPpI= github.com/tgs266/dawn-go-common v0.0.0-20221205185728-2a3bf79effee/go.mod h1:6beeKsmO0CLGRQj/mCk5jqvocsHqr76n5u4NAGmz5w8= +github.com/tgs266/dawn-go-common v0.0.0-20221206030504-5f380b46dded h1:mI0dR/ji2qIlYBDBj8KZEwycwEv81cuWUT0VQBRMDAQ= +github.com/tgs266/dawn-go-common v0.0.0-20221206030504-5f380b46dded/go.mod h1:gRZb/gtB9UhxUxfdbPyyUDikyNAksVyPohqOrCOLEqE= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/undefinedlabs/go-mpatch v1.0.6 h1:h8q5ORH/GaOE1Se1DMhrOyljXZEhRcROO7agMqWXCOY= diff --git a/models/enums/product_type_test.go b/models/enums/product_type_test.go deleted file mode 100644 index 6de04b9d6775ce4d687344c5e3eef9bf0712d1f7..0000000000000000000000000000000000000000 --- a/models/enums/product_type_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package enums - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestProduct(t *testing.T) { - testTable := make(map[string]string) - testTable["corn"] = "CORN" - testTable["coRn"] = "CORN" - testTable["soybean"] = "SOYBEAN" - testTable["sunflower"] = "SUNFLOWER" - testTable["tomato"] = "TOMATO" - testTable["sugar_beet"] = "SUGAR_BEET" - testTable["peanut"] = "PEANUT" - testTable["cotton"] = "COTTON" - testTable["potato"] = "POTATO" - testTable["wheat"] = "WHEAT" - testTable["pea"] = "PEA" - testTable["oat"] = "OAT" - testTable["spring_wheat"] = "SPRING_WHEAT" - testTable["rice"] = "RICE" - testTable["sorghum"] = "SORGHUM" - - for k := range testTable { - assert.Equal(t, testTable[k], GetProductFromString(k).Name) - } -} diff --git a/models/maturity.go b/models/maturity.go index 561f0584fd3bcd1fb6aa4bcbaa8bb948b5f7c51e..5c4a1e41dad0686700e8c2be22883d25ad116e9b 100644 --- a/models/maturity.go +++ b/models/maturity.go @@ -1,154 +1,154 @@ -package models - -import ( - "strconv" - "time" - - validation "github.com/go-ozzo/ozzo-validation" - - "github.com/tgs266/dawn-go-common/common" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence/entities" -) - -type CultivarRequest struct { - Name string `json:"name"` -} - -type Cultivar struct { - VarName string `json:"var_name"` - VarNum string `json:"var_num"` - EcoNum string `json:"eco_num"` - P1 float64 `json:"p1"` - P2 float64 `json:"p2"` - P5 float64 `json:"p5"` - G2 float64 `json:"g2"` - G3 float64 `json:"g3"` - PHINT float64 `json:"phint"` -} - -type CultivarResponse struct { - Cultivars []Cultivar `json:"cultivars"` -} - -func CreateCultivar(c entities.Cultivar) Cultivar { - return Cultivar{ - VarName: c.VarName, - VarNum: c.VarNum, - EcoNum: c.EcoNum, - P1: c.P1, - P2: c.P2, - P5: c.P5, - G2: c.P2, - G3: c.G3, - PHINT: c.PHINT, - } -} - -type CornMaturityRequest struct { - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` - PlantDate time.Time `json:"plant_date"` - VarName string `json:"var_name"` - VarNum string `json:"var_num"` - EcoNum string `json:"eco_num"` - P1 float64 `json:"p1"` - P2 float64 `json:"p2"` - P5 float64 `json:"p5"` - G2 float64 `json:"g2"` - G3 float64 `json:"g3"` - PHINT float64 `json:"phint"` -} - -type CornRMMaturityRequest struct { - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` - PlantDate time.Time `json:"plant_date"` - RelativeMaturity int `json:"relative_maturity"` -} - -type CornMaturityResponse struct { - HarvestDate time.Time `json:"harvest_date"` -} - -func (r CornMaturityRequest) Validate() error { - - return validation.ValidateStruct(&r, - validation.Field(&r.Latitude, validation.Required, validation.Min(-90.0), validation.Max(90.0)), - validation.Field(&r.Longitude, validation.Required, validation.Min(-180.0), validation.Max(180.0)), - ) -} - -func (r CornRMMaturityRequest) Validate() error { - - return validation.ValidateStruct(&r, - validation.Field(&r.Latitude, validation.Required, validation.Min(-90.0), validation.Max(90.0)), - validation.Field(&r.Longitude, validation.Required, validation.Min(-180.0), validation.Max(180.0)), - ) -} - -func BuildCornMaturityRequest(ctx common.DawnCtx) CornMaturityRequest { - - latitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("latitude", "-100000.0"), 64) - longitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("longitude", "-100000.0"), 64) - - varName := ctx.FiberCtx.Query("var_name", "") - varNum := ctx.FiberCtx.Query("var_num", "") - ecoNum := ctx.FiberCtx.Query("eco_num", "") - plant_month, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_month", "0")) - plant_day, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_day", "0")) - - plant_date := time.Date(time.Now().Year(), time.Month(plant_month), plant_day, 0, 0, 0, 0, time.UTC) - - p1, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p1", "0"), 64) - p2, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p2", "0"), 64) - p5, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p5", "0"), 64) - g2, _ := strconv.ParseFloat(ctx.FiberCtx.Query("g2", "0"), 64) - g3, _ := strconv.ParseFloat(ctx.FiberCtx.Query("g3", "0"), 64) - phint, _ := strconv.ParseFloat(ctx.FiberCtx.Query("phint", "0"), 64) - rNew := CornMaturityRequest{ - Latitude: latitude, - Longitude: longitude, - VarName: varName, - VarNum: varNum, - EcoNum: ecoNum, - P1: p1, - P2: p2, - P5: p5, - G2: g2, - G3: g3, - PHINT: phint, - PlantDate: plant_date, - } - - if rNew.Validate() != nil { - panic(config.BAD_REQUEST) - } - return rNew - -} - -func BuildCornRMMaturityRequest(ctx common.DawnCtx) CornRMMaturityRequest { - - latitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("latitude", "-100000.0"), 64) - longitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("longitude", "-100000.0"), 64) - rm, _ := strconv.Atoi(ctx.FiberCtx.Query("relative_maturity", "0")) - - plant_month, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_month", "0")) - plant_day, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_day", "0")) - - plant_date := time.Date(time.Now().Year(), time.Month(plant_month), plant_day, 0, 0, 0, 0, time.UTC) - - rNew := CornRMMaturityRequest{ - Latitude: latitude, - Longitude: longitude, - PlantDate: plant_date, - RelativeMaturity: rm, - } - - if err := rNew.Validate(); err != nil { - panic(config.BAD_REQUEST.PutDetail("reason", err.Error())) - } - return rNew - -} +package models + +import ( + "strconv" + "time" + + validation "github.com/go-ozzo/ozzo-validation" + + "github.com/tgs266/dawn-go-common/common" + "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" + "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence/entities" +) + +type CultivarRequest struct { + Name string `json:"name"` +} + +type Cultivar struct { + VarName string `json:"var_name"` + VarNum string `json:"var_num"` + EcoNum string `json:"eco_num"` + P1 float64 `json:"p1"` + P2 float64 `json:"p2"` + P5 float64 `json:"p5"` + G2 float64 `json:"g2"` + G3 float64 `json:"g3"` + PHINT float64 `json:"phint"` +} + +type CultivarResponse struct { + Cultivars []Cultivar `json:"cultivars"` +} + +func CreateCultivar(c entities.Cultivar) Cultivar { + return Cultivar{ + VarName: c.VarName, + VarNum: c.VarNum, + EcoNum: c.EcoNum, + P1: c.P1, + P2: c.P2, + P5: c.P5, + G2: c.P2, + G3: c.G3, + PHINT: c.PHINT, + } +} + +type CornMaturityRequest struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + PlantDate time.Time `json:"plant_date"` + VarName string `json:"var_name"` + VarNum string `json:"var_num"` + EcoNum string `json:"eco_num"` + P1 float64 `json:"p1"` + P2 float64 `json:"p2"` + P5 float64 `json:"p5"` + G2 float64 `json:"g2"` + G3 float64 `json:"g3"` + PHINT float64 `json:"phint"` +} + +type CornRMMaturityRequest struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + PlantDate time.Time `json:"plant_date"` + RelativeMaturity int `json:"relative_maturity"` +} + +type CornMaturityResponse struct { + HarvestDate time.Time `json:"harvest_date"` +} + +func (r CornMaturityRequest) Validate() error { + + return validation.ValidateStruct(&r, + validation.Field(&r.Latitude, validation.Required, validation.Min(-90.0), validation.Max(90.0)), + validation.Field(&r.Longitude, validation.Required, validation.Min(-180.0), validation.Max(180.0)), + ) +} + +func (r CornRMMaturityRequest) Validate() error { + + return validation.ValidateStruct(&r, + validation.Field(&r.Latitude, validation.Required, validation.Min(-90.0), validation.Max(90.0)), + validation.Field(&r.Longitude, validation.Required, validation.Min(-180.0), validation.Max(180.0)), + ) +} + +func BuildCornMaturityRequest(ctx common.DawnCtx) CornMaturityRequest { + + latitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("latitude", "-100000.0"), 64) + longitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("longitude", "-100000.0"), 64) + + varName := ctx.FiberCtx.Query("var_name", "") + varNum := ctx.FiberCtx.Query("var_num", "") + ecoNum := ctx.FiberCtx.Query("eco_num", "") + plant_month, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_month", "0")) + plant_day, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_day", "0")) + + plant_date := time.Date(time.Now().Year(), time.Month(plant_month), plant_day, 0, 0, 0, 0, time.UTC) + + p1, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p1", "0"), 64) + p2, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p2", "0"), 64) + p5, _ := strconv.ParseFloat(ctx.FiberCtx.Query("p5", "0"), 64) + g2, _ := strconv.ParseFloat(ctx.FiberCtx.Query("g2", "0"), 64) + g3, _ := strconv.ParseFloat(ctx.FiberCtx.Query("g3", "0"), 64) + phint, _ := strconv.ParseFloat(ctx.FiberCtx.Query("phint", "0"), 64) + rNew := CornMaturityRequest{ + Latitude: latitude, + Longitude: longitude, + VarName: varName, + VarNum: varNum, + EcoNum: ecoNum, + P1: p1, + P2: p2, + P5: p5, + G2: g2, + G3: g3, + PHINT: phint, + PlantDate: plant_date, + } + + if rNew.Validate() != nil { + panic(config.BAD_REQUEST) + } + return rNew + +} + +func BuildCornRMMaturityRequest(ctx common.DawnCtx) CornRMMaturityRequest { + + latitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("latitude", "-100000.0"), 64) + longitude, _ := strconv.ParseFloat(ctx.FiberCtx.Query("longitude", "-100000.0"), 64) + rm, _ := strconv.Atoi(ctx.FiberCtx.Query("relative_maturity", "0")) + + plant_month, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_month", "0")) + plant_day, _ := strconv.Atoi(ctx.FiberCtx.Query("plant_day", "0")) + + plant_date := time.Date(time.Now().Year(), time.Month(plant_month), plant_day, 0, 0, 0, 0, time.UTC) + + rNew := CornRMMaturityRequest{ + Latitude: latitude, + Longitude: longitude, + PlantDate: plant_date, + RelativeMaturity: rm, + } + + if err := rNew.Validate(); err != nil { + panic(config.BAD_REQUEST.PutDetail("reason", err.Error())) + } + return rNew + +} diff --git a/persistence/mongodb.go b/persistence/mongodb.go index 08ac7a5815d31f1da033371dc174c1a4fbb729b3..7277c890fabc0bbc0486dbad5bbf2ad41f752ad0 100644 --- a/persistence/mongodb.go +++ b/persistence/mongodb.go @@ -2,7 +2,6 @@ package persistence import ( "context" - "strings" "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" @@ -24,7 +23,8 @@ func NomadsRepository() repositories.NomadsRepository { return repositories.NewNomadsRepository(Session) } -func FreezingDatesRepository() repositories.FreezingDatesRepository { +// so we can replace during testing +var FreezingDatesRepository = func() repositories.FreezingDatesRepository { return repositories.NewFreezingDatesRepository(Session) } @@ -78,67 +78,6 @@ func buildLocationRequestLarger(location entities.Location, year *int) bson.M { return filter } -func FindFreezingDates(location entities.Location) entities.FreezingDates { - coll := Session.Collection("freezing_dates") - - filter := buildLocationRequest(location, nil) - - var g entities.FreezingDates - err := coll.FindOne(Session.Ctx, filter).Decode(&g) - if err != nil { - panic(config.NO_DATA_FOUND) - } - - return g -} - -func FindSeed(seedName string) entities.Seed { - coll := Session.Collection("seeds") - - filter := bson.D{ - {Key: "seed", Value: seedName}, - } - - var g entities.Seed - err := coll.FindOne(Session.Ctx, filter).Decode(&g) - if err != nil { - panic(config.NO_DATA_FOUND) - } - - return g -} - -func FindSeeds(product string) []entities.Seed { - - coll := Session.Collection("seeds") - - filter := bson.D{ - {Key: "type", Value: strings.ToLower(product)}, - } - - var results []entities.Seed - - options := options.Find() - - cursor, err := coll.Find(Session.Ctx, filter, options) - if err != nil { - panic(config.NO_DATA_FOUND) - } - - for cursor.Next(context.TODO()) { - - var elem entities.Seed - err := cursor.Decode(&elem) - if err != nil { - panic(config.NO_DATA_FOUND) - } - - results = append(results, elem) - } - - return results -} - func FindCultivarByName(name string) entities.Cultivar { coll := Session.Collection("dssat") diff --git a/persistence/repositories/freezing_dates.go b/persistence/repositories/freezing_dates.go index a7fffcc717b8d949f5e0c899fa85276004c2c6c8..417fdc2584bb0c6a8840f04c12d1eed2feaf97d3 100644 --- a/persistence/repositories/freezing_dates.go +++ b/persistence/repositories/freezing_dates.go @@ -1,6 +1,7 @@ package repositories import ( + "context" errs "errors" "github.com/tgs266/dawn-go-common/common" @@ -10,7 +11,7 @@ import ( ) type FreezingDatesRepository interface { - FindFreezingDatesByLocation(ctx common.DawnCtx, location entities.Location) entities.FreezingDates + FindFreezingDatesByLocation(ctx context.Context, location entities.Location) entities.FreezingDates } type freezingDatesRepositoryImpl struct { @@ -23,13 +24,13 @@ func NewFreezingDatesRepository(session *common.DBSession) FreezingDatesReposito } } -func (g *freezingDatesRepositoryImpl) FindFreezingDatesByLocation(ctx common.DawnCtx, location entities.Location) entities.FreezingDates { +func (g *freezingDatesRepositoryImpl) FindFreezingDatesByLocation(ctx context.Context, location entities.Location) entities.FreezingDates { coll := g.session.Collection("freezing_dates") filter := buildLocationRequest(location, nil) var v entities.FreezingDates - err := coll.FindOne(ctx.FiberCtx.Context(), filter).Decode(&v) + err := coll.FindOne(ctx, filter).Decode(&v) if errs.Is(err, mongo.ErrNoDocuments) { panic(errors.NewNotFound(err).PutDetail("reason", "freezing_dates")) } else if err != nil { diff --git a/persistence/repositories/gdd.go b/persistence/repositories/gdd.go index b7ff7934503c9ca51c9ed87d25ff897a341bbbf0..3a9a5b88fa93bf2c90ed1caf85b44737063089b7 100644 --- a/persistence/repositories/gdd.go +++ b/persistence/repositories/gdd.go @@ -1,6 +1,7 @@ package repositories import ( + "context" errs "errors" "github.com/tgs266/dawn-go-common/common" @@ -14,16 +15,16 @@ import ( type GddRepository interface { // FindCurrentGddByLocation finds the current GDD value for a given location. - FindCurrentGddByLocation(ctx common.DawnCtx, location entities.Location) entities.Gdd + FindCurrentGddByLocation(ctx context.Context, location entities.Location) entities.Gdd // FindGddByLocationAndYear finds the GDD value for a given location and year. - FindGddByLocationAndYear(ctx common.DawnCtx, year int, location entities.Location) entities.Gdd + FindGddByLocationAndYear(ctx context.Context, year int, location entities.Location) entities.Gdd // FindGddsOverNormalsRangeByLocation finds the GDD values for a given location over a range of years. - FindGddsOverNormalsRangeByLocation(ctx common.DawnCtx, location entities.Location) []entities.Gdd + FindGddsOverNormalsRangeByLocation(ctx context.Context, location entities.Location) []entities.Gdd // FindAnalogYearByLocation finds the analog year for a given location. - FindAnalogYearByLocation(ctx common.DawnCtx, location entities.Location) models.AnalogResponse + FindAnalogYearByLocation(ctx context.Context, location entities.Location) models.AnalogResponse } type gddRepositoryImpl struct { @@ -74,13 +75,13 @@ func buildLocationRequestLarger(location entities.Location, year *int) bson.M { } // FindCurrentGddByLocation finds the current Gdd based on the given location. -func (g *gddRepositoryImpl) FindCurrentGddByLocation(ctx common.DawnCtx, location entities.Location) entities.Gdd { +func (g *gddRepositoryImpl) FindCurrentGddByLocation(ctx context.Context, location entities.Location) entities.Gdd { coll := g.session.Collection("gdd_current") filter := buildLocationRequest(location, nil) var gdd entities.Gdd - if err := coll.FindOne(ctx.FiberCtx.Context(), filter).Decode(&gdd); err != nil { + if err := coll.FindOne(ctx, filter).Decode(&gdd); err != nil { if errs.Is(err, mongo.ErrNoDocuments) { panic(errors.NewNotFound(err).PutDetail("reason", "gdd_current")) } @@ -90,13 +91,13 @@ func (g *gddRepositoryImpl) FindCurrentGddByLocation(ctx common.DawnCtx, locatio } // FindGddByLocationAndYear finds the Gdd based on the given location and year. -func (g *gddRepositoryImpl) FindGddByLocationAndYear(ctx common.DawnCtx, year int, location entities.Location) entities.Gdd { +func (g *gddRepositoryImpl) FindGddByLocationAndYear(ctx context.Context, year int, location entities.Location) entities.Gdd { coll := g.session.Collection("gdd") filter := buildLocationRequest(location, &year) var gdds entities.Gdd - if err := coll.FindOne(ctx.FiberCtx.Context(), filter).Decode(&gdds); err != nil { + if err := coll.FindOne(ctx, filter).Decode(&gdds); err != nil { if errs.Is(err, mongo.ErrNoDocuments) { panic(errors.NewNotFound(err).PutDetail("reason", "gdd")) } @@ -107,19 +108,19 @@ func (g *gddRepositoryImpl) FindGddByLocationAndYear(ctx common.DawnCtx, year in // FindGddsOverNormalsRangeByLocation returns a slice of Gdd entities for the given location // within the year range from 1991 to 2020. It panics if an error occurs or if no Gdd entities are found. -func (g *gddRepositoryImpl) FindGddsOverNormalsRangeByLocation(ctx common.DawnCtx, location entities.Location) []entities.Gdd { +func (g *gddRepositoryImpl) FindGddsOverNormalsRangeByLocation(ctx context.Context, location entities.Location) []entities.Gdd { coll := g.session.Collection("gdd") filter := buildLocationRequest(location, nil) filter["year"] = bson.M{"$gte": 1991, "$lte": 2020} - cursor, err := coll.Find(ctx.FiberCtx.Context(), filter, options.Find().SetLimit(30)) + cursor, err := coll.Find(ctx, filter, options.Find().SetLimit(30)) if err != nil { panic(errors.NewInternal(err).PutDetail("reason", "gdd")) } var gdds []entities.Gdd - if err = cursor.All(ctx.FiberCtx.Context(), &gdds); err != nil { + if err = cursor.All(ctx, &gdds); err != nil { panic(errors.NewInternal(err)) } @@ -129,7 +130,7 @@ func (g *gddRepositoryImpl) FindGddsOverNormalsRangeByLocation(ctx common.DawnCt return gdds } -func (g *gddRepositoryImpl) FindAnalogYearByLocation(ctx common.DawnCtx, location entities.Location) models.AnalogResponse { +func (g *gddRepositoryImpl) FindAnalogYearByLocation(ctx context.Context, location entities.Location) models.AnalogResponse { gdds := g.FindCurrentGddByLocation(ctx, location) return models.AnalogResponse{ ClosestLatitude: gdds.Location.Coordinates[1], diff --git a/persistence/repositories/nomads.go b/persistence/repositories/nomads.go index 866ea44dbbdb9e2026adc8fa447372c947d9dac1..1f298479df9bd95c84afc08b5ac1058e3d2d1cf7 100644 --- a/persistence/repositories/nomads.go +++ b/persistence/repositories/nomads.go @@ -1,6 +1,7 @@ package repositories import ( + "context" errs "errors" "github.com/bradfitz/slice" @@ -12,10 +13,10 @@ import ( ) type NomadsRepository interface { - FindCfsByLocation(ctx common.DawnCtx, location entities.Location) []entities.CfsGdd - FindCfsByLocationWithExpand(ctx common.DawnCtx, location entities.Location, areaExpand int) []entities.CfsGdd - FindCfsAverageByLocation(ctx common.DawnCtx, location entities.Location) entities.CfsGdd - FindGefsByLocation(ctx common.DawnCtx, location entities.Location) []entities.GefsGdd + FindCfsByLocation(ctx context.Context, location entities.Location) []entities.CfsGdd + FindCfsByLocationWithExpand(ctx context.Context, location entities.Location, areaExpand int) []entities.CfsGdd + FindCfsAverageByLocation(ctx context.Context, location entities.Location) entities.CfsGdd + FindGefsByLocation(ctx context.Context, location entities.Location) []entities.GefsGdd } type nomadsRepositoryImpl struct { @@ -28,7 +29,7 @@ func NewNomadsRepository(session *common.DBSession) NomadsRepository { } } -func (g *nomadsRepositoryImpl) FindGefsByLocation(ctx common.DawnCtx, location entities.Location) []entities.GefsGdd { +func (g *nomadsRepositoryImpl) FindGefsByLocation(ctx context.Context, location entities.Location) []entities.GefsGdd { coll := g.session.Collection("gefs") filter := buildLocationRequestLarger(location, nil) @@ -40,12 +41,12 @@ func (g *nomadsRepositoryImpl) FindGefsByLocation(ctx common.DawnCtx, location e count := 10 options.SetLimit(int64(count)) - cursor, err := coll.Find(ctx.FiberCtx.Context(), filter, options) + cursor, err := coll.Find(ctx, filter, options) if err != nil { panic(errors.NewInternal(err).PutDetail("reason", "gefs")) } - if err = cursor.All(ctx.FiberCtx.Context(), &results); err != nil { + if err = cursor.All(ctx, &results); err != nil { panic(errors.NewInternal(err)) } @@ -60,14 +61,14 @@ func (g *nomadsRepositoryImpl) FindGefsByLocation(ctx common.DawnCtx, location e } // returns -1 member from cfs, which is the average of all other members -func (g *nomadsRepositoryImpl) FindCfsAverageByLocation(ctx common.DawnCtx, location entities.Location) entities.CfsGdd { +func (g *nomadsRepositoryImpl) FindCfsAverageByLocation(ctx context.Context, location entities.Location) entities.CfsGdd { coll := g.session.Collection("cfs") filter := buildLocationRequestLarger(location, nil) // -1 is the mean of all filter["member"] = -1 var cfs entities.CfsGdd - err := coll.FindOne(ctx.FiberCtx.Context(), filter).Decode(&cfs) + err := coll.FindOne(ctx, filter).Decode(&cfs) if errs.Is(err, mongo.ErrNoDocuments) { panic(errors.NewNotFound(err).PutDetail("reason", "cfs")) @@ -79,13 +80,13 @@ func (g *nomadsRepositoryImpl) FindCfsAverageByLocation(ctx common.DawnCtx, loca } // this gets the cfs for a location, and using the parameter areaExpand allows you to expand the area of the data collection to get more samples -func (g *nomadsRepositoryImpl) findCfsByLocationInternal(ctx common.DawnCtx, location entities.Location, areaExpand int) []entities.CfsGdd { +func (g *nomadsRepositoryImpl) findCfsByLocationInternal(ctx context.Context, location entities.Location, areaExpand int) []entities.CfsGdd { count := g.FindCfsAverageByLocation(ctx, location).Count coll := g.session.Collection("cfs") filter := buildLocationRequestLarger(location, nil) - cursor, err := coll.Find(ctx.FiberCtx.Context(), filter, options.Find().SetLimit(int64(count*areaExpand))) + cursor, err := coll.Find(ctx, filter, options.Find().SetLimit(int64(count*areaExpand))) var gs []entities.CfsGdd @@ -93,7 +94,7 @@ func (g *nomadsRepositoryImpl) findCfsByLocationInternal(ctx common.DawnCtx, loc panic(errors.NewInternal(err).PutDetail("reason", "cfs")) } - if err = cursor.All(ctx.FiberCtx.Context(), &gs); err != nil { + if err = cursor.All(ctx, &gs); err != nil { panic(errors.NewInternal(err)) } @@ -104,10 +105,10 @@ func (g *nomadsRepositoryImpl) findCfsByLocationInternal(ctx common.DawnCtx, loc return gs } -func (g *nomadsRepositoryImpl) FindCfsByLocation(ctx common.DawnCtx, location entities.Location) []entities.CfsGdd { +func (g *nomadsRepositoryImpl) FindCfsByLocation(ctx context.Context, location entities.Location) []entities.CfsGdd { return g.findCfsByLocationInternal(ctx, location, 1) } -func (g *nomadsRepositoryImpl) FindCfsByLocationWithExpand(ctx common.DawnCtx, location entities.Location, areaExpand int) []entities.CfsGdd { +func (g *nomadsRepositoryImpl) FindCfsByLocationWithExpand(ctx context.Context, location entities.Location, areaExpand int) []entities.CfsGdd { return g.findCfsByLocationInternal(ctx, location, areaExpand) } diff --git a/services/confidence_interval_service.go b/services/confidence_interval_service.go index 6ff62605587ec4db193b9233bbc8d03efe2fbd62..acc1f62c7b174bc708881452f83d0db030e27aed 100644 --- a/services/confidence_interval_service.go +++ b/services/confidence_interval_service.go @@ -1,14 +1,15 @@ package services import ( - "github.com/tgs266/dawn-go-common/common" + "context" + "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/utils" "gonum.org/v1/gonum/stat" ) -func GetConfidenceInterval(ctx common.DawnCtx, request models.ConfidenceIntervalRequest) models.ConfidenceIntervalResposne { +func GetConfidenceInterval(ctx context.Context, request models.ConfidenceIntervalRequest) models.ConfidenceIntervalResposne { gs := persistence.GddRepository().FindGddsOverNormalsRangeByLocation(ctx, request.BuildLocation()) product := request.Product diff --git a/services/data_download_service.go b/services/data_download_service.go index 58ade9f278e7423027fe7618d0acf95bb94cb9e5..d6370eb9e263c643fdb99b6653b7e89f48fad29e 100644 --- a/services/data_download_service.go +++ b/services/data_download_service.go @@ -1,6 +1,7 @@ package services import ( + "context" "encoding/csv" "fmt" "io/ioutil" @@ -111,7 +112,7 @@ func getPrimary(c common.DawnCtx, request models.CSVRequest, dates []time.Time) return gddValues } -func getNormals(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time) []float64 { +func getNormals(ctx context.Context, request models.CSVRequest, dates []time.Time) []float64 { gddRequest := models.GddRequest{ PlantingDate: utils.GetFirstOfTheYearForYear(request.Year), Product: request.Product, @@ -194,7 +195,7 @@ func parseDate(date string, year int) time.Time { panic(config.DATE_PARSE_FAILURE.AddLogDetails("Failed converting " + date + " to proper format.")) } -func getFreezingDates(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time) [][]int { +func getFreezingDates(ctx context.Context, request models.CSVRequest, dates []time.Time) [][]int { freezingRequest := models.FreezingDateRequest{ Latitude: request.Latitude, @@ -254,7 +255,7 @@ func getComparisonYear(c common.DawnCtx, request models.CSVRequest, dates []time return gddValues } -func getConfidenceInterval(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time) [][]float64 { +func getConfidenceInterval(ctx context.Context, request models.CSVRequest, dates []time.Time) [][]float64 { ciRequest := models.ConfidenceIntervalRequest{ Interval: request.Range, @@ -268,7 +269,7 @@ func getConfidenceInterval(ctx common.DawnCtx, request models.CSVRequest, dates return [][]float64{response.LowerBound, response.UpperBound} } -func getCfsData(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time) [][]float64 { +func getCfsData(ctx context.Context, request models.CSVRequest, dates []time.Time) [][]float64 { gddRequest := models.GddRequest{ PlantingDate: utils.GetFirstOfTheYearForYear(request.Year), @@ -315,7 +316,7 @@ func getCfsData(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time return [][]float64{fullGddValues, fullLowerBound, fullUpperBound} } -func getGefsData(ctx common.DawnCtx, request models.CSVRequest, dates []time.Time) []float64 { +func getGefsData(ctx context.Context, request models.CSVRequest, dates []time.Time) []float64 { gddRequest := models.GddRequest{ PlantingDate: utils.GetFirstOfTheYearForYear(request.Year), diff --git a/services/data_download_service_test.go b/services/data_download_service_test.go deleted file mode 100644 index 892040d167917e2bddb66680728e9c4c4d7793b9..0000000000000000000000000000000000000000 --- a/services/data_download_service_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package services - -import ( - "testing" - "time" - - DawnTest "github.com/tgs266/dawn-go-common/testing" - - "github.com/stretchr/testify/assert" - "github.com/tgs266/dawn-go-common/common" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence/entities" -) - -var CSVRequest = models.CSVRequest{ - Analog: true, - Cfs: true, - CfsLower: true, - CfsUpper: true, - Comparison: true, - FirstFreezing: true, - Gefs: true, - LastFreezing: true, - Maximum: true, - Minimum: true, - Normals: true, - Primary: true, - ComparisonYear: 2019, - Product: "soybean", - Range: 95.0, - Temperature: 28, - Year: 2020, - Latitude: 12.0, - Longitude: 12.0, -} - -func mockGetGddValues(c common.DawnCtx, request models.GddRequest) models.GddResponse { - return models.GddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - LastDate: time.Date(2021, time.January, 4, 0, 0, 0, 0, time.Now().Location()), - } -} - -func mockGetCfsGddValues(request models.GddRequest) models.CfsGddResponse { - return models.CfsGddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - UpperBound: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - LowerBound: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - FirstDate: time.Date(2021, time.January, 3, 0, 0, 0, 0, time.UTC), - } -} - -func mockGetGefsGddValues(request models.GddRequest) models.GefsGddResponse { - return models.GefsGddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - UpperBound: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - LowerBound: []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}, - FirstDate: time.Date(2021, time.January, 3, 0, 0, 0, 0, time.UTC), - LastDate: time.Date(2021, time.January, 13, 0, 0, 0, 0, time.UTC), - } -} - -func mockGetNormalValues(request models.GddRequest) models.GddResponse { - return models.GddResponse{ - Product: request.Product, - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - GddValues: []float64{1.0, 2.0, 3.0, 4.0}, - LastDate: time.Date(2021, time.January, 4, 0, 0, 0, 0, time.Now().Location()), - } -} - -func mockFindAnalogYear(location entities.Location) models.AnalogResponse { - return models.AnalogResponse{ - ClosestLatitude: 4.0, - ClosestLongitude: 4.0, - AnalogYear: 2001, - } -} - -func mockGetConfidenceInterval(request models.ConfidenceIntervalRequest) models.ConfidenceIntervalResposne { - return models.ConfidenceIntervalResposne{ - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - LowerBound: []float64{1.0, 1.0, 2.0, 2.0}, - UpperBound: []float64{5.0, 5.0, 10.0, 10.0}, - } -} - -func mockGetFreezingDate(request models.FreezingDateRequest) models.FreezingDateResponse { - firstDateCounts := make(map[string]*models.SingleFreezingDate) - firstDateCounts["01-04"] = &models.SingleFreezingDate{ - Count: 4, - Years: []int{2020, 2014, 2013, 2011}, - } - firstDateCounts["03-04"] = &models.SingleFreezingDate{ - Count: 3, - Years: []int{1988, 2005, 1985}, - } - - lastDateCounts := make(map[string]*models.SingleFreezingDate) - lastDateCounts["10-04"] = &models.SingleFreezingDate{ - Count: 4, - Years: []int{2020, 2014, 2013, 2011}, - } - lastDateCounts["10-04"] = &models.SingleFreezingDate{ - Count: 3, - Years: []int{1988, 2005, 1985}, - } - return models.FreezingDateResponse{ - ClosestLatitude: request.Latitude, - ClosestLongitude: request.Longitude, - FirstDateCounts: firstDateCounts, - LastDateCounts: lastDateCounts, - } -} - -func TestFillKeys(t *testing.T) { - keys := fillKeys(CSVRequest) - assert.Equal(t, "Date", keys[0]) - assert.Equal(t, "Analog Year GDD", keys[1]) - assert.Equal(t, "Primary GDD (2020)", keys[12]) -} - -func TestParseDate(t *testing.T) { - year := 2021 - - date := "01-05" - nd, _ := time.Parse("2006-Jan-02", "2021-Jan-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "02-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Feb-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "03-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Mar-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "04-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Apr-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "05-05" - nd, _ = time.Parse("2006-Jan-02", "2021-May-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "06-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Jun-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "07-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Jul-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "08-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Aug-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "09-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Sep-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "10-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Oct-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "11-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Nov-05") - assert.Equal(t, nd, parseDate(date, year)) - - date = "12-05" - nd, _ = time.Parse("2006-Jan-02", "2021-Dec-05") - assert.Equal(t, nd, parseDate(date, year)) -} - -func TestGetPrimary(t *testing.T) { - mock := DawnTest.CreateMock(GetGddValues, mockGetGddValues) - defer mock.Unpatch() - - dates := fillDates() - - response := getPrimary(common.DawnCtx{}, CSVRequest, dates) - assert.Equal(t, 1.0, response[0]) -} - -// func TestGetNormals(t *testing.T) { -// mock := DawnTest.CreateMock(GetNormalValues, mockGetNormalValues) -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getNormals(CSVRequest, dates) -// assert.Equal(t, 1.0, response[0]) -// } - -// func TestGetAnalogYear(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.FindAnalogYear, mockFindAnalogYear) -// mock.AddMock(GetGddValues, mockGetGddValues) - -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getAnalogYear(&fiber.Ctx{}, CSVRequest, dates) -// assert.Equal(t, 1.0, response[0]) -// } - -// func TestGetFreezingDates(t *testing.T) { -// mock := DawnTest.CreateMock(GetFreezingDate, mockGetFreezingDate) - -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getFreezingDates(CSVRequest, dates) -// assert.Equal(t, 4, response[0][3]) -// } - -func TestGetComparisonYear(t *testing.T) { - mock := DawnTest.CreateMock(GetGddValues, mockGetGddValues) - - defer mock.Unpatch() - - dates := fillDates() - - response := getComparisonYear(common.DawnCtx{}, CSVRequest, dates) - assert.Equal(t, 1.0, response[0]) -} - -// func TestGetConfidenceInterval(t *testing.T) { -// mock := DawnTest.CreateMock(GetConfidenceInterval, mockGetConfidenceInterval) - -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getConfidenceInterval(CSVRequest, dates) -// assert.Equal(t, 1.0, response[0][0]) - -// } - -// func TestGetCfsData(t *testing.T) { -// mock := DawnTest.CreateMock(GetCfsGddValues, mockGetCfsGddValues) - -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getCfsData(CSVRequest, dates) -// assert.Equal(t, 1.0, response[0][2]) - -// } - -// func TestGetGefsGdd(t *testing.T) { -// mock := DawnTest.CreateMock(GetGefsGddValues, mockGetGefsGddValues) - -// defer mock.Unpatch() - -// dates := fillDates() - -// response := getGefsData(CSVRequest, dates) -// assert.Equal(t, 1.0, response[2]) -// } - -// func TestPullData(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.FindAnalogYear, mockFindAnalogYear) -// mock.AddMock(GetCfsGddValues, mockGetCfsGddValues) -// mock.AddMock(GetGddValues, mockGetGddValues) -// mock.AddMock(GetFreezingDate, mockGetFreezingDate) -// mock.AddMock(GetGefsGddValues, mockGetGefsGddValues) -// mock.AddMock(GetConfidenceInterval, mockGetConfidenceInterval) -// mock.AddMock(GetNormalValues, mockGetNormalValues) - -// defer mock.Unpatch() - -// response := pullData(common.DawnCtx{}, CSVRequest) -// assert.Equal(t, 1.0, response.Primary[0]) -// } diff --git a/services/forecast_service.go b/services/forecast_service.go index 9dfa564f5cacc09c3551d54d25a35f0088cd45de..6be38cbe3b285fdea461312292f475ae917286d4 100644 --- a/services/forecast_service.go +++ b/services/forecast_service.go @@ -1,11 +1,11 @@ package services import ( + "context" "math" "sort" "time" - "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" @@ -99,7 +99,7 @@ func getMatchKeys(matches map[string]float64) []string { hardcode the alpha (for lagrange smoothing) and binCount */ -func forecast(ctx common.DawnCtx, gddReq models.GddRequest, plantdate time.Time, matches map[string]float64, observed models.GddResponse, cfs []entities.CfsGdd) map[string]*models.Bins { +func forecast(ctx context.Context, gddReq models.GddRequest, plantdate time.Time, matches map[string]float64, observed models.GddResponse, cfs []entities.CfsGdd) map[string]*models.Bins { alpha := 1.0 binCount := 5 product := enums.GetProductFromString(gddReq.Product) @@ -238,7 +238,7 @@ func forecast(ctx common.DawnCtx, gddReq models.GddRequest, plantdate time.Time, // will use normals to determine dates for each stage // // this function allows normals to "wrap around" to get continuous values -func comparisonNormals(ctx common.DawnCtx, request models.GddRequest, plantdate time.Time, matches map[string]float64) map[string]time.Time { +func comparisonNormals(ctx context.Context, request models.GddRequest, plantdate time.Time, matches map[string]float64) map[string]time.Time { normals := GetNormalValues(ctx, request, 1) observedValues := normals.GddValues accumulatedGdds := 0.0 @@ -279,7 +279,7 @@ func comparisonNormals(ctx common.DawnCtx, request models.GddRequest, plantdate } // dispatches a go routine to handle the comparison values -func comparisonGoRoutine(ctx common.DawnCtx, request models.GddRequest, plantdate time.Time, matches map[string]float64, comparisonMode int, thread *dispatch.Thread[map[string]time.Time]) { +func comparisonGoRoutine(ctx context.Context, request models.GddRequest, plantdate time.Time, matches map[string]float64, comparisonMode int, thread *dispatch.Thread[map[string]time.Time]) { defer func() { thread.Recover(recover()) }() @@ -291,7 +291,7 @@ func comparisonGoRoutine(ctx common.DawnCtx, request models.GddRequest, plantdat return } -func asyncCollectGddsAndCfs(ctx common.DawnCtx, gddReq models.GddRequest) (models.GddResponse, []entities.CfsGdd) { +func asyncCollectGddsAndCfs(ctx context.Context, gddReq models.GddRequest) (models.GddResponse, []entities.CfsGdd) { gddThread := dispatch.New[models.GddResponse]() go func() { defer func() { @@ -336,7 +336,7 @@ func asyncCollectGddsAndCfs(ctx common.DawnCtx, gddReq models.GddRequest) (model 5. Join, and merge comparison results */ -func CalculateStages(ctx common.DawnCtx, request models.StageRequest) map[string]*models.Bins { +func CalculateStages(ctx context.Context, request models.StageRequest) map[string]*models.Bins { gddReq := models.GddRequest{ PlantingDate: request.PlantDate, Latitude: request.Latitude, @@ -382,7 +382,7 @@ func AvgDiff(data []int) float64 { return sum / float64(c) } -func ForecastFirstLastFreeze(ctx common.DawnCtx, request models.FreezingForecastRequest) models.FreezingForecastResponse { +func ForecastFirstLastFreeze(ctx context.Context, request models.FreezingForecastRequest) models.FreezingForecastResponse { // lastFreezeIdx := 0 // firstFreezeIdx := 0 diff --git a/services/freezing_date_service.go b/services/freezing_date_service.go index 08d2b3849150cd0c3f5a5a9e937aa5236c75b566..16bfea099af54f3301d5876a804b73f4a2364a96 100644 --- a/services/freezing_date_service.go +++ b/services/freezing_date_service.go @@ -1,10 +1,10 @@ package services import ( + "context" "fmt" "time" - "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" @@ -31,7 +31,7 @@ func isLeapYear(year int) bool { } } -func GetFreezingDate(ctx common.DawnCtx, request models.FreezingDateRequest) models.FreezingDateResponse { +func GetFreezingDate(ctx context.Context, request models.FreezingDateRequest) models.FreezingDateResponse { var freezingDates entities.FreezingDates freezingDates = persistence.FreezingDatesRepository().FindFreezingDatesByLocation(ctx, request.BuildLocation()) diff --git a/services/freezing_date_service_test.go b/services/freezing_date_service_test.go deleted file mode 100644 index 74f428a103b7a6a9c01c4b3fbe78e8ce018b8dbd..0000000000000000000000000000000000000000 --- a/services/freezing_date_service_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package services - -// func TestIsLeapYear(t *testing.T) { -// assert.True(t, isLeapYear(2000)) -// assert.False(t, isLeapYear(1999)) -// assert.True(t, isLeapYear(1980)) -// assert.False(t, isLeapYear(1990)) -// } - -// func mockFindFreezingDates(loc entities.Location) entities.FreezingDates { -// var dateCounts [][]int -// var inner []int -// inner = append(inner, 0) -// inner = append(inner, 0) -// inner = append(inner, -1) -// inner = append(inner, -0) -// dateCounts = append(dateCounts, inner) -// return entities.FreezingDates{ -// ID: "id", -// Location: loc, -// FirstDates: dateCounts, -// LastDates: dateCounts, -// AllowedTemps: []int{28}, -// } -// } - -// func TestGetFreezingDate(t *testing.T) { -// request := models.FreezingDateRequest{ -// Latitude: 12.0, -// Longitude: 12.0, -// FreezingTemp: 28, -// } - -// mock := DawnTest.CreateMock(persistence.FindFreezingDates, mockFindFreezingDates) -// defer mock.Unpatch() - -// response := GetFreezingDate(request) -// assert.Equal(t, 3, response.FirstDateCounts["01-01"].Count) -// } diff --git a/services/gdd_service.go b/services/gdd_service.go index 71ba4cbd8ca29a2221067f586c6500650b24173c..68766efcbeb3cf8c503f91d59557bf9177be5816 100644 --- a/services/gdd_service.go +++ b/services/gdd_service.go @@ -1,9 +1,9 @@ package services import ( + "context" "time" - "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" @@ -12,7 +12,7 @@ import ( "gonum.org/v1/gonum/stat" ) -func GetGddValues(ctx common.DawnCtx, request models.GddRequest) models.GddResponse { +func GetGddValues(ctx context.Context, request models.GddRequest) models.GddResponse { product := enums.GetProductFromString(request.Product) var gdds entities.Gdd if request.PlantingDate.Year() == time.Now().Year() { @@ -44,7 +44,7 @@ func GetGddValues(ctx common.DawnCtx, request models.GddRequest) models.GddRespo return returnGdds } -func GetNormalValues(ctx common.DawnCtx, request models.GddRequest, repeatYears int) models.GddResponse { +func GetNormalValues(ctx context.Context, request models.GddRequest, repeatYears int) models.GddResponse { product := enums.GetProductFromString(request.Product) gs := persistence.GddRepository().FindGddsOverNormalsRangeByLocation(ctx, request.BuildLocation()) var returnGdds models.GddResponse diff --git a/services/maturity_service.go b/services/maturity_service.go index 009d7ee01e4a63ebd8a74b42052c47c146f72b91..ae2eaa026ddf2dba79ba1d7fdd1d9b27b2b79d07 100644 --- a/services/maturity_service.go +++ b/services/maturity_service.go @@ -1,6 +1,7 @@ package services import ( + "context" "encoding/json" "fmt" "io" @@ -13,7 +14,6 @@ import ( "strings" "time" - "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" @@ -30,7 +30,7 @@ type CornMaturityConfig struct { Units string `json:"units"` } -func GetCultivars(ctx common.DawnCtx, request models.CultivarRequest) models.CultivarResponse { +func GetCultivars(ctx context.Context, request models.CultivarRequest) models.CultivarResponse { if request.Name != "" { elem := persistence.FindCultivarByName(request.Name) cultivar := models.CreateCultivar(elem) @@ -49,7 +49,7 @@ func GetCultivars(ctx common.DawnCtx, request models.CultivarRequest) models.Cul } } -func getFullYearData(ctx common.DawnCtx, latitude float64, longitude float64, plantDate time.Time) CornMaturityConfig { +func getFullYearData(ctx context.Context, latitude float64, longitude float64, plantDate time.Time) CornMaturityConfig { location := entities.Location{ Type: "Point", Coordinates: []float64{longitude, latitude}, @@ -77,7 +77,7 @@ func getFullYearData(ctx common.DawnCtx, latitude float64, longitude float64, pl } } -func CalculateMaturity(ctx common.DawnCtx, request models.CornMaturityRequest) models.CornMaturityResponse { +func CalculateMaturity(ctx context.Context, request models.CornMaturityRequest) models.CornMaturityResponse { cfg := getFullYearData(ctx, request.Latitude, request.Longitude, request.PlantDate) fileId := rand.Intn(99-10) + 10 @@ -153,7 +153,7 @@ func CalculateMaturity(ctx common.DawnCtx, request models.CornMaturityRequest) m } } -func CalculateRMMaturity(ctx common.DawnCtx, request models.CornRMMaturityRequest) models.CornMaturityResponse { +func CalculateRMMaturity(ctx context.Context, request models.CornRMMaturityRequest) models.CornMaturityResponse { fyData := getFullYearData(ctx, request.Latitude, request.Longitude, request.PlantDate) gdds := utils.CalculateGddValues(fyData.Tmins, fyData.Tmaxs, enums.ProductType.CORN, false) diff --git a/services/nomads_service.go b/services/nomads_service.go index d93cf81b3e247fc918bf3392d60c898b922ad687..1836df6d258ee7f23011015ab1b8c6d2e35e7dc6 100644 --- a/services/nomads_service.go +++ b/services/nomads_service.go @@ -1,9 +1,9 @@ package services import ( + "context" "math" - "github.com/tgs266/dawn-go-common/common" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" @@ -11,7 +11,7 @@ import ( "gonum.org/v1/gonum/stat" ) -func GetGefsGddValues(ctx common.DawnCtx, request models.GddRequest) models.GefsGddResponse { +func GetGefsGddValues(ctx context.Context, request models.GddRequest) models.GefsGddResponse { product := enums.GetProductFromString(request.Product) location := request.BuildLocation() g := persistence.NomadsRepository().FindGefsByLocation(ctx, location) @@ -68,7 +68,7 @@ func GetGefsGddValues(ctx common.DawnCtx, request models.GddRequest) models.Gefs return returnGdds } -func GetCfsGddValues(ctx common.DawnCtx, request models.GddRequest) models.CfsGddResponse { +func GetCfsGddValues(ctx context.Context, request models.GddRequest) models.CfsGddResponse { location := request.BuildLocation() gs := persistence.NomadsRepository().FindCfsByLocation(ctx, location) product := enums.GetProductFromString(request.Product) diff --git a/services/nomads_service_test.go b/services/nomads_service_test.go deleted file mode 100644 index 5d5b0c9cf37fca82ca3e21ac637a2cb10b16ec8b..0000000000000000000000000000000000000000 --- a/services/nomads_service_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package services - -import ( - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence/entities" -) - -func mockGefsFindAllByLocation(location entities.Location) []entities.GefsGdd { - var arr []entities.GefsGdd - - filler := entities.GefsGdd{ - ID: "id", - Location: entities.Location{ - Type: "point", - Coordinates: []float64{12.0, 12.0}, - }, - MinTemp: 45.0, - MaxTemp: 76.0, - VarMin: 1.0, - VarMax: 1.0, - Date: 215342634, - } - - arr = append(arr, - entities.GefsGdd{ - ID: "id", - Location: entities.Location{ - Type: "point", - Coordinates: []float64{12.0, 12.0}, - }, - MinTemp: 45.0, - MaxTemp: 76.0, - VarMin: 1.0, - VarMax: 1.0, - Date: 215342634, - }, - ) - - arr = append(arr, - entities.GefsGdd{ - ID: "id", - Location: entities.Location{ - Type: "point", - Coordinates: []float64{12.0, 12.0}, - }, - MinTemp: 65.0, - MaxTemp: 106.0, - VarMin: 1.0, - VarMax: 1.0, - Date: 215342634, - }, - ) - - arr = append(arr, - entities.GefsGdd{ - ID: "id", - Location: entities.Location{ - Type: "point", - Coordinates: []float64{12.0, 12.0}, - }, - MinTemp: 23.0, - MaxTemp: 45.0, - VarMin: 1.0, - VarMax: 1.0, - Date: 215342634, - }, - ) - - for i := 0; i < 7; i++ { - arr = append(arr, filler) - } - - return arr -} - -func mockCfsFindAllByLocation(location entities.Location) entities.CfsGdd { - return entities.CfsGdd{ - ID: "id", - Location: entities.Location{ - Type: "point", - Coordinates: []float64{12.0, 12.0}, - }, - MaxTemps: []float64{35.0, 55.0, 78.0}, - MinTemps: []float64{65.0, 43.0, 54.0}, - VarMin: []float64{1.0, 1.0, 1.0}, - VarMax: []float64{1.0, 1.0, 1.0}, - Date: 342653425, - } -} - -// func TestGetGefsGddValues(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.GefsFindAllByLocation, mockGefsFindAllByLocation) -// defer mock.Unpatch() - -// request := models.GddRequest{ -// Product: "soybean", -// Latitude: 12.0, -// Longitude: 12.0, -// Year: 2020, -// Accumulate: false, -// } - -// gdds := GetGefsGddValues(request) -// assert.Equal(t, 10.5, gdds.GddValues[0], "must equal") -// assert.Equal(t, 0.0, gdds.GddValues[2], "must equal") -// } - -// func TestGetGefsGddValuesAccumulate(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.GefsFindAllByLocation, mockGefsFindAllByLocation) -// defer mock.Unpatch() - -// request := models.GddRequest{ -// Product: "soybean", -// Latitude: 12.0, -// Longitude: 12.0, -// Year: 2020, -// Accumulate: true, -// } - -// gdds := GetGefsGddValues(request) -// assert.Equal(t, 10.5, gdds.GddValues[0], "must equal") -// assert.Equal(t, 46.0, gdds.GddValues[2], "must equal") -// } - -// func TestGetCefsGddValues(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.CfsFindAllByLocation, mockCfsFindAllByLocation) -// defer mock.Unpatch() - -// request := models.GddRequest{ -// Product: "soybean", -// Latitude: 12.0, -// Longitude: 12.0, -// Year: 2020, -// Accumulate: false, -// } - -// gdds := GetCfsGddValues(request) -// assert.Equal(t, 0.0, gdds.GddValues[0], "must equal") -// assert.Equal(t, 16.0, gdds.GddValues[2], "must equal") -// } - -// func TestGetCefsGddValuesAccumulate(t *testing.T) { -// mock := DawnTest.CreateMock(persistence.CfsFindAllByLocation, mockCfsFindAllByLocation) -// defer mock.Unpatch() - -// request := models.GddRequest{ -// Product: "corn", -// Latitude: 12.0, -// Longitude: 12.0, -// Year: 2020, -// Accumulate: true, -// } - -// gdds := GetCfsGddValues(request) -// assert.Equal(t, 7.5, gdds.GddValues[0], "must equal") -// assert.Equal(t, 26.0, gdds.GddValues[2], "must equal") -// } diff --git a/services/seed_service.go b/services/seed_service.go index f2c02b5195cb8fae0b664e7a835277dfd1663953..104be2dc4185d98f36b311a5400f7a4fd77c5189 100644 --- a/services/seed_service.go +++ b/services/seed_service.go @@ -1,69 +1,69 @@ -package services - -// import ( -// "math" -// "time" - -// "github.com/tgs266/dawn-go-common/common" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" -// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/utils" - -// "github.com/gofiber/fiber/v2" -// ) - -// func GetSeedList(c *fiber.Ctx, request models.SeedListRequest) models.SeedListResponse { -// product := enums.GetProductFromString(request.Product) -// if product.Name != enums.ProductType.CORN.Name && product.Name != enums.ProductType.SOYBEAN.Name { -// panic(config.INVALID_PRODUCT(request.Product)) -// } -// seeds := persistence.FindSeeds(product.Name) -// var results []string -// for i := 0; i < len(seeds); i++ { -// results = append(results, seeds[i].Seed) -// } -// return models.SeedListResponse{Seeds: results} -// } - -// func GetCornMaturityDate(ctx common.DawnCtx, request models.CornMaturityRequest) models.CornMaturityResponse { - -// gddRequest := models.GddRequest{ -// Year: time.Now().Year(), -// Product: "corn", -// Latitude: request.Latitude, -// Longitude: request.Longitude, -// Accumulate: false, -// } - -// gdds := GetFullYearGddValues(ctx, gddRequest) -// closestValue := 0.0 -// closestIdx := 0 -// gdus := 0.0 - -// startingDate := time.Date(time.Now().Year(), time.Month(request.Month), request.Date, 0, 0, 0, 0, time.UTC) -// startingIdx := startingDate.Sub(time.Date(time.Now().Year(), time.January, 1, 0, 0, 0, 0, time.UTC)) -// startingIdxVal := int(startingIdx.Hours() / 24) -// if isLeapYear(time.Now().Year()) { -// startingIdxVal -= 1 -// } - -// for i := startingIdxVal; i < len(gdds.GddValues); i++ { -// value := gdds.GddValues[i] -// gdus += value -// if math.Abs(gdus-request.Gdds) < math.Abs(closestValue-request.Gdds) { -// closestValue = gdus -// closestIdx = i -// } -// } -// response := models.CornMaturityResponse{ -// Date: utils.ConvertDateIdxToDate(closestIdx), -// GDD: request.Gdds, -// ClosestGDD: closestValue, -// ClosestLatitude: gdds.ClosestLatitude, -// ClosestLongitude: gdds.ClosestLongitude, -// } -// return response - -// } +package services + +// import ( +// "math" +// "time" + +// "github.com/tgs266/dawn-go-common/common" +// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/config" +// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models" +// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" +// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/persistence" +// "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/utils" + +// "github.com/gofiber/fiber/v2" +// ) + +// func GetSeedList(c *fiber.Ctx, request models.SeedListRequest) models.SeedListResponse { +// product := enums.GetProductFromString(request.Product) +// if product.Name != enums.ProductType.CORN.Name && product.Name != enums.ProductType.SOYBEAN.Name { +// panic(config.INVALID_PRODUCT(request.Product)) +// } +// seeds := persistence.FindSeeds(product.Name) +// var results []string +// for i := 0; i < len(seeds); i++ { +// results = append(results, seeds[i].Seed) +// } +// return models.SeedListResponse{Seeds: results} +// } + +// func GetCornMaturityDate(ctx context.Context, request models.CornMaturityRequest) models.CornMaturityResponse { + +// gddRequest := models.GddRequest{ +// Year: time.Now().Year(), +// Product: "corn", +// Latitude: request.Latitude, +// Longitude: request.Longitude, +// Accumulate: false, +// } + +// gdds := GetFullYearGddValues(ctx, gddRequest) +// closestValue := 0.0 +// closestIdx := 0 +// gdus := 0.0 + +// startingDate := time.Date(time.Now().Year(), time.Month(request.Month), request.Date, 0, 0, 0, 0, time.UTC) +// startingIdx := startingDate.Sub(time.Date(time.Now().Year(), time.January, 1, 0, 0, 0, 0, time.UTC)) +// startingIdxVal := int(startingIdx.Hours() / 24) +// if isLeapYear(time.Now().Year()) { +// startingIdxVal -= 1 +// } + +// for i := startingIdxVal; i < len(gdds.GddValues); i++ { +// value := gdds.GddValues[i] +// gdus += value +// if math.Abs(gdus-request.Gdds) < math.Abs(closestValue-request.Gdds) { +// closestValue = gdus +// closestIdx = i +// } +// } +// response := models.CornMaturityResponse{ +// Date: utils.ConvertDateIdxToDate(closestIdx), +// GDD: request.Gdds, +// ClosestGDD: closestValue, +// ClosestLatitude: gdds.ClosestLatitude, +// ClosestLongitude: gdds.ClosestLongitude, +// } +// return response + +// } diff --git a/utils/clip_test.go b/utils/clip_test.go deleted file mode 100644 index e6e6db45c2c3d389495859ab90e1911ea34bc419..0000000000000000000000000000000000000000 --- a/utils/clip_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package utils - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestClipInt(t *testing.T) { - value := 10 - assert.Equal(t, value, ClipInt(value, 0, 11)) -} - -func TestClipIntLow(t *testing.T) { - value := 4 - assert.Equal(t, 10, ClipInt(value, 10, 11)) -} - -func TestClipIntAbove(t *testing.T) { - value := 100 - assert.Equal(t, 11, ClipInt(value, 10, 11)) -} - -func TestClipFloat(t *testing.T) { - value := 10.0 - assert.Equal(t, value, ClipFloat(value, 0.0, 11.0)) -} - -func TestClipFloatLow(t *testing.T) { - value := 4.0 - assert.Equal(t, 10.0, ClipFloat(value, 10.0, 11.0)) -} - -func TestClipFloatAbove(t *testing.T) { - value := 100.0 - assert.Equal(t, 11.0, ClipFloat(value, 10.0, 11.0)) -} diff --git a/utils/gdd_calculations_test.go b/utils/gdd_calculations_test.go deleted file mode 100644 index 1257d62c7b96934565c6efb49412330fd0d3711e..0000000000000000000000000000000000000000 --- a/utils/gdd_calculations_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package utils - -import ( - "testing" - - "gitlab.cs.umd.edu/dawn/go-backend/dawn-gdd/models/enums" - - "github.com/stretchr/testify/assert" -) - -var minTempsArr = [...]float64{55.5, 62.4, 22.5, 96.5} -var maxTempsArr = [...]float64{78.4, 92.5, 55.8, 35.2} - -var normalBaseArr = [...]float64{50, 60, 70, 80} - -func Test_CalculateSingleGdd(t *testing.T) { - minTemp := minTempsArr[0] - maxTemp := maxTempsArr[0] - - expectedGdd := (minTemp + maxTemp) / 2 - expectedGdd -= enums.ProductType.SOYBEAN.BaseTemp - - assert.Equal(t, expectedGdd, CalculateSingleGdd(minTemp, maxTemp, enums.ProductType.SOYBEAN)) -} - -func Test_CalculateSingleGdd_Corn(t *testing.T) { - minTemp := minTempsArr[0] - maxTemp := maxTempsArr[0] - - expectedGdd := (minTemp + maxTemp) / 2 - expectedGdd -= enums.ProductType.CORN.BaseTemp - - assert.Equal(t, expectedGdd, CalculateSingleGdd(minTemp, maxTemp, enums.ProductType.CORN)) -} - -func Test_CalculateGddValues(t *testing.T) { - var expectedGdd []float64 - - for i := 0; i < 4; i++ { - val := (minTempsArr[i] + maxTempsArr[i]) / 2 - val -= enums.ProductType.OAT.BaseTemp - expectedGdd = append(expectedGdd, ClipMinFloat(val, 0)) - } - - assert.Equal(t, expectedGdd, CalculateGddValues(minTempsArr[:], maxTempsArr[:], enums.ProductType.OAT, false)) -} - -func Test_CalculateGddValues_Corn(t *testing.T) { - var expectedGdd []float64 - - for i := 0; i < 4; i++ { - val := (ClipFloat(minTempsArr[i], 50, 86) + ClipFloat(maxTempsArr[i], 50, 86)) / 2 - val -= enums.ProductType.CORN.BaseTemp - expectedGdd = append(expectedGdd, val) - } - - assert.Equal(t, expectedGdd, CalculateGddValues(minTempsArr[:], maxTempsArr[:], enums.ProductType.CORN, false)) -} - -func Test_CalculateGddValues_Accumulated(t *testing.T) { - var expectedGdd []float64 - for i := 0; i < 4; i++ { - val := (minTempsArr[i] + maxTempsArr[i]) / 2 - val -= enums.ProductType.WHEAT.BaseTemp - val = ClipMinFloat(val, 0) - if i > 0 { - val += expectedGdd[len(expectedGdd)-1] - } - expectedGdd = append(expectedGdd, val) - } - - assert.Equal(t, expectedGdd, CalculateGddValues(minTempsArr[:], maxTempsArr[:], enums.ProductType.WHEAT, true)) -}