licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 3324 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, rasterurl, CHELSA_warn_version, layers
bioclim_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "BioClim")
@testset "CHELSEA BioClim" begin
@test rasterpath(CHELSA{BioClim}) == bioclim_path
@test rasterurl(CHELSA) ==
URI(scheme="https", host="os.zhdk.cloud.switch.ch", path="")
# version 1
@test rastername(CHELSA{BioClim}, 5; version = 1) == "CHELSA_bio10_05.tif" # version 1
@test rasterpath(CHELSA{BioClim}, 5; version = 1) == joinpath(bioclim_path, "CHELSA_bio10_05.tif")
@test rasterurl(CHELSA{BioClim}, 5; version = 1) ==
URI(scheme="https", host="os.zhdk.cloud.switch.ch", path="/chelsav1/climatologies/bio/CHELSA_bio10_05.tif")
raster_path = joinpath(bioclim_path, "CHELSA_bio10_05.tif")
@test getraster(CHELSA{BioClim}, :bio5; version = 1) == raster_path
@test getraster(CHELSA{BioClim}, (5,); version = 1) == (bio5=raster_path,)
@test getraster(CHELSA{BioClim}, 5:5; version = 1) == (bio5=raster_path,)
@test getraster(CHELSA{BioClim}, [:bio5]; version = 1) == (bio5=raster_path,)
@test isfile(raster_path)
# version 2 (default)
# test if warning when downloading data for a new chelsa version works
@test_logs (:info, ) CHELSA_warn_version(CHELSA{BioClim}, 5, 2, 1, rasterpath(CHELSA{BioClim}, 5; version = 2))
@test rastername(CHELSA{BioClim}, 6) == "CHELSA_bio6_1981-2010_V.2.1.tif" # version 2
@test rasterpath(CHELSA{BioClim}, 6) == joinpath(bioclim_path, "CHELSA_bio6_1981-2010_V.2.1.tif")
@test rasterurl(CHELSA{BioClim}, 6) ==
URI(scheme="https", host="os.zhdk.cloud.switch.ch", path="/chelsav2/GLOBAL/climatologies/1981-2010/bio/CHELSA_bio6_1981-2010_V.2.1.tif")
raster_path = joinpath(bioclim_path, "CHELSA_bio6_1981-2010_V.2.1.tif")
@test getraster(CHELSA{BioClim}, :bio6) == raster_path
@test getraster(CHELSA{BioClim}, (6,)) == (bio6=raster_path,)
@test getraster(CHELSA{BioClim}, 6:6) == (bio6=raster_path,)
@test getraster(CHELSA{BioClim}, [:bio6]) == (bio6=raster_path,)
@test isfile(raster_path)
@test RasterDataSources.getraster_keywords(CHELSA{BioClim}) == (:version, :patch)
# test non-valid version
@test_throws ArgumentError rastername(CHELSA{BioClim}, 6; version = 3)
end
@testset "CHELSEA BioClimPlus" begin
@test rastername(CHELSA{BioClimPlus}, :bio5) == rastername(CHELSA{BioClim}, 5)
@test rasterpath(CHELSA{BioClimPlus}) == bioclim_path
@test rasterpath(CHELSA{BioClimPlus}, :clt_mean) == joinpath(bioclim_path, "CHELSA_clt_mean_1981-2010_V.2.1.tif")
@test rasterurl(CHELSA{BioClimPlus}, :clt_mean) ==
URI(scheme="https", host="os.zhdk.cloud.switch.ch", path="/chelsav2/GLOBAL/climatologies/1981-2010/bio/CHELSA_clt_mean_1981-2010_V.2.1.tif")
raster_path = joinpath(bioclim_path, "CHELSA_clt_mean_1981-2010_V.2.1.tif")
@test getraster(CHELSA{BioClimPlus}, :clt_mean) == raster_path
@test getraster(CHELSA{BioClimPlus}, [:clt_mean]) == (clt_mean=raster_path,)
@test isfile(raster_path)
@test RasterDataSources.getraster_keywords(CHELSA{BioClimPlus}) == (:version, :patch)
@test length(layers(CHELSA{BioClimPlus})) == 75
@test length(layers(CHELSA{Future{BioClimPlus}})) == 46
end | RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1115 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, rasterurl, layers
@testset "CHELSA Climate" begin
tmax_name = "CHELSA_tasmax_07_1981-2010_V.2.1.tif"
@test rastername(CHELSA{Climate}, :tasmax; month=7) == tmax_name
climate_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "Climate")
@test rasterpath(CHELSA{Climate}) == climate_path
raster_path = joinpath(climate_path, "tasmax", tmax_name)
@test rasterpath(CHELSA{Climate}, :tasmax; month=7) == raster_path
@test rasterurl(CHELSA{Climate}, :pr; month=6) |> string ==
"https://os.zhdk.cloud.switch.ch/chelsav2/GLOBAL/climatologies/1981-2010/pr/CHELSA_pr_06_1981-2010_V.2.1.tif"
@test getraster(CHELSA{Climate}, :tasmax; month=7) == raster_path
@test getraster(CHELSA{Climate}, [:tasmax]; month=7) == (tasmax=raster_path,)
@test getraster(CHELSA{Climate}, (:tasmax,); month=7:7) == [(tasmax=raster_path,)]
@test isfile(raster_path)
@test RasterDataSources.getraster_keywords(CHELSA{Climate}) == (:month,)
@test length(layers(CHELSA{Climate})) == 12
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 6754 | using RasterDataSources, Test, Dates
using RasterDataSources: rasterurl, rastername, rasterpath
@testset "CHELSA Future BioClim CMIP5" begin
@test rastername(CHELSA{Future{BioClim,CMIP5,CCSM4,RCP26}}, 5; date=Date(2050)) == "CHELSA_bio_mon_CCSM4_rcp26_r1i1p1_g025.nc_5_2041-2060_V1.2.tif"
bioclim_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "Future", "BioClim", "RCP26", "CCSM4")
@test rasterpath(CHELSA{Future{BioClim,CMIP5,CCSM4,RCP26}}) == bioclim_path
raster_path = joinpath(bioclim_path, "CHELSA_bio_mon_CCSM4_rcp26_r1i1p1_g025.nc_5_2041-2060_V1.2.tif")
@test getraster(CHELSA{Future{BioClim,CMIP5,CCSM4,RCP26}}, 5; date=Date(2050)) == raster_path
@test getraster(CHELSA{Future{BioClim,CMIP5,CCSM4,RCP26}}, (5,); date=Date(2050)) == (bio5=raster_path,)
@test getraster(CHELSA{Future{BioClim,CMIP5,CCSM4,RCP26}}, [5]; date=Date(2050)) == (bio5=raster_path,)
@test isfile(raster_path)
@test RasterDataSources.getraster_keywords(CHELSA{Future{BioClim}}) == (:date,)
end
@testset "CHELSA Future BioClim CMIP6" begin
bioclim_name = "CHELSA_bio5_2041-2070_mri-esm2-0_ssp126_V.2.1.tif"
@test rastername(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, 5; date=Date(2050)) == bioclim_name
bioclim_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "Future", "BioClim", "SSP126", "MRIESM2")
@test rasterpath(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}) == bioclim_path
raster_path = joinpath(bioclim_path, bioclim_name)
raster_path2 = joinpath(bioclim_path, "CHELSA_bio5_2071-2100_mri-esm2-0_ssp126_V.2.1.tif")
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, 5; date=Date(2050)) == raster_path
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, (5,); date=Date(2050)) == (bio5=raster_path,)
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, [5]; date=Date(2050)) == (bio5=raster_path,)
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, (5,); date=[Date(2050)]) ==
[(bio5=raster_path,)]
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, :bio5; date=Date(2050)) == raster_path
@test getraster(CHELSA{Future{BioClim,CMIP6,MRIESM2,SSP126}}, (:bio5,); date=Date(2050)) == (bio5=raster_path,)
@test getraster(CHELSA{Future{BioClimPlus,CMIP6,MRIESM2,SSP126}}, :bio5; date=Date(2050)) == raster_path
@test getraster(CHELSA{Future{BioClimPlus,CMIP6,MRIESM2,SSP126}}, (:bio5,); date=Date(2050)) == (bio5=raster_path,)
@test isfile(raster_path)
# bioclimplus requires symbol input
@test_throws ArgumentError getraster(CHELSA{Future{BioClimPlus,CMIP6,MRIESM2,SSP126}}, 5; date=Date(2050))
end
@testset "CHELSA Future Climate CMIP5" begin
tmax_name = "CHELSA_tasmax_mon_CCSM4_rcp60_r1i1p1_g025.nc_7_2041-2060_V1.2.tif"
@test rastername(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, :tmax; date=Date(2050), month=7) == tmax_name
climate_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "Future", "Climate", "RCP60", "CCSM4")
@test rasterpath(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}) == climate_path
raster_path = joinpath(climate_path, tmax_name)
@test rasterpath(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, :tmax; date=Date(2050), month=7) == raster_path
@test rasterurl(CHELSA{Future{Climate,CMIP5,CCSM4,RCP45}}, :prec; date=Date(2050), month=6) |> string ==
"https://os.zhdk.cloud.switch.ch/chelsav1/cmip5/2041-2060/prec/CHELSA_pr_mon_CCSM4_rcp45_r1i1p1_g025.nc_6_2041-2060.tif"
@test rasterurl(CHELSA{Future{Climate,CMIP5,CCSM4,RCP45}}, :tmin; date=Date(2050), month=1) |> string ==
"https://os.zhdk.cloud.switch.ch/chelsav1/cmip5/2041-2060/tmin/CHELSA_tasmin_mon_CCSM4_rcp45_r1i1p1_g025.nc_1_2041-2060_V1.2.tif"
@test getraster(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, :tmax; date=Date(2050), month=7) == raster_path
@test getraster(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, [:tmax]; date=Date(2050), month=7) == (tmax=raster_path,)
@test getraster(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, (:tmax,); date=Date(2050), month=7:7) == [(tmax=raster_path,)]
@test getraster(CHELSA{Future{Climate,CMIP5,CCSM4,RCP60}}, :tmax; date=[Date(2050)], month=7:7) == [[raster_path]]
@test isfile(raster_path)
@test RasterDataSources.getraster_keywords(CHELSA{Future{Climate}}) == (:date, :month)
end
@testset "CHELSA Future Climate CMIP6" begin
date_name = "CHELSA_gfdl-esm4_r1i1p1f1_w5e5_ssp585_tas_01_2011_2040_norm.tif"
date_name2 = "CHELSA_gfdl-esm4_r1i1p1f1_w5e5_ssp585_tas_01_2041_2070_norm.tif"
date_name3 = "CHELSA_gfdl-esm4_r1i1p1f1_w5e5_ssp585_tas_01_2071_2100_norm.tif"
month_name = "CHELSA_gfdl-esm4_r1i1p1f1_w5e5_ssp585_tas_01_2011_2040_norm.tif"
month_name2 = "CHELSA_gfdl-esm4_r1i1p1f1_w5e5_ssp585_tas_02_2011_2040_norm.tif"
@test rastername(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) == date_name
climate_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "CHELSA", "Future", "Climate", "SSP585", "GFDLESM4")
@test rasterpath(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}) == climate_path
date_path = joinpath(climate_path, date_name)
date_path2 = joinpath(climate_path, date_name2)
date_path3 = joinpath(climate_path, date_name3)
month_path = joinpath(climate_path, month_name)
month_path2 = joinpath(climate_path, month_name2)
@test rasterpath(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) == date_path
@test rasterpath(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) == date_path
date_url = "https://os.zhdk.cloud.switch.ch/chelsav2/GLOBAL/climatologies/2011-2040/GFDL-ESM4/ssp585/tas/" * date_name
@test rasterurl(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) |> string == date_url
@test getraster(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) == date_path
@test getraster(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, (:temp,); date=Date(2030), month=1) == (temp=date_path,)
@test getraster(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, :temp; date=Date(2030), month=1) == date_path
# Month is the inner vector
@test getraster(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, [:temp]; date=[Date(2030)], month=1:2) ==
[[(temp=month_path,), (temp=month_path2,)]]
@test getraster(CHELSA{Future{Climate,CMIP6,GFDLESM4,SSP585}}, [:temp]; date=(Date(2030), Date(2090)), month=1:1) ==
[[(temp=date_path,)], [(temp=date_path2,)], [(temp=date_path3,)]]
@test isfile(date_path)
@test isfile(date_path2)
@test isfile(date_path3)
@test isfile(month_path)
@test isfile(month_path2)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1399 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, rasterurl
@testset "EarthEnv HabitatHeterogeneity" begin
using RasterDataSources: rastername, rasterurl, rasterpath
@test rastername(EarthEnv{HabitatHeterogeneity}, :Dissimilarity; res="1km") == "Dissimilarity_1km.tif"
hh_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "EarthEnv", "HabitatHeterogeneity")
@test rasterpath(EarthEnv{HabitatHeterogeneity}) == hh_path
@test rasterpath(EarthEnv{HabitatHeterogeneity}, :Dissimilarity; res="1km") == joinpath(hh_path, "1km", "Dissimilarity_1km.tif")
@test rasterurl(EarthEnv{HabitatHeterogeneity}, :Dissimilarity; res="1km") ==
URI(scheme="https", host="data.earthenv.org", path="/habitat_heterogeneity/1km/Dissimilarity_01_05_1km_uint32.tif")
raster_path = joinpath(hh_path, "25km", "Dissimilarity_25km.tif")
@test getraster(EarthEnv{HabitatHeterogeneity}, :dissimilarity; res="25km") == raster_path
@test getraster(EarthEnv{HabitatHeterogeneity}, (:Dissimilarity,)) == (dissimilarity=raster_path,)
@test getraster(EarthEnv{HabitatHeterogeneity}, [:dissimilarity]) == (dissimilarity=raster_path,)
@test isfile(raster_path)
files = getraster(EarthEnv{HabitatHeterogeneity})
@test all(map(isfile, files))
@test RasterDataSources.getraster_keywords(EarthEnv{HabitatHeterogeneity}) == (:res,)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1988 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, rasterurl
@testset "EarthEnv LandCover" begin
using RasterDataSources: rastername, rasterurl, rasterpath
@test rastername(EarthEnv{LandCover{:DISCover}}, 2) == "consensus_full_class_2.tif"
landcover_path = joinpath(ENV["RASTERDATASOURCES_PATH"], "EarthEnv", "LandCover")
@test rasterpath(EarthEnv{LandCover{:DISCover}}) == joinpath(landcover_path, "with_DISCover")
@test rasterpath(EarthEnv{LandCover}) == joinpath(landcover_path, "without_DISCover")
@test rasterpath(EarthEnv{LandCover{:DISCover}}, 2) == joinpath(landcover_path, "with_DISCover", "consensus_full_class_2.tif")
@test rasterurl(EarthEnv{LandCover{:DISCover}}, 2) ==
URI(scheme="https", host="data.earthenv.org", path="/consensus_landcover/with_DISCover/consensus_full_class_2.tif")
without_discover_path = joinpath(landcover_path, "without_DISCover", "Consensus_reduced_class_2.tif")
with_discover_path = joinpath(landcover_path, "with_DISCover", "consensus_full_class_2.tif")
@test getraster(EarthEnv{LandCover{:DISCover}}, 2) == with_discover_path
@test isfile(with_discover_path)
@test getraster(EarthEnv{LandCover}, :evergreen_broadleaf_trees) == without_discover_path
@test getraster(EarthEnv{LandCover}, (2,)) == (evergreen_broadleaf_trees=without_discover_path,)
@test getraster(EarthEnv{LandCover}, (:evergreen_broadleaf_trees,)) == (evergreen_broadleaf_trees=without_discover_path,)
@test getraster(EarthEnv{LandCover}, 2:2) == (evergreen_broadleaf_trees=without_discover_path,)
@test getraster(EarthEnv{LandCover}, [:evergreen_broadleaf_trees]) == (evergreen_broadleaf_trees=without_discover_path,)
@test isfile(without_discover_path)
for layer in RasterDataSources.layers(EarthEnv{LandCover})
getraster(EarthEnv{LandCover{:DISCover}}, layer)
end
@test RasterDataSources.getraster_keywords(EarthEnv{LandCover}) == ()
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 2256 | using RasterDataSources, Test, Dates
using RasterDataSources: rastername, rasterpath, zipurl, zipname, zippath, layers
@testset verbose = true "MODIS interface functions" begin
@testset "Core interface functionality" begin
@test rastername(
MOD13Q1; RasterDataSources.crozon...
) == "48.24_-4.5_2012-02-02.asc"
raster_file = joinpath(
ENV["RASTERDATASOURCES_PATH"],
"MODIS",
"MOD13Q1",
"250m_16_days_NDVI",
"48.2313_-4.513_2012-02-02.asc"
)
@test rasterpath(MOD13Q1, :NDVI; lat = 48.2313, lon = -4.513, date = "2012-02-02") == raster_file
@test getraster(MOD13Q1, :NDVI; RasterDataSources.crozon...) == raster_file
@test getraster(MOD13Q1, (:NDVI,); RasterDataSources.crozon...) == (NDVI = raster_file,)
@test getraster(MOD13Q1, [:NDVI]; RasterDataSources.crozon...) == (NDVI = raster_file,)
@test isfile(raster_file)
## covers three different use cases :
# - more than 10 dates
# - MODIS{ModisProduct}
# - integer layer
@test length(getraster(MODIS{MOD13Q1}, 3; RasterDataSources.broceliande...)) > 10
## covers three use cases:
# - iterable `date` of length > 2
# - integer layer
# - `date` is a
@test length(getraster(MOD13Q1, 3; RasterDataSources.crozon2...)) == 3
@test layers(MOD13Q1) == Tuple(1:12)
end
@testset "date_sequence" begin
twodates = [Date(2011, 1, 1), Date(2011, 1, 17)]
@test RasterDataSources.date_sequence(MOD13Q1, (Date(2011,1,1), Date(2011,2,1)); RasterDataSources.broceliande...) == twodates
@test RasterDataSources.date_sequence(MODIS{MOD09A1}, (Date(2011,1,1), Date(2011,2,1)); RasterDataSources.broceliande...) == twodates
end
@testset "Ensure metadata copy opt out" begin
@test RasterDataSources.has_constant_metadata(MODIS{MOD13Q1}) == false
@test RasterDataSources.has_constant_metadata(VNP09A1) == false
end
@test RasterDataSources.getraster_keywords(MODIS) == (:lat, :lon, :km_ab, :km_lr, :date, :end)
@test RasterDataSources.getraster_keywords(MOD13Q1) == (:lat, :lon, :km_ab, :km_lr, :date, :end)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 663 | using RasterDataSources, Test
@testset verbose = true "MODIS product information functions" begin
# product name
@test RasterDataSources.product(VNP09A1) == "VNP09A1"
# layers list
@test RasterDataSources.list_layers(SIF005) == ["EVI_Quality", "SIF_740_daily_corr", "SIF_740_daily_corr_SD"]
# dates list (2 modis dates 16 days apart), in two formats
@test length(RasterDataSources.list_dates(MOD13Q1; lat = 48.25, lon = -4.5, from = "2012-02-02", to = "2012-02-18", format = "ModisDate")) == 2
@test string(RasterDataSources.list_dates(MOD13Q1; lat = 48.25, lon = -4.5, from = "2012-02-02", to = "2012-02-18")[1]) == "2012-02-02"
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1324 | using RasterDataSources, Test
@testset verbose = true "MODIS utility functions" begin
@testset "Coordinate conversions" begin
@test RasterDataSources.sinusoidal_to_latlon(0,0) == (0.0, 0.0)
@test RasterDataSources.meters_to_latlon(0, 45) == (0.0, 0.0)
@test RasterDataSources.meters_to_latlon(111000, 0)[1] ≈ 1.0 rtol = 0.01
end
@testset "Low-level MODIS functions" begin
# example request : the middle of Crozon peninsula in western France
simple_request = RasterDataSources.modis_request(
MOD13Q1,
"250m_16_days_EVI",
48.24,
-4.5,
1,
1,
"A2012033",
"A2012033"
)
# look for a layer by its name
@test RasterDataSources.modis_int(VNP21A2, :Emis_15) == 2
# build a geotransform
@test RasterDataSources._maybe_prepare_params(155555, 266666, 100, 142.4) == (xll = 1.4001660509018832, yll = 2.398184953639242, dx = 0.0012803223271200504, dy = 0.0012835043749800093)
# request to MODIS and process it
@test length(simple_request[1]) == 1 # one (date, band)
@test length(simple_request[2]) == 5 # 5 header params
@test typeof(RasterDataSources.process_subset(MOD13Q1, simple_request...)) == String
end
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1729 | using SafeTestsets, Aqua, RasterDataSources, Pkg
if VERSION >= v"1.5.0"
# HTTP.jl `write` is full of ambiguities
# Aqua.test_ambiguities([RasterDataSources, Base, Core])
Aqua.test_unbound_args(RasterDataSources)
# Aqua.test_stale_deps(RasterDataSources)
Aqua.test_undefined_exports(RasterDataSources)
Aqua.test_project_extras(RasterDataSources)
# Aqua.test_deps_compat(RasterDataSources)
# Aqua.test_project_toml_formatting(RasterDataSources)
end
# TODO ALWB data is all giving 404s
# Check in later to see if BOM have fixed this
# @time @safetestset "alwb" begin include("alwb.jl") end
@time @safetestset "awap" begin include("awap.jl") end
@time @safetestset "chelsa bioclim" begin include("chelsa-bioclim.jl") end
@time @safetestset "chelsa climate" begin include("chelsa-climate.jl") end
@time @safetestset "chelsa future" begin include("chelsa-future.jl") end
@time @safetestset "earthenv habitat heterogeneity" begin include("earthenv-heterogeneity.jl") end
@time @safetestset "earthenv landcover" begin include("earthenv-landcover.jl") end
@time @safetestset "worldclim bioclim" begin include("worldclim-bioclim.jl") end
@time @safetestset "worldclim climate" begin include("worldclim-climate.jl") end
@time @safetestset "worldclim weather" begin include("worldclim-weather.jl") end
@time @safetestset "worldclim elevation" begin include("worldclim-elevation.jl") end
# SRTM SSL certs have expired
# @time @safetestset "srtm" begin include("srtm.jl") end
@time @safetestset "modis utilities" begin include("modis-utilities.jl") end
@time @safetestset "modis product info" begin include("modis-products.jl") end
@time @safetestset "modis interface" begin include("modis-interface.jl") end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1339 |
using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rasterpath, zipurl, zipname
@testset "SRTM" begin
zip_url = URI(scheme = "https", host = "srtm.csi.cgiar.org", path = "/wp-content/uploads/files/srtm_5x5/TIFF/srtm_02_01.zip")
tile_index1 = CartesianIndex(1, 2) # [y, x] order
tile_index2 = CartesianIndex(2, 2) # [y, x] order
@test zipurl(SRTM; tile_index = tile_index1) == zip_url
@test zipurl(SRTM; tile_index = tile_index1) == zip_url
@test zipname(SRTM; tile_index = tile_index1) == "srtm_02_01.zip"
raster_path1 = joinpath(ENV["RASTERDATASOURCES_PATH"], "SRTM", "srtm_02_01.tif")
raster_path2 = joinpath(ENV["RASTERDATASOURCES_PATH"], "SRTM", "srtm_02_02.tif")
@test rasterpath(SRTM; tile_index = tile_index1) == raster_path1
@test getraster(SRTM; tile_index = tile_index1) == raster_path1
@test isfile(raster_path1)
lon1, lat1 = -175, 60 # Coordinates of [0, 0] pixel of tile x=2, y=1
@test getraster(SRTM; bounds=((lon1, lon1), (lat1, lat1))) == reshape([raster_path1], 1, 1)
lon2, lat2 = -171, 55 # Coordinates of [3000, 3000] pixel of tile x=2, y=2
@test getraster(SRTM; bounds=((lon1, lon2), (lat2, lat1))) == permutedims([raster_path1 raster_path2])
@test RasterDataSources.getraster_keywords(SRTM) == (:bounds, :tile_index)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1010 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, zipurl, zipname, zippath
@testset "WorldClim BioClim" begin
zip_url = URI(scheme="https", host="geodata.ucdavis.edu", path="/climate/worldclim/2_1/base/wc2.1_10m_bio.zip")
@test zipurl(WorldClim{BioClim}, 2; res="10m") == zip_url
@test zipname(WorldClim{BioClim}, 2; res="10m") == "wc2.1_10m_bio.zip"
raster_file = joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "BioClim", "wc2.1_10m_bio_2.tif")
@test rasterpath(WorldClim{BioClim}, 2; res="10m") == raster_file
@test getraster(WorldClim{BioClim}, :bio2; res="10m") == raster_file
@test getraster(WorldClim{BioClim}, (2,); res="10m") == (bio2=raster_file,)
@test getraster(WorldClim{BioClim}, 2:2; res="10m") == (bio2=raster_file,)
@test getraster(WorldClim{BioClim}, [:bio2]; res="10m") == (bio2=raster_file,)
@test isfile(raster_file)
@test RasterDataSources.getraster_keywords(WorldClim{BioClim}) == (:res,)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1110 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, zipurl, zipname, zippath
@testset "WorldClim Climate" begin
zip_url = URI(scheme="https", host="geodata.ucdavis.edu", path="/climate/worldclim/2_1/base/wc2.1_10m_wind.zip")
@test zipurl(WorldClim{Climate}, :wind; res="10m") == zip_url
@test zipname(WorldClim{Climate}, :wind; res="10m") == "wc2.1_10m_wind.zip"
raster_file = joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "Climate", "wind", "wc2.1_10m_wind_01.tif")
@test rasterpath(WorldClim{Climate}, :wind; month=1, res="10m") == raster_file
@test getraster(WorldClim{Climate}, (:wind,); month=1, res="10m") == (wind=raster_file,)
@test getraster(WorldClim{Climate}, :wind; month=1:1, res="10m") == [raster_file]
@test getraster(WorldClim{Climate}, (:wind,); month=1:1, res="10m") == [(; wind=raster_file)]
@test getraster(WorldClim{Climate}, [:wind]; month=1:1, res="10m") == [(; wind=raster_file)]
@test isfile(raster_file)
@test RasterDataSources.getraster_keywords(WorldClim{Climate}) == (:month, :res,)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1041 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, zipurl, zipname, zippath
@testset "WorldClim Elevation" begin
zip_url = URI(scheme="https", host="geodata.ucdavis.edu", path="/climate/worldclim/2_1/base/wc2.1_10m_elev.zip")
@test zipurl(WorldClim{Elevation}, :elev; res="10m") == zip_url
@test zipname(WorldClim{Elevation}, :elev; res="10m") == "wc2.1_10m_elev.zip"
raster_file = joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "Elevation", "wc2.1_10m_elev.tif")
@test rasterpath(WorldClim{Elevation}, :elev; res="10m") == raster_file
@test getraster(WorldClim{Elevation}; res="10m") == (elev=raster_file,)
@test getraster(WorldClim{Elevation}, (:elev,); res="10m") == (elev=raster_file,)
@test getraster(WorldClim{Elevation}, :elev; res="10m") == raster_file
@test getraster(WorldClim{Elevation}, [:elev]; res="10m") == (elev=raster_file,)
@test isfile(raster_file)
@test RasterDataSources.getraster_keywords(WorldClim{Elevation}) == (:res,)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | code | 1845 | using RasterDataSources, URIs, Test, Dates
using RasterDataSources: rastername, rasterpath, zipurl, zipname, zippath
@testset "WorldClim Weather" begin
raster_file = joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "Weather", "prec", "wc2.1_2.5m_prec_2001-01.tif")
@test rasterpath(WorldClim{Weather}, :prec; date=Date(2001, 1)) == raster_file
@test rastername(WorldClim{Weather}, :prec; date=Date(2001, 1)) == "wc2.1_2.5m_prec_2001-01.tif"
zip_file = joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "Weather", "zips", "wc2.1_2.5m_prec_2010-2018.zip")
@test zippath(WorldClim{Weather}, :prec; decade=Date(2010)) == zip_file
@test zipurl(WorldClim{Weather}, :prec; decade=Date(2010)) ==
URI(scheme="https", host="geodata.ucdavis.edu", path="/climate/worldclim/2_1/hist/wc2.1_2.5m_prec_2010-2018.zip")
@test zipname(WorldClim{Weather}, :prec; decade=Date(2010)) ==
"wc2.1_2.5m_prec_2010-2018.zip"
# These files are 3GB each. Too big to test in CI.
if !haskey(ENV, "CI")
@test getraster(WorldClim{Weather}, :prec; date=Date(2001, 1)) == raster_file
@test getraster(WorldClim{Weather}, (:prec,); date=Date(2001, 1)) == (prec=raster_file,)
raster_files = [joinpath(ENV["RASTERDATASOURCES_PATH"], "WorldClim", "Weather", "prec", "wc2.1_2.5m_prec_2001-$(lpad(string(x), 2, '0')).tif") for x in 1:12]
@test getraster(WorldClim{Weather}, :prec; date=Date(2001):Month(1):Date(2001, 12)) == raster_files
@test getraster(WorldClim{Weather}, (:prec,); date=Date(2001):Month(1):Date(2001, 12)) == map(f -> (prec=f,), raster_files)
@test getraster(WorldClim{Weather}, [:prec]; date=Date(2001):Month(1):Date(2001, 12)) == map(f -> (prec=f,), raster_files)
end
@test RasterDataSources.getraster_keywords(WorldClim{Weather}) == (:date,)
end
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | docs | 3505 | # RasterDataSources.jl
[](https://ecojulia.github.io/RasterDataSources.jl/stable)
[](https://ecojulia.github.io/RasterDataSources.jl/dev)
[](https://github.com/EcoJulia/RasterDataSources.jl/actions/workflows/CI.yml)
[](http://codecov.io/github/ecojulia/RasterDataSources.jl?branch=master)
RasterDataSources downloads raster data for local use or for integration into other spatial data packages, like
[Rasters.jl](https://github.com/rafaqz/Rasters.jl). The collection is largely focussed on datasets relevant
to ecology, but will have a lot of crossover with other sciences.
Currently sources include:
| Source | URL | Status |
| --------- | ---------------------------------------- | ---------------------------------------- |
| CHELSA | https://chelsa-climate.org | BioClim, BioClimPlus, and Climate |
| WorldClim | https://www.worldclim.org | Climate, Weather, BioClim, and Elevation |
| EarthEnv | http://www.earthenv.org | LandCover and HabitatHeterogeneity |
| AWAP | http://www.bom.gov.au/jsp/awap/index.jsp | Complete |
| ALWB | http://www.bom.gov.au/water/landscape/ | Complete |
| SRTM | https://www2.jpl.nasa.gov/srtm/ | Complete |
| MODIS | https://modis.ornl.gov | Complete (beta) |
Please open an issue if you need more datasets added, or (even better) open a pull request
following the form of the other datasets where possible.
## Retrieving data
Usage is generally via the `getraster` method - which will download the
raster data source if it isn't available locally, or simply return the path/s
of the raster file/s:
```julia
julia> using RasterDataSources
julia> getraster(WorldClim{Climate}, :wind; month=1:12)
12-element Array{String,1}:
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_01.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_02.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_03.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_04.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_05.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_06.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_07.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_08.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_09.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_10.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_11.tif"
"/home/user/Data/WorldClim/Climate/wind/wc2.1_10m_wind_12.tif"
```
## Installation and setup
Install as usual with:
```julia
] add RasterDataSources
```
To download data you will need to specify a folder to put it in. You can do this
by assigning the environment variable `RASTERDATASOURCES_PATH`:
```julia
ENV["RASTERDATASOURCES_PATH"] = "/home/user/Data/"
```
This can be put in your `startup.jl` file or the system environment.
RasterDataSources was based on code from the `SimpleSDMDataSoures.jl` package by Timothée Poisot.
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"MIT"
] | 0.6.1 | dfab74c3efb21c6df589f30f7bbe5b9b8dbbe3c9 | docs | 2826 | # RasterDataSources.jl
```@docs
RasterDataSources
```
# getraster
RasterDataSources.jl only exports a single function, `getraster`.
```@docs
getraster
```
Specific implementations are included with each source, below.
# Data sources
```@docs
RasterDataSources.RasterDataSource
```
## ALWB
```@docs
ALWB
getraster(T::Type{<:ALWB}, layers::Union{Tuple,Symbol}; date)
```
## AWAP
```@docs
AWAP
getraster(T::Type{AWAP}, layer::Union{Tuple,Symbol}; date)
```
## CHELSA
```@docs
CHELSA
getraster(T::Type{CHELSA{BioClim}}, layer::Union{Tuple,Int,Symbol})
getraster(T::Type{<:CHELSA{<:Future{Climate}}}, layers::Union{Tuple,Symbol}; date, month)
```
## EarthEnv
```@docs
EarthEnv
getraster(T::Type{EarthEnv{HabitatHeterogeneity}}, layers::Union{Tuple,Symbol}; res)
getraster(T::Type{EarthEnv{LandCover}}, layers::Union{Tuple,Int,Symbol}; res)
```
## WorldClim
```@docs
WorldClim
getraster(T::Type{WorldClim{BioClim}}, layers::Union{Tuple,Int,Symbol}; res)
getraster(T::Type{WorldClim{Weather}}, layers::Union{Tuple,Symbol}; date)
getraster(T::Type{WorldClim{Climate}}, layers::Union{Tuple,Symbol}; month, res)
getraster(T::Type{WorldClim{Elevation}}, layers::Union{Tuple,Symbol}; month, res)
```
## MODIS
```@docs
MODIS
getraster(T::Type{<:ModisProduct})
ModisProduct
RasterDataSources.layerkeys(T::Type{<:ModisProduct})
```
# Datasets
```@docs
RasterDataSources.RasterDataSet
BioClim
Climate
Weather
Elevation
LandCover
HabitatHeterogeneity
Future
```
# Models, phases and scenarios for [`Future`](@ref) data.
```@docs
RasterDataSources.ClimateModel
RasterDataSources.CMIPphase
CMIP5
CMIP6
RasterDataSources.ClimateScenario
RasterDataSources.RepresentativeConcentrationPathway
RasterDataSources.SharedSocioeconomicPathway
```
# Other
```@docs
Values
Deciles
```
# Internal interface
These methods are not exported at this stage, but are for the most part
internally consistent. Any new sources added to the package should use these
methods in a consistent way for readability, consistency and the potential to use
them for other things later.
```@docs
RasterDataSources.layerkeys
RasterDataSources.rastername
RasterDataSources.rasterpath
RasterDataSources.rasterurl
RasterDataSources.zipname
RasterDataSources.zippath
RasterDataSources.zipurl
```
# Internal MODIS interface
Unlike all the other currently supported data sources, MODIS data is not
available online in raster file format. Building rasters out of the
available information therefore requires internal functions that are not
exported. They might be extended as needed if other similar sources get
supported.
### Requesting to server and building raster files
```@docs
RasterDataSources.modis_request
RasterDataSources.process_subset
```
### Miscellaneous
```@docs
RasterDataSources.product
RasterDataSources.sinusoidal_to_latlon
```
| RasterDataSources | https://github.com/EcoJulia/RasterDataSources.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1819 | module XDiag
using Printf
using CxxWrap
using XDiag_jll
using LinearAlgebra
import Base: +, *, ==, !=, getindex, setindex!, size, isreal, convert, show, real, imag, push!, iterate, fill, rand, zeros, zero
import LinearAlgebra: dot, norm
@wrapmodule(XDiag_jll.get_libxdiagjl_path)
printlib() = println(XDiag_jll.get_libxdiagjl_path())
export printlib
export say_hello, print_version, set_verbosity
include("operators/coupling.jl")
export Coupling, type, isreal, ismatrix, isexplicit
include("operators/op.jl")
export Op, coupling, sites
include("operators/opsum.jl")
export OpSum, couplings, defined
include("symmetries/permutation.jl")
export Permutation, inverse
include("symmetries/permutation_group.jl")
export PermutationGroup, n_sites
include("symmetries/representation.jl")
export Representation
include("operators/symmetrize.jl")
export symmetrize
include("states/product_state.jl")
export ProductState, _begin, _end
abstract type Block end
include("blocks/spinhalf.jl")
include("blocks/tj.jl")
include("blocks/electron.jl")
export Spinhalf, tJ, Electron, n_up, n_dn, dim, permutation_group, irrep, index
include("states/state.jl")
export State, vector, matrix, col, make_complex!, n_rows, n_cols
include("states/random_state.jl")
export RandomState, seed, normalized
include("states/gpwf.jl")
export GPWF
include("states/fill.jl")
export fill
include("states/create_state.jl")
export product
include("algebra/matrix.jl")
export matrix
include("algebra/apply.jl")
export apply
include("algebra/algebra.jl")
export norm, norm1, norminf, dot, inner
include("algorithms/sparse_diag.jl")
export eig0, eigval0
include("algorithms/lanczos/eigvals_lanczos.jl")
export eigvals_lanczos
include("algorithms/lanczos/eigs_lanczos.jl")
export eigs_lanczos
function __init__()
@initcxx
end
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1423 | LinearAlgebra.norm(state::State) = Float64(cxx_norm(state.cxx_state))
norm1(state::State) = Float64(cxx_norm1(state.cxx_state))
norminf(state::State) = Float64(cxx_norminf(state.cxx_state))
function LinearAlgebra.dot(v::State, w::State)
if isreal(v) && isreal(w)
return cxx_dot(v.cxx_state, w.cxx_state)
else
return cxx_dotC(v.cxx_state, w.cxx_state)
end
end
function inner(ops::OpSum, v::State)
if isreal(ops) && isreal(v)
return cxx_inner(ops.cxx_opsum, v.cxx_state)
else
return cxx_innerC(ops.cxx_opsum, v.cxx_state)
end
end
function inner(op::Op, v::State)
if isreal(op) && isreal(v)
return cxx_inner(op.cxx_op, v.cxx_state)
else
return cxx_innerC(op.cxx_op, v.cxx_state)
end
end
# Vector space operations
Base.:+(v::State, w::State) = State(cxx_add(v.cxx_state, w.cxx_state))
Base.:-(v::State, w::State) = State(cxx_sub(v.cxx_state, w.cxx_state))
Base.:*(alpha::Float64, v::State) = State(cxx_scalar_mult(alpha, v.cxx_state))
Base.:*(alpha::ComplexF64, v::State) = State(cxx_scalar_mult(alpha, v.cxx_state))
Base.:*(v::State, alpha::Float64) = State(cxx_scalar_mult(alpha, v.cxx_state))
Base.:*(v::State, alpha::ComplexF64) = State(cxx_scalar_mult(alpha, v.cxx_state))
Base.:/(v::State, alpha::Float64) = State(cxx_scalar_div(v.cxx_state, alpha))
Base.:/(v::State, alpha::ComplexF64) = State(cxx_scalar_div(v.cxx_state, alpha))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 261 | apply(ops::OpSum, v::State, w::State, precision::Float64 = 1e-12) =
cxx_apply(ops.cxx_opsum, v.cxx_state, w.cxx_state, precision)
apply(op::Op, v::State, w::State, precision::Float64 = 1e-12) =
cxx_apply(op.cxx_op, v.cxx_state, w.cxx_state, precision)
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 2062 | function matrix(
ops::OpSum,
block_in::Block,
block_out::Block;
force_complex::Bool = false,
precision::Float64 = 1e-12,
)
if isreal(ops) && isreal(block_in) && isreal(block_out) && !force_complex
# Allocate matrix on julia side
mat = Matrix{Float64}(undef, size(block_in), size(block_out))
# Let the C++ routine write to this matrix
matrix(
Base.unsafe_convert(Ptr{Float64}, mat),
ops.cxx_opsum,
block_in.cxx_block,
block_out.cxx_block,
precision,
)
return mat
else
# Allocate matrix on julia side
mat = Matrix{ComplexF64}(undef, size(block_in), size(block_out))
# Let the C++ routine write to this matrix
# the following works but is ugly because wrapper is wrong
if typeof(block_in) <: Spinhalf
matrixC(
Base.unsafe_convert(Ptr{ComplexF64}, mat),
ops.cxx_opsum,
block_in.cxx_block,
block_out.cxx_block,
precision,
)
else
matrix(
Base.unsafe_convert(Ptr{ComplexF64}, mat),
ops.cxx_opsum,
block_in.cxx_block,
block_out.cxx_block,
precision,
)
end
return mat
end
end
function matrix(
op::Op,
block_in::Block,
block_out::Block;
force_complex::Bool = false,
precision::Float64 = 1e-12,
)
ops = OpSum([op])
matrix(ops, block_in, block_out; force_complex = force_complex, precision = precision)
end
function matrix(
ops::OpSum,
block::Block;
force_complex::Bool = false,
precision::Float64 = 1e-12,
)
return matrix(ops, block, block; force_complex = force_complex, precision = precision)
end
function matrix(
op::Op,
block::Block;
force_complex::Bool = false,
precision::Float64 = 1e-12,
)
return matrix(op, block, block; force_complex = force_complex, precision = precision)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 566 | function eig0(
ops::OpSum,
block::Block;
precision::Real = 1e-12,
maxiter::Int64 = 1000,
force_complex::Bool = false,
seed::Int64 = 42,
)
e0, cxx_state = eig0(ops.cxx_opsum, block.cxx_block, precision, maxiter, force_complex, seed)
return e0, State(cxx_state)
end
function eigval0(
ops::OpSum,
block::Block;
precision::Real = 1e-12,
maxiter::Integer = 1000,
force_complex::Bool = false,
seed::Integer = 42,
)
return eigval0(ops.cxx_opsum, block.cxx_block, precision, maxiter, force_complex, seed)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 894 | struct EigsLanczosResult
alphas::Vector{Float64}
betas::Vector{Float64}
eigenvalues::Vector{Float64}
eigenvectors::State
niterations::Int64
criterion::String
end
function eigs_lanczos(
ops::OpSum,
block::Block;
neigvals::Int64 = 1,
precision::Float64 = 1e-12,
max_iterations::Int64 = 1000,
force_complex::Bool = false,
deflation_tol::Float64 = 1e-7,
random_seed::Int64 = 42,
)
cxx_res = cxx_eigs_lanczos(
ops.cxx_opsum,
block.cxx_block,
neigvals,
precision,
max_iterations,
force_complex,
deflation_tol,
random_seed,
)
return EigsLanczosResult(
to_julia(alphas(cxx_res)),
to_julia(betas(cxx_res)),
to_julia(eigenvalues(cxx_res)),
State(eigenvectors(cxx_res)),
niterations(cxx_res),
criterion(cxx_res),
)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 844 | struct EigvalsLanczosResult
alphas::Vector{Float64}
betas::Vector{Float64}
eigenvalues::Vector{Float64}
niterations::Int64
criterion::String
end
function eigvals_lanczos(
ops::OpSum,
block::Block;
neigvals::Int64 = 1,
precision::Float64 = 1e-12,
max_iterations::Int64 = 1000,
force_complex::Bool = false,
deflation_tol::Float64 = 1e-7,
random_seed::Int64 = 42,
)
cxx_res = cxx_eigvals_lanczos(
ops.cxx_opsum,
block.cxx_block,
neigvals,
precision,
max_iterations,
force_complex,
deflation_tol,
random_seed,
)
return EigvalsLanczosResult(
to_julia(alphas(cxx_res)),
to_julia(betas(cxx_res)),
to_julia(eigenvalues(cxx_res)),
niterations(cxx_res),
criterion(cxx_res),
)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1671 | struct Electron <: Block
cxx_block::cxx_Electron
end
# Constructors
Electron(n_sites::Integer) = Electron(cxx_Electron(n_sites))
Electron(n_sites::Integer, n_up::Integer, n_dn::Integer) =
Electron(cxx_Electron(n_sites, n_up, n_dn))
Electron(n_sites::Integer, group::PermutationGroup, irrep::Representation) =
Electron(cxx_Electron(n_sites, group.cxx_group, irrep.cxx_representation))
Electron(
n_sites::Integer,
n_up::Integer,
n_dn::Integer,
group::PermutationGroup,
irrep::Representation,
) = Electron(cxx_Electron(n_sites, n_up, n_dn, group.cxx_group, irrep.cxx_representation))
# Methods
n_sites(block::Electron) = n_sites(block.cxx_block)
n_up(block::Electron) = n_up(block.cxx_block)
n_dn(block::Electron) = n_dn(block.cxx_block)
permutation_group(block::Electron) = PermutationGroup(permutation_group((block.cxx_block)))
irrep(block::Electron) = Representation(irrep(block.cxx_block))
Base.isreal(block::Electron) = isreal(block.cxx_block)
dim(block::Electron) = dim(block.cxx_block)
Base.size(block::Electron) = size(block.cxx_block)
index(block::Electron, pstate::ProductState) =
Int64(index(block.cxx_block, pstate.cxx_product_state)) + 1
# Iterators
function Base.iterate(block::Electron)
if size(block) > 0
b = _begin(block.cxx_block)
return ProductState(_deref(b)), b
else
return nothing
end
end
function Base.iterate(block::Electron, state)
_incr(state)
if state != _end(block.cxx_block)
return ProductState(_deref(state)), state
else
return nothing
end
end
# Output
Base.show(io::IO, block::Electron) = print(io, "\n" * to_string(block.cxx_block))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1560 | struct Spinhalf <: Block
cxx_block::cxx_Spinhalf
end
# Constructors
Spinhalf(n_sites::Integer) = Spinhalf(cxx_Spinhalf(n_sites))
Spinhalf(n_sites::Integer, n_up::Integer) = Spinhalf(cxx_Spinhalf(n_sites, n_up))
Spinhalf(n_sites::Integer, group::PermutationGroup, irrep::Representation) =
Spinhalf(cxx_Spinhalf(n_sites, group.cxx_group, irrep.cxx_representation))
Spinhalf(n_sites::Integer, n_up::Integer, group::PermutationGroup, irrep::Representation) =
Spinhalf(cxx_Spinhalf(n_sites, n_up, group.cxx_group, irrep.cxx_representation))
# Methods
n_sites(block::Spinhalf) = n_sites(block.cxx_block)
n_up(block::Spinhalf) = n_up(block.cxx_block)
permutation_group(block::Spinhalf) = PermutationGroup(permutation_group((block.cxx_block)))
irrep(block::Spinhalf) = Representation(irrep(block.cxx_block))
Base.isreal(block::Spinhalf) = isreal(block.cxx_block)
dim(block::Spinhalf) = dim(block.cxx_block)
Base.size(block::Spinhalf) = size(block.cxx_block)
index(block::Spinhalf, pstate::ProductState) =
Int64(index(block.cxx_block, pstate.cxx_product_state)) + 1
# Iterators
function Base.iterate(block::Spinhalf)
if size(block) > 0
b = _begin(block.cxx_block)
return ProductState(_deref(b)), b
else
return nothing
end
end
function Base.iterate(block::Spinhalf, state)
_incr(state)
if state != _end(block.cxx_block)
return ProductState(_deref(state)), state
else
return nothing
end
end
# Output
Base.show(io::IO, block::Spinhalf) = print(io, "\n" * to_string(block.cxx_block))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1330 | struct tJ <: Block
cxx_block::cxx_tJ
end
# Constructors
tJ(n_sites::Integer, n_up::Integer, n_dn::Integer) = tJ(cxx_tJ(n_sites, n_up, n_dn))
tJ(
n_sites::Integer,
n_up::Integer,
n_dn::Integer,
group::PermutationGroup,
irrep::Representation,
) = tJ(cxx_tJ(n_sites, n_up, n_dn, group.cxx_group, irrep.cxx_representation))
# Methods
n_sites(block::tJ) = n_sites(block.cxx_block)
n_up(block::tJ) = n_up(block.cxx_block)
n_dn(block::tJ) = n_dn(block.cxx_block)
permutation_group(block::tJ) = PermutationGroup(permutation_group((block.cxx_block)))
irrep(block::tJ) = Representation(irrep(block.cxx_block))
Base.isreal(block::tJ) = isreal(block.cxx_block)
dim(block::tJ) = dim(block.cxx_block)
Base.size(block::tJ) = size(block.cxx_block)
index(block::tJ, pstate::ProductState) =
Int64(index(block.cxx_block, pstate.cxx_product_state)) + 1
# Iterators
function Base.iterate(block::tJ)
if size(block) > 0
b = _begin(block.cxx_block)
return ProductState(_deref(b)), b
else
return nothing
end
end
function Base.iterate(block::tJ, state)
_incr(state)
if state != _end(block.cxx_block)
return ProductState(_deref(state)), state
else
return nothing
end
end
# Output
Base.show(io::IO, block::tJ) = print(io, "\n" * to_string(block.cxx_block))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 2378 | include("../utils/armadillo.jl")
struct Coupling
cxx_coupling::cxx_Coupling
end
# Constructors
Coupling() = Coupling(cxx_Coupling())
Coupling(name::String) = Coupling(cxx_Coupling(name))
Coupling(val::Float64) = Coupling(cxx_Coupling(val))
Coupling(val::ComplexF64) = Coupling(cxx_Coupling(val))
Coupling(mat::Matrix{Float64}) = Coupling(cxx_Coupling(to_armadillo(mat)))
Coupling(mat::Matrix{Int64}) = Coupling(convert(Matrix{Float64}, mat))
Coupling(mat::Matrix{ComplexF64}) = Coupling(cxx_Coupling(to_armadillo(mat)))
Coupling(mat::Matrix{Complex{Int64}}) = Coupling(convert(Matrix{ComplexF64}, mat))
# Methods
type(cpl::Coupling) = String(type(cpl.cxx_coupling))
isreal(cpl::Coupling) = Bool(isreal(cpl.cxx_coupling))
ismatrix(cpl::Coupling) = Bool(ismatrix(cpl.cxx_coupling))
isexplicit(cpl::Coupling) = Bool(isexplicit(cpl.cxx_coupling))
# Output
Base.show(io::IO, cpl::Coupling) = print(io, to_string(cpl.cxx_coupling))
# Conversion
function Base.convert(::Type{String}, cpl::Coupling)
if is_string(cpl.cxx_coupling)
return String(as_string(cpl.cxx_coupling))
else
error(@sprintf "Coupling is of type \"%s\" cannot be converted to type \"String\"" type(cpl))
end
end
function Base.convert(::Type{Float64}, cpl::Coupling)
if is_double(cpl.cxx_coupling)
return Float64(as_double(cpl.cxx_coupling))
else
error(@sprintf "Coupling is of type \"%s\" cannot be converted to type \"Float64\"" type(cpl))
end
end
function Base.convert(::Type{ComplexF64}, cpl::Coupling)
if is_double(cpl.cxx_coupling) || is_complex(cpl.cxx_coupling)
return ComplexF64(as_complex(cpl.cxx_coupling))
else
error(@sprintf "Coupling is of type \"%s\" cannot be converted to type \"ComplexF64\"" type(cpl))
end
end
function Base.convert(::Type{Matrix{Float64}}, cpl::Coupling)
if is_mat(cpl.cxx_coupling)
return to_julia(as_mat(cpl.cxx_coupling))
else
error(@sprintf "Coupling is of type \"%s\" cannot be converted to type \"Matrix{Float64}\"" type(cpl))
end
end
function Base.convert(::Type{Matrix{ComplexF64}}, cpl::Coupling)
if is_mat(cpl.cxx_coupling) || is_cx_mat(cpl.cxx_coupling)
return to_julia(as_cx_mat(cpl.cxx_coupling))
else
error(@sprintf "Coupling is of type \"%s\" cannot be converted to type \"Matrix{ComplexF64}\"" type(cpl))
end
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 2350 | using Printf
struct Op
cxx_op::cxx_Op
end
# Constructors
Op() = Op(cxx_Op())
Op(type::String, cpl::Coupling, sites::Vector{Int64}) =
Op(cxx_Op(type, cpl.cxx_coupling, StdVector(sites .- 1)))
Op(type::String, cpl::Coupling, site::Int64) = Op(cxx_Op(type, cpl.cxx_coupling, site - 1))
Op(type::String, name::String, sites::Vector{Int64}) =
Op(cxx_Op(type, name, StdVector(sites .- 1)))
Op(type::String, name::String, site::Int64) = Op(cxx_Op(type, name, site - 1))
Op(type::String, val::Float64, sites::Vector{Int64}) =
Op(cxx_Op(type, val, StdVector(sites .- 1)))
Op(type::String, val::Float64, site::Int64) = Op(cxx_Op(type, val, site - 1))
Op(type::String, val::ComplexF64, sites::Vector{Int64}) =
Op(cxx_Op(type, val, StdVector(sites .- 1)))
Op(type::String, val::ComplexF64, site::Int64) = Op(cxx_Op(type, val, site - 1))
Op(type::String, mat::Matrix{Float64}, sites::Vector{Int64}) =
Op(cxx_Op(type, to_armadillo(mat), StdVector(sites .- 1)))
Op(type::String, mat::Matrix{Float64}, site::Int64) =
Op(cxx_Op(type, to_armadillo(mat), site - 1))
Op(type::String, mat::Matrix{Int64}, sites::Vector{Int64}) =
Op(type, convert(Matrix{Float64}, mat), sites)
Op(type::String, mat::Matrix{Int64}, site::Int64) =
Op(type, convert(Matrix{Float64}, mat), site)
Op(type::String, mat::Matrix{ComplexF64}, sites::Vector{Int64}) =
Op(cxx_Op(type, to_armadillo(mat), StdVector(sites .- 1)))
Op(type::String, mat::Matrix{ComplexF64}, site::Int64) =
Op(cxx_Op(type, to_armadillo(mat), site - 1))
Op(type::String, mat::Matrix{Complex{Int64}}, sites::Vector{Int64}) =
Op(type, convert(Matrix{ComplexF64}, mat), sites)
Op(type::String, mat::Matrix{Complex{Int64}}, site::Int64) =
Op(type, convert(Matrix{ComplexF64}, mat), site)
# methods
type(op::Op) = String(strip(type(op.cxx_op)))
coupling(op::Op) = Coupling(coupling(op.cxx_op))
Base.size(op::Op) = Int64(size(op.cxx_op))
Base.getindex(op::Op, idx::Int64) = Int64(getindex(op.cxx_op, idx)) + 1
sites(op::Op) = Vector{Int64}(sites(op.cxx_op)) .+ 1
isreal(op::Op) = Bool(isreal(op.cxx_op))
ismatrix(op::Op) = Bool(ismatrix(op.cxx_op))
isexplicit(op::Op) = Bool(isexplicit(op.cxx_op))
# Output
function Base.show(io::IO, op::Op)
# print(io, "\n" * to_string(op.cxx_op))
print(io, @sprintf "%s %s %s" type(op) coupling(op) sites(op))
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 963 | struct OpSum
cxx_opsum::cxx_OpSum
end
# Constructors
OpSum() = OpSum(cxx_OpSum())
function OpSum(ops::Vector{Op})
cxx_ops = cxx_VectorOp()
for op in ops
push_back(cxx_ops, op.cxx_op)
end
OpSum(cxx_OpSum(cxx_ops))
end
# Methods
Base.size(ops::OpSum) = Int64(size(ops.cxx_opsum))
defined(ops::OpSum, name::String) = Bool(defined(ops.cxx_opsum, name))
Base.getindex(ops::OpSum, name::String) = Coupling(getindex(ops.cxx_opsum, name))
Base.setindex!(ops::OpSum, cpl, name::String) = setindex!(ops.cxx_opsum, Coupling(cpl).cxx_coupling, name)
couplings(ops::OpSum) = Vector{String}(couplings(ops.cxx_opsum))
isreal(ops::OpSum) = Bool(isreal(ops.cxx_opsum))
isexplicit(ops::OpSum) = Bool(isexplicit(ops.cxx_opsum))
Base.:+(ops::OpSum, ops2::OpSum) = OpSum(ops.cxx_opsum + ops2.cxx_opsum)
Base.:+(ops::OpSum, op2::Op) = OpSum(ops.cxx_opsum + op2.cxx_op)
# Output
Base.show(io::IO, ops::OpSum) = print(io, "\n" * to_string(ops.cxx_opsum))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 514 | symmetrize(ops::OpSum, group::PermutationGroup) =
OpSum(cxx_symmetrize(ops.cxx_opsum, group.cxx_group))
symmetrize(op::Op, group::PermutationGroup) =
OpSum(cxx_symmetrize(op.cxx_op, group.cxx_group))
symmetrize(ops::OpSum, group::PermutationGroup, irrep::Representation) =
OpSum(cxx_symmetrize(ops.cxx_opsum, group.cxx_group, irrep.cxx_representation))
symmetrize(op::Op, group::PermutationGroup, irrep::Representation) =
OpSum(cxx_symmetrize(op.cxx_op, group.cxx_group, irrep.cxx_representation))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 460 | product(block::Block, local_states::Vector{String}; real::Bool=true) = State(cxx_product(block.cxx_block, StdVector(StdString.(local_states)), real))
Base.rand(block::Block; real::Bool=true, seed::Int64=42, normalized::Bool=true) =
State(cxx_rand(block.cxx_block, real, seed, normalized))
Base.zeros(block::Block; real::Bool=true, n_col::Int64=1) =
State(cxx_zeros(block.cxx_block, real, n_col))
Base.zero(state::State) = cxx_zero(state.cxx_state)
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 349 | fill(state::State, pstate::ProductState, ncol::Int64 = 1) =
cxx_fill(state.cxx_state, pstate.cxx_product_state, ncol-1)
fill(state::State, rstate::RandomState, ncol::Int64 = 1) =
cxx_fill(state.cxx_state, rstate.cxx_random_state, ncol-1)
fill(state::State, gpwf::GPWF, ncol::Int64 = 1) =
cxx_fill(state.cxx_state, gpwf.cxx_gpwf, ncol-1)
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 494 | struct GPWF
cxx_gpwf::cxx_GPWF
end
# Constructors
GPWF() = GPWF(cxx_GPWF())
GPWF(mat::Matrix{Float64}, n_up::Int64 = -1) = GPWF(cxx_GPWF(to_armadillo(mat), n_up))
GPWF(mat::Matrix{ComplexF64}, n_up::Int64 = -1) = GPWF(cxx_GPWF(to_armadillo(mat), n_up))
# Methods
n_sites(state::GPWF) = n_sites(state.cxx_gpwf)
n_up(state::GPWF) = n_up(state.cxx_gpwf)
Base.isreal(state::GPWF) = isreal(state.cxx_gpwf)
# Output
Base.show(io::IO, state::GPWF) = print(io, "\n" * to_string(state.cxx_gpwf))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1306 | struct ProductState
cxx_product_state::cxx_ProductState
end
# Constructors
ProductState() = ProductState(cxx_ProductState())
ProductState(n_sites::Int64) = ProductState(cxx_ProductState(n_sites))
ProductState(local_states::Vector{String}) = ProductState(cxx_ProductState(StdVector(StdString.(local_states))))
# Methods
n_sites(state::ProductState) = n_sites(state.cxx_product_state)
Base.size(state::ProductState) = size(state.cxx_product_state)
Base.getindex(state::ProductState, idx::Int64) = getindex(state.cxx_product_state, idx)
Base.setindex!(state::ProductState, local_state::String, idx::Int64) = setindex!(state.cxx_product_state, local_state, idx)
Base.push!(state::ProductState, local_state::String) = push!(state.cxx_product_state, local_state)
_begin(state::ProductState) = _begin(state.cxx_product_state)
_end(state::ProductState) = _end(state.cxx_product_state)
# Iterators
function Base.iterate(s::ProductState)
if size(s) > 0
return s[1], _begin(s)
else
return nothing
end
end
function Base.iterate(s::ProductState, state)
_incr(state)
if state == _end(s)
return nothing
else
return _deref(state), state
end
end
# Output
Base.show(io::IO, state::ProductState) = print(io, "\n" * to_string(state.cxx_product_state))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 416 | struct RandomState
cxx_random_state::cxx_RandomState
end
# Constructors
RandomState(seed::Int64 = 42, normalized::Bool = true) = RandomState(cxx_RandomState(seed, normalized))
# Methods
seed(state::RandomState) = seed(state.cxx_random_state)
normalized(state::RandomState) = seed(state.cxx_random_state)
# Output
Base.show(io::IO, state::RandomState) = print(io, "\n" * to_string(state.cxx_random_state))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 2405 | struct State
cxx_state::cxx_State
end
# Constructors
State(block::Block; real::Bool = true, n_cols::Int64 = 1) =
State(cxx_State(block.cxx_block, real, n_cols))
function State(block::Block, vec::Vector{Float64})
m = length(vec)
if m != size(block)
error("Vector and Block do not have the same size!")
end
memptr = Base.unsafe_convert(Ptr{Float64}, vec)
State(cxx_State(block.cxx_block, memptr, 1, 1))
end
function State(block::Block, vec::Vector{ComplexF64})
m = length(vec)
if m != size(block)
error("Vector and Block do not have the same size!")
end
memptr = Base.unsafe_convert(Ptr{ComplexF64}, vec)
State(cxx_State(block.cxx_block, memptr, 1))
end
function State(block::Block, mat::Matrix{Float64})
m = size(mat)[1]
n = size(mat)[2]
if m != size(block)
error("First dimension of matrix and Block do not have the same size!")
end
memptr = Base.unsafe_convert(Ptr{Float64}, mat)
State(cxx_State(block.cxx_block, memptr, n, 1))
end
function State(block::Block, mat::Matrix{ComplexF64})
m = size(mat)[1]
n = size(mat)[2]
if m != size(block)
error("First dimension of matrix and Block do not have the same size!")
end
memptr = Base.unsafe_convert(Ptr{ComplexF64}, mat)
State(cxx_State(block.cxx_block, memptr, n))
end
# Methods
n_sites(state::State) = n_sites(state.cxx_state)
Base.isreal(state::State) = isreal(state.cxx_state)
Base.real(state::State) = State(real(state.cxx_state))
Base.imag(state::State) = State(imag(state.cxx_state))
make_complex!(state::State) = make_complex(state.cxx_state)
dim(state::State) = dim(state.cxx_state)
Base.size(state::State) = size(state.cxx_state)
n_rows(state::State) = n_rows(state.cxx_state)
n_cols(state::State) = n_cols(state.cxx_state)
col(state::State, n::Int64 = 1; copy::Bool = true) =
State(col(state.cxx_state, n - 1, copy))
function vector(state::State; n::Int64 = 1)
if isreal(state)
return to_julia(vector(state.cxx_state, n-1, false))
else
return to_julia(vectorC(state.cxx_state, n-1, false))
end
end
function matrix(state::State)
if isreal(state)
return to_julia(matrix(state.cxx_state, false))
else
return to_julia(matrixC(state.cxx_state, false))
end
end
# Output
Base.show(io::IO, state::State) = print(io, "\n" * to_string(state.cxx_state))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 610 | struct Permutation
cxx_perm::cxx_Permutation
end
# Constructors
Permutation(array::Vector{Int64}) = Permutation(cxx_Permutation(StdVector(array .- 1)))
# Methods
Base.size(perm::Permutation) = size(array(perm.cxx_perm))
inverse(perm::Permutation) = Permutation(inverse(perm.cxx_perm))
Base.:getindex(perm::Permutation, idx::Integer) = array(perm.cxx_perm)[idx]
Base.:*(p1::Permutation, p2::Permutation) = Permutation(multiply(p1.cxx_perm, p2.cxx_perm))
# Output
function Base.show(io::IO, perm::Permutation)
# print(io, "\n" * to_string(perm.cxx_perm))
print(io, array(perm.cxx_perm) .+ 1)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 624 | struct PermutationGroup
cxx_group::cxx_PermutationGroup
end
# Constructors
function PermutationGroup(permutations::Vector{Permutation})
cxx_perms = cxx_VectorPermutation()
for p in permutations
push_back(cxx_perms, p.cxx_perm)
end
PermutationGroup(cxx_PermutationGroup(cxx_perms))
end
# Methods
Base.size(group::PermutationGroup) = size(group.cxx_group)
n_sites(group::PermutationGroup) = n_sites(group.cxx_group)
inverse(group::PermutationGroup, idx::Integer) = inverse(group.cxx_group, idx)
# Output
Base.show(io::IO, group::PermutationGroup) = print(io, "\n" * to_string(group.cxx_group))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 763 | struct Representation
cxx_representation::cxx_Representation
end
# Constructors
function Representation(characters::Vector{<:Number})
characters_cplx = Vector{ComplexF64}(characters)
memptr = Base.unsafe_convert(Ptr{ComplexF64}, characters_cplx)
n = length( characters_cplx)
return Representation(cxx_Representation(memptr, n))
end
# Methods
Base.size(irrep::Representation) = size(irrep.cxx_representation)
Base.isreal(irrep::Representation; precision::Real=1e-12) = isreal(irrep.cxx_representation, precision)
Base.:*(r1::Representation, r2::Representation) = Representation(multiply(r1.cxx_representation, r2.cxx_representation))
# Output
Base.show(io::IO, irrep::Representation) = print(io, "\n" * to_string(irrep.cxx_representation))
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1719 | function to_armadillo(mat::Matrix{Float64}; copy=true)
m, n = size(mat)
memptr = Base.unsafe_convert(Ptr{Float64}, mat)
return cxx_arma_mat(memptr, m, n, copy, true)
end
function to_armadillo(mat::Matrix{ComplexF64}; copy=true)
m, n = size(mat)
memptr = Base.unsafe_convert(Ptr{ComplexF64}, mat)
return cxx_arma_cx_mat(memptr, m, n, copy, true)
end
function to_julia(vec::cxx_arma_vec)
m = n_rows(vec)
julia_vec = Vector{Float64}(undef, m)
# Low level C call to copy
vec_ptr = memptr(vec).cpp_object
julia_vec_ptr = Base.unsafe_convert(Ptr{Float64}, julia_vec)
Base.unsafe_copyto!(julia_vec_ptr, vec_ptr, m)
return julia_vec
end
function to_julia(vec::cxx_arma_cx_vec)
m = n_rows(vec)
julia_vec = Vector{ComplexF64}(undef, m)
# Low level C call to copy
vec_ptr = memptr(vec).cpp_object
julia_vec_ptr = Base.unsafe_convert(Ptr{ComplexF64}, julia_vec)
Base.unsafe_copyto!(julia_vec_ptr, vec_ptr, m)
return julia_vec
end
function to_julia(mat::cxx_arma_mat)
m = n_rows(mat)
n = n_cols(mat)
N = n_elem(mat)
julia_mat = Matrix{Float64}(undef, m, n)
# Low level C call to copy
mat_ptr = memptr(mat).cpp_object
julia_mat_ptr = Base.unsafe_convert(Ptr{Float64}, julia_mat)
Base.unsafe_copyto!(julia_mat_ptr, mat_ptr, N)
return julia_mat
end
function to_julia(mat::cxx_arma_cx_mat)
m = n_rows(mat)
n = n_cols(mat)
N = n_elem(mat)
julia_mat = Matrix{ComplexF64}(undef, m, n)
# Low level C call to copy
mat_ptr = memptr(mat).cpp_object
julia_mat_ptr = Base.unsafe_convert(Ptr{ComplexF64}, julia_mat)
Base.unsafe_copyto!(julia_mat_ptr, mat_ptr, N)
return julia_mat
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 239 | using XDiag
using Test
include("operators/coupling.jl")
include("operators/op.jl")
include("operators/opsum.jl")
include("states/state.jl")
include("blocks/blocks.jl")
include("algebra/algebra.jl")
include("algorithms/eigs_lanczos.jl")
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 436 | @testset "algebra" begin
N = 8
block = Spinhalf(N, N ÷ 2)
ops = OpSum()
for i in 1:N
ops += Op("HB", 1.0, [i, mod1(i+1, N)])
end
e0, psi = eig0(ops, block);
# @show vector(psi)
v = vector(psi)
# @show e0
n2 = norm(psi)
n1 = norm1(psi)
ni = norminf(psi)
@test ni < n2
@test n2 < n1
@test isapprox(dot(psi, psi), 1.0)
@test isapprox(e0, inner(ops, psi))
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 299 | @testset "eigs_lanczos" begin
N = 8
block = Spinhalf(N, N ÷ 2)
ops = OpSum()
for i in 1:N
ops += Op("HB", 1.0, [i, mod1(i+1, N)])
end
res = eigs_lanczos(ops, block)
psi0 = res.eigenvectors
E = inner(ops, psi0)
@test isapprox(E, res.eigenvalues[1])
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 895 | @testset "blocks" begin
N = 4
nup = 2
ndn = 1
p1 = Permutation([1, 2, 3, 4])
p2 = Permutation([2, 3, 4, 1])
p3 = Permutation([3, 4, 1, 2])
p4 = Permutation([4, 1, 2, 3])
group = PermutationGroup([p1, p2, p3, p4])
rep = Representation([1, -1, 1, -1])
block_sym = tJ(N, nup, ndn, group, rep)
# Iteration
idx = 1
for pstate in block_sym
@test index(block_sym, pstate) == idx
# @show pstate
idx += 1
end
block_sym = Electron(N, nup, ndn, group, rep)
# Iteration
idx = 1
for pstate in block_sym
@test index(block_sym, pstate) == idx
# @show pstate
idx += 1
end
block_sym = Spinhalf(N, nup, group, rep)
# Iteration
idx = 1
for pstate in block_sym
@test index(block_sym, pstate) == idx
# @show pstate
idx += 1
end
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1308 | @testset "Coupling" begin
c = Coupling("hello")
# @show c, type(c), isexplicit(c)
@test type(c) == "string"
@test isexplicit(c) == false
@test convert(String, c) == "hello"
c = Coupling(1.0)
# @show c, type(c), isreal(c), ismatrix(c), isexplicit(c)
@test type(c) == "double"
@test isreal(c) == true
@test ismatrix(c) == false
@test isexplicit(c) == true
@test convert(Float64, c) == 1.0
@test convert(ComplexF64, c) == 1.0 + 0.0im
c = Coupling(2.0 + 3im)
# @show c, type(c), isreal(c), ismatrix(c), isexplicit(c)
@test type(c) == "complex"
@test isreal(c) == false
@test ismatrix(c) == false
@test isexplicit(c) == true
@test convert(ComplexF64, c) == 2.0 + 3.0im
cm = [0.0 1.0; 2.0 0.0]
c = Coupling(cm)
# @show c, type(c), isreal(c), ismatrix(c), isexplicit(c)
@test type(c) == "mat"
@test isreal(c) == true
@test ismatrix(c) == true
@test isexplicit(c) == true
@test cm == convert(Matrix{Float64}, c)
cm = [0 -im; im 0.0]
c = Coupling(cm)
# @show c, type(c), isreal(c), ismatrix(c), isexplicit(c)
@test type(c) == "cx_mat"
@test isreal(c) == false
@test ismatrix(c) == true
@test isexplicit(c) == true
@test cm == convert(Matrix{ComplexF64}, c)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 1595 | @testset "Op" begin
op = Op("HOP", "T", [1, 2])
@test type(op) == "HOP"
@test convert(String, coupling(op)) == "T"
@test size(op) == 2
@test op[1] == 1
@test op[2] == 2
@test sites(op) == [1, 2]
@test isexplicit(op) == false
c = 1.23
op = Op("HOP", c, [1, 2])
@test type(op) == "HOP"
@test convert(Float64, coupling(op)) == c
@test size(op) == 2
@test op[1] == 1
@test op[2] == 2
@test sites(op) == [1, 2]
@test isreal(op) == true
@test ismatrix(op) == false
@test isexplicit(op) == true
c = 3.21 + 1.23im
op = Op("HOP", c, [1, 2])
@test type(op) == "HOP"
@test convert(ComplexF64, coupling(op)) == c
@test size(op) == 2
@test op[1] == 1
@test op[2] == 2
@test sites(op) == [1, 2]
@test isreal(op) == false
@test ismatrix(op) == false
@test isexplicit(op) == true
c = [0 1; 1 0]
op = Op("HOP", c, [1, 2])
@test type(op) == "HOP"
@test convert(Matrix{Float64}, coupling(op)) == convert(Matrix{Float64}, c)
@test size(op) == 2
@test op[1] == 1
@test op[2] == 2
@test sites(op) == [1, 2]
@test isreal(op) == true
@test ismatrix(op) == true
@test isexplicit(op) == true
c = [0 -im; im 0]
op = Op("HOP", c, [1, 2])
@test type(op) == "HOP"
@test convert(Matrix{ComplexF64}, coupling(op)) == convert(Matrix{ComplexF64}, c)
@test size(op) == 2
@test op[1] == 1
@test op[2] == 2
@test sites(op) == [1, 2]
@test isreal(op) == false
@test ismatrix(op) == true
@test isexplicit(op) == true
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 617 | @testset "OpSum" begin
op1 = Op("HOP", "T", [1, 2])
op2 = Op("HOP", "T", [2, 3])
ops = OpSum([op1, op2])
@test size(ops) == 2
ops += Op("HOP", "T", [3, 4])
@test size(ops) == 3
# @test isexplicit(ops) == false
ops2 = OpSum()
ops2 += Op("HB", "J", [1, 2])
ops2 += Op("HB", "J", [2, 3])
ops2 += Op("HB", "J", [4, 5])
J = 1.23
ops2["J"] = J
@test convert(Float64, ops2["J"]) == J
@test size(ops2) == 3
@test isexplicit(ops2) == false
ops3 = OpSum()
ops3 += Op("HB", 1.23, [0, 1])
ops3 += Op("HB", 1.23, [1, 2])
@test isexplicit(ops3)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | code | 696 | @testset "State" begin
block = Spinhalf(2)
v = [1.0, 2.0, 3.0, 4.0]
psi1 = State(block, v)
@test v == vector(psi1)
@test isreal(psi1)
make_complex!(psi1)
@test !isreal(psi1)
@test [1.0 + 0.0im, 2.0 + 0.0im, 3.0 + 0.0im, 4.0 + 0.0im] == vector(psi1)
@test size(psi1) == 4
@test dim(psi1) == 4
psi2 = State(block, real=false, n_cols=3)
@test all(isapprox.(matrix(psi2), 0.0))
@test n_rows(psi2) == 4
@test n_cols(psi2) == 3
@test !isreal(psi2)
v = [1.0+4.0im, 2.0+3.0im, 3.0+2.0im, 4.0+1.0im]
psi3 = State(block, v)
@test !isreal(psi3)
@test vector(real(psi3)) == real(v)
@test vector(imag(psi3)) == imag(v)
end
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"Apache-2.0"
] | 0.2.3 | 0abe5af94f5aaf31dc0afc0d1284656964d745dc | docs | 2054 | 
[](https://awietek.github.io/xdiag)
[](https://github.com/awietek/xdiag/actions/workflows/linux.yml)
[](https://github.com/awietek/xdiag/actions/workflows/osx.yml)
[](https://github.com/awietek/XDiag.jl/actions/workflows/CI.yml)
[](https://zenodo.org/badge/latestdoi/169422780)
# XDiag
## High-performance Yxact Diagonalization Routines and Algorithms
A Julia library to perform efficient Exact Diagonalizations of quantum many body systems.
### Features:
- Basic algebra of operators in quantum many-body systems
- Iterative linear algebra for computing eigendecompositions and time-evolutions (e.g. Lanczos algorithm)
- Local spin, t-J, or fermionic models
- Full support of generic space group symmetries
- parallelization using OpenMP
- based on C++ library [xdiag](https://github.com/awietek/xdiag)
### Installation:
Enter the package mode using `]` in the Julia REPL and add type
```bash
add XDiag
```
That's it!
### Example Code:
```julia
using XDiag
let
N = 16;
nup = N ÷ 2;
block = Spinhalf(N, nup);
# Define the nearest-neighbor Heisenberg model
ops = OpSum()
for i in 1:N
ops += Op("HB", "J", [i, mod1(i+1, N)])
end
ops["J"] = 1.0;
set_verbosity(2); # set verbosity for monitoring progress
e0 = eigval0(ops, block); # compute ground state energy
println("Ground state energy: $e0");
end
```
### Documentation
The full documentation is available at [awietek.github.io/xdiag](https://awietek.github.io/xdiag).
### About
author: Alexander Wietek
license: Apache License 2.0
| XDiag | https://github.com/awietek/XDiag.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 795 | using Documenter
using UtilityModels
makedocs(
warnonly = true,
sitename = "UtilityModels",
format = Documenter.HTML(
assets = [
asset(
"https://fonts.googleapis.com/css?family=Montserrat|Source+Code+Pro&display=swap",
class = :css
)
],
collapselevel = 1
),
modules = [
UtilityModels
# Base.get_extension(SequentialSamplingModels, :TuringExt),
# Base.get_extension(SequentialSamplingModels, :PlotsExt)
],
pages = [
"Home" => "index.md",
"Models" => [
"Expected Utility Theory" => "expected_utility.md"
],
"Parameter Estimation" => "parameter_estimation.md"
]
)
deploydocs(
repo = "github.com/itsdfish/UtilityModels.jl.git",
)
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 1278 | """
ExpectedUtility{T <: Real} <: UtilityModel
A model object for expected utility theory
# Fields
- `α`: utility curvature
- `θ`: temperature or decisional consistency
# Constructors
````julia
ExpectedUtility(; α = .80, θ = 1.0)
````
````julia
ExpectedUtility(α, θ)
````
# Example
```julia
using UtilityModels
gamble1 = Gamble(;
p = [.25, .25, .50],
v = [44, 40, 5]
)
gamble2 = Gamble(;
p = [.25, .25, .50],
v = [98, 10, 5]
)
gambles = [gamble1,gamble2]
mean.(model, gambles)
std.(model, gambles)
model = ExpectedUtility(; α = .80, θ = 1.0)
pdf(model, gambles, 1)
logpdf(model, gambles, 1)
```
"""
mutable struct ExpectedUtility{T <: Real} <: UtilityModel
α::T
θ::T
end
function ExpectedUtility(; α = 0.80, θ = 1.0)
return ExpectedUtility(α, θ)
end
function ExpectedUtility(α, θ)
return ExpectedUtility(promote(α, θ)...)
end
"""
compute_utility(model::ExpectedUtility, gamble::Gamble)
Computes utility of gamble outcomes according to expected utility theory.
# Arguments
- `model::ExpectedUtility`: a model object for prospect theory
- `gamble::Gamble`: a gamble object
"""
function compute_utility(model::ExpectedUtility, gamble::Gamble)
(; α) = model
(; v) = gamble
return @. sign(v) * abs(v)^α
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 606 | """
Gamble{T <: Real}
A gamble object with probability vector `p` and outcome vector `v`.
# Fields
- `p`: probability vector
- `v`: outcome vector
# Constructors
Gamble(; p = [0.5, 0.5], v = [10.0, 0.0])
Gamble(p, v)
"""
mutable struct Gamble{T <: Real}
p::Vector{T}
v::Vector{T}
end
function Gamble(; p = [0.5, 0.5], v = [10.0, 0.0])
return Gamble(p, v)
end
function Gamble(p, v)
T = promote_type(typeof(p), typeof(v))
return Gamble(T(p), T(v))
end
function sample(gamble::Gamble)
return sample(gamble.v, Weights(gamble.p))
end
mean(g::Gamble) = g.v' * g.p
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 3785 | abstract type AbstractProspectTheory <: UtilityModel end
"""
ProspectTheory{T <: Real} <: AbstractProspectTheory
A model object for cummulative prospect theory.
By default, parameters for utility curvature and probability weigting are equal gains and losses.
# Fields
- `α = .80`: utility curvature for gains
- `β = α`: utility curvature for losses
- `γg = .70`: probability weighting parameter for gains
- `γl = γg`: probability weighting parameter for losses
- `λ = 2.25`: loss aversion parameter
- `θ`: temperature or decisional consistency
# Constructors
```julia
ProspectTheory(; α = 0.80, β = α, γg = 0.70, γl = γg, λ = 2.25, θ = 1.0)
ProspectTheory(α, β, γg, γl, λ, θ)
```
# Example
```julia
using UtilityModels
gamble1 = Gamble(;
p = [.25, .25, .50],
v = [44, 40, 5]
)
gamble2 = Gamble(;
p = [.25, .25, .50],
v = [98, 10, 5]
)
gambles = [gamble1,gamble2]
mean.(model, gambles)
std.(model, gambles)
model = ProspectTheory(;
α = 0.80,
γg = 0.70,
λ = 2.25,
θ = 1.0
)
pdf(model, gambles, 1)
logpdf(model, gambles, 1)
```
# References
Fennema, H., & Wakker, P. (1997). Original and cumulative prospect theory: A discussion of empirical differences. Journal of Behavioral Decision Making, 10(1), 53-64.
Tversky, A., & Kahneman, D. (1992). Advances in prospect theory: Cumulative representation of uncertainty. Journal of Risk and uncertainty, 5(4), 297-323.
"""
mutable struct ProspectTheory{T <: Real} <: AbstractProspectTheory
α::T
β::T
γg::T
γl::T
λ::T
θ::T
end
function ProspectTheory(; α = 0.80, β = α, γg = 0.70, γl = γg, λ = 2.25, θ = 1.0)
return ProspectTheory(α, β, γg, γl, λ, θ)
end
function ProspectTheory(α, β, γg, γl, λ, θ)
return ProspectTheory(promote(α, β, γg, γl, λ, θ)...)
end
"""
compute_utility(model::AbstractProspectTheory, gamble)
Computes utility of gamble outcomes according to prospect theory
# Arguments
- `model::AbstractProspectTheory`: a model object for prospect theory
- `gamble`: a gamble object
"""
function compute_utility(model::AbstractProspectTheory, gamble)
(; α, β, λ) = model
vl, vg = split_values(gamble)
utilg = vg .^ α
utill = @. -λ * abs(vl)^β
return [utill; utilg]
end
"""
compute_weights(model::AbstractProspectTheory, gamble::Gamble)
Computes decision weights based on cummulative outcomes
# Arguments
- `model::AbstractProspectTheory`: a model object for prospect theory
- `gamble`: a gamble object
"""
function compute_weights(model::AbstractProspectTheory, gamble::Gamble)
pl, pg = split_probs(gamble)
(; γg, γl) = model
ω = [_compute_weights(pl, γl); _compute_weights(pg, γg)]
return ω
end
"""
_compute_weights(p, γ)
Computes decision weights based on cummulative outcomes
# Arguments
- `p`: a probability vector
- `γ`: parameter that controls weighting of low and high probabilities
"""
function _compute_weights(p, γ)
n = length(p)
f(i) = weight(sum(p[i:n]), γ) - weight(sum(p[(i + 1):n]), γ)
ω = [f(i) for i = 1:(n - 1)]
isempty(p) ? nothing : push!(ω, weight(p[n], γ))
return ω
end
function weight(p, γ)
p = min(p, 1.0) # to deal with overflow
return (p^γ) / (p^γ + (1 - p)^γ)^(1 / γ)
end
function sort!(model::AbstractProspectTheory, gamble::Gamble)
(; p, v) = gamble
i = sortperm(v)
p .= p[i]
v .= v[i]
gains = v .>= 0
pl = @view p[.!gains]
vl = @view v[.!gains]
reverse!(vl)
reverse!(pl)
return nothing
end
function split_values(gamble)
(; v) = gamble
gains = v .>= 0
vg = @view v[gains]
vl = @view v[.!gains]
return vl, vg
end
function split_probs(gamble)
(; v, p) = gamble
gains = v .>= 0
pg = @view p[gains]
pl = @view p[.!gains]
return pl, pg
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 2784 | abstract type AbstractTAX <: UtilityModel end
"""
TAX{T <: Real} <: AbstractTAX
A model object for transfer of attention exchange.
# Fields
- `δ = 1.0`: transfer of attention parameter
- `γ = 1.0`: probability weighting parameter
- `β = .70`: utility curvature
- `θ`: temperature or decisional consistency
# Constructors
```julia
TAX(; δ = -1.0, β = 1.0, γ = 0.70, θ = 1.0)
TAX(δ, γ, β, θ)
```
# Example
```julia
using UtilityModels
gamble1 = Gamble(;
p = [.25, .25, .50],
v = [44, 40, 5]
)
gamble2 = Gamble(;
p = [.25, .25, .50],
v = [98, 10, 5]
)
gambles = [gamble1,gamble2]
mean.(model, gambles)
std.(model, gambles)
model = TAX(; δ = -1.0,
β = 1.0,
γ = 0.70,
θ = 1.0
)
pdf(model, gambles, 1)
logpdf(model, gambles, 1)
```
# References
Birnbaum, M. H., & Chavez, A. (1997). Tests of theories of decision making: Violations of branch independence and distribution independence. Organizational Behavior and Human Decision Processes, 71(2), 161-194.
Birnbaum, M. H. (2008). New paradoxes of risky decision making. Psychological Review, 115(2), 463.
"""
mutable struct TAX{T <: Real} <: AbstractTAX
δ::T
γ::T
β::T
θ::T
end
function TAX(; δ = -1.0, β = 1.0, γ = 0.70, θ = 1.0)
return TAX(δ, γ, β, θ)
end
function TAX(δ, γ, β, θ)
return TAX(promote(δ, γ, β, θ)...)
end
"""
compute_utility(model::AbstractTAX, gamble)
Computes utility of gamble outcomes according to TAX
# Arguments
- `model::AbstractTAX`: a model object for TAX
- `gamble`: a gamble object
"""
function compute_utility(model::AbstractTAX, gamble)
(; β) = model
(; v) = gamble
utility = @. sign(v) * abs(v)^β
return utility
end
tax_weight(p, γ) = (p^γ)
function ω(p, pk, n, δ, γ)
if δ > 0
return δ * tax_weight(pk, γ) / (n + 1)
end
return δ * tax_weight(p, γ) / (n + 1)
end
function sort!(model::AbstractTAX, gamble::Gamble)
(; p, v) = gamble
i = sortperm(v)
p .= p[i]
v .= v[i]
return nothing
end
"""
mean(model::AbstractTAX, gamble::Gamble)
Computes mean utility for the TAX model
# Arguments
- `model::AbstractTAX`: a model M <: UtilityModel
- `gamble::Gamble`: a gamble object
"""
function mean(model::AbstractTAX, gamble::Gamble)
(; p, v) = gamble
(; γ, δ) = model
n = length(p)
sort!(model, gamble)
utility = compute_utility(model, gamble)
eu = 0.0
sum_weight = 0.0
for i ∈ 1:n
eu += tax_weight(p[i], γ) * utility[i]
sum_weight += tax_weight(p[i], γ)
for k ∈ 1:(i - 1)
eu += (utility[i] - utility[k]) * ω(p[i], p[k], n, δ, γ)
end
end
return eu / sum_weight
end
function var(model::AbstractTAX, gamble::Gamble)
error("var not implimented for TAX")
return -100.0
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 4460 | """
UtilityModel <: DiscreteMultivariateDistribution
`UtilityModel` is an abstract type for utility-based models
````
"""
abstract type UtilityModel <: DiscreteMultivariateDistribution end
"""
mean(model::UtilityModel, gamble::Gamble)
Computes mean or expected utility
# Arguments
- `model::UtilityModel`: a model M <: UtilityModel
- `gamble::Gamble`: a gamble object
````
"""
function mean(model::UtilityModel, gamble::Gamble)
sort!(model, gamble)
weights = compute_weights(model, gamble)
utility = compute_utility(model, gamble)
return weights' * utility
end
Base.broadcastable(model::UtilityModel) = Ref(model)
length(model::UtilityModel) = 1
"""
var(model::UtilityModel, gamble::Gamble)
Computes the variance of the gamble
# Arguments
- `model::UtilityModel`: a utility model
- `gamble::Gamble`: a gamble object
"""
function var(model::UtilityModel, gamble::Gamble)
(; p) = gamble
utility = compute_utility(model, gamble)
eu = mean(model, gamble)
return sum(p .* (utility .- eu) .^ 2)
end
"""
std(model::UtilityModel, gamble::Gamble)
Computes the standard deviation of the gamble
# Arguments
- `model::UtilityMode`: a model M <: UtilityModel
- `gamble::Gamble`: a gamble object
"""
std(model::UtilityModel, gamble::Gamble) = sqrt(var(model, gamble))
"""
compute_weights(model::UtilityModel, gamble::Gamble)
Computes decision weights as `gamble.p` by default .
# Arguments
- `model::UtilityModel`: a model M <: UtilityModel
- `gamble::Gamble`: a gamble object
"""
compute_weights(model::UtilityModel, gamble::Gamble) = gamble.p
"""
sort!(model::UtilityModel, gamble)
Sorts gamble probabilities and values. The generic method
does not sort the gambles
# Arguments
- `model::UtilityModel`: a utility model
- `gamble::Gamble`: a gamble object
"""
function sort!(model::UtilityModel, gamble::Gamble) end
"""
pdf(model::UtilityModel, gambles::Vector{<:Gamble}, choice::Int)
Computes the choice probability for a vector of gambles.
# Arguments
- `model::UtilityModel`: a utility model
- `gambles::Vector{<:Gamble}`: a vector of gambles representing a choice set
- `choice_idxs::Vector{<:Int}`: indices for the chosen gambles
"""
function pdf(model::UtilityModel, gambles::Vector{<:Gamble}, choice_idxs::Vector{<:Int})
utility = mean.(model, gambles)
util_exp = exp.(model.θ .* utility)
n = sum(choice_idxs)
p = util_exp ./ sum(util_exp)
return pdf(Multinomial(n, p), choice_idxs)
end
"""
logpdf(model::UtilityModel, gambles::Vector{<:Gamble}, choice::Int)
Computes the choice log probability for a vector of gambles.
# Arguments
- `model::UtilityModel`: a utility model
- `gambles::Vector{<:Gamble}`: a vector of gambles representing a choice set
- `choice_idxs::Vector{<:Int}`: indices for the chosen gambles
"""
function logpdf(model::UtilityModel, gambles::Vector{<:Gamble}, choice_idxs::Vector{<:Int})
utility = mean.(model, gambles)
util_exp = exp.(model.θ .* utility)
T = typeof(model.θ)
n = sum(choice_idxs)
p = util_exp ./ sum(util_exp)
!isprobvec(p) ? (return T(-Inf)) : nothing
return logpdf(Multinomial(n, p), choice_idxs)
end
isprobvec(p::AbstractVector{<:Real}) =
all(x -> x ≥ zero(x), p) && isapprox(sum(p), one(eltype(p)))
function logpdf(model::UtilityModel, data::Tuple)
return logpdf(model, data[1], data[2])
end
loglikelihood(
model::UtilityModel,
data::Tuple{Vector{<:Vector{<:Gamble}}, Vector{<:Vector{<:Integer}}}
) = loglikelihood(model, data[1], data[2])
loglikelihood(
model::UtilityModel,
gambles::Vector{<:Vector{<:Gamble}},
choices::Vector{<:Vector{<:Integer}}
) = sum(logpdf.(model, gambles, choices))
loglikelihood(
model::UtilityModel,
gambles::Vector{<:Gamble},
choices::Vector{<:Integer}
) = sum(logpdf(model, gambles, choices))
loglikelihood(
model::UtilityModel,
data::Tuple{Vector{<:Gamble}, Vector{<:Integer}}
) = sum(logpdf(model, data[1], data[2]))
"""
rand(model::UtilityModel, gambles::Vector{<:Gamble})
Generates a simulated choice
# Arguments
- `model::UtilityModel`: a utility model
- `gambles::Vector{<:Gamble}`: a vector of gambles representing a choice set
"""
function rand(model::UtilityModel, gambles::Vector{<:Gamble}, n_sim::Int = 1)
utility = mean.(model, gambles)
util_exp = exp.(model.θ .* utility)
probs = util_exp ./ sum(util_exp)
return rand(Multinomial(n_sim, probs))
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 742 | module UtilityModels
using StatsBase
using StatsFuns
using Distributions
import Distributions: length
import Distributions: loglikelihood
import Distributions: logpdf
import Distributions: mean
import Distributions: pdf
import Distributions: std
import Distributions: rand
import Distributions: var
import StatsBase: sample
import Base: sort!
export ExpectedUtility
export Gamble
export ProspectTheory
export TAX
export UtilityModel
export ValenceExpectancy
export compute_utility
export mean
export loglikelihood
export logpdf
export pdf
export var
export sample
export std
include("Gamble.jl")
include("UtilityModel.jl")
include("ProspectTheory.jl")
include("ExpectedUtility.jl")
include("ValenceExpectancy.jl")
include("TAX.jl")
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 2571 | abstract type AbstractValenceExpectancy <: UtilityModel end
"""
ValenceExpectancy{T <: Real} <: AbstractValenceExpectancy
A model object for expected utility theory
# Fields
- `υ`: a vector of expected utilities
- `Δ`: learning rate where `Δ ∈ [0,1]`
- `α`: utility shape parameter where `α > 0`
- `λ`: loss aversion where `λ > 0`
- `c`: temperature
# Constructors
```julia
ValenceExpectancy(; n_options, Δ, α = 0.80, λ, c)
ValenceExpectancy(Δ, α, λ, c)
```
"""
mutable struct ValenceExpectancy{T <: Real} <: AbstractValenceExpectancy
υ::Vector{T}
Δ::T
α::T
λ::T
c::T
end
function ValenceExpectancy(; n_options, Δ, α = 0.80, λ, c)
υ = zeros(n_options)
return ValenceExpectancy(υ, Δ, α, λ, c)
end
function ValenceExpectancy(Δ, α, λ, c)
Δ, α, λ, c = promote(Δ, α, λ, c)
υ = zeros(typeof(Δ), n_options)
return ValenceExpectancy(υ, Δ, α, λ, c)
end
"""
compute_utility(model::ValenceExpectancy, outcomes::Vector)
`compute_utility` computes utility of gamble outcomes according to expected utility theory
- `model`: a model object for prospect theory
- `gamble`: a gamble object
Function Signature
````julia
compute_utility(model::ExpectedUtility, gamble::Gamble)
````
"""
function compute_utility(model::ValenceExpectancy, outcomes)
(; λ, α) = model
v = sum(outcomes)
utility = sign(v) * abs(v)^α
utility *= v < 0 ? λ : 1
return utility
end
function update_utility!(model::AbstractValenceExpectancy, choice_idx, outcomes)
υ = model.υ
υ[choice_idx] += model.Δ * (compute_utility(model, outcomes) - υ[choice_idx])
return υ
end
function compute_probs(model::AbstractValenceExpectancy, trial_idx)
(; υ, c) = model
θ = min(300, (trial_idx / 10)^c)
v = exp.(υ * θ)
return v ./ sum(v)
end
function logpdf(model::AbstractValenceExpectancy, choices, outcomes)
LL = 0.0
for i ∈ 1:length(choices)
probs = compute_probs(model, i)
p = max(1e-10, probs[choices[i]])
LL += log(p)
update_utility!(model, choices[i], outcomes[i])
end
return LL
end
function rand(model::AbstractValenceExpectancy, gambles, n_trials::Int)
choices = fill(0, n_trials)
n_options = length(gambles)
outcomes = fill(0.0, n_trials)
for i ∈ 1:length(choices)
probs = compute_probs(model, i)
choice = sample(1:n_options, Weights(probs))
choices[i] = choice
outcome = sample(gambles[choice])
outcomes[i] = outcome
update_utility!(model, choice, outcome)
end
return choices, outcomes
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 3527 | @safetestset "pdf" begin
@safetestset "1" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-10, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [gamble1, gamble2]
model = ExpectedUtility(; α = 1.0, θ = 1.0)
prob = pdf(model, gambles, [1, 0])
@test prob ≈ 0.50
end
@safetestset "2" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [gamble1, gamble2]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
prob = pdf(model, gambles, [1, 0])
@test prob ≈ 1 / (1 + exp(-2 * -0.5))
end
end
@safetestset "logpdf" begin
@safetestset "1" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [gamble1, gamble2]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
log_prob = pdf(model, gambles, [1, 0]) |> log
@test log_prob ≈ logpdf(model, gambles, [1, 0])
end
end
@safetestset "loglikelihood" begin
@safetestset "1" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [gamble1, gamble2]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
log_prob = pdf(model, gambles, [1, 0]) |> log
@test log_prob ≈ loglikelihood(model, gambles, [1, 0])
end
@safetestset "2" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [gamble1, gamble2]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
log_prob = pdf(model, gambles, [1, 0]) |> log
data = (gambles, [1, 0])
@test log_prob ≈ loglikelihood(model, data)
end
@safetestset "3" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [[gamble1, gamble2], [gamble1, gamble2]]
choices = [[1, 0], [0, 1]]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
sumlogpdf =
logpdf(model, gambles[1], choices[1]) + logpdf(model, gambles[2], choices[2])
@test sumlogpdf ≈ loglikelihood(model, gambles, choices)
end
@safetestset "4" begin
using Test
using UtilityModels
gamble1 = Gamble(;
p = [0.50, 0.50],
v = [-11, 10]
)
gamble2 = Gamble(;
p = [1],
v = [0]
)
gambles = [[gamble1, gamble2], [gamble1, gamble2]]
choices = [[1, 0], [0, 1]]
model = ExpectedUtility(; α = 1.0, θ = 2.0)
sumlogpdf =
logpdf(model, gambles[1], choices[1]) + logpdf(model, gambles[2], choices[2])
@test sumlogpdf ≈ loglikelihood(model, (gambles, choices))
end
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 526 | @safetestset "ExpectedUtility" begin
using Test
using UtilityModels
α = 1.0
θ = 1.0
model = ExpectedUtility(α, θ)
p = [0.3, 0.2, 0.3, 0.2]
v = [10.0, 3.0, -2.0, -1.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ p' * v atol = 1e-4
α = 0.8
θ = 1.0
model = ExpectedUtility(α, θ)
p = [0.3, 0.2, 0.3, 0.2]
v = [10.0, 3.0, -2.0, -1.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ (sign.(v) .* abs.(v) .^ α)' * p atol = 1e-4
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 936 | @safetestset "Prospect Theory" begin
# test values based on http://psych.fullerton.edu/mbirnbaum/calculators/cpt_calculator.htm
using Test
using UtilityModels
import UtilityModels: compute_weights
α = 0.8
β = 0.9
γg = 0.6
γl = 0.7
λ = 2.25
model = ProspectTheory(; α, β, γg, γl, λ)
p = [0.3, 0.2, 0.3, 0.2]
v = [10.0, 3.0, -2.0, -1.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ 0.5672 atol = 1e-4
ω = compute_weights(model, gamble)
@test ω ≈ [0.1293, 0.3281, 0.0992, 0.3165] atol = 1e-4
α = 1.2
β = 1.5
γg = 0.8
γl = 0.9
λ = 1.5
model = ProspectTheory(; α, β, γg, γl, λ)
p = [0.1, 0.2, 0.5, 0.2]
v = [1.0, 3.0, -5.0, -2.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ -8.1017 atol = 1e-4
ω = compute_weights(model, gamble)
@test ω ≈ [0.1811, 0.4962, 0.0848, 0.2415] atol = 1e-4
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 110 | using SafeTestsets
files = filter(x -> x ≠ "runtests.jl", readdir())
for file ∈ files
include(file)
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 1260 | @safetestset "TAX" begin
# tested against http://psych.fullerton.edu/mbirnbaum/calculators/taxcalculator.htm
# using gambles from Birnbaum 2008
using Test
using UtilityModels
model = TAX()
p = [0.25, 0.25, 0.50]
v = [100.0, 0.0, -50.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ -15.5125 atol = 1e-4
model = TAX()
p = [0.80, 0.10, 0.10]
v = [110.0, 44.0, 40.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ 65.02513599372996 atol = 1e-8
model = TAX()
p = [0.05, 0.05, 0.90]
v = [96.0, 12.0, 3.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
@test eu ≈ 8.803653482548164 atol = 1e-8
δ = 1.0
β = 0.9
γ = 0.70
model = TAX(; δ, β, γ)
p = [0.05, 0.05, 0.90]
v = [96.0, 12.0, 3.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
# calculator uses certainty equivalent
@test (eu)^(1 / β) ≈ 33.567163255247856 atol = 1e-8
δ = -0.8
β = 1.1
γ = 0.70
model = TAX(; δ, β, γ)
p = [0.90, 0.05, 0.05]
v = [10.0, 12.0, 2.0]
gamble = Gamble(; p, v)
eu = mean(model, gamble)
# calculator uses certainty equivalent
@test (eu)^(1 / β) ≈ 7.964935426997389 atol = 1e-8
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | code | 1494 | using Test
@testset verbose = true "Valence Expectancy" begin
@safetestset "compute_probs" begin
using Test
using UtilityModels
using UtilityModels: compute_probs
gambles = [Gamble(; p = [0.5, 0.5], v = [10.0, 0.0]),
Gamble(; p = [0.9, 0.1], v = [5.0, 8.0])]
parms = (n_options = 2, Δ = 0.3, α = 0.5, λ = 1.0, c = 0.5)
model = ValenceExpectancy(; parms...)
probs = compute_probs(model, 1)
@test probs ≈ [0.5, 0.5]
parms = (n_options = 2, Δ = 0.3, α = 0.5, λ = 1.0, c = 1.0)
model = ValenceExpectancy(; parms...)
model.υ = [0.0, 2^2]
probs = compute_probs(model, 5)
p = 1 / (1 + exp(-2))
true_probs = [(1 - p), p]
@test true_probs ≈ probs
end
@safetestset "compute_utility" begin
using Test
using UtilityModels
using UtilityModels: compute_utility
parms = (n_options = 2, Δ = 0.3, α = 0.5, λ = 2.0, c = 0.5)
model = ValenceExpectancy(; parms...)
utility = -6.0
@test utility ≈ compute_utility(model, [-10, 1])
end
@safetestset "update_utility!" begin
using Test
using UtilityModels
using UtilityModels: update_utility!
parms = (n_options = 2, Δ = 0.3, α = 0.5, λ = 2.0, c = 0.5)
model = ValenceExpectancy(; parms...)
utility = [0.0, -6.0 * 0.3]
@test utility ≈ update_utility!(model, 2, [-10, 1]) atol = 1e-8
end
end
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | docs | 529 | # UtilityModels
UtilityModels.jl is a collection of utility based decision models. Currently, expected utlity theory, transfer of attention exchange, and prospect theory are implemented. More models soon to follow. See the [documentation](https://itsdfish.github.io/UtilityModels.jl/dev/) for more details.
# Quick Example
````julia
using UtilityModels
# TAX with default values
model = TAX()
p = [.25,.25,.50]
v = [100.0,0.0,-50.0]
gamble = Gamble(; p, v)
# expected utility
mean(model, gamble)
````
````julia
-15.51253
````
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | docs | 5524 | # Expected Utility Theory
The Leaky Competing Accumulator (LCA; Usher & McClelland, 2001) is a sequential sampling model in which evidence for options races independently. The LCA is similar to the Linear Ballistic Accumulator (LBA), but additionally assumes an intra-trial noise and leakage (in contrast, the LBA assumes that evidence accumulates in a ballistic fashion, i.e., linearly and deterministically until it hits the threshold).
# Example
In this example, we will demonstrate how to use the LCA in a generic two alternative forced choice task.
```@setup expected_utility
using Plots
using Random
using UtilityModels
```
## Load Packages
The first step is to load the required packages.
```@example expected_utility
using Plots
using Random
using UtilityModels
Random.seed!(8741)
```
## Create Choice Set
We will consider the following two options in this example. Note that the package can handle choices between an arbitrary number of options.
```@example expected_utility
gamble1 = Gamble(;
p = [.20, .20, .60],
v = [58, 56, 2]
)
gamble2 = Gamble(;
p = [.20, .20, .60],
v = [96, 4, 2]
)
gambles = [gamble1,gamble2]
```
## Create Model Object
In the code below, we will define parameters for the LBA and create a model object to store the parameter values.
### Utility Curvature
The utility curvature parameter $\alpha$ controls whether the utility function is concave, linear, or convex. The utility function is given by:
```math
U(x) = \mathrm{sign}(x)|x|^\alpha.
```
The parameter $\alpha$ can be intrepreted in terms of risk profile as follows:
- risk averse: ``0 \geq \alpha < 1``
- risk neutral: ``\alpha = 1``
- risk seeking: ``\alpha > 1``
The utility function $U(x)$ is plotted below for a range of values of $\alpha$.
```@raw html
<details><summary>Show Plotting Code</summary>
```
```@example expected_utility
model = ExpectedUtility()
vals = [-20:.5:20;]
gamble = Gamble(; v = vals)
αs = range(0, 1.5, length = 5)
utilities = [compute_utility(ExpectedUtility(; α) , gamble) for α ∈ αs]
utility_plot = plot(vals, utilities, xlabel = "x", ylabel = "U(x)", labels = αs', legendtitle = "α", grid = false)
```
```@raw html
</details>
```
```@example expected_utility
utility_plot
```
Below, we set the $\alpha$ parameter to a value associated with moderate risk aversion.
```@example expected_utility
α = .80
```
### Decisional Consistency
The parameter $\theta$—sometimes known as decisional consistency or sensitivity—controls how deterministically a model selects the option with the higher expected utility. In the equation below, the probability of selecting $\x_i$ from choice set $\{x_1,\dots, x_n\}$ is computed with the soft max function.
```math
\Pr(X = x_i \mid \{x_1, \dots, x_n\}) = \frac{e^{\theta \cdot \mathrm{EU}(x_i)}}{\sum_{j=1}^n e^{\theta \cdot \mathrm{EU}(x_j)}}
```
As shown in the plot below, parameter $\theta$ modulates the choice probability.
```@raw html
<details><summary>Show Plotting Code</summary>
```
```@example expected_utility
vals = [-10:.1:10;]
θs = range(0, 2, length = 5)
probs = [pdf(ExpectedUtility(; α = 1, θ) , [Gamble(; p = [1], v = [0]), Gamble(; p = [1], v=[v])], [1,0]) for v ∈ vals, θ ∈ θs]
prob_plot = plot(reverse!(vals), probs, xlabel = "U(A) - U(B)", ylabel = "Probability A", labels = θs', legendtitle = "θ", grid = false)
```
```@raw html
</details>
```
```@example expected_utility
prob_plot
```
We will set $\theta$ to the following value:
```@example expected_utility
θ = 1.0
```
### Expected Utility Constructor
Now that values have been asigned to the parameters, we will pass them to `ExpectedUtility` to generate the model object.
```@example expected_utility
dist = ExpectedUtility(; α, θ)
```
## Expected Utility
The expected utilities of each gamble can be computed via `mean` as demonstrated below:
```@example expected_utility
mean.(dist, gambles)
```
## Standard Deviation Utility
The standard deviation of utilities of each gamble can be computed via `std` as demonstrated below:
```@example expected_utility
std.(dist, gambles)
```
The larger standard deviation of the second gamble indicates it is a riskier option.
## Simulate Model
Now that the model is defined, we will generate $10$ choices using `rand`.
```@example expected_utility
choices = rand(dist, gambles, 10)
```
In the code block above, the output is a sample from a multinomial distribution in which the
## Compute Choice Probability
The probability of choosing the first option can be obtained as follows:
```@example expected_utility
pdf(dist, gambles, [1,0])
```
The relatively high choice probability for the first option makes sense in light of its higher expected value (and lower variance).
## Multiple Choice Sets
The logic above can be easily extended to situations involving multiple choice sets by wrapping them in vectors. Consider the following situation involing two repetitions of two choice sets:
```@example expected_utility
choice_sets = [
[
Gamble(; p = [0.20, 0.20, 0.60], v = [58, 56, 2]),
Gamble(; p = [0.20, 0.20, 0.60], v = [96, 4, 2])
],
[
Gamble(; p = [0.45, 0.45, 0.10], v = [58, 56, 2]),
Gamble(; p = [0.45, 0.45, 0.10], v = [96, 4, 2])
]
]
```
Next, we simulate two choices for each choice set:
```@example expected_utility
choices = rand.(dist, choice_sets, [2,2])
```
Finally, we compute the joint choice probabilities for each choice set:
```@example expected_utility
choices = pdf.(dist, choice_sets, choices)
``` | UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | docs | 55 | # UtilityModels.jl
Documentation for UtilityModels.jl
| UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.4.0 | cb9308adec767a59c3f9857af1c567b81c4cfe73 | docs | 3697 | # Parameter Estimation
In this brief tutorial, we will demonstrate how to perform Bayesian parameter estimation using [Turing.jl](https://turinglang.org/docs/tutorials/docs-00-getting-started/index.html). For simplicity, we will estimate the utility curvature parameter of an expected utility model from 50 independent identically distributed observations from a single choice set.
## Load Packages
The first step is to load the required packages.
```julia
using Plots
using Random
using Turing
using UtilityModels
Random.seed!(6541)
```
## Choice Set
Next, we will create the choice set from two trinary gambles. The first gamble is less risky than the second gamble, as defined by lower variance.
```julia
gamble1 = Gamble(;
p = [.25, .25, .50],
v = [44, 40, 5]
)
```
The second gamble is relatively more risky.
```julia
gamble2 = Gamble(;
p = [.25, .25, .50],
v = [98, 10, 5]
)
```
In the code block below, we combine the gambles into a vector representing the available options. In addition, we create a model object and generate 50 simulated choices. The gambles and simulated choices are combined into a single data structure so it can be passed to `logpdf` via Turing and subsequently parsed.
```julia
gambles = [gamble1,gamble2]
eu_model = ExpectedUtility(; α = .80, θ = 1)
choices = rand(eu_model, gambles, 50)
data = (gambles,choices)
```
## Create Turing Model
Below, we create a turing model by prefixing a function with the `@model` macro. The function passes the data and defines two sampling statements: a prior distribution on the utlity curvature parameter, and a sampling statement for the data.
```julia
@model function model(data)
α ~ truncated(Normal(.8, 1), 0, Inf)
data ~ ExpectedUtility(; α, θ = 1)
end
```
## Estimate Parameters
Now that the Turing model has been defined, we can pass it, along with the data, to `sample` to perform Bayesian parameter estimation with an MCMC algorithm called the No-U-turn sampler. The function call below will sample 2,000 times from the posterior distribution (discarding the first 1,000 warmup samples), for 4 parallel chains.
```julia
chain = sample(model(data), NUTS(1000, .85), MCMCThreads(), 1000, 4)
```
```julia
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.025
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Info: Found initial step size
└ ϵ = 3.2
Chains MCMC chain (1000×13×4 Array{Float64, 3}):
Iterations = 1001:1:2000
Number of chains = 4
Samples per chain = 1000
Wall duration = 0.91 seconds
Compute duration = 3.03 seconds
parameters = α
internals = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, max_hamiltonian_energy_error, tree_depth, numerical_error, step_size, nom_step_size
Summary Statistics
parameters mean std mcse ess_bulk ess_tail rhat ess_per_sec
Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64
α 0.8031 0.0317 0.0009 1299.4792 1501.7839 1.0008 428.8710
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
α 0.7346 0.7841 0.8055 0.8240 0.8591
```
## Plot Posterior Distribution
Inspection of the trace plot does not reveal any anomolies. The density plot shows that the posterior distribution is centered near the data generating value of $\alpha = .80$ and spans roughtly between .75 and .85, suggesting good recovery of the parameter.
```julia
plot(chain, grid = false)
```
 | UtilityModels | https://github.com/itsdfish/UtilityModels.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 1517 |
# set to true to support intel fortran compiler
try
println("************************Trying to build ParSpMatVec ******************************")
useIntelFortran = false
# construct absolute path
depsdir = splitdir(Base.source_path())[1]
builddir = joinpath(depsdir,"builds")
srcdir = joinpath(depsdir,"src")
println("=== Building ParSpMatVec ===")
println("depsdir = $depsdir")
println("builddir = $builddir")
println("srcdir = $srcdir")
println("useIntel = $useIntelFortran")
if !isdir(builddir)
println("creating build directory")
mkdir(builddir)
if !isdir(builddir)
error("Could not create build directory")
end
end
@static if Sys.isunix()
src1 = joinpath(srcdir,"A_mul_B.f90")
src2 = joinpath(srcdir,"Ac_mul_B.f90")
outfile = joinpath(builddir,"ParSpMatVec.so")
if useIntelFortran
run(`ifort -O3 -xHost -fPIC -fpp -openmp -integer-size 64 -diag-disable=7841 -shared $src1 $src2 -o $outfile`)
else
println("fortran version")
# run(`gfortran --version`)
run(`gfortran -v -O3 -fPIC -cpp -fopenmp -fdefault-integer-8 -shared $src1 $src2 -o $outfile`)
println("Done compiling.")
end
end
@static if Sys.iswindows()
src1 = joinpath(srcdir,"A_mul_B.f90")
src2 = joinpath(srcdir,"Ac_mul_B.f90")
outfile = joinpath(builddir,"ParSpMatVec.dll")
run(`gfortran --version`)
run(`gfortran -v -O3 -cpp -fopenmp -fdefault-integer-8 -shared -DBUILD_DLL $src1 $src2 -o $outfile`)
end
catch
@warn "Warning: Unable to build ParSpMatVec"
end
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 3729 |
export A_mul_B!
function A_mul_B!( alpha::Float64,
A::SparseMatrixCSC{Float64,Int},
x::Array{Float64},
beta::Float64,
y::Array{Float64},
nthreads::Int64=0 )
# Real: y = beta*y + alpha * A*x
if nthreads == 0
#Base.A_mul_B!( alpha, A, x, beta, y )
mul!(y,A,x, alpha, beta)
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != m || size(y,1) != n
throw(DimensionMismatch("length(x) != m || length(y) != n"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:a_mul_b_rr_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}, Ptr{Float64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), A.nzval, A.rowval, A.colptr, x, y);
end # function A_mul_B!
#------------------------------------------------------------------------------
function A_mul_B!( alpha::ComplexF64,
A::SparseMatrixCSC{Float64,Int},
x::Array{ComplexF64},
beta::ComplexF64,
y::Array{ComplexF64},
nthreads::Int64=0 )
# Real, Complex A: y = beta*y + alpha * A*x
if nthreads == 0
mul!(y,A,x, alpha, beta) # Base.A_mul_B!( alpha, complex(A), x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != m || size(y,1) != n
throw(DimensionMismatch("length(x) != m || length(y) != n"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:a_mul_b_rc_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{Float64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), A.nzval, A.rowval, A.colptr, convert(Ptr{ComplexF64}, pointer(x)), convert(Ptr{ComplexF64}, pointer(y)));
end # function A_mul_B!
#------------------------------------------------------------------------------
function A_mul_B!( alpha::ComplexF64,
A::SparseMatrixCSC{ComplexF64,Int},
x::Array{ComplexF64},
beta::ComplexF64,
y::Array{ComplexF64},
nthreads::Int64=0 )
# Complex A: y = beta*y + alpha * A*x
if nthreads == 0
mul!(y,A,x, alpha, beta) # Base.A_mul_B!( alpha, A, x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != m || size(y,1) != n
throw(DimensionMismatch("length(x) != m || length(y) != n"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:a_mul_b_cc_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), convert(Ptr{ComplexF64}, pointer(A.nzval)), A.rowval, A.colptr, convert(Ptr{ComplexF64}, pointer(x)), convert(Ptr{ComplexF64}, pointer(y)));
end # function A_mul_B!
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 7463 |
export Ac_mul_B!
function Ac_mul_B!( alpha::Float64,
A::SparseMatrixCSC{Float64,Int},
x::Array{Float64},
beta::Float64,
y::Array{Float64},
nthreads::Int64=0 )
# Real: y = beta*y + alpha * A'*x
if nthreads == 0
#Ac_mul_B!( alpha, A, x, beta, y )
mul!(y,adjoint(A),x, alpha, beta)
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("size(x) != n || size(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_rr_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}, Ptr{Float64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), A.nzval, A.rowval, A.colptr, x, y);
end # function Ac_mul_B!
#------------------------------------------------------------------------------
function Ac_mul_B!( alpha::ComplexF64,
A::SparseMatrixCSC{Float64,Int},
x::Array{ComplexF64},
beta::ComplexF64,
y::Array{ComplexF64},
nthreads::Int64=0 )
# Real, Complex A: y = beta*y + alpha * A'*x
if nthreads == 0
mul!(y,adjoint(A),x, alpha, beta)
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("length(x) != n || length(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_rc_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{Float64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), A.nzval, A.rowval, A.colptr, convert(Ptr{ComplexF64}, pointer(x)), convert(Ptr{ComplexF64}, pointer(y)));
end # function Ac_mul_B!
#------------------------------------------------------------------------------
function Ac_mul_B!( alpha::ComplexF64,
A::SparseMatrixCSC{ComplexF64,Int},
x::Array{ComplexF64},
beta::ComplexF64,
y::Array{ComplexF64},
nthreads::Int64=0 )
# Complex: y = beta*y + alpha * A'*x
if nthreads == 0
mul!(y,adjoint(A),x, alpha, beta) #Base.Ac_mul_B!( alpha, A, x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("length(x) != n || length(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_cc_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), convert(Ptr{ComplexF64}, pointer(A.nzval)), A.rowval, A.colptr, convert(Ptr{ComplexF64}, pointer(x)), convert(Ptr{ComplexF64}, pointer(y)));
end # function Ac_mul_B!
function Ac_mul_B!( alpha::ComplexF32,
A::SparseMatrixCSC{ComplexF32,Int64},
x::Array{ComplexF32},
beta::ComplexF32,
y::Array{ComplexF32},
nthreads::Int64=0 )
# Complex: y = beta*y + alpha * A'*x
if nthreads == 0
mul!(y,adjoint(A),x, alpha, beta) #Base.Ac_mul_B!( alpha, A, x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("length(x) != n || length(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_cc_short_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF32}, Ptr{ComplexF32}, Ptr{ComplexF32}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF32}, Ptr{ComplexF32}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), convert(Ptr{ComplexF32}, pointer(A.nzval)), A.rowval, A.colptr, convert(Ptr{ComplexF32}, pointer(x)), convert(Ptr{ComplexF32}, pointer(y)));
end # function Ac_mul_B!
function Ac_mul_B!( alpha::ComplexF32,
A::SparseMatrixCSC{Float32,Int64},
x::Array{ComplexF32},
beta::ComplexF32,
y::Array{ComplexF32},
nthreads::Int64=0 )
# Complex: y = beta*y + alpha * A'*x
if nthreads == 0
mul!(y,adjoint(A),x, alpha, beta) #Base.Ac_mul_B!( alpha, A, x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("length(x) != n || length(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_rc_short_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF32}, Ptr{ComplexF32}, Ptr{Float32}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF32}, Ptr{ComplexF32}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), A.nzval, A.rowval, A.colptr, convert(Ptr{ComplexF32}, pointer(x)), convert(Ptr{ComplexF32}, pointer(y)));
end # function Ac_mul_B!
function Ac_mul_B!( alpha::ComplexF64,
A::SparseMatrixCSC{ComplexF32,Int64},
x::Array{ComplexF64},
beta::ComplexF64,
y::Array{ComplexF64},
nthreads::Int64=0 )
# Complex: y = beta*y + alpha * A'*x
if nthreads == 0
mul!(y,adjoint(A),x, alpha, beta) #Base.Ac_mul_B!( alpha, A, x, beta, y )
return
elseif nthreads < 1
throw(ArgumentError("nthreads < 1"))
end
n,m = size(A)
nvec = size(x,2)
if size(x,1) != n || size(y,1) != m
throw(DimensionMismatch("length(x) != n || length(y) != m"))
elseif size(y,2) != nvec
throw(DimensionMismatch("length(y,2) != nvec"))
end
p = ccall( (:ac_mul_b_cc_mixed_, spmatveclib),
Int64, ( Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}, Ptr{ComplexF32}, Ptr{Int64}, Ptr{Int64}, Ptr{ComplexF64}, Ptr{ComplexF64}),
Ref(nthreads), Ref(nvec), Ref(m), Ref(n), Ref(alpha), Ref(beta), convert(Ptr{ComplexF32}, pointer(A.nzval)), A.rowval, A.colptr, convert(Ptr{ComplexF64}, pointer(x)), convert(Ptr{ComplexF64}, pointer(y)));
end # function Ac_mul_B!
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 360 | module ParSpMatVec
using SparseArrays
using LinearAlgebra
using Libdl
const spmatveclib = abspath(joinpath(splitdir(Base.source_path())[1],"..","deps","builds","ParSpMatVec"))
include("A_mul_B.jl")
include("Ac_mul_B.jl")
export isBuilt
function isBuilt()
println(spmatveclib)
return find_library([spmatveclib])!=""
end
end # module
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 54 | include("test_A_mul_B.jl")
include("test_Ac_mul_B.jl") | ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 3341 |
using ParSpMatVec
using Test
using SparseArrays
using Printf
using LinearAlgebra
n = 50000
nvec = 20
A = sprand(n,n, 2.e-6);
numProcs = 4;
x = rand(n,nvec); x = x*10 .- 5;
y = rand(n,nvec); y = y*10 .- 5;
println("Real")
alpha = 123.56
beta = 543.21
y2 = copy(y)
println("y = beta*y + alpha * A*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
# test error handling for nprocs
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, -1)
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x[1:10,:], beta, y3, 1)
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3[:,3], 1)
catch E
@test isa(E,DimensionMismatch)
end
println("Complex Scalars, Real Matrix")
alpha = 123.56 + 1im*randn()
beta = 543.21 + 1im*randn()
y = rand(n,nvec) + 1im* rand(n,nvec)
x = rand(n,nvec) + 1im* rand(n,nvec)
println("y = beta*y + alpha * A*x")
BaseTime = @elapsed y2 = beta*y + alpha * A*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, -1)
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x[1:10,:], beta, y3, 1)
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3[:,3], 1)
catch E
@test isa(E,DimensionMismatch)
end
println()
#-----------------------------------
# Complex
y2=0;
ii,jj,vv = findnz(A)
ai = ones(length(ii));
vv = vv + im*ai
A = sparse(ii,jj, vv, n,n)
ii=0; jj=0; vv=0; ai=0;
xi = rand(n,nvec); xi = xi*10 .- 5;
x = x + im*xi
xi=0
yi = rand(n,nvec); yi = yi*10 .- 5;
y = y + im*yi
yi=0
println("Complex")
alpha = complex(123.56, 333.444)
beta = complex(543.21, 111.222)
y2 = copy(y)
println("y = beta*y + alpha * A*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A*x
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3, -1)
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x[1:10,:], beta, y3, 1)
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.A_mul_B!( alpha, A, x, beta, y3[:,3], 1)
catch E
@test isa(E,DimensionMismatch)
end
println()
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | code | 6267 |
using ParSpMatVec
using Test
using SparseArrays
using Printf
using LinearAlgebra
n = 50000
numProcs =4;
nvec = 5
A = sprand(n,n, 2.e-6);
x = rand(n,nvec); x = x*10 .- 5;
y = rand(n,nvec); y = y*10 .- 5;
println("Real")
alpha = 123.56
beta = 543.21
y2 = copy(y)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
println()
# test error handling for nthreads
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, -1);
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x[1:10,:], beta, y3, 1);
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3[:,2], 1);
catch E
@test isa(E,DimensionMismatch)
end
println("Complex Scalars, Real matrix")
alpha = 123.56 .+ 1im*randn()
beta = 543.21 .+ 1im*randn()
y = rand(n,nvec) + 1im* rand(n,nvec)
x = rand(n,nvec) + 1im* rand(n,nvec)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, -1);
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x[1:10,:], beta, y3, 1);
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3[:,2], 1);
catch E
@test isa(E,DimensionMismatch)
end
println()
#-----------------------------------
# Complex
y2=0;
ii,jj,vv = findnz(A)
ai = ones(length(ii));
vv = vv + im*ai
A = sparse(ii,jj, vv, n,n)
ii=0; jj=0; vv=0; ai=0;
xi = rand(n,nvec); xi = xi*10 .- 5;
x = x + im*xi
xi=0
yi = rand(n,nvec); yi = yi*10 .- 5;
y = y + im*yi
yi=0
println("Complex")
alpha = complex(123.56, 333.444)
beta = complex(543.21, 111.222)
y2 = copy(y)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-12
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, -1);
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x[1:10,:], beta, y3, 1);
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3[:,2], 1);
catch E
@test isa(E,DimensionMismatch)
end
println()
println("Complex short")
alpha = convert(ComplexF32, alpha)
beta = convert(ComplexF32,beta);
A = convert(SparseMatrixCSC{ComplexF32,Int64},A);
x = convert(Array{ComplexF32},x);
y = convert(Array{ComplexF32},y);
y2 = copy(y)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-4
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, -1);
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x[1:10,:], beta, y3, 1);
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3[:,2], 1);
catch E
@test isa(E,DimensionMismatch)
end
println()
println("Complex short with a real matrix")
alpha = convert(ComplexF32, alpha)
beta = convert(ComplexF32,beta);
A = convert(SparseMatrixCSC{Float32,Int64},real(A));
x = convert(Array{ComplexF32},x);
y = convert(Array{ComplexF32},y);
y2 = copy(y)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-5
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, -1);
catch E
@test isa(E,ArgumentError)
end
# test error handling for sizes
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x[1:10,:], beta, y3, 1);
catch E
@test isa(E,DimensionMismatch)
end
try
y3 = copy(y)
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3[:,2], 1);
catch E
@test isa(E,DimensionMismatch)
end
println()
println("Complex single with a complex matrix but double target and source")
alpha = convert(ComplexF64, alpha)
beta = convert(ComplexF64,beta);
A = convert(SparseMatrixCSC{ComplexF32,Int64},real(A) + 1im*A);
x = convert(Array{ComplexF64},x);
y = convert(Array{ComplexF64},y);
y2 = copy(y)
println("y = beta*y + alpha * A'*x")
BaseTime = @elapsed y2 = beta*y2 + alpha * A'*x;
for k=0:numProcs
y3 = copy(y)
println("ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3,",k,")")
PSMVtime = @elapsed ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, y3, k );
@printf "Base=%1.4f\t ParSpMatVec=%1.4f\t speedup=%1.4f\n" BaseTime PSMVtime BaseTime/PSMVtime
@test norm(y3-y2) / norm(y) < 1.e-5
norm(y3-y2) / norm(y)
end
println()
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 0.1.1 | 78a1c05f2d1a5ac6c178590594195031a222aaba | docs | 1814 | [](https://travis-ci.org/JuliaInv/ParSpMatVec.jl)
[](https://coveralls.io/github/JuliaInv/ParSpMatVec.jl?branch=master)
[](https://ci.appveyor.com/project/lruthotto/parspmatvec-jl-fmwu5)
# ParSpMatVec.jl
Shared-memory implementation of parallel sparse matrix vector product in Julia. We thank Roman Shekhtman (UBC) for providing the Fortran code.
## Installation
To install on a unix machine, follow these steps
```
Pkg.add("ParSpMatVec")
Pkg.test("ParSpMatVec")
```
The first line downloads the package and (on unix) compiles the Fortran codes (`gfortran` is used by default). Currently there is no automatic build procedure for Windows. Pull requests are welcome.
The second line tests the package.
## Usage
Currently, we do not overload the matrix vector product in `Base` (this might be added in the future). Let `A` be a sparse matrix, `alpha` and `beta` floating point numbers and `x` and `y` be real- or complex values vectors of appropriate size. Then, the following commands are equivalent
```
nproc = 4; # choose number of OMP threads
yt = copy(y)
y = beta*y + alpha * A*x
ParSpMatVec.A_mul_B!( alpha, A, x, beta, yt, nproc)
```
Similarly, for the transpose matrix-vector product:
```
yt= copy(y)
y = beta*y + alpha * A'*x
ParSpMatVec.Ac_mul_B!( alpha, A, x, beta, yt, nproc)
```
The last input, `nproc`, determines how many OpenMP threads are used. Note that, due to the compressed column storage, products with the adjoint of `A` are expected to scale better.
## ToDo
A few things to do:
- [ ] automatic build on Windows
| ParSpMatVec | https://github.com/JuliaInv/ParSpMatVec.jl.git |
|
[
"MIT"
] | 1.0.0 | c8bc9ee15c7c395e0f3f3ea9a8a882bb66566cbe | code | 68 | module SparsePCA
export SPCA
include("functions.jl")
end # module
| SparsePCA | https://github.com/Deepmalya3D/SparsePCA.jl.git |
|
[
"MIT"
] | 1.0.0 | c8bc9ee15c7c395e0f3f3ea9a8a882bb66566cbe | code | 2177 | using LinearAlgebra
using ProgressMeter
using ElasticPDMats
using SparseArrays
using GLMNet
function SPCA(X, n_components, l1, l2 = 0.01, max_iter = 10000, tol = 0.0001)
"""
SPCA algorithm for simultaneous sparse coding and principal component analysis.
Parameters:
X: Array of shape (n_samples, n_features)
The input data matrix.
n_components: Int
Number of principal components to retain.
l1: Float64
Sparsity controlling parameter. Higher values lead to sparser components.
l2: Float64
Amount of ridge shrinkage to apply in order to improve conditioning when calling the transform method.
max_iter: Int
Maximum number of iterations for the optimization.
tol: Float64
Maximum allowed tolerance
Returns:
sparse_components : Array of shape (n_samples, n_components)
The sparse codes for the input data.
loadings: Array of shape (n_features, n_components)
The projection matrix for the principal components.
"""
cor_mat = X' * X
eigen_decomp = eigen(cor_mat)
V = eigen_decomp.vectors[:, sortperm(eigen_decomp.values, rev=true)]
A = V[:, 1:n_components]
B = zeros(size(V, 1), n_components)
iter = 0
pbar = Progress(max_iter+1)
while iter < max_iter
diff = 0
B_temp = zeros(size(V, 1), n_components)
for j in 1:size(A, 2)
y_s = X * A[:, j]
x_s = X
alpha = l1[j] + 2 * l2
l1_ratio = l1[j] / (l1[j] + 2 * l2)
elas_net = glmnet(x_s, y_s, alpha=l1_ratio, lambda=[alpha])
B_temp[:, j] = elas_net.betas
end
diff = norm(B_temp - B)
B = B_temp
cor_B = cor_mat * B
U, D, V_ = svd(cor_B)
A = U * V_'
iter += 1
if diff < tol
break
elseif iter == max_iter - 1
println("Max Iterations reached")
end
next!(pbar)
end
loadings = B / norm(B)
sparse_components = X * loadings
return sparse_components, loadings
end
| SparsePCA | https://github.com/Deepmalya3D/SparsePCA.jl.git |
|
[
"MIT"
] | 1.0.0 | c8bc9ee15c7c395e0f3f3ea9a8a882bb66566cbe | code | 392 | using SparsePCA
using Test
using RDatasets
using LinearAlgebra
iris = dataset("datasets", "iris")
describe(iris)
X = Array(iris[:, 1:4])
y = Vector(iris[:, 5])
@testset "SparsePCA.jl" begin
w, z = SparsePCA.SPCA(X, 2, [0.1, 0.26])
@test z == [0.7628055537099959 0.0; 0.011448860867247397 0.0; 0.016680144792570066 -0.5890917106637228; 0.14750795241577716 -0.22120294750550107]
end
| SparsePCA | https://github.com/Deepmalya3D/SparsePCA.jl.git |
|
[
"MIT"
] | 1.0.0 | c8bc9ee15c7c395e0f3f3ea9a8a882bb66566cbe | docs | 857 | # SparsePCA
SparsePCA.jl is a Julia package that provides an implementation of the sparse principal component analysis (SparsePCA) algorithm. SparsePCA is a dimensionality reduction technique that finds a sparse representation of high-dimensional data by identifying a set of orthogonal basis vectors that capture the most variation in the data while minimizing the number of non-zero coefficients in each basis vector.
The SparsePCA.jl package provides a flexible implementation of the SparsePCA algorithm that allows for various optimization methods and penalty functions. The package also includes parameters for selecting the optimal number of components and hyperparameters.
The package is designed to be fast and memory-efficient, making it suitable for large-scale problems. The implementation uses the GLMNet.jl package for Elastic net penalty.
| SparsePCA | https://github.com/Deepmalya3D/SparsePCA.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 584 | using FuncTransforms
using Documenter
DocMeta.setdocmeta!(FuncTransforms, :DocTestSetup, :(using FuncTransforms); recursive=true)
makedocs(;
modules=[FuncTransforms],
authors="chengchingwen <[email protected]> and contributors",
sitename="FuncTransforms.jl",
format=Documenter.HTML(;
canonical="https://chengchingwen.github.io/FuncTransforms.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/chengchingwen/FuncTransforms.jl",
devbranch="main",
)
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 7329 | module FuncTransforms
export FuncTransform, NA, FA, VA, toCodeInfo, FuncInfo, FuncInfoIter,
renamearg!, renamevar!, arg2var!, addarg!, addvar!, deletearg!, deletevar!,
getparg, insertparg!, deleteparg!, addparg!, addva!, getva, setva!,
firstssavalue, lastssavalue, prevssavalue, nextssavalue,
replacestmt!, addstmt!, addstmtafter!, addstmtbefore!, insertafter!, insertbefore!,
repackva!, assignva!
include("utils.jl")
include("funcinfo.jl")
include("functransform.jl")
"""
abstract type FuncArgs
An abstract type for representing function arguments in a function transformation context for constructing `FuncTransform`.
Subtypes of `FuncArgs` include:
- `NA`: Represents a new argument to be added to the function.
- `FA`: Represents an existing function argument, possibly with modifications.
- `VA`: Specifically denotes a Vararg.
"""
FuncArgs
"""
NA(name::Symbol; gen = true)
A "New Argument" with `name`. Used to introduce new position argument.
"""
NA
"""
FA(name::Symbol, slotnumber::Int; gen = true)
A "Function Argument" from the transformed function with old `slotnumber` renamed to `name`.
"""
FA
"""
VA(name::Symbol, drop::Int; gen = true)
A "VarArg". With `VA`, we can assign the values in this argument to the arguments of the transformed function.
`drop` would drop the given number of arguments of the transformed function (var"#self#" also counts).
"""
VA
"""
FuncTransform(sig, world, fargs::Union{Vector{FuncArgs}, Nothing} = nothing;
caller::Union{MethodInstance, Nothing} = nothing,
method_tables::Union{Nothing, MethodTable} = nothing)
Constructs a `FuncTransform` object used to perform transformations on function `sig` of world age `world`.
`fargs` is used to specific the new function arguments of the new function. If `fargs` is `nothing`, the origin
arguments would be used. If `caller` is provided, it also set the backedge accordingly. The transformations
should be applied to `FuncTransform(...).fi::FuncInfo` and use `toCodeInfo` to get the result.
"""
FuncTransform
"""
toCodeInfo(fi::Union{FuncInfo, FuncTransform})
Converts a `FuncInfo` or `FuncTransform` into a `Core.CodeInfo`.
"""
toCodeInfo
"""
FuncInfo(sig, world; method_tables::Union{Nothing, MethodTable} = nothing)
Lookup to `Core.CodeInfo` of a function signature `sig` with specific world age and convert the `Core.CodeInfo` into `FuncInfo`.
"""
FuncInfo
"""
FuncInfoIter(fi::FuncInfo, start = firstssavalue(fi))
Creates an iterator over the code statements of a function's code block starting from a given SSA value.
"""
FuncInfoIter
"""
renamearg!(fi::FuncInfo, slot, name::Symbol)
Renames an argument identified by `slot` in `FuncInfo` to the new `name` provided.
"""
renamearg!
"""
renamevar!(fi::FuncInfo, slot, name::Symbol)
Renames a variable identified by `slot` in `FuncInfo` to the new `name` provided.
"""
renamevar!
"""
arg2var!(fi::FuncInfo, id::Union{SlotNumber, Int})
Moves an argument identified by `id` from the argument slots to variable slots in `FuncInfo`.
"""
arg2var!
"""
addarg!(fi::FuncInfo, name::Symbol)
Adds a new argument to `FuncInfo` with the specified `name`. Returns the new `SlotNumber`.
"""
addarg!
"""
addvar!(fi::FuncInfo, name::Symbol)
Adds a new variable to `FuncInfo` with the specified `name`. Returns the new `SlotNumber`.
"""
addvar!
"""
deletearg!(fi::FuncInfo, id::Union{SlotNumber, Int})
Deletes an argument from `FuncInfo` identified by `id`.
"""
deletearg!
"""
deletevar!(fi::FuncInfo, id::Union{SlotNumber, Int})
Deletes a variable from `FuncInfo` identified by `id`.
"""
deletevar!
"""
getparg(fi::FuncInfo, index::Integer)
Retrieves the `SlotNumber` of the positional argument at the given `index` in `FuncInfo`.
"""
getparg
"""
insertparg!(fi::FuncInfo, id::Union{SlotNumber, Int}, index::Integer)
Inserts an existing argument identified by `id` into the positional arguments of `FuncInfo` at the specified `index`.
"""
insertparg!
"""
deleteparg!(fi::FuncInfo, id::Union{SlotNumber, Int})
Removes the positional argument from `FuncInfo` identified by `id`.
"""
deleteparg!
"""
addparg!(fi::FuncInfo, name::Symbol [, index::Integer])
Adds a new argument to `FuncInfo` with the specified `name`, and insert it to the position arguments.
If `index` is not provided, insert it to the last non-vararg position. Returns the new `SlotNumber`.
Equivalent to `addarg!` + `insertparg!`.
"""
addparg!
"""
addva!(fi::FuncInfo, name::Symbol)
Adds a new argument to `FuncInfo` and sets it as the vararg. Returns the `SlotNumber` of the new argument.
"""
addva!
"""
getva(fi::FuncInfo)
Returns the `SlotNumber` of the vararg in `FuncInfo`.
"""
getva
"""
setva!(fi::FuncInfo, id::Union{SlotNumber, Int})
Sets the vararg of `FuncInfo` to the specified `id`.
"""
setva!
"""
firstssavalue(fi::FuncInfo)
Returns the first SSA value in the code block of `FuncInfo`.
"""
firstssavalue
"""
lastssavalue(fi::FuncInfo)
Returns the last SSA value in the code block of `FuncInfo`.
"""
lastssavalue
"""
prevssavalue(fi::FuncInfo, i::Union{SSAValue, Int})
Returns the previous SSA value of the given SSA Value `i` in the code block of `FuncInfo`.
"""
prevssavalue
"""
nextssavalue(fi::FuncInfo, i::Union{SSAValue, Int})
Returns the next SSA value of the given SSA value `i` in the code block of `FuncInfo`.
"""
nextssavalue
"""
replacestmt!(fi::FuncInfo, id::Union{SSAValue, Int}, stmt)
Replaces the statement at the given SSA Value `id` in `FuncInfo`'s code block with a new statement.
"""
replacestmt!
"""
addstmt!(fi::FuncInfo, stmt)
Adds a new statement to `FuncInfo` but not insert into the code block. Returns the new `SSAValue`.
"""
addstmt!
"""
addstmtafter!(fi::FuncInfo, id::Union{SSAValue, Int}, stmt)
Inserts a new statement after the statement identified by `id` in `FuncInfo`.
Returns the new `SSAValue` for the inserted statement. Equivalent to `addstmt!` + `insertafter!`.
"""
addstmtafter!
"""
addstmtbefore!(fi::FuncInfo, id::Union{SSAValue, Int}, stmt)
Inserts a new statement before the statement identified by `id` in `FuncInfo`.
Returns the new `SSAValue` for the inserted statement. Equivalent to `addstmt!` + `insertbefore!`.
"""
addstmtbefore!
"""
insertafter!(fi::FuncInfo, id::Union{SSAValue, Int}, stmtid::Union{SSAValue, Int})
Inserts the statement identified by `stmtid` after the statement identified by `id` in `FuncInfo`.
"""
insertafter!
"""
insertbefore!(fi::FuncInfo, id::Union{SSAValue, Int}, stmtid::Union{SSAValue, Int})
Inserts the statement identified by `stmtid` before the statement identified by `id` in `FuncInfo`.
"""
insertbefore!
"""
repackva!(fi::FuncInfo, varid::Union{SlotNumber, Int}, vaid::Union{SlotNumber, Int}, indices::Vector{Integer})
Add the code at the beginning of code block that: given the new vararg (`vaid`),
extract the element at `indices`, pack them as a tuple and assign to the old vararg (`varid`).
"""
repackva!
"""
assignva!(fi::FuncInfo, varid::Union{SlotNumber, Int}, vaid::Union{SlotNumber, Int}, index::Integer)
Add the code at the beginning of code block that: given the new vararg (`vaid`),
extract the element at `index and assign to the old argument `varid`.
"""
assignva!
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 17851 | using Core.Compiler: IR_FLAG_NULL, IR_FLAG_INBOUNDS, IR_FLAG_INLINE, IR_FLAG_NOINLINE
using Base: SLOT_USED
const SlotFlagType = eltype(fieldtype(CodeInfo, :slotflags))
const SSAFlagType = eltype(fieldtype(CodeInfo, :ssaflags))
const HAS_DEBUGINFO = isdefined(Core, :DebugInfo)
@static if HAS_DEBUGINFO
const CodeLocType = Any
else
const CodeLocType = eltype(fieldtype(CodeInfo, :codelocs))
end
const SlotID = Union{Int, SlotNumber}
const SSAID = Union{Int, SSAValue}
_id(id::Int) = id
_id(slotnumber::SlotNumber) = slotnumber.id
_id(ssavalue::SSAValue) = ssavalue.id
mutable struct Slot
name::Symbol
flag::SlotFlagType
end
Slot(name::Symbol) = Slot(name, SLOT_USED)
_slot(val::Slot) = (val.name, val.flag)
_slot(val) = val
struct Slots
name2id::Dict{Symbol, Any}
id2nameflag::Dict{Int, Slot}
end
Slots() = Slots(Dict{Symbol, Any}(), Dict{Int, Slot}())
function getunique(slots::Slots, name::Symbol)
id = slots.name2id[name]
id isa Int || error("multiple slot with same name, use slot id directly.")
return id
end
getslot(slots::Slots, id::SlotID) = slots.id2nameflag[_id(id)]
getslot(slots::Slots, name::Symbol) = slots.id2nameflag[getunique(slots, name)]
setslot!(slots::Slots, id::SlotID, slot::Slot) = slots.id2nameflag[_id(id)] = slot
Base.length(slots::Slots) = length(slots.id2nameflag)
Base.getindex(slots::Slots, id::SlotID) = _slot(getslot(slots, id))
Base.getindex(slots::Slots, name::Symbol) = getunique(slots, name)
Base.haskey(slots::Slots, id::SlotID) = haskey(slots.id2nameflag, _id(id))
Base.haskey(slots::Slots, name::Symbol) = haskey(slots.name2id, name)
Base.get(slots::Slots, id::SlotID, default) = _slot(get(slots.id2nameflag, _id(id), default))
Base.get(slots::Slots, name::Symbol, default) = haskey(slots.name2id, name) ? getunique(slots, name) : default
function Base.delete!(slots::Slots, name::Symbol)
id = getunique(slots, name)
delete!(slots.name2id, name)
delete!(slots.id2nameflag, id)
return slots
end
function _deleteid!(slots::Slots, name::Symbol, id::SlotID)
id = _id(id)
ids = slots.name2id[name]
if ids isa Int
ids == id && delete!(slots.name2id, name)
else
delete!(ids, id)
end
end
function _pushid!(slots::Slots, name::Symbol, id::SlotID)
id = _id(id)
if haskey(slots, name)
ids = slots.name2id[name]
if ids isa Int
slots.name2id[name] = BitSet((ids, id))
else
push!(ids, id)
end
else
slots.name2id[name] = id
end
end
function Base.delete!(slots::Slots, id::SlotID)
id = _id(id)
name, _ = slots[id]
delete!(slots.id2nameflag, id)
_deleteid!(slots, name, id)
return slots
end
function Base.setindex!(slots::Slots, @nospecialize(_nameflag::Union{Tuple{Symbol, Integer}, Symbol}), id::SlotID)
hasflag = _nameflag isa Tuple
nameflag = hasflag ? _nameflag : (_nameflag,)
name = nameflag[1]
id = _id(id)
if haskey(slots, id)
slot = getslot(slots, id)
_deleteid!(slots, slot.name, id)
_pushid!(slots, name, id)
slot.name = nameflag[1]
hasflag && (slot.flag = nameflag[2])
else
slot = Slot(nameflag...)
_pushid!(slots, name, id)
setslot!(slots, id, slot)
end
return _slot(slot)
end
function Base.iterate(slots::Slots, state...)
iter = iterate(slots.id2nameflag, state...)
isnothing(iter) && return nothing
kv, nstate = iter
id, slot = kv
(; name, flag) = slot
return (id, name, flag), nstate
end
function rename!(slots::Slots, name2::Symbol, name::Symbol)
@assert haskey(slots, name2) "renamed slot($name2) not exist"
return rename!(slots, slots[name2], name)
end
function rename!(slots::Slots, id::SlotID, name::Symbol)
id = _id(id)
@assert get(slots, name, id) == id "renamed slot($id) to an existing name \"$name\""
@assert haskey(slots, id) "renamed slot($id) not exist"
slot = getslot(slots, id)
name2 = slot.name
slots[id] = name
return name2
end
mutable struct PrevNext
prev::Int
next::Int
end
mutable struct Code
stmt::Any
flag::SSAFlagType
loc::CodeLocType
end
Code(@nospecialize(stmt::Any), flag::Integer) = Code(stmt, flag, 0)
Code(@nospecialize(stmt::Any)) = Code(stmt, IR_FLAG_NULL)
Base.getindex(c::Code, i) = getfield(c, i)
Base.iterate(c::Code, s=1) = s > 3 ? nothing : (c[s], s+1)
inlineflag!(c::Code) = (c.flag |= IR_FLAG_INLINE; nothing)
noinlineflag!(c::Code) = (c.flag |= IR_FLAG_NOINLINE; nothing)
inboundsflag!(c::Code) = (c.flag |= IR_FLAG_INBOUNDS; nothing)
struct CodeBlock
id2stmtflagloc::Dict{Int, Code}
order::Dict{Int, PrevNext}
linetable::Any
end
CodeBlock(linetable) = CodeBlock(Dict{Int, Code}(), Dict{Int, PrevNext}(), linetable)
getcode(codes::CodeBlock, id::SSAID) = codes.id2stmtflagloc[_id(id)]
setcode!(codes::CodeBlock, id::SSAID, code::Code) = codes.id2stmtflagloc[_id(id)] = code
getorder(codes::CodeBlock, id::SSAID) = codes.order[_id(id)]
getnext(codes::CodeBlock, id::SSAID) = codes.order[_id(id)].next
getprev(codes::CodeBlock, id::SSAID) = codes.order[_id(id)].prev
setorder!(codes::CodeBlock, id::SSAID, order::NTuple{2, Int}) = codes.order[_id(id)] = PrevNext(order...)
function setnext!(codes::CodeBlock, id::SSAID, next::SSAID)
order = getorder(codes, id)
next2 = order.next
order.next = _id(next)
return next2
end
function setprev!(codes::CodeBlock, id::SSAID, prev::SSAID)
order = getorder(codes, id)
prev2 = order.prev
order.prev = _id(prev)
return prev2
end
Base.length(codes::CodeBlock) = length(codes.order)
Base.getindex(codes::CodeBlock, id::SSAID) = getcode(codes, id)
Base.haskey(codes::CodeBlock, id::SSAID) = haskey(codes.id2stmtflagloc, _id(id))
Base.get(codes::CodeBlock, id::SSAID, default) = get(codes.id2stmtflagloc, _id(id), default)
function Base.delete!(codes::CodeBlock, id::SSAID)
id = _id(id)
delete!(codes.id2stmtflagloc, id)
delete!(codes.order, id)
return codes
end
function _setindex!(codes::CodeBlock, @nospecialize(stmtflagloc::Tuple), id::SSAID)
if haskey(codes, id)
code = getcode(codes, id)
code.stmt = stmtflagloc[1]
length(stmtflagloc) > 1 && (code.flag = stmtflagloc[2])
length(stmtflagloc) > 2 && (code.loc = stmtflagloc[3])
else
code = Code(stmtflagloc...)
setcode!(codes, id, code)
end
return code
end
Base.setindex!(codes::CodeBlock, @nospecialize(stmtflagloc::Tuple{Any, Integer, Integer}), id::SSAID) = _setindex!(codes, stmtflagloc, id)
Base.setindex!(codes::CodeBlock, @nospecialize(stmtflag::Tuple{Any, Integer}), id::SSAID) = _setindex!(codes, stmtflag, id)
Base.setindex!(codes::CodeBlock, @nospecialize(stmt::Tuple{Any}), id::SSAID) = _setindex!(codes, stmt, id)
struct CodeIter
codes::CodeBlock
start::Int
end
CodeIter(codes::CodeBlock, start::SSAValue) = CodeIter(codes, _id(start))
function Base.iterate(iter::CodeIter, ssavalue = iter.start)
!haskey(iter.codes.order, ssavalue) && return nothing
nextssa = getnext(iter.codes, ssavalue)
return ((ssavalue, iter.codes[ssavalue]), ssavalue == nextssa ? 0 : nextssa)
end
# In FuncInfo, we give the id of `SlotNumber`/`SSAValue` a different meaning as the unique id instead of index.
# This make it easier to modify the code without worrying the shift of id. The correct id/index will be reassigned
# when generating new CodeInfo.
mutable struct FuncInfo
pargs::Vector{Int} # position of args w/o vararg
va::Int # vararg id
first::Int
last::Int
args::Slots
vars::Slots
codes::CodeBlock
end
function FuncInfo(meth::Method, ci::CodeInfo)
args = Slots()
vars = Slots()
@static if hasfield(CodeInfo, :nargs)
nargs = ci.nargs
isva = ci.isva
else
nargs = meth.nargs
isva = meth.isva
end
pargs = collect(1:nargs - isva)
va = isva ? nargs : 0
for (slotnumber, (name, flag)) in enumerate(zip(ci.slotnames, ci.slotflags))
(slotnumber <= nargs ? args : vars)[slotnumber] = (name, flag)
end
@static if HAS_DEBUGINFO
codes = CodeBlock(nothing)
for (ssavalue, code_flag) in enumerate(zip(ci.code, ci.ssaflags))
codes[ssavalue] = code_flag
end
else
codes = CodeBlock(ismutable(ci.linetable) ? copy(ci.linetable) : ci.linetable)
for (ssavalue, code_flag_loc) in enumerate(zip(ci.code, ci.ssaflags, ci.codelocs))
codes[ssavalue] = code_flag_loc
end
end
ssavalues = length(ci.code)
for ssavalue in 1:ssavalues
prev = ssavalue == 1 ? 1 : ssavalue - 1
next = ssavalue == ssavalues ? ssavalues : ssavalue + 1
setorder!(codes, ssavalue, (prev, next))
end
return FuncInfo(pargs, va, min(ssavalues, 1), ssavalues, args, vars, codes)
end
function FuncInfo(
@nospecialize(fsig), world; method_tables::Union{Nothing, MethodTable, Vector{MethodTable}} = nothing
)
match = method_by_ftype(fsig, method_tables, world)
meth = match.method
inst = Core.Compiler.specialize_method(match)
ci = get_codeinfo(inst, world)
Meta.partially_inline!(ci.code, Any[], meth.sig, Any[match.sparams...], 0, 0, :propagate)
return FuncInfo(meth, ci)
end
newslotnumber(fi::FuncInfo) = length(fi.args) + length(fi.vars) + 1
newssavalue(fi::FuncInfo) = length(fi.codes.id2stmtflagloc) + 1
Base.getindex(fi::FuncInfo, slotnumber::SlotNumber) = haskey(fi.args, id) ? fi.args[id] : fi.vars[id]
Base.getindex(fi::FuncInfo, ssavalue::SSAValue) = fi.codes[id]
renamearg!(fi::FuncInfo, slot, name::Symbol) = rename!(fi.args, slot, name)
renamevar!(fi::FuncInfo, slot, name::Symbol) = rename!(fi.vars, slot, name)
arg2var!(fi::FuncInfo, name::Symbol) = arg2var!(fi, fi.args[name])
function arg2var!(fi::FuncInfo, id::SlotID)
id = _id(id)
@assert haskey(fi.args, id) "arg slot($id) not exist"
name, flag = fi.args[id]
delete!(fi.args, id)
addvar!(fi, name, flag, id)
end
function addarg!(fi::FuncInfo, name::Symbol, flag::Integer = SLOT_USED, id::SlotID = newslotnumber(fi))
id = _id(id)
fi.args[id] = (name, flag)
return SlotNumber(id)
end
function addvar!(fi::FuncInfo, name::Symbol, flag::Integer = SLOT_USED, id::SlotID = newslotnumber(fi))
id = _id(id)
fi.vars[id] = (name, flag)
return SlotNumber(id)
end
deletearg!(fi::FuncInfo, id::SlotID) = deletearg!(fi, first(fi.args[id]))
function deletearg!(fi::FuncInfo, name::Symbol)
id = fi.args[name]
_deleteslot!(fi.args, id, name)
return SlotNumber(id)
end
deletevar!(fi::FuncInfo, id::SlotID) = deletevar!(fi, first(fi.vars[id]))
function deletevar!(fi::FuncInfo, name::Symbol)
id = fi.varsyms[name]
_deleteslot!(fi.vars, id, name)
return SlotNumber(id)
end
getparg(fi::FuncInfo, index::Integer) = SlotNumber(fi.pargs[index])
insertparg!(fi::FuncInfo, name::Symbol, index::Integer) = insertparg!(fi, fi.args[name], index)
function insertparg!(fi::FuncInfo, id::SlotID, index::Integer)
id = _id(id)
@assert haskey(fi.args, id)
insert!(fi.pargs, index, id)
return SlotNumber(id)
end
deleteparg!(fi::FuncInfo, name::Symbol) = deleteparg!(fi, fi.args[name])
function deleteparg!(fi::FuncInfo, id::SlotID)
id = _id(id)
index = findfirst(==(id), fi.pargs)
@assert !isnothing(index) "id $id not found in position arguments"
deletepargat!(fi, index)
end
deletepargat!(fi::FuncInfo, index::Integer) = SlotNumber(popat!(fi.pargs, index))
addparg!(fi::FuncInfo, name::Symbol, index::Integer = length(fi,pargs) + 1) = insertparg!(fi, addarg!(fi, name), index)
hasva(fi::FuncInfo) = !iszero(fi.va)
function addva!(fi::FuncInfo, name::Symbol, flag::Integer = SLOT_USED, id::SlotID = newslotnumber(fi))
id = addarg!(fi, name, flag, id)
return setva!(fi, id)
end
getva(fi::FuncInfo) = SlotNumber(fi.va)
function setva!(fi::FuncInfo, id::SlotID)
id = _id(id)
fi.va = id
return SlotNumber(id)
end
firstssavalue(fi::FuncInfo) = fi.first
lastssavalue(fi::FuncInfo) = fi.last
prevssavalue(fi::FuncInfo, i::SSAID) = getorder(fi.codes, i).prev
nextssavalue(fi::FuncInfo, i::SSAID) = getorder(fi.codes, i).next
function ithssavalue(fi::FuncInfo, i)
ssavalues = length(fi.codes)
rev = i > div(ssavalues, 2)
ssavalue = (rev ? lastssavalue : firstssavalue)(fi)
for _ = 1:(rev ? ssavalues - i : i)
ssavalue = (rev ? prevssavalue : nextssavalue)(fi, ssavalue)
end
return ssavalue
end
function replacestmt!(fi::FuncInfo, id::SSAID, stmtflagloc...)
id = _id(id)
@assert haskey(fi.codes, id) "ssa($id) not found in codes"
fi.codes[id] = stmtflagloc
end
function addstmt!(fi::FuncInfo, @nospecialize(stmt::Any), flag = IR_FLAG_NULL, loc = 0, id::SSAID = newssavalue(fi))
id = _id(id)
fi.codes[id] = (stmt, flag, loc)
return SSAValue(id)
end
addstmtafter!(fi::FuncInfo, id::SSAID, @nospecialize(stmt::Any), flag = IR_FLAG_NULL, loc = 0,
stmtid::SSAID = newssavalue(fi)) = insertafter!(fi, id, addstmt!(fi, stmt, flag, loc, stmtid))
addstmtbefore!(fi::FuncInfo, id::SSAID, @nospecialize(stmt::Any), flag = IR_FLAG_NULL, loc = 0,
stmtid::SSAID = newssavalue(fi)) = insertbefore!(fi, id, addstmt!(fi, stmt, flag, loc, stmtid))
function insertafter!(fi::FuncInfo, id::SSAID, stmtid::SSAID)
# id -> next => id -> stmtid -> next
id = _id(id)
stmtid = _id(stmtid)
next = setnext!(fi.codes, id, stmtid)
if next == id # last
setorder!(fi.codes, stmtid, (id, stmtid))
fi.last = stmtid
else
setorder!(fi.codes, stmtid, (id, next))
setprev!(fi.codes, next, stmtid)
end
return SSAValue(stmtid)
end
function insertbefore!(fi::FuncInfo, id::SSAID, stmtid::SSAID)
# prev -> id => prev -> stmtid -> id
id = _id(id)
stmtid = _id(stmtid)
prev = setprev!(fi.codes, id, stmtid)
if prev == id # first
setorder!(fi.codes, stmtid, (stmtid, id))
fi.first = stmtid
else
setorder!(fi.codes, stmtid, (prev, id))
setnext!(fi.codes, prev, stmtid)
end
return SSAValue(stmtid)
end
function repackva!(fi::FuncInfo, varid::SlotID, vaid::SlotID, indices)
var = SlotNumber(_id(varid))
va = SlotNumber(_id(vaid))
stmts = SSAValue[]
for index in indices
stmt = Expr(:call, GlobalRef(Core, :getfield), va, index, true)
push!(stmts, addstmt!(fi, stmt))
end
vastmt = Expr(:(=), var, Expr(:call, GlobalRef(Core, :tuple), stmts...))
push!(stmts, addstmt!(fi, vastmt))
for id in Iterators.reverse(stmts)
insertbefore!(fi, firstssavalue(fi), id)
end
return last(stmts)
end
function assignva!(fi::FuncInfo, varid::SlotID, vaid::SlotID, index)
var = SlotNumber(_id(varid))
va = SlotNumber(_id(vaid))
stmt = Expr(:(=), var, Expr(:call, GlobalRef(Core, :getfield), va, index, true))
addstmtbefore!(fi, firstssavalue(fi), stmt)
end
FuncInfoIter(fi::FuncInfo, start::SSAID = firstssavalue(fi)) = CodeIter(fi.codes, _id(start))
function toCodeInfo(fi::FuncInfo, ci::Union{CodeInfo, Nothing} = nothing;
inline = false, noinline = false, propagate_inbounds = false)
fargs = Symbol[]
slotnames = Any[]
slotflags = UInt8[]
slotremap = Dict{Int, Int}()
for (slotnumber, id) in enumerate(fi.pargs)
name, flag = fi.args[id]
push!(fargs, name)
push!(slotnames, name)
push!(slotflags, flag)
slotremap[id] = slotnumber
end
if hasva(fi)
id = getva(fi).id
name, flag = fi.args[id]
push!(fargs, name)
push!(slotnames, name)
push!(slotflags, flag)
slotremap[id] = length(slotremap) + 1
end
offset = length(slotremap)
for (i, (id, name, flag)) in enumerate(fi.vars)
push!(slotnames, name)
push!(slotflags, flag)
slotremap[id] = offset + i
end
if isnothing(ci)
ci = create_codeinfo(fargs, Expr(:block); inline, noinline, propagate_inbounds)
else
ci = copy(ci)
@assert nand(inline, noinline)
@assert nand(propagate_inbounds, noinline)
if propagate_inbounds
ci.inlining = 0x01
ci.propagate_inbounds = true
elseif inline
ci.inlining = 0x01
elseif noinline
ci.inlining = 0x02
end
end
@static if hasfield(CodeInfo, :nargs)
ci.nargs = length(fi.pargs) + hasva(fi)
ci.isva = hasva(fi)
end
code = Any[]
ssaflags = UInt8[]
@static if !HAS_DEBUGINFO
codelocs = fieldtype(CodeInfo, :codelocs)()
end
ssaremap = Dict{Int, Int}()
ssavalues = length(fi.codes)
for (ssavalue, (id, stmtflagloc)) in enumerate(FuncInfoIter(fi))
stmt, flag, loc = stmtflagloc
push!(code, stmt)
push!(ssaflags, flag)
@static if !HAS_DEBUGINFO
push!(codelocs, loc)
end
ssaremap[id] = ssavalue
end
for (ssavalue, stmt) in enumerate(code)
newstmt = walk(stmt) do x
if x isa SlotNumber
id = get(slotremap, _id(x), nothing)
isnothing(id) && error("slot id $id used in code but not found in the output")
return SlotNumber(id)
elseif x isa SSAValue
id = get(ssaremap, _id(x), nothing)
isnothing(id) && error("ssa id $id used in code but not found in the output")
return SSAValue(id)
else
return x
end
end
@inbounds code[ssavalue] = newstmt
end
ci.slotnames = slotnames
ci.slotflags = slotflags
ci.code = code
ci.ssaflags = ssaflags
ci.ssavaluetypes = ssavalues
@static if !HAS_DEBUGINFO
ci.codelocs = codelocs
ci.linetable = fi.codes.linetable
end
return ci
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 3654 | abstract type FuncArgs end
FuncArgs(name::Symbol) = NA(name)
FuncArgs(arg::FuncArgs) = arg
struct NA <: FuncArgs
name::Symbol
NA(name; gen = true) = new(gen ? gensym(name) : name)
end
struct FA <: FuncArgs
name::Symbol
slotnumber::Int
FA(name, slotnumber; gen = true) = new(gen ? gensym(name) : name, slotnumber)
end
struct VA <: FuncArgs
name::Symbol
drop::Int
VA(name, drop; gen = true) = new(gen ? gensym(name) : name, drop)
end
struct FuncTransform
# old info
meth::Method
inst::MethodInstance
ci::CodeInfo
# transform
fargs::Vector{FuncArgs}
fi::FuncInfo
function FuncTransform(meth::Method, inst::MethodInstance, ci::CodeInfo, fargs = nothing)
if isnothing(fargs)
fargs = FuncArgs[FA(name, i) for (i, name) in zip(1:meth.nargs, ci.slotnames)]
end
nva = count(arg->arg isa VA, fargs)
if nva == 1
!isa(last(fargs), VA) && error("Vararg must be the last argument")
drop = last(fargs).drop
any(arg->arg isa FA && arg.slotnumber > drop, fargs) && error("Argument $(arg.name) is reassigned but not dropped")
elseif nva > 1
error("can only has 1 Vararg")
end
fi = FuncInfo(meth, ci)
ft = new(meth, inst, ci, map(FuncArgs, fargs), fi)
updateargs!(ft)
return ft
end
end
function FuncTransform(
@nospecialize(fsig), world, fargs = nothing;
caller::Union{MethodInstance, Nothing} = nothing,
method_tables::Union{Nothing, MethodTable, Vector{MethodTable}} = nothing
)
match = method_by_ftype(fsig, method_tables, world)
meth = match.method
inst = Core.Compiler.specialize_method(match)
ci = get_codeinfo(inst, world)
Meta.partially_inline!(ci.code, Any[], meth.sig, Any[match.sparams...], 0, 0, :propagate)
add_backedge!(caller, inst)
return FuncTransform(meth, inst, ci, fargs)
end
function updateargs!(ft::FuncTransform)
unseen = BitSet(ft.fi.pargs)
hasva(ft.fi) && push!(unseen, getva(ft.fi).id)
for (i, arg) in enumerate(ft.fargs)
updatearg!(ft, arg, i, unseen)
end
@assert isempty(unseen) """arguments [$(join((first(ft.fi.args[i]) for i in unseen), ", "))] not handled."""
return ft
end
function updatearg!(ft::FuncTransform, arg::NA, i, unseen)
addparg!(ft.fi, arg.name, i)
return unseen
end
function updatearg!(ft::FuncTransform, arg::FA, i, unseen)
id = arg.slotnumber
if getva(ft.fi).id != id
deleteparg!(ft.fi, id)
insertparg!(ft.fi, id, i)
end
renamearg!(ft.fi, id, arg.name)
delete!(unseen, id)
return unseen
end
function updatearg!(ft::FuncTransform, arg::VA, i, unseen)
va = getva(ft.fi).id
!iszero(va) && delete!(unseen, va)
newva = addva!(ft.fi, arg.name).id
index = 1
for id = 1:ft.meth.nargs
if id == va
# the number of element the original Vararg should get
vasize = length(ft.inst.specTypes.parameters) - ft.meth.nargs
arg2var!(ft.fi, id)
repackva!(ft.fi, id, newva, index:index+vasize)
elseif id > arg.drop
arg2var!(ft.fi, id)
assignva!(ft.fi, id, newva, index)
deleteparg!(ft.fi, id)
index += 1
elseif id in unseen
deleteparg!(ft.fi, id)
end
delete!(unseen, id)
end
return unseen
end
function toCodeInfo(ft::FuncTransform; inline = false, noinline = false, propagate_inbounds = false)
ci = toCodeInfo(ft.fi, ft.ci; inline, noinline, propagate_inbounds)
ci.method_for_inference_limit_heuristics = ft.meth
return ci
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 5043 | using Core: CodeInfo, MethodTable, MethodInstance, SSAValue, SlotNumber, NewvarNode, ReturnNode, GotoNode, GotoIfNot, PhiNode
using Base.Meta: isexpr
create_codeinfo(argnames, body; kws...) = create_codeinfo(argnames, nothing, body; kws...)
create_codeinfo(mod::Module, argnames, body; kws...) = create_codeinfo(mod, argnames, nothing, body; kws...)
create_codeinfo(argnames, spnames, body; kws...) = create_codeinfo(@__MODULE__, argnames, spnames, body; kws...)
function create_codeinfo(mod::Module, argnames, spnames, body;
inline = false, noinline = false, propagate_inbounds = false)
# argnames: `Vector{Symbol}` representing the variable names, starts with `Symbol("#self#")`.
# spnames: the variable names in `where {...}`
@assert isexpr(body, :block) "body should be `Expr(:block, ...)`."
@assert nand(inline, noinline)
@assert nand(propagate_inbounds, noinline)
if propagate_inbounds
body = Expr(:block, Expr(:meta, :inline, :propagate_inbounds), body.args...)
elseif inline
body = Expr(:block, Expr(:meta, :inline), body.args...)
elseif noinline
body = Expr(:block, Expr(:meta, :noinline), body.args...)
end
expr = Expr(:lambda, argnames, Expr(Symbol("scope-block"), body))
if !isnothing(spnames)
expr = Expr(Symbol("with-static-parameters"), expr, spnames...)
end
ci = ccall(:jl_expand, Any, (Any, Any), expr, mod) # expand macrocall and return code_info
ci.inlineable = true
return ci
end
walk(fn, x, guard) = fn(x)
walk(fn, x::SSAValue, guard) = fn(x)
walk(fn, x::SlotNumber, guard) = fn(x)
walk(fn, x::NewvarNode, guard) = NewvarNode(walk(fn, x.slot, guard))
walk(fn, x::ReturnNode, guard) = ReturnNode(walk(fn, x.val, guard))
walk(fn, x::GotoNode, guard) = GotoNode(walk(fn, SSAValue(x.label), guard).id)
walk(fn, x::GotoIfNot, guard) = GotoIfNot(walk(fn, x.cond, guard), walk(fn, SSAValue(x.dest), guard).id)
walk(fn, x::Expr, guard) = Expr(x.head, walk(fn, x.args, guard)...)
walk(fn, x::Vector, guard) = Core.Compiler.anymap(el -> walk(fn, el, guard), x)
walk(fn, x::PhiNode, guard) = PhiNode(map(i->Int32(walk(fn, SSAValue(Int(i)), guard).id), x.edges), walk(fn, x.values, guard))
walk(fn, x) = walk(fn, x, nothing)
resolve(x) = x
resolve(gr::GlobalRef) = getproperty(gr.mod, gr.name)
function lookup_method(@nospecialize(fsig::Type), @nospecialize(mt::Union{Nothing, MethodTable}), world)
matches = Base._methods_by_ftype(fsig, mt, -1, world)
return !isnothing(matches) && !isempty(matches) ? only(matches) : nothing
end
function lookup_method(@nospecialize(fsig::Type), @nospecialize(method_tables::Vector{MethodTable}), world)
for mt in method_tables
matches = Base._methods_by_ftype(fsig, mt, -1, world)
!isnothing(matches) && !isempty(matches) && return only(matches)
end
return nothing
end
function method_by_ftype(@nospecialize(fsig::Type), @nospecialize(mt::Union{MethodTable, Vector{MethodTable}}), world)
meth = lookup_method(fsig, mt, world)
return isnothing(meth) ? only(Base._methods_by_ftype(fsig, -1, world)) : meth
end
method_by_ftype(@nospecialize(fsig::Type), @nospecialize(::Nothing), world) = only(Base._methods_by_ftype(fsig, -1, world))
function get_codeinfo(inst::MethodInstance, world)
ci = Core.Compiler.retrieve_code_info(inst, world)
isnothing(ci) && error("Could not get codeinfo for ", inst)
return copy(ci)
end
# `func` is not directly called, so we need to set the backedges manually so that change of `func`
# trigger recompilation. On Julia below v1.11, GPUCompiler use a callback for invalidations, but the callback
# might not be set for `func`, so we add our callback to trigger the callback of the caller.
function add_backedge!(caller::Union{MethodInstance, Nothing}, inst::MethodInstance)
isnothing(caller) && return
@static if VERSION < v"1.11.0-DEV.1552"
callercallback!(caller, inst)
end
ccall(:jl_method_instance_add_backedge, Cvoid, (Any, Any, Any), inst, nothing, caller)
return
end
@static if VERSION < v"1.11.0-DEV.1552"
struct CallerCallback
caller::MethodInstance
end
function (callback::CallerCallback)(replaced::MethodInstance, max_world,
seen::Set{MethodInstance} = Set{MethodInstance}())
push!(seen, replaced)
# run callback of caller
caller = callback.caller
isdefined(caller, :callbacks) || return
for cb in caller.callbacks
cb(caller, max_world, seen)
end
return
end
function callercallback!(caller::Union{MethodInstance, Nothing}, inst::MethodInstance)
isnothing(caller) && return
cb = CallerCallback(caller)
hascallbacks = isdefined(inst, :callbacks)
if hascallbacks
callbacks = inst.callbacks
isnothing(findfirst(==(cb), callbacks)) || return
push!(callbacks, cb)
else
inst.callbacks = Any[cb]
end
return
end
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 2933 | module Contextual
using Core: MethodTable
using Core.Compiler: specialize_method
using Base.Meta: isexpr
using FuncTransforms
using FuncTransforms: create_codeinfo, method_by_ftype, lookup_method, walk, resolve
struct WithCtxGenerator{MT<:Union{Nothing, MethodTable, Vector{MethodTable}}}
overlay_tables::MT
end
function (g::WithCtxGenerator)(world, source, self, ctx, func, args)
fsig = Tuple{func, args...}
overlaymeth = isnothing(g.overlay_tables) ? nothing : lookup_method(fsig, g.overlay_tables, world)
overlay = !isnothing(overlaymeth)
dispatchsig = Tuple{typeof(ctxcall), ctx, func, args...}
dispatchmeth = lookup_method(dispatchsig, nothing, world)
hasdispatch = !isnothing(dispatchmeth)
match = method_by_ftype(Tuple{self, ctx, func, args...}, g.overlay_tables, world) # withctx overlaid
meth = match.method
caller = specialize_method(match)
descend = !(hasdispatch || overlay)
if hasdispatch
ft = FuncTransform(dispatchsig, world, [:withctx, FA(:__ctx__, 2), FA(:func, 3), VA(:__args__, 3)]; caller)
elseif overlay
ft = FuncTransform(fsig, world, [:withctx, :__ctx__, FA(:func, 1), VA(:__args__, 1)];
caller, method_tables = g.overlay_tables)
else
ft = FuncTransform(fsig, world, [:withctx, :__ctx__, FA(:func, 1), VA(:__args__, 1)]; caller)
end
if descend
witharg = getparg(ft.fi, 1)
ctxarg = getparg(ft.fi, 2)
end
for (ssavalue, code) in FuncInfoIter(ft.fi, 1)
stmt = code.stmt
if descend && isexpr(stmt, :call)
callee = resolve(stmt.args[1])
if callee isa Core.Builtin || callee isa Type{Core.TypeVar}
if callee isa typeof(Core._apply_iterate)
id = addstmtbefore!(ft.fi, ssavalue, Expr(:call, GlobalRef(Core, :tuple), ctxarg, stmt.args[3]))
newstmt = Expr(:call, stmt.args[1], stmt.args[2], witharg, id, stmt.args[4:end]...)
else
newstmt = stmt
end
else
newstmt = Expr(:call, witharg, ctxarg, stmt.args...)
end
code.stmt = newstmt
end
end
ci = toCodeInfo(ft)
mt_edges = Core.Compiler.vect(typeof(ctxcall).name.mt, Tuple{typeof(ctxcall), ctx, func, Vararg{Any}})
ci.edges = mt_edges
return ci
end
abstract type Context end
# for dispatch only, would never be called directly
# behavior default to `withctx(ctx, func, args...)`
ctxcall(ctx::Context, func::Core.Builtin, args...) = func(args...)
ctxcall(ctx::Context, func::typeof(Core._apply_iterate), iter, f, args...) = Core._apply_iterate(iter, withctx, (ctx, f), args...)
ctxcall(ctx::Context, T::Type{Core.TypeVar}, args...) = T(args...)
@eval function withctx(ctx::Context, func, args...)
$(Expr(:meta, :generated, WithCtxGenerator(nothing)))
$(Expr(:meta, :generated_only))
end
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | code | 4461 | using FuncTransforms
using Test
include("contextual.jl")
macro isinferred(ex)
esc(quote
try
@inferred $ex
true
catch err
@error err
isa(err, ErrorException) ? false : rethrow(err)
end
end)
end
macro resultshow(a, val, ex)
expr_str = sprint(Base.show_unquoted, ex)
expr = Symbol(expr_str)
linfo = findfirst("=# ", expr_str)
if !isnothing(linfo)
expr_str = expr_str[last(linfo)+1:end]
end
return quote
@time $(esc(ex))
print($expr_str)
print(" = ")
$expr = collect($(esc(a)))[]
println($expr)
@test $expr ≈ $val
end
end
@testset "FuncTransforms.jl" begin
function f(::Type{T}, ::Type, a, b, c, d...) where T
z = sum(d)
return a + b + c + z
end
fi = FuncInfo(Tuple{typeof(f), Type{Int}, Type{Float32}, Int, Int, Int, Int, Int}, Base.get_world_counter())
@test length(fi.pargs) == 6 # "self", "unused", "unused, :a, :b, :c
@test FuncTransforms.hasva(fi)
@test length(fi.args) == 7 # pargs + va
@test length(fi.vars) == 1
@test haskey(fi.args, :a)
@test haskey(fi.args, :d)
@test !haskey(fi.args, :T)
@test !haskey(fi.args, :z)
@test !haskey(fi.vars, :a)
@test haskey(fi.vars, :z)
ci = FuncTransforms.create_codeinfo(@__MODULE__, [], quote end; inline = true)
@test ci.inlining == 1
@test !ci.propagate_inbounds
ci = FuncTransforms.create_codeinfo(@__MODULE__, [], quote end; propagate_inbounds = true)
@test ci.inlining == 1
@test ci.propagate_inbounds
ci = FuncTransforms.create_codeinfo(@__MODULE__, [], quote end; noinline = true)
@test ci.inlining == 2
@test !ci.propagate_inbounds
@test_throws AssertionError FuncTransforms.create_codeinfo(@__MODULE__, [], quote end; noinline = true, inline = true)
@test_throws AssertionError FuncTransforms.create_codeinfo(@__MODULE__, [], quote end; noinline = true, propagate_inbounds = true)
@testset "Contextual" begin
using .Contextual
using .Contextual: withctx, Context
struct Sin2Cos <: Context end
foo(x) = sin(2 * x) / 2
bar(a, x) = (a[1] = foo(x); return)
baz(a, x) = (withctx(Sin2Cos(), bar, a, x); return)
qux(a, x) = (a[1] = withctx(Sin2Cos(), sin, x); return)
a_cpu = Float32[0]
println("\nbefore:")
@resultshow a_cpu sin(2 * 0.7) / 2 withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu sin(2 * 0.7) / 2 baz(a_cpu, 0.7)
@resultshow a_cpu sin(0.3) qux(a_cpu, 0.3)
Contextual.ctxcall(::Sin2Cos, ::typeof(sin), x) = cos(x)
println("\nafter:")
@resultshow a_cpu cos(2 * 0.7) / 2 withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu cos(2 * 0.7) / 2 baz(a_cpu, 0.7)
@resultshow a_cpu cos(0.3) qux(a_cpu, 0.3)
Contextual.ctxcall(::Sin2Cos, ::typeof(sin), x) = tan(x)
println("\nredefine:")
@resultshow a_cpu tan(2 * 0.7) / 2 withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu tan(2 * 0.7) / 2 baz(a_cpu, 0.7)
@resultshow a_cpu tan(0.3) qux(a_cpu, 0.3)
ms = methods(Contextual.ctxcall, Tuple{Sin2Cos, typeof(sin), Any})
while length(ms) != 0
Base.delete_method(ms[1])
ms = methods(Contextual.ctxcall, Tuple{Sin2Cos, typeof(sin), Any})
end
println("\ndelete:")
@resultshow a_cpu sin(2 * 0.7) / 2 withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu sin(2 * 0.7) / 2 baz(a_cpu, 0.7)
@resultshow a_cpu sin(0.3) qux(a_cpu, 0.3)
Contextual.ctxcall(ctx::Sin2Cos, ::typeof(foo), x) = sin(x) + withctx(ctx, cos, x)
Contextual.ctxcall(ctx::Sin2Cos, ::typeof(cos), x) = tan(x)
println("\nafter2:")
@resultshow a_cpu sin(0.7) + tan(0.7) withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu sin(0.7) + tan(0.7) baz(a_cpu, 0.7)
@resultshow a_cpu sin(0.3) qux(a_cpu, 0.3)
Contextual.ctxcall(ctx::Sin2Cos, ::typeof(foo), x) = sin(x) + cos(x)
println("\nredefine2:")
@resultshow a_cpu sin(0.7) + cos(0.7) withctx(Sin2Cos(), bar, a_cpu, 0.7)
@resultshow a_cpu sin(0.7) + cos(0.7) baz(a_cpu, 0.7)
@resultshow a_cpu sin(0.3) qux(a_cpu, 0.3)
@test @isinferred withctx(Sin2Cos(), x->hcat(x,x)[1], [8,9,99])
@test @isinferred withctx(Sin2Cos(), sort!, [3,1,2])
@test withctx(Sin2Cos(), sort!, [3,1,2]) == [1,2,3]
end
end
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | docs | 692 | # FuncTransforms
[](https://chengchingwen.github.io/FuncTransforms.jl/stable/)
[](https://chengchingwen.github.io/FuncTransforms.jl/dev/)
[](https://github.com/chengchingwen/FuncTransforms.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/chengchingwen/FuncTransforms.jl)
Small tool for manipulate and construct `Core.CodeInfo` for a function.
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | e544bbe81878317d24af5383540aff1429416586 | docs | 211 | ```@meta
CurrentModule = FuncTransforms
```
# FuncTransforms
Documentation for [FuncTransforms](https://github.com/chengchingwen/FuncTransforms.jl).
```@index
```
```@autodocs
Modules = [FuncTransforms]
```
| FuncTransforms | https://github.com/chengchingwen/FuncTransforms.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 1275 | using PsychExpAPIs
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
# Moving Ball Exampile
#-=============================
function main()
InitPsychoJL()
# make a new floating window using the PsychoPy coordinate space and and color space
win = Window( [1280, 720], false; colorSpace = "PsychoPy", coordinateSpace = "PsychoPy", timeScale = "seconds") # 2560, 1440 [1000,1000]
myCirc = Circle(win,
[ 0.0, 0.0], # screen center
0.1, # radius is 10% of the screen height
fillColor = [+1.0,-1.0,-1.0, +1.0], # r,g,b, alpha
lineColor = "yellow", # has color names
fill = true)
draw(myCirc) # everything draws into memory
flip(win) # copies to screen
waitTime(win, 0.5) # wait one second
for i in 0:10
x = -.5 + (i*0.1)
setPos(myCirc, [x, 0])
draw(myCirc) # everything draws into memory
#println(x)
flip(win) # copies to screen
waitTime(win, 0.1) # 0.10
end
closeWinOnly(win)
#core.quit()
#sys.exit(0)
#exit()
end
#-===============================================================
main()
| PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 4067 | println("\n----------------------------- NEW RUN ------------------------------\n")
using PsychExpAPIs
using Random
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
using SDL2_ttf_jll
using SDL2_gfx_jll
const setSizes = [8, 16, 24]
const targetPresences = 2
const repetitions = 30
mutable struct ExperimentDesign # we'll pass this around instead of globals
numTrials::Int64
trialSS::Vector{Int64} # this holds the combination of SetSize control
trialTP::Vector{Int64} #
randomOrder::Vector{Int64} # this will hold the random order in which the trials will be displayed.
end
#-----
function main()
# global setSizes # global constants are kosher in Julia, but not gloval variables.
# global targetPresences
# global repetitions
InitPsychoJL()
myWin = Window( [1000,1000], false)
exp = makeExperimentalDesign(setSizes, targetPresences, repetitions) # returns an ExperimentDesign struct
spinningDemo(myWin, 10)
#practice
for t in 1:10
doATrial(myWin, t, false)
end
println("done!")
SDL_Delay(2000)
exit()
end
#-============================================================================
# I did this to demonstrate reusing TextStim objects. Ideally you should
# not be making, and releasing, objects all of the time. Might not matter
# in the big picture, but reuse == speed.
function spinningDemo(win::Window, trials::Int64)
DEFAULT_TEXT = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog", "house"]
myTextStim = TextStim(win, DEFAULT_TEXT[1], [750, 750], color = [rand(128:255), rand(128:255), rand(128:255)])
#myTextStim = TextStim(win, DEFAULT_TEXT[trialNum], [750, 750], color = [rand(128:255), 0, 0])
for trialNum in 1:trials
myTextStim.textMessage = DEFAULT_TEXT[trialNum]
myTextStim.fontSize = 24
myTextStim.orientation = (trialNum*10) - 45
myTextStim.horizAlignment = 0
myTextStim.scale = 1 + trialNum/4
#myTextStim.fontSize = 1 + round(Int64,trialNum/4)
draw(myTextStim)
flip(win)
SDL_Delay(15)
#SDL_Delay(285)
flip(win)
#SDL_Delay(15)
print("boo")
end
end#-============================================================================
# We'll make the target an O among Q's
function doATrial(win::Window, trialNum::Int64, realOrPractice::Bool = true)
DEFAULT_TEXT = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog", "house"]
myTextStim = TextStim(win, DEFAULT_TEXT[trialNum], [750, 750], color = [rand(128:255), rand(128:255), rand(128:255)])
#myTextStim = TextStim(win, DEFAULT_TEXT[trialNum], [750, 750], color = [rand(128:255), 0, 0])
myTextStim.fontSize = 24
myTextStim.orientation = trialNum*10
myTextStim.horizAlignment = -1
myTextStim.scale = 1 + trialNum/4
#myTextStim.fontSize = 1 + round(Int64,trialNum/4)
draw(myTextStim)
flip(win)
SDL_Delay(285)
flip(win)
SDL_Delay(15)
print("boo")
end
#-============================================================================
# Algorithmically make the control variables for the experiment
function makeExperimentalDesign(SS, TP, Reps)
numTrials = sizeof(SS) * TP * Reps
trialSetSize = zeros(Int64, numTrials) # this will holder the set size control variable that we will fill below
trialTP = zeros(Int64, numTrials) # this will holder the target presence control variable that we will fill below
trial = 1
for r in 1:repetitions # we do this outer because it makes block randomization easier
for ss in SS # array of set setSizes
for pres in 1:TP # target presence
trialSetSize[trial] = ss
trialTP[trial] = pres-1 # 0 = absent, 1 = present
trial += 1
end
end
end
# next, create the random order for the trials. This is not fancy block randomization.
order = collect(1:numTrials)
shuffleOrder = shuffle(order)
# below we fill the struct with info about the experimental design and return it.
designInfo = ExperimentDesign(numTrials, trialSetSize, trialTP, shuffleOrder)
return designInfo
end
#-============================================================================
main() | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 10029 | #=
THINGS TO ADD/FIX
Save subject data
have the screen scaling change whether it is full screen or not (done in Win?)
=#
println("\n----------------------------- NEW RUN ------------------------------\n")
using PsychExpAPIs
using Random
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
using SDL2_ttf_jll
using SDL2_gfx_jll
using Printf
const setSizes = [8, 16, 24] # global constants are kosher in Julia, but not global variables.
const targetPresences = 2
const repetitions = 30
mutable struct ExperimentDesign # we'll pass this around instead of globals
numTrials::Int64
trialSS::Vector{Int64} # this holds the combination of SetSize control
trialTP::Vector{Int64} # Target Presence
randomOrder::Vector{Int64} # this will hold the random order in which the trials will be displayed.
end
#-----
function main()
global subjInfo
global subjID
InitPsychoJL()
subjID = getSubjectInfo()
subjFile = openDataFile(subjID)
myWin = Window( [2560,1440], true) # 5120 × 2880, or 2560 x 1440 [1000,1000]
mouseVisible(false)
exp = makeExperimentalDesign(setSizes, targetPresences, repetitions) # returns an ExperimentDesign struct
showInstructions(myWin)
#practice
for t in 1:3
doATrial(myWin, t, exp, subjFile, false )
end
for t in 1:10
doATrial(myWin, t, exp, subjFile, true )
end
shutDown(myWin, subjFile)
#exit()
end
#-============================================================================
function showInstructions(win::Window, )
x2 = win.pos[1]
y2 = win.pos[1]
x,y = getPos(win)
posMes = @sprintf("(%d, %d) (%d, %d)", x,y,x2,y2)
posText = TextStim(win, posMes, [100, 100 ])
posText.horizAlignment = -1
draw(posText)
w2 = Ref{Cint}()
h2 = Ref{Cint}()
SDL_GetWindowSize(win.win, w2, h2)
posText.textMessage = @sprintf("SDL_GetWindowSize (%d, %d)", w2[],h2[])
posText.pos = [100, 150 ]
draw(posText)
w3 = Ref{Cint}()
h3 = Ref{Cint}()
SDL_GL_GetDrawableSize(win.win, w3, h3)
posText.textMessage = @sprintf("SDL_GL_GetDrawableSize (%d, %d)", w3[],h3[])
posText.pos = [100, 200 ]
draw(posText)
line1 = Line(win, [x, 0], [x, y*2], width = 1, lineColor = [255,0,0,255] )
line2 = Line(win, [0, y], [x* 2, y], width = 1, lineColor = [0,0,255,255] )
draw(line1)
draw(line2)
#x = win.pos[1] ÷ 2 # divide by two for retina scaling issue
#y = win.pos[2] ÷ 2
print("x and y = ", x,", ",y)
message1 = "Press the '/' key if a T is present."
TextStim1 = TextStim(win, message1, [x, y - 50 ])
TextStim1.color = [255, 255, 255]
TextStim1.scale = 1.5
TextStim1.horizAlignment = 0 # center aligned
draw(TextStim1)
message2 = "Press the 'z' key if the target T is absent."
TextStim2 = TextStim(win, message2, [x, y + 50 ])
TextStim2.color = [255, 255, 255]
TextStim2.scale = 1.5
TextStim2.horizAlignment = 0 # center aligned
draw(TextStim2)
message3 = "Press the space bar when you are ready to continue."
TextStim3 = TextStim(win, message3, [x, y + 250 ])
TextStim3.color = [255, 255, 0]
draw(TextStim3)
flip(win)
getKey(win)
end
#-============================================================================
function shutDown(win::Window, subjFile::IOStream)
close(subjFile)
mouseVisible(true)
setFullScreen(win, false)
hideWindow(win)
happyMessage( "Thank-you for participating")
closeAndQuitPsychoJL(win)
println("post closeAndQuitPsychoJL")
end
#-============================================================================
function openDataFile(subjID::String)
fileName = "subj" * subjID * ".txt"
println(pwd())
println(fileName)
while isfile(fileName) == true && subjID != "999"
message = fileName * " already exists!"
displayMessage( message)
subjID = getSubjectInfo()
fileName = "subj" * subjID * ".txt"
end
f = open(fileName, "a") # append, so that we can stream the data
write(f,"TrialNum\tOrder\tTargetPresent\tSetSize\tRT\tCorrect\tkeypressed\n")
return f
end
#-============================================================================
# We'll make the target a left or right rotated T among rotated Ls
function doATrial(win::Window, trialNum::Int64, trialInfo::ExperimentDesign, subjFile::IOStream, realOrPractice::Bool = true)
#---------
# make an ErrSound object
errSound = ErrSound()
# NOTE: Ideally you would not do this here, because it
# (1) creates a sound object and loads a sound file
# (2) destroys the sound object after each trial
# however, it probably does not have an effect on performance.
theTrial = trialInfo.randomOrder[trialNum] # get our randomized trial number
# (2) need to fill an array full of stimuli to display, depending on set size, target presence, etc.
# make a list of distractors as orientatons 0-4 (90 degree). Target will be coded as -1
stimList = zeros(trialInfo.trialSS[theTrial])
ori = 0 # distractor orientation
for i in eachindex(stimList)
stimList[i] = ori
ori += 1
if ori >= 4
ori = 0
end
end
if trialInfo.trialTP[theTrial] == 1 # if the target is present
stimList[1] = -1 # replace the first item in stimList with the target (-1)
end
# (3) need to randomly pick the locations
locations = collect(0:99) # these are in a 10 x 10 grid
shuffle!(locations)
# (4) Premake the stimuli
stimDrawList::Vector{TextStim} = []
_, gridSize = getSize(win) # square display area, so grabbing window's height
gridSize *= 0.9 # we'll use 90% of the area
gridSize *= 0.1 # and divide it into 10
xScootch, _ = win.pos # find the middle of the window...
xScootch = round(Int64, xScootch /2) # ... and take half that. We'll scootch the stimuli over so that they are centered.
for i in eachindex(stimList)
#x = 50+((locations[i]%10)*100) # 1000 x 1000, steps of 100
#y = 50+(floor(Int64, locations[i]/10)*100) # 1000 x 1000, steps of 100
x = (gridSize÷2)+((locations[i]%10)*gridSize) # 1000 x 1000, steps of 100
y = (gridSize÷2)+(floor(Int64, locations[i]/10)*gridSize) # 1000 x 1000, steps of 100
x += xScootch
x = round(Int64, x)
y = round(Int64, y)
if stimList[i] == -1 # target
ori = rand(1:2)
if ori == 1
ori = -90
else
ori = +90
end
tempStim = TextStim(win, "T", [x, y], color = [255,255,0], fontSize = 24, orientation = ori)
push!(stimDrawList, tempStim) # append it to stimDrawList
else # else it is a distractor
tempStim = TextStim(win, "L", [x, y], color = [255,255,255], fontSize = 24, orientation = floor(Int, stimList[i] * 90) )
push!(stimDrawList, tempStim) # append it to stimDrawList
end
end
if stimList[1] == -1
println("target present\n", theTrial)
else
println("target absent\n", theTrial)
end
for s in stimDrawList
draw(s)
end
flip(win)
startTimer(win)
keypressed = getKey(win)
RT = stopTimer(win)
# Grade Keypress
accuracy = 0
if keypressed == "z" && trialInfo.trialTP[theTrial] == 0
accuracy = 1
elseif keypressed == "/" && trialInfo.trialTP[theTrial] == 1
accuracy = 1
elseif keypressed == "7" # secret abort key
shutDown(win, subjFile)
else
play(errSound)
end
#------
if realOrPractice == true # do not save practice data
buf = @sprintf("%d\t%d\t%d\t", trialNum, theTrial, trialInfo.trialTP[theTrial])
buf = buf * @sprintf("%d\t%4.1f\t%d\t%s\n", trialInfo.trialSS[theTrial], RT, accuracy, keypressed)
write(subjFile, buf)
end
end
#-============================================================================
# Algorithmically make the control variables for the experiment
function makeExperimentalDesign(SS, TP, Reps)
numTrials = length(SS) * TP * Reps
trialSetSize = zeros(Int64, numTrials) # this will holder the set size control variable that we will fill below
trialTP = zeros(Int64, numTrials) # this will holder the target presence control variable that we will fill below
trial = 1
for r in 1:repetitions # we do this outer because it makes block randomization easier
for ss in SS # array of set setSizes
for pres in 1:TP # target presence
trialSetSize[trial] = ss
trialTP[trial] = pres-1 # 0 = absent, 1 = present
trial += 1
end
end
end
# next, create the random order for the trials. This is not fancy block randomization.
order = collect(1:numTrials)
shuffleOrder = shuffle(order)
# below we fill the struct with info about the experimental design and return it.
designInfo = ExperimentDesign(numTrials, trialSetSize, trialTP, shuffleOrder)
return designInfo
end
#-===============================================================
function OldgetSubjectInfo()
#subjInfo = {"Particpant":""}
subjInfo= Dict("Particpant" => "")
dictDlg = DlgFromDict(subjInfo)
if dictDlg[1] == "OK"
println(subjInfo)
else
println("User Cancelled")
displayMessage("User Cancelled")
waitTimeMsec(3000)
exit()
end
subjID = dictDlg[2]["Particpant"]
subjID = String(strip(subjID, ' ')) # sometimes returns an extra space
println("subject name = ", subjID,"\n")
return subjID
end
#-============================================================================
function getSubjectInfo()
done = false
subjID = "" # ensures that subjID is not local to the while loop
while done == false
subjInfo= Dict("Particpant" => "")
dictDlg = DlgFromDict(subjInfo)
if dictDlg[1] == "OK"
println(subjInfo)
else
print("User Cancelled")
displayMessage("User Cancelled")
waitTimeMsec(3000)
exit()
end
subjID = dictDlg[2]["Particpant"]
subjID = String(strip(subjID, ' ')) # sometimes returns an extra space
println("subjID = ", subjID,"\n")
# check if the filename is valid (length <= 8 & no special char)
fileName = "subj" * subjID * ".txt"
if isfile(fileName) == true && subjID != "999" # 999 is my demo subject
message = fileName * " already exists!"
displayMessage( message)
#subjID = getSubjectInfo()
#fileName = "subj" * subjID * ".txt"
else
done = true
end
end
return subjID
end
main() | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 2017 | using Documenter, PsychExpAPIs
using Dates
println("------------------ NEW MAKE ------------------")
println("----- ", now())
makedocs( modules = [PsychExpAPIs],
sitename="PsychExpAPIs.jl",
checkdocs=:none,
pages = [
"Home" => "index.md",
"Initialization and Timing" => "InitializationAndTiming.md",
"Windows" => "Windows.md",
"Colors" => "Colors.md",
"Coordinates Systems" => "Coordinates.md",
"GUI" => "GUI.md",
"Images" => "ImageStim.md",
"Input Events" => "InputEvents.md",
"Setter Functions" => "SetterFunctions.md",
"Shapes" => "Shapes.md",
"Sound" => "SoundStim.md",
"Text" => "TextStim.md",
"Timing" => "Timings.md"
#= "Getting Started" => "start.md",
"Concepts" => "concepts.md",
"Library" => Any[
"Agents" => Any[
"library/Agents/index.md",
"library/Agents/stationary.md",
"library/Agents/nonstationary.md"
],
"Arms" => Any[
"library/Arms/index.md",
"library/Arms/stationary.md",
"library/Arms/nonstationary.md"
]
],
"Manual" => Any[
"contributing.md",
"ack.md"
]
=#
],
)
deploydocs(
repo = "github.com/mpeters2/PsychExpAPIs.jl.git",
target = "build",
deps = nothing,
make = nothing
)
#=
Order = [:function, :type]
deploydocs(
repo = "https://github.com/mpeters2/PsychoJL.jl",
target = "build",
deps = nothing,
make = nothing
)
=#
#=
```@docs
InitPsychoJL()
wait(win::Window, time::Float64)
MakeInt8Color(r,g,b,a)
```
- link to [..core.jl](@ref)
- link to [`InitPsychoJL()`](@ref)
```
@autodocs
Modules = [PsychoJL, core]
Private = false
Order = [:function, :type]
```
```
checkdocs=:exports
```
```@docs
InitPsychoJL()
waitTime()
```
=#
#=
## Random Auto-generated list of functions and objects.
```@autodocs
Modules = [PsychoJL]
Private = false
Order = [:function, :type]
```
=#
#=
chapters
Initialization and timing
Window
input
GUI
Shapes
Text
Images
=# | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 3167 | " Module for writing Psychology Experiments inspired by Psychopy"
module PsychExpAPIs
# need to make an alignment option for all widgets, like I did with textStim.
# Look at this about scaling and SDL with SDL_WINDOW_ALLOW_HIGHDPI https://discourse.libsdl.org/t/high-dpi-mode/34411/7
# Need to add copyright for whatever fotn I am using.
#=
- link to [core.jl](@ref)
- link to [`InitPsychoJL()`](@ref)
- link to [`MakeInt8Color(r,g,b,a)`](@ref)
=#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
using SDL2_ttf_jll
using StaticArrays
using Colors
#using Documenter
using JET
#println("---------------------------- NEW RUN -----------------------------")
#print("\ncurrent directory: ", pwd(),"\n\n")
#cd("src")
#print("\ncurrent directory: ", pwd(),"\n\n")
include( "window.jl")
include( "core.jl" )
include( "shapes.jl" )
include( "textStim.jl" )
include( "events.jl" )
include( "imageStim.jl" )
include( "buttons.jl" )
include( "SDL2_gfxPrimitives.jl" )
#include( "SDL2_ttf_wrapping.jl" )
include( "gui.jl" )
include( "popUpMenu.jl" )
include( "timings.jl" )
include( "soundStim.jl" )
export InitPsychoJL, MakeInt8Color, waitTime, waitTimeMsec, colorToSDL, SDLcoords
export PsychoColor, PsychoCoords
export Window, closeAndQuitPsychoJL, flip, closeWinOnly, hideWindow, getPos, getSize, setFullScreen
export mouseVisible
export Rect, Ellipse, Line, Circle, ShapeStim, Polygon, Line2
export setColor, setLineColor, setFillColor, setPos
export TextStim, TextStimExp, setColor
export waitKeys, getKey
export ImageStim
export infoMessage, inputDialog, askQuestionDialog, fileOpenDlg, textInputDialog, DlgFromDict
export alertMessage, happyMessage
export roundedRectangleRGBA, aaRoundRectRGBA, wuAACircle, aaRoundRectRGBAThick, aaFilledRoundRectRGBA
export ButtonStim, ButtonMap, buttonDraw, buttonDrawClicked, buttonStim
export PopUpMenu, PopUpMap
export startTimer, stopTimer
export ErrSound, SoundStim, play
#/Users/MattPetersonsAccount/.julia/dev/PsychoJL/src/testStim.jl
#/Users/MattPetersonsAccount/.julia/dev/PsychoJL/src/textStim.jl
#-==============================================0
# scratchpad for future PsychoJL functions, structs, and stuff
#=
ToDo
Fix super hi-res scaling issue
√ add a gui
Add multiple coordinate systems
√ TextStim STruct
√ GEt and show images
√ GEt and show images
√ waitKeys
√ draw for ellipse (not sdl_ellipse() )
√ draw for ellipse (not sdl_ellipse() )
change color methods so that they can handle 255, 1.0, and Psychopy
√ add line
√ thickLineRGBA looks like shit. How can I anti-alias?
√ add fullscreen to window
√ show images
add documenter
√ upload to github
√ Need Gui interface for getting information
=#
#----------
# needed for converting SDL pointers
#unsafe_convert(::Type{Ptr{Float32}}, q::Quaternions.Quaternion{Float64}) =
# convert(Ptr{Float32}, Ptr{Float32}(pointer_from_objref([imag(q), real(q)])))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
end # module PsychoJL
| PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 3163 | " Module for writing Psychology Experiments inspired by Psychopy"
module PsychoJL
# need to make an alignment option for all widgets, like I did with textStim.
# Look at this about scaling and SDL with SDL_WINDOW_ALLOW_HIGHDPI https://discourse.libsdl.org/t/high-dpi-mode/34411/7
# Need to add copyright for whatever fotn I am using.
#=
- link to [core.jl](@ref)
- link to [`InitPsychoJL()`](@ref)
- link to [`MakeInt8Color(r,g,b,a)`](@ref)
=#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
using SDL2_ttf_jll
using StaticArrays
using Colors
#using Documenter
using JET
#println("---------------------------- NEW RUN -----------------------------")
#print("\ncurrent directory: ", pwd(),"\n\n")
#cd("src")
#print("\ncurrent directory: ", pwd(),"\n\n")
include( "window.jl")
include( "core.jl" )
include( "shapes.jl" )
include( "textStim.jl" )
include( "events.jl" )
include( "imageStim.jl" )
include( "buttons.jl" )
include( "SDL2_gfxPrimitives.jl" )
#include( "SDL2_ttf_wrapping.jl" )
include( "gui.jl" )
include( "popUpMenu.jl" )
include( "timings.jl" )
include( "soundStim.jl" )
export InitPsychoJL, MakeInt8Color, waitTime, waitTimeMsec, colorToSDL, SDLcoords
export PsychoColor, PsychoCoords
export Window, closeAndQuitPsychoJL, flip, closeWinOnly, hideWindow, getPos, getSize, setFullScreen
export mouseVisible
export Rect, Ellipse, Line, Circle, ShapeStim, Polygon, Line2
export setColor, setLineColor, setFillColor, setPos
export TextStim, TextStimExp, setColor
export waitKeys, getKey
export ImageStim
export infoMessage, inputDialog, askQuestionDialog, fileOpenDlg, textInputDialog, DlgFromDict
export alertMessage, happyMessage
export roundedRectangleRGBA, aaRoundRectRGBA, wuAACircle, aaRoundRectRGBAThick, aaFilledRoundRectRGBA
export ButtonStim, ButtonMap, buttonDraw, buttonDrawClicked, buttonStim
export PopUpMenu, PopUpMap
export startTimer, stopTimer
export ErrSound, SoundStim, play
#/Users/MattPetersonsAccount/.julia/dev/PsychoJL/src/testStim.jl
#/Users/MattPetersonsAccount/.julia/dev/PsychoJL/src/textStim.jl
#-==============================================0
# scratchpad for future PsychoJL functions, structs, and stuff
#=
ToDo
Fix super hi-res scaling issue
√ add a gui
Add multiple coordinate systems
√ TextStim STruct
√ GEt and show images
√ GEt and show images
√ waitKeys
√ draw for ellipse (not sdl_ellipse() )
√ draw for ellipse (not sdl_ellipse() )
change color methods so that they can handle 255, 1.0, and Psychopy
√ add line
√ thickLineRGBA looks like shit. How can I anti-alias?
√ add fullscreen to window
√ show images
add documenter
√ upload to github
√ Need Gui interface for getting information
=#
#----------
# needed for converting SDL pointers
#unsafe_convert(::Type{Ptr{Float32}}, q::Quaternions.Quaternion{Float64}) =
# convert(Ptr{Float32}, Ptr{Float32}(pointer_from_objref([imag(q), real(q)])))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
end # module PsychoJL
| PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 95159 | # SDL2_gfxPrimitives.c
# https://github.com/RobLoach/sdl2_gfx/blob/edc1880666d5a62e8d58c71cee094c21ba7c5d53/SDL2_gfxPrimitives.c#L1733
#
# Translated to Julia by Matt Peterson, December 2023
#
# semicolon note: Julia is happy with or without semicolons at the end of lines. I just left them there.
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
#using .window
using Printf
using Images
const ELLIPSE_OVERSCAN::Int64 = 4
const AAlevels::Int64 = 256
const AAbits::Int64 = 8
const POLYSIZE::Int64 = 16384
truncInt(x) = floor(Int, x) # for typecasting floats to ints when indexing
#------
lrint(x) = truncInt(round(x))
#-=======================================================================
function line(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64)
return SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
end
#-------------
function vline(renderer::Ptr{SDL_Renderer}, x::Int64, y1::Int64, y2::Int64)
return SDL_RenderDrawLine(renderer, x, y1, x, y2);;
end
#-------------
function hline(renderer::Ptr{SDL_Renderer}, x1::Int64, x2::Int64, y::Int64)
return SDL_RenderDrawLine(renderer, x1, y, x2, y);;
end
#-=======================================================================
function pixelRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
result::Int64 = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawPoint(renderer, x, y);
return result;
end
#-------------
#function pixelRGBAfloat(renderer::Ptr{SDL_Renderer}, x::Float64, y::Float64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
function pixelRGBAfloat(renderer::Ptr{SDL_Renderer}, x::Float64, y::Float64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawPointF(renderer, x, y);
return result;
end
#-------------
function pixelRGBAWeight(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8, weight::Int64)
#=
* Modify Alpha by weight
=#
ax::UInt8 = a;
ax = ((ax * weight) >> 8);
if (ax > 255)
a = 255;
else
a = ax & 0x000000ff
end
return pixelRGBA(renderer, x, y, r, g, b, convert(UInt8, a));
end
#-------------
function pixelColor(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, c::Vector{UInt8})
return pixelRGBA(renderer, x, y, c[1], c[2], c[3], c[4]);
end
#-------------
function pixelColorWeight(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, c::Vector{UInt8}, weight::Int64)
#=
* Modify Alpha by weight
=#
ax::Int64 = c[4];
ax = ((ax * weight) >> 8);
if (ax > 255)
c[4] = 255;
else
c[4] = ax & 0x000000ff
end
return pixelRGBA(renderer, x, y, c[1], c[2], c[3], c[4]);
end
#-=======================================================================
function _drawQuadrants(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, dx::Int64, dy::Int64, flag::Bool)
result::Int64 = 0
xpdx::Int64 = 0
xmdx::Int64 = 0
ypdy::Int64 = 0
ymdy::Int64 = 0
if (dx == 0)
if (dy == 0)
result = result | pixel(renderer, x, y);
else
ypdy = y + dy;
ymdy = y - dy;
if (flag)
result = result | vline(renderer, x, ymdy, ypdy);
else
result = result | pixel(renderer, x, ypdy);
result = result | pixel(renderer, x, ymdy);
end
end
else
xpdx = x + dx;
xmdx = x - dx;
ypdy = y + dy;
ymdy = y - dy;
if (flag)
result = result | vline(renderer, xpdx, ymdy, ypdy);
result = result | vline(renderer, xmdx, ymdy, ypdy);
else
result = result | pixel(renderer, xpdx, ypdy);
result = result | pixel(renderer, xmdx, ypdy);
result = result | pixel(renderer, xpdx, ymdy);
result = result | pixel(renderer, xmdx, ymdy);
end
end
return result
end
#=!
brief Internal function to draw ellipse or filled ellipse with blending.
param renderer The renderer to draw on.
param x X coordinate of the center of the ellipse.
param y Y coordinate of the center of the ellipse.
param rx Horizontal radius in pixels of the ellipse.
param ry Vertical radius in pixels of the ellipse.
param r The red value of the ellipse to draw.
param g The green value of the ellipse to draw.
param b The blue value of the ellipse to draw.
param a The alpha value of the ellipse to draw.
param f Flag indicating if the ellipse should be filled (1) or not (0).
returns Returns 0 on success, -1 on failure.
=#
#-===========================================================================================================================
function _ellipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8, flag::Bool)
result::Int64 = 0
rx2::Int64 = 0
ry2::Int64 = 0
rx22::Int64 = 0
ry22::Int64 = 0
error::Int64 = 0
curX::Int64 = 0
curY::Int64 = 0
curXp1::Int64 = 0
curYm1::Int64 = 0
scrX::Int64 = 0
scrY::Int64 = 0
oldX::Int64 = 0
oldY::Int64 = 0
deltaX::Int64 = 0
deltaY::Int64 = 0
#=
* Sanity check radii
=#
if ((rx < 0) || (ry < 0))
return (-1)
end
#=
* Set color
=#
result = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
#=
* Special cases for rx=0 and/or ry=0: draw a hline/vline/pixel
=#
if (rx == 0)
if (ry == 0)
return (pixel(renderer, x, y));
else
return (vline(renderer, x, y - ry, y + ry));
end
else
if (ry == 0)
return (hline(renderer, x - rx, x + rx, y));
end
end
#=
* Top/bottom center points.
=#
oldX = scrX = 0
oldY = scrY = ry
result = result | _drawQuadrants(renderer, x, y, 0, ry, flag)
#= Midpoint ellipse algorithm with overdraw =#
rx *= ELLIPSE_OVERSCAN;
ry *= ELLIPSE_OVERSCAN;
rx2 = rx * rx;
rx22 = rx2 + rx2;
ry2 = ry * ry;
ry22 = ry2 + ry2;
curX = 0;
curY = ry;
deltaX = 0;
deltaY = rx22 * curY;
#= Points in segment 1 =#
error = ry2 - rx2 * ry + rx2 / 4;
while (deltaX <= deltaY)
curX += 1
deltaX += ry22;
error += deltaX + ry2;
if (error >= 0)
curY -= 1
deltaY -= rx22;
error -= deltaY;
end
scrX = lrint(curX / ELLIPSE_OVERSCAN)
scrY = lrint(curY / ELLIPSE_OVERSCAN)
if ((scrX != oldX && scrY == oldY) || (scrX != oldX && scrY != oldY))
result |= _drawQuadrants(renderer, x, y, scrX, scrY, flag);
oldX = scrX;
oldY = scrY;
end
end
#= Points in segment 2 =#
if (curY > 0)
curXp1 = curX + 1;
curYm1 = curY - 1;
error = lrint(ry2 * curX * curXp1 + ((ry2 + 3) / 4) + rx2 * curYm1 * curYm1 - rx2 * ry2)
while (curY > 0)
curY -= 1
deltaY -= rx22;
error += rx2;
error -= deltaY;
if (error <= 0)
curX += 1
deltaX += ry22;
error += deltaX;
end
scrX = lrint(curX/ELLIPSE_OVERSCAN)
scrY = lrint(curY/ELLIPSE_OVERSCAN)
if ((scrX != oldX && scrY == oldY) || (scrX != oldX && scrY != oldY))
oldY -= 1;
yyy = oldY
#for (;oldY >= scrY; oldY -= 1)
for yyy in oldY:-1:scrY
result |= _drawQuadrants(renderer, x, y, scrX, oldY, flag);
#= prevent overdraw =#
if (flag)
oldY = scrY - 1;
end
end
oldX = scrX;
oldY = scrY;
end
end
#= Remaining points in vertical =#
if (!flag)
oldY -= 1
#for (;oldY >= 0; oldY -= 1) # equivalent to (for yyy = oldY; zzz >=0; zzz -= 1) then assign yyy to oldy when done; Julia for yyy in oldY:-1:0
yyy = oldY
for yyy in oldY:-1:0
result |= _drawQuadrants(renderer, x, y, scrX, yyy, flag);
end
oldY = yyy
end
end
return (result)
end
#=!
brief Draw ellipse with blending.
param renderer The renderer to draw on.
param x X coordinate of the center of the ellipse.
param y Y coordinate of the center of the ellipse.
param rx Horizontal radius in pixels of the ellipse.
param ry Vertical radius in pixels of the ellipse.
param color The color value of the ellipse to draw (0xRRGGBBAA).
returns Returns 0 on success, -1 on failure.
=#
#-===========================================================================================================================
#=!
\brief Draw anti-aliased ellipse with blending.
\param renderer The renderer to draw on.
\param x X coordinate of the center of the aa-ellipse.
\param y Y coordinate of the center of the aa-ellipse.
\param rx Horizontal radius in pixels of the aa-ellipse.
\param ry Vertical radius in pixels of the aa-ellipse.
\param r The red value of the aa-ellipse to draw.
\param g The green value of the aa-ellipse to draw.
\param b The blue value of the aa-ellipse to draw.
\param a The alpha value of the aa-ellipse to draw.
\returns Returns 0 on success, -1 on failure.
=#
function _aaellipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64, color::Vector{Int64}, flag::Bool)
aaellipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64,
convert(UInt8, color[1]),
convert(UInt8, color[2]),
convert(UInt8, color[3]),
convert(UInt8, color[4]),
flag::Bool)
end
# anti-alliased ellipse
function aaellipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8, flag::Bool)
result::Int64 = 0
i::Int64 = 0
a2::Int64 = 0
b2::Int64 = 0
ds::Int64 = 0
dt::Int64 = 0
dxt::Int64 = 0
t::Int64 = 0
s::Int64 = 0
d::Int64 = 0
p::Int64 = 0
yp::Int64 = 0
xs::Int64 = 0
ys::Int64 = 0
dyt::Int64 = 0
od::Int64 = 0
xx::Int64 = 0
yy::Int64 = 0
xc2::Int64 = 0
yc2::Int64 = 0
cp::Float64 = 0
sab::Float64 = 0
weight::Int64 = 0
iweight::Int64 = 0
#=
* Sanity check radii
=#
if ((rx < 0) || (ry < 0))
return (-1);
end
#=
* Special cases for rx=0 and/or ry=0: draw a hline/vline/pixel
=#
if (rx == 0)
if (ry == 0)
return (pixelRGBA(renderer, x, y, r, g, b, a));
else
return (vlineRGBA(renderer, x, y - ry, y + ry, r, g, b, a));
end
else
if (ry == 0)
return (hlineRGBA(renderer, x - rx, x + rx, y, r, g, b, a));
end
end
#= Variable setup =#
a2 = rx * rx;
b2 = ry * ry;
ds = 2 * a2;
dt = 2 * b2;
xc2 = 2 * x;
yc2 = 2 * y;
sab = sqrt(a2 + b2) # sab = sqrt((double)(a2 + b2));
od = lrint(lrint(sab*0.01) + 1) #= introduce some overdraw =#
dxt = lrint(lrint(a2 / sab) + od)
t = 0;
s = -2 * a2 * ry;
d = 0;
xp = x;
yp = y - ry;
#= Draw =#
result = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
#= "End points" =#
result |= pixelRGBA(renderer, xp, yp, r, g, b, a);
result |= pixelRGBA(renderer, xc2 - xp, yp, r, g, b, a);
result |= pixelRGBA(renderer, xp, yc2 - yp, r, g, b, a);
result |= pixelRGBA(renderer, xc2 - xp, yc2 - yp, r, g, b, a);
#for (i = 1; i <= dxt; i += 1)
for i in 1:dxt
xp -= 1;
d += t - b2;
if (d >= 0)
ys = yp - 1;
elseif ((d - s - a2) > 0)
if ((2 * d - s - a2) >= 0)
ys = yp + 1;
else
ys = yp;
yp += 1;
d -= s + a2;
s += ds;
end
else
yp += 1;
ys = yp + 1;
d -= s + a2;
s += ds;
end
t -= dt;
#= Calculate alpha =#
if (s != 0)
cp = abs(d) / abs(s); # (float) abs(d) / (float) abs(s);
if (cp > 1.0)
cp = 1.0;
end
else
cp = 1.0;
end
#= Calculate weights =#
weight = lrint( (cp * 255))
iweight = 255 - weight;
#= Upper half =#
xx = xc2 - xp; # mirrors xp
result |= pixelRGBAWeight(renderer, xp, yp, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xx, yp, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xp, ys, r, g, b, a, weight);
result |= pixelRGBAWeight(renderer, xx, ys, r, g, b, a, weight);
##hline(renderer, xp, xx, yp);
#hline(renderer, xp, xx, ys);
#= Lower half =#
yy = yc2 - yp; # mirrors yp
result |= pixelRGBAWeight(renderer, xp, yy, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xx, yy, r, g, b, a, iweight);
yy = yc2 - ys;
result |= pixelRGBAWeight(renderer, xp, yy, r, g, b, a, weight);
result |= pixelRGBAWeight(renderer, xx, yy, r, g, b, a, weight);
end
#= Replaces original approximation code dyt = abs(yp - yc); =#
dyt = lrint(b2 / sab ) + od;
#for (i = 1; i <= dyt; i += 1)
for i in 1:dyt
yp += 1;
d -= s + a2;
if (d <= 0)
xs = xp + 1;
elseif ((d + t - b2) < 0)
if ((2 * d + t - b2) <= 0)
xs = xp - 1;
else
xs = xp;
xp -= 1;
d += t - b2;
t -= dt;
end
else
xp -= 1;
xs = xp - 1;
d += t - b2;
t -= dt;
end
s += ds;
#= Calculate alpha =#
if (t != 0)
cp = abs(d) / abs(t); # MSP this had (float)...does it matter in Julia?
if (cp > 1.0)
cp = 1.0;
end
else
cp = 1.0;
end
#= Calculate weight =#
weight = lrint( (cp * 255) )
iweight = 255 - weight;
#= Left half =#
xx = xc2 - xp;
yy = yc2 - yp;
result |= pixelRGBAWeight(renderer, xp, yp, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xx, yp, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xp, yy, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xx, yy, r, g, b, a, iweight);
#vline(renderer, xp, yp, yy);
#vline(renderer, xx, yp, yy);
#= Right half =#
xx = xc2 - xs;
result |= pixelRGBAWeight(renderer, xs, yp, r, g, b, a, weight);
result |= pixelRGBAWeight(renderer, xx, yp, r, g, b, a, weight);
result |= pixelRGBAWeight(renderer, xs, yy, r, g, b, a, weight);
result |= pixelRGBAWeight(renderer, xx, yy, r, g, b, a, weight);
#vline(renderer, xs, yp, yy);
#vline(renderer, xx, yp, yy);
end
return (result)
end
#=
\brief Draw thick ellipse with blending.
\param renderer The renderer to draw on.
\param xc X coordinate of the center of the ellipse.
\param yc Y coordinate of the center of the ellipse.
\param xr Horizontal radius in pixels of the ellipse.
\param yr Vertical radius in pixels of the ellipse.
\param r The red value of the ellipse to draw.
\param g The green value of the ellipse to draw.
\param b The blue value of the ellipse to draw.
\param a The alpha value of the ellipse to draw.
\param thick The line thickness in pixels
\returns Returns 0 on success, -1 on failure.
=#
function thickEllipseRGBA(renderer::Ptr{SDL_Renderer}, xc::Int64, yc::Int64, xr::Int64, yr::Int64, r::Int64, g::Int64, b::Int64, a::Int64, thick::Int64)
result::Int64 = 0 ;
#xi, yi, xo, yo, x, y, z ;
#double xi2, yi2, xo2, yo2 ;
#if (thick <= 1)
# return _aaellipseRGBA(renderer, xc, yc, xr, yr, r, g, b, a) ;
#end
xi = xr - thick / 2 ;
xo = xi + thick - 1 ;
yi = yr - thick / 2 ;
yo = yi + thick - 1 ;
if ((xi <= 0) || (yi <= 0))
return -1 ;
end
xi2 = xi * xi ;
yi2 = yi * yi ;
xo2 = xo * xo ;
yo2 = yo * yo ;
if (a != 255)
result |= SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
if (xr < yr)
#for (x = -xo; x <= -xi; x++)
for x in -xo:xi
y = sqrt(yo2 * (1.0 - x*x/xo2)) + 0.5 ;
result |= renderdrawline(renderer, xc+x, yc-y, xc+x, yc+y) ;
end
#for (x = -xi + 1; x <= xi - 1; x++)
for x in -xi:(xi - 1)
y = sqrt(yo2 * (1.0 - x*x/xo2)) + 0.5 ;
z = sqrt(yi2 * (1.0 - x*x/xi2)) + 0.5 ;
result |= renderdrawline(renderer, xc+x, yc+z, xc+x, yc+y) ;
result |= renderdrawline(renderer, xc+x, yc-z, xc+x, yc-y) ;
end
#for (x = xo; x >= xi; x--)
for x in xo:-1:xi
y = sqrt(yo2 * (1.0 - x*x/xo2)) + 0.5 ;
result |= renderdrawline(renderer, xc+x, yc-y, xc+x, yc+y) ;
end
else
#for (y = -yo; y <= -yi; y++)
for y in -yo:-yi
x = sqrt(xo2 * (1.0 - y*y/yo2)) + 0.5 ;
result |= renderdrawline(renderer, xc-x, yc+y, xc+x, yc+y) ;
end
#for (y = -yi + 1; y <= yi - 1; y++)
for y in (-yi + 1):(yi - 1)
x = sqrt(xo2 * (1.0 - y*y/yo2)) + 0.5 ;
z = sqrt(xi2 * (1.0 - y*y/yi2)) + 0.5 ;
result |= renderdrawline(renderer, xc+z, yc+y, xc+x, yc+y) ;
result |= renderdrawline(renderer, xc-z, yc+y, xc-x, yc+y) ;
end
#for (y = yo; y >= yi; y--)
for y in yo:-1:yi;
x = sqrt(xo2 * (1.0 - y*y/yo2)) + 0.5 ;
result |= renderdrawline(renderer, xc-x, yc+y, xc+x, yc+y) ;
end
end
return result
end
#-============================================================================================================================================================
# function to draw anti-aliased filled ellipse
# int aaFilledEllipseRGBA(SDL_Renderer * renderer, float cx, float cy, float rx, float ry, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
#----------
function aaFilledEllipseRGBA(renderer::Ptr{SDL_Renderer}, cx::Int64, cy::Int64, rx::Int64, ry, r::Int64, g::Int64, b::Int64, a::Int64)
aaFilledEllipseRGBA(renderer,
convert(Float64, cx),
convert(Float64, cy),
convert(Float64, rx),
convert(Float64, ry),
convert(UInt8, r),
convert(UInt8, g),
convert(UInt8, b),
convert(UInt8, a)
)
end
#----------
function aaFilledEllipseRGBA(renderer::Ptr{SDL_Renderer}, cx::Float64, cy::Float64, rx::Float64, ry::Float64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
n::Int64 = 0
xi::Int64 = 0
yi::Int64 = 0
result::Int64 = 0
s::Float64 = 0
v::Float64 = 0
x::Float64 = 0
y::Float64 = 0
dx::Float64 = 0
dy::Float64 = 0
if ((rx <= 0.0) || (ry <= 0.0))
return -1 ;
end
result |= SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND) ;
if (rx >= ry)
n = ry + 1 ;
#for (yi = cy - n - 1; yi <= cy + n + 1; yi++)
for yi in (cy - n):1:(cy + n + 2)
if (yi < (cy - 0.5))
y = yi ;
else
y = yi + 1 ;
end
s = (y - cy) / ry ;
s = s * s ;
x = 0.5 ;
if (s < 1.0)
x = rx * sqrt(1.0 - s) ;
if (x >= 0.5)
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a ) ;
result |= renderdrawline(renderer, cx - x + 1, yi, cx + x - 1, yi) ;
end
end
s = 8 * ry * ry ;
dy = abs(y - cy) - 1.0 ;
xi = trunc(cx - x) ; # left
while (true)
dx = (cx - xi - 1) * ry / rx ;
v = s - 4 * (dx - dy) * (dx - dy) ;
if (v < 0)
break ;
end
v = (sqrt(v) - 2 * (dx + dy)) / 4 ;
if (v < 0)
break ;
end
if (v > 1.0)
v = 1.0 ;
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, truncInt(a * v) ) ;
result |= SDL_RenderDrawPoint(renderer, xi, yi) ;
xi -= 1 ;
end
xi = trunc(cx + x) ; # right
while (true)
dx = (xi - cx) * ry / rx ;
v = s - 4 * (dx - dy) * (dx - dy) ;
if (v < 0)
break ;
end
v = (sqrt(v) - 2 * (dx + dy)) / 4 ;
if (v < 0)
break ;
end
if (v > 1.0)
v = 1.0 ;
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, truncInt(a * v) ) ;
result |= SDL_RenderDrawPoint(renderer, xi, yi) ;
xi += 1 ;
end
end
else
n = rx + 1 ;
#for (xi = cx - n - 1; xi <= cx + n + 1; xi++)
for xi in (cx - n - 0):1:( cx + n + 2)
if (xi < (cx - 0.5))
x = xi ;
else
x = xi + 1 ;
end
s = (x - cx) / rx ;
s = s * s ;
y = 0.5 ;
if (s < 1.0)
y = ry * sqrt(1.0 - s) ;
if (y >= 0.5)
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a ) ;
result |= renderdrawline(renderer, xi, cy - y + 1, xi, cy + y - 1) ;
end
end
s = 8 * rx * rx ;
dx = abs(x - cx) - 1.0 ;
yi = trunc(cy - y) ; # top
while (true)
dy = (cy - yi - 1) * rx / ry ;
v = s - 4 * (dy - dx) * (dy - dx) ;
if (v < 0)
break ;
end
v = (sqrt(v) - 2 * (dy + dx)) / 4 ;
if (v < 0)
break ;
end
if (v > 1.0)
v = 1.0 ;
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, truncInt(a * v) ) ;
result |= SDL_RenderDrawPoint(renderer, xi, yi) ;
yi -= 1 ;
end
yi = trunc(cy + y) ; # bottom
while (true)
dy = (yi - cy) * rx / ry ;
v = s - 4 * (dy - dx) * (dy - dx) ;
if (v < 0)
break ;
end
v = (sqrt(v) - 2 * (dy + dx)) / 4 ;
if (v < 0)
break ;
end
if (v > 1.0)
v = 1.0 ;
break
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a * v) ;
result |= SDL_RenderDrawPoint(renderer, xi, yi) ;
yi += 1 ;
end
end
end
return result ;
end
#---------------------------
function renderdrawline(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64)
#ifndef __EMSCRIPTEN__
#= if ((x1 == x2) && (y1 == y2))
result = SDL_RenderDrawPoint (renderer, x1, y1) ;
else if (y1 == y2)
{
int x ;
if (x1 > x2) { x = x1 ; x1 = x2 ; x2 = x ; }
SDL_Point *points = (SDL_Point*) malloc ((x2 - x1 + 1) * sizeof(SDL_Point)) ;
if (points == NULL) return -1 ;
for (x = x1; x <= x2; x++)
{
points[x - x1].x = x ;
points[x - x1].y = y1 ;
}
result = SDL_RenderDrawPoints (renderer, points, x2 - x1 + 1) ;
free (points) ;
}
else if (x1 == x2)
{
int y ;
if (y1 > y2) { y = y1 ; y1 = y2 ; y2 = y ; }
SDL_Point *points = (SDL_Point*) malloc ((y2 - y1 + 1) * sizeof(SDL_Point)) ;
if (points == NULL) return -1 ;
for (y = y1; y <= y2; y++)
{
points[y - y1].x = x1 ;
points[y - y1].y = y ;
}
result = SDL_RenderDrawPoints (renderer, points, y2 - y1 + 1) ;
free (points) ;
}
else
=#
#endif
result = SDL_RenderDrawLine(renderer, x1, y1, x2, y2) ;
return result ;
end
#-----------
function renderdrawline(renderer::Ptr{SDL_Renderer}, x1::Float64, y1::Float64, x2::Float64, y2::Float64)
return SDL_RenderDrawLine(renderer,
truncInt(x1), # C would trunc floats to ints, so I'm not rounding
truncInt(y1),
truncInt(x2),
truncInt(y2)
)
end
#-===========================================================================================================================
# unfilled ellipse
function ellipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
return _ellipseRGBA(renderer, x, y, rx, ry, r, g, b, a, false);
end
#---------------
# filled ellipse
function filledEllipseRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, rx::Int64, ry::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
return _ellipseRGBA(renderer, x, y, rx, ry, r, g, b, a, true);
end
#-===========================================================================================================================
# unfilled circle
function circleRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, radius::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
return ellipseRGBA(renderer, x, y, radius, radius, r, g, b, a);
end
#---------------
# filled circle
function filledCircleRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, radius::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
return _ellipseRGBA(renderer, x, y, radius, radius, r, g ,b, a, true);
end
#-===========================================================================================================================
#-===========================================================================================================================
function thickLineRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, width::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
wh::Int64 = 1;
LineStyle::Int64 = -1;
if (renderer == C_NULL)
return -1;
end
if (width < 1)
return -1;
end
# Special case: thick "point"
if ((x1 == x2) && (y1 == y2))
wh = width / 2;
return boxRGBA(renderer, x1 - wh, y1 - wh, x2 + width, y2 + width, r, g, b, a);
end
# Set color
result = 0;
if (a != 255)
result |= SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
#
draw_varthick_line(renderer, LineStyle, x1, y1, x2, y2, convert(Float64, width));
return(result);
end
#-===========================================================================================================================
function draw_varthick_line(B::Ptr{SDL_Renderer}, style::Int64, x0::Int64,y0::Int64, x1::Int64, y1::Int64, thickness::Float64)
dx::Int64 = 0
dy::Int64 = 0
xstep::Int64 = 0
ystep::Int64 = 0
pxstep::Int64 = 0
pystep::Int64 = 0;
dx= x1-x0;
dy= y1-y0;
xstep= ystep= 1;
if (dx<0)
dx= -dx; xstep= -1;
end
if (dy<0)
dy= -dy; ystep= -1;
end
if (dx==0)
xstep= 0;
end
if (dy==0)
ystep= 0;
end
if (xstep + ystep*4) == ( -1 + -1*4 )
pystep= -1; pxstep= 1; # -5
elseif (xstep + ystep*4) == (-1 + 0*4)
pystep= -1; pxstep= 0; # -1
elseif (xstep + ystep*4) == (-1 + 1*4)
pystep= 1; pxstep= 1; # 3
elseif (xstep + ystep*4) == (0 + -1*4)
pystep= 0; pxstep= -1; # -4
elseif (xstep + ystep*4) == (0 + 0*4)
pystep= 0; pxstep= 0; # 0
elseif (xstep + ystep*4) == (0 + 1*4)
pystep= 0; pxstep= 1; # 4
elseif (xstep + ystep*4) == (1 + -1*4)
pystep= -1; pxstep= -1; # -3
elseif (xstep + ystep*4) == (1 + 0*4)
pystep= -1; pxstep= 0; # 1
elseif (xstep + ystep*4) == (1 + 1*4)
pystep= 1; pxstep= -1; # 5
end
#=
switch(xstep + ystep*4)
{
case -1 + -1*4 : pystep= -1; pxstep= 1; break; # -5
case -1 + 0*4 : pystep= -1; pxstep= 0; break; # -1
case -1 + 1*4 : pystep= 1; pxstep= 1; break; # 3
case 0 + -1*4 : pystep= 0; pxstep= -1; break; # -4
case 0 + 0*4 : pystep= 0; pxstep= 0; break; # 0
case 0 + 1*4 : pystep= 0; pxstep= 1; break; # 4
case 1 + -1*4 : pystep= -1; pxstep= -1; break; # -3
case 1 + 0*4 : pystep= -1; pxstep= 0; break; # 1
case 1 + 1*4 : pystep= 1; pxstep= -1; break; # 5
}
=#
if (dx>dy)
x_varthick_line(B,style,x0,y0,dx,dy,xstep,ystep,
thickness+1.0,
pxstep,pystep);
else
y_varthick_line(B,style,x0,y0,dx,dy,xstep,ystep,
thickness+1.0,
pxstep,pystep);
end
return;
end
#-===========================================================================================================================
function y_varthick_line(B::Ptr{SDL_Renderer},
style::Int64,
x0::Int64,
y0::Int64,
dx::Int64,
dy::Int64,
xstep::Int64,
ystep::Int64,
thickness::Float64,
pxstep::Int64,
pystep::Int64
)
p_error::Int64 = 0
error::Int64 = 0
x::Int64 = x0
y::Int64 = y0
threshold::Int64 = dy - 2*dx;
E_diag::Int64 = -2*dy
E_square::Int64 = 2*dx
length::Int64 = dy+1
p::Int64 = 0
D::Float64= sqrt(dx*dx+dy*dy);
w_left::Int64 = lrint(thickness*D + 0.5)
w_right::Int64 = lrint(2.0 * thickness*D + 0.5)
w_right -= w_left;
#=
D::Float64 = 0.0
p_error= 0;
error= 0;
y= y0;
x= x0;
threshold = dy - 2*dx;
E_diag= -2*dy;
E_square= 2*dx;
length = dy+1;
w_left= thickness*D + 0.5;
w_right= 2.0*thickness*D + 0.5;
=#
# for(p=0;p<length;p++)
for p in 0:1:length
style = (style << 1) | (style < 0);
if (style < 0)
y_perpendicular(B,x,y, dx, dy, pxstep, pystep, p_error,w_left,w_right,error);
end
if (error>=threshold)
x = x + xstep;
error = error + E_diag;
if (p_error>=threshold)
if (style < 0)
y_perpendicular(B, x, y, dx, dy, pxstep, pystep,
p_error+E_diag+E_square,
w_left, w_right, error);
end
p_error= p_error + E_diag;
end
p_error= p_error + E_square;
end
error = error + E_square;
y= y + ystep;
end
end
#-===========================================================================================================================
#-===========================================================================================================================
function y_perpendicular(B::Ptr{SDL_Renderer},
x0::Int64, y0::Int64, dx::Int64, dy::Int64, xstep::Int64, ystep::Int64,
einit::Int64, w_left::Int64, w_right::Int64, winit::Int64
)
threshold::Int64 = dy - 2*dx
E_diag::Int64 = -2*dy
E_square::Int64 = 2*dx
tk::Int64 = dx + dy + winit
error::Int64 = -einit
p::Int64 = 0
q::Int64 = 0;
y::Int64 = y0;
x::Int64 = x0;
while(tk<=w_left)
SDL_RenderDrawPoint(B,x,y);
if (error>threshold)
y= y + ystep;
error = error + E_diag;
tk= tk + 2*dx;
end
error = error + E_square;
x= x + xstep;
tk= tk + 2*dy;
q += 1
end
y= y0;
x= x0;
error = einit;
tk= dx + dy - winit;
while(tk<=w_right)
if (p > 0)
SDL_RenderDrawPoint(B,x,y);
end
if (error>=threshold)
y= y - ystep;
error = error + E_diag;
tk= tk + 2*dx;
end
error = error + E_square;
x= x - xstep;
tk= tk + 2*dy;
p +=1;
end
if (q==0 && p<2)
SDL_RenderDrawPoint(B,x0,y0); # we need this for very thin lines
end
end
#-============================================================================================================================================================
#-============================================================================================================================================================
function lineRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, r::UInt64, g::UInt64, b::UInt64, a::UInt64)
result::Int16 = 0;
if (a != 255)
result |= SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
end
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
return result;
end
#-============================================================================================================================================================
# This one works in Julia. Could not get _aalineRGBA to work at all without jaggies.
# below is the original from Mike Abrash's Black Box book
#renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, r::Int64, g::Int64, b::Int64, a::Int64, draw_endpoint::Bool)
function DrawWuLine(renderer::Ptr{SDL_Renderer}, X0::Int64, Y0::Int64, X1::Int64, Y1::Int64, r::UInt64, g::UInt64, b::UInt64, a::UInt64)
IntensityShift::UInt32 = 0
ErrorAdj::UInt32 = 0
ErrorAcc::UInt32 = 0;
ErrorAccTemp::UInt32 = 0
Weighting::UInt32 = 0
WeightingComplementMask::UInt32 = 0
DeltaX::Int32 = 0
DeltaY::Int32 = 0
Temp::Int32 = 0
XDir::Int32 = 0
#= Make sure the line runs top to bottom =#
if (Y0 > Y1)
Temp = Y0;
Y0 = Y1;
Y1 = Temp;
Temp = X0;
X0 = X1;
X1 = Temp;
end
#= Draw the initial pixel, which is always exactly intersected by the line and so needs no weighting =#
#DrawPixel(X0, Y0, BaseColor);
pixelRGBA(renderer, convert(Int64, X0), convert(Int64, Y0), r, g, b, a);
if ((DeltaX = X1 - X0) >= 0)
XDir = 1;
else
Dir = -1;
DeltaX = -DeltaX; #= make DeltaX positive =#
end
#= Special-case horizontal, vertical, and diagonal lines, which require no weighting because they go right through the center of every pixel =#
if ((DeltaY = Y1 - Y0) == 0)
#= Horizontal line =#
DeltaX -= 1
while (DeltaX != 0)
X0 += XDir;
pixelRGBA(renderer, convert(Int64, X0), convert(Int64, Y0), r, g, b, a)
DeltaX -= 1
end
return
end
if DeltaX == 0
# vertical line
while DeltaY != 0
Y0 += 1
pixelRGBA(renderer, convert(Int64, X0), convert(Int64, Y0), r, g, b, a)
DeltaY -= 1
end
return
end
if DeltaX == DeltaY
# diagonal line
while DeltaY != 0
X0 += XDir;
Y0 += 1
DeltaY -= 1
end
return
end
#= line is not horizontal, diagonal, or vertical =#
ErrorAcc =0 # initialize the line error accumulator to 0
# # of bits by which to shift ErrorAcc to get intensity level
IntensityShift = 16 - AAbits
#= Mask used to flip all bits in an intensity weighting, producing the
result (1 - intensity weighting) =#
WeightingComplementMask = AAlevels - 1;
#= Is this an X-major or Y-major line? =#
if (DeltaY > DeltaX)
#= Y-major line; calculate 16-bit fixed-point fractional part of a
pixel that X advances each time Y advances 1 pixel, truncating the
result so that we won't overrun the endpoint along the X axis =#
#ErrorAdj = ((unsigned long) DeltaX << 16) / (unsigned long) DeltaY; #= Draw all pixels other than the first and last =#
println(DeltaX,", ",DeltaY)
ErrorAdj = truncInt( ( DeltaX << 16) / DeltaY )
#= Draw all pixels other than the first and last =#
while (DeltaY > 0)
ErrorAccTemp = ErrorAcc; #= remember currrent accumulated error =#
ErrorAcc += ErrorAdj; #= calculate error for next pixel =#
if (ErrorAcc <= ErrorAccTemp)
#= The error accumulator turned over, so advance the X coord =#
X0 += XDir;
end
Y0 +=1; #= Y-major, so always advance Y =#
#= The IntensityBits most significant bits of ErrorAcc give us the
intensity weighting for this pixel, and the complement of the
weighting for the paired pixel =#
Weighting = ErrorAcc >> IntensityShift;
#DrawPixel(X0, Y0, BaseColor + Weighting);
pixelRGBAWeight(renderer, convert(Int64, X0), convert(Int64, Y0), r, g, b, a, convert(Int64, Weighting))
#DrawPixel(X0 + XDir, Y0, BaseColor + (Weighting ^ WeightingComplementMask));
pixelRGBAWeight(renderer, convert(Int64, X0 + XDir), convert(Int64, Y0), r, g, b, a, convert(Int64, Weighting ^ WeightingComplementMask) );
#pixelRGBAWeight(renderer, convert(Int64, X0 + XDir), convert(Int64, Y0), r, g, b, a, convert(Int64, wgt) );
DeltaY -= 1
end
#= Draw the final pixel, which is always exactly intersected by the line and so needs no weighting =#
pixelRGBA(renderer, convert(Int64, X1), convert(Int64, Y1), r, g, b, a)
return
end
#= It's an X-major line; calculate pixel that Y advances each time result to avoid overrunning the
16-bit fixed-point fractional part of a X advances 1 pixel, truncating the endpoint along the X axis =#
#ErrorAdj = ((unsigned long) DeltaY << 16) / (unsigned long) DeltaX; #= Draw all pixels other than the first and last =#
ErrorAdj = truncInt( ( DeltaY << 16) / DeltaX) #= Draw all pixels other than the first and last =#
DeltaX -= 1
#while (--DeltaX)
while DeltaX > 0
ErrorAccTemp = ErrorAcc; #= remember currrent accumulated error =#
ErrorAcc += ErrorAdj; #= calculate error for next pixel =#
if (ErrorAcc <= ErrorAccTemp)
#= The error accumulator turned over, so advance the Y coord =#
Y0 += 1
end
X0 += XDir; #= X-major, so always advance X =#
#= The IntensityBits most significant bits of ErrorAcc give us the
intensity weighting for this pixel, and the complement of the
weighting for the paired pixel =#
Weighting = ErrorAcc >> IntensityShift;
#DrawPixel(X0, Y0, BaseColor + Weighting);
#DrawPixel(X0, Y0 + 1, BaseColor + (Weighting ^ WeightingComplementMask));
pixelRGBAWeight(renderer, convert(Int64, X0), convert(Int64, Y0), r, g, b, a, convert(Int64, Weighting))
pixelRGBAWeight(renderer, convert(Int64, X0), convert(Int64, Y0 + 1), r, g, b, a, convert(Int64, Weighting ^ WeightingComplementMask) );
DeltaX -= 1
end
#= Draw the final pixel, which is always exactly intersected by the line and so needs no weighting =#
pixelRGBA(renderer, convert(Int64, X1), convert(Int64, Y1), r, g, b, a)
end
#-====================================================================================
# returns fractional part of any number.
function fpart( x::Float64)
return (x-floor(x))
end
#----
function rfpart( x::Float64)
return (1-fpart(x));
end
#----
# https://en.wikipedia.org/wiki/Talk%3AXiaolin_Wu%27s_line_algorithm
# void WULinesAlpha(double x1,double y1,double x2,double y2,Uint32 color,SDL_Surface* screen)
function WULinesAlpha(win::Window, x1::Float64, y1::Float64, x2::Float64, y2::Float64, colR::UInt8, colG::UInt8, colB::UInt8, colAlpha::UInt8)
vertical::Bool =false;
r::UInt8 = 0
g::UInt8 = 0
b::UInt8 = 0
# temporary Surface with alpha support.
# screen = SDL_GetWindowSurface(win)
# alpha = SDL_CreateRGBSurface(SDL_ALPHA_OPAQUE,WIDTH,HEIGHT,32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
#SDL_GetRGB(color,screen.format, r, g, b);
# new color but with alpha value.
#colorAlpha = SDL_MapRGBA(alpha.format,r,g,b,255);
orignalAlpha = colAlpha
#colorAlpha = SDL_Color(colR, colG, colB, colAlpha)
colorAlpha::Vector{UInt8} = [ colR, colG, colB, colAlpha]
# checking if this is a vertical or horizental line type.
if(abs(y2-y1)>abs(x2-x1))
vertical=true;
end
# make vertical lines horizental.
if (vertical)
temp = x1
x1 = y1
y1 = temp
temp = x2
x2 = y2
y2 = temp
end
# if x is decreasing swap x1 and x2;
if (x2 < x1)
temp = x1
x1 = x2
x2 = temp
temp = y1
y1 = y2
y2 = temp
end
# line WIDTH and HEIGHT!!!
dx::Int32 = lrint(x2 - x1);
dy::Int32 = lrint(y2 - y1);
# this is for calculating y from x ;)
gradient::Float64 = (dy) / (dx);
# handle first endpoint. endpoints will be handle seperately. cuz they are thricky.
# wu's line algorithm can draw lines with non integer start and end. so we need to
# have an integer to start with.
xend::Int32 = round(x1);
# some good y for end point this is also an int.
yend::Float64 = y1 + gradient * (xend - x1);
# xgap is simply pixel around integer
xgap::Float64 = rfpart(x1 + 0.5);
xpxl1::Int32 = xend; # this will be used in the main loop
# in original algorithm, ypxl1 was integer part of yend!!!
ypxl1::Int32 = floor(yend);
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255 * (rfpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255 * (rfpart(yend) * xgap))]
if(vertical)
#putPixel(ypxl1,xpxl1,colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, ypxl1), convert(Int64, xpxl1), r, g, b, a)
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1), colorAlpha)
#colorAlpha=SDL_MapRGBA(alpha->format,r,g,b,255*(fpart(yend) * xgap));
#colorAlpha[4] = 255*(fpart(yend) * xgap)
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
#putPixel(ypxl1 + 1, xpxl1, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, ypxl1+1), convert(Int64, xpxl1), r, g, b, a)
pixelColor(win.renderer, convert(Int64, xpxl1+1), convert(Int64, ypxl1), colorAlpha)
else
#putPixel(xpxl1, ypxl1,colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1), r, g, b, a)
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1), colorAlpha)
#colorAlpha=SDL_MapRGBA(alpha->format,r,g,b,255*(fpart(yend) * xgap));
#colorAlpha[4] = 255*(fpart(yend) * xgap)
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(yend) * xgap)) )
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
#putPixel(xpxl1, ypxl1 + 1, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1+1), r, g, b, a)
# <<<<<<<<<<<<<<<<<<<<, I think in here we can add the width. For horizontal-based lines, ypxl1+1 is the pixel
# <<<<<<<<<<<<<<<<<<<< we are merging into. We can insert a solid color here.
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1+1), colorAlpha)
end
# putPixel(xpxl1, ypxl1,colorAlpha,alpha);
intery::Float64 = yend + gradient; # first y-intersection for the main loop
# handle second endpoint
xend = round(x2);
yend = y2 + gradient * (xend - x2);
xgap = fpart(x2 + 0.5);
xpxl2::Int32 = xend; # this will be used in the main loop
ypxl2::Int32 = floor(yend);
# calculate color of pixel based in its distant from logical line.
#colorAlpha[4] = 255*(rfpart(yend) * xgap);
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(rfpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255*(rfpart(yend) * xgap))]
# following if, elses are for handling vertical and horizental lines:
if(vertical)
# first pixel
#putPixel(ypxl2, xpxl2, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, ypxl2), convert(Int64, xpxl2), r, g, b, a)
pixelColor(win.renderer, convert(Int64, ypxl2), convert(Int64, xpxl2), colorAlpha)
# calculate color of pixel based in its distant from logical line.
#colorAlpha[4] = 255*(fpart(yend) * xgap)
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
# second pixel
#putPixel(ypxl2 + 1,xpxl2, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, ypxl2+1), convert(Int64, xpxl2), r, g, b, a)
pixelColor(win.renderer, convert(Int64, ypxl2+1), convert(Int64, xpxl2), colorAlpha)
else # same as if.
#putPixel(xpxl2, ypxl2, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2), r, g, b, a)
pixelColor(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2), colorAlpha)
#colorAlpha[4] = 255*(fpart(yend) * xgap);
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
#putPixel(xpxl2, ypxl2 + 1, colorAlpha,alpha);
#pixelColorWeight(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2+1), color, colorAlpha)
pixelColor(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2+1), colorAlpha)
end
# main loop. this is where we draw the rest of the line. like end points
# we need to draw 2 pixel. and their alpha is calculaed from their distance
# ^^^ - this could be 2, 3, 8, 20, whatever. The in-between are solid
# fillers. For first pass, I would simply add filler, but that will offset the line
# Final version should center the line, so that instead of intery, we have intery-1, intery-4, etc.
# from logical line.
#for (int i=xpxl1+1;i<=xpxl2-1;i++)
for i in xpxl1+1:1:xpxl2
#colorAlpha[4] = 255*(rfpart(intery));
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(rfpart(intery))))
colorAlpha = [colR, colG, colB, lrint(255*(rfpart(intery)))]
if(vertical)
#putPixel(floor(intery),i, colorAlpha,alpha);
pixelColor(win.renderer, convert(Int64, floor(intery)), convert(Int64, i), colorAlpha)
#colorAlpha[4] = 255*( fpart(intery));
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(intery))))
colorAlpha = [colR, colG, colB, lrint(255*(fpart(intery)))]
#putPixel(floor(intery) + 1,i, colorAlpha,alpha);
pixelColor(win.renderer, convert(Int64, floor(intery+1)), convert(Int64, i), colorAlpha)
else
#putPixel(i,floor(intery), colorAlpha,alpha);
pixelColor(win.renderer, convert(Int64, i), convert(Int64, floor(intery)), colorAlpha)
#colorAlpha[4] = 255*( fpart(intery))
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(fpart(intery))))
colorAlpha = [colR, colG, colB, lrint(255*(fpart(intery)))]
#putPixel(i, floor(intery) + 1, colorAlpha,alpha);
pixelColor(win.renderer, convert(Int64, i), convert(Int64, floor(intery+1)), colorAlpha)
end
intery = intery + gradient;
end# end for now we need to blit alpha surface to original one
# SDL_BlitSurface(alpha,0,screen,0);
# SDL_FreeSurface(alpha);
end
#-..........................................................................................
# This clarified how to make the lines variable width https://github.com/jambolo/thick-xiaolin-wu/blob/master/cs/thick-xiaolin-wu.coffee
function WULinesAlphaWidth(win::Window, x1::Float64, y1::Float64, x2::Float64, y2::Float64, colR::UInt8, colG::UInt8, colB::UInt8, colAlpha::UInt8,width::Int64)
vertical::Bool =false;
r::UInt8 = 0
g::UInt8 = 0
b::UInt8 = 0
# for odd widths, we will start at -(w-1)/2. So a width of 3 starts at -1, width of 5 starts at -2, etc.
# for even widths, we will start at -(w-2)/2. So a width of 2 starts at 0, a width of 4 starts at -1, etc.
# If we were really cool, we would center Even lines by somehow antialiasing the sides (cut alpha in half?)
# in order to make the lines look centered at the start point instead of offset like we do here.
if width%2 == 0 # even
start = -(width-2)÷2 # integer division returns turncated int (like C)
else
start = -(width-1)÷2 # integer division returns turncated int (like C)
end
originalColor::Vector{UInt8} = [ colR, colG, colB, colAlpha]
#colorAlpha = SDL_Color(colR, colG, colB, colAlpha)
colorAlpha::Vector{UInt8} = [ colR, colG, colB, colAlpha]
# checking if this is a vertical or horizental line type.
if(abs(y2-y1)>abs(x2-x1))
vertical=true;
end
# make vertical lines horizental.
if (vertical)
temp = x1
x1 = y1
y1 = temp
temp = x2
x2 = y2
y2 = temp
end
# if x is decreasing swap x1 and x2;
if (x2 < x1)
temp = x1
x1 = x2
x2 = temp
temp = y1
y1 = y2
y2 = temp
end
# line WIDTH and HEIGHT!!!
dx::Int32 = lrint(x2 - x1);
dy::Int32 = lrint(y2 - y1);
# this is for calculating y from x ;)
gradient::Float64 = (dy) / (dx);
# handle first endpoint. endpoints will be handle seperately. cuz they are thricky.
# wu's line algorithm can draw lines with non integer start and end. so we need to
# have an integer to start with.
xend::Int32 = round(x1);
# some good y for end point this is also an int.
yend::Float64 = y1 + gradient * (xend - x1);
# xgap is simply pixel around integer
xgap::Float64 = rfpart(x1 + 0.5);
xpxl1::Int32 = xend; # this will be used in the main loop
# in original algorithm, ypxl1 was integer part of yend!!!
ypxl1::Int32 = floor(Int32, yend);
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255 * (rfpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255 * (rfpart(yend) * xgap))]
if(vertical)
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1), colorAlpha)
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
pixelColor(win.renderer, convert(Int64, xpxl1+1), convert(Int64, ypxl1), colorAlpha)
else
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1), colorAlpha)
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
#putPixel(xpxl1, ypxl1 + 1, colorAlpha,alpha);
#pixelRGBA(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1+1), r, g, b, a)
pixelColor(win.renderer, convert(Int64, xpxl1), convert(Int64, ypxl1+1), colorAlpha)
end
# putPixel(xpxl1, ypxl1,colorAlpha,alpha);
intery::Float64 = yend + gradient; # first y-intersection for the main loop
# handle second endpoint
xend = round(x2);
yend = y2 + gradient * (xend - x2);
xgap = fpart(x2 + 0.5);
xpxl2::Int32 = xend; # this will be used in the main loop
ypxl2::Int32 = floor(yend);
# calculate color of pixel based in its distant from logical line.
#colorAlpha[4] = 255*(rfpart(yend) * xgap);
#colorAlpha = SDL_Color(colR, colG, colB, lrint(255*(rfpart(yend) * xgap)))
colorAlpha = [colR, colG, colB, lrint(255*(rfpart(yend) * xgap))]
# following if, elses are for handling vertical and horizental lines:
if(vertical)
# first pixel
pixelColor(win.renderer, convert(Int64, ypxl2), convert(Int64, xpxl2), colorAlpha)
# calculate color of pixel based in its distant from logical line.
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
# second pixel
pixelColor(win.renderer, convert(Int64, ypxl2+1), convert(Int64, xpxl2), colorAlpha)
else # same as if.
pixelColor(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2), colorAlpha)
colorAlpha = [colR, colG, colB, lrint(255*(fpart(yend) * xgap))]
pixelColor(win.renderer, convert(Int64, xpxl2), convert(Int64, ypxl2+1), colorAlpha)
end
# main loop. this is where we draw the rest of the line. like end points
# we need to draw 2 pixel. and their alpha is calculaed from their distance
# ^^^ - this could be 2, 3, 8, 20, whatever. The in-between are solid
# fillers. For first pass, I would simply add filler, but that will offset the line
# Final version should center the line, so that instead of intery, we have intery-1, intery-4, etc.
# from logical line.
#for (int i=xpxl1+1;i<=xpxl2-1;i++)
for i in xpxl1+1:1:xpxl2
colorAlpha = [colR, colG, colB, lrint(255*(rfpart(intery)))]
if(vertical)
# pixelColor( renderer, x, y, color)
pixelColor(win.renderer, convert(Int64, floor(intery+start)), convert(Int64, i), colorAlpha)
#This is how we add the width. Only sides are antialiased.
for w in 1:(width-1)
pixelColor(win.renderer, convert(Int64, floor(intery+start+w)), convert(Int64, i), originalColor)
end
colorAlpha = [colR, colG, colB, lrint(255*(fpart(intery)))]
pixelColor(win.renderer, convert(Int64, floor(intery+start+width)), convert(Int64, i), colorAlpha)
else
pixelColor(win.renderer, convert(Int64, i), convert(Int64, floor(intery+start)), colorAlpha) # x, intery , rfpart
for w in 1:(width-1)
pixelColor(win.renderer, convert(Int64, i), convert(Int64, floor(intery+start+w)), originalColor)
end
colorAlpha = [colR, colG, colB, lrint(255*(fpart(intery)))]
pixelColor(win.renderer, convert(Int64, i), convert(Int64, floor(intery+start+width)), colorAlpha) # x, intery + w, fpart
end
intery = intery + gradient;
end# end for now we need to blit alpha surface to original one
end
#pixelColorWeight
#=
# main loop
if steep
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel y , x, rfpart
drawPixel y + i, x, 1 for i in [1...w]
drawPixel y + w, x, fpart
intery = intery + gradient
else
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel x, y , rfpart
drawPixel x, y + i, 1 for i in [1...w]
drawPixel x, y + w, fpart
intery = intery + gradient
return
=#
#-====================================================================================
#-====================================================================================
#= ---- Rounded Rectangle =#
#=!
\brief Draw rounded-corner rectangle with blending.
\param renderer The renderer to draw on.
\param x1 X coordinate of the first point (i.e. top right) of the rectangle.
\param y1 Y coordinate of the first point (i.e. top right) of the rectangle.
\param x2 X coordinate of the second point (i.e. bottom left) of the rectangle.
\param y2 Y coordinate of the second point (i.e. bottom left) of the rectangle.
\param radius The radius of the corner arc.
\param color The color value of the rectangle to draw (0xRRGGBBAA).
\returns Returns 0 on success, -1 on failure.
=#
function roundedRectangleColor(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, color::SDL_Color)
#Uint8 *c = (Uint8 *)&color;
return aaRoundRectangleRGBA(renderer, x1, y1, x2, y2, radius, color.r, color.g, color.b, color.a);
end
#=!
\brief Draw rounded-corner rectangle with blending.
\param renderer The renderer to draw on.
\param x1 X coordinate of the first point (i.e. top right) of the rectangle.
\param y1 Y coordinate of the first point (i.e. top right) of the rectangle.
\param x2 X coordinate of the second point (i.e. bottom left) of the rectangle.
\param y2 Y coordinate of the second point (i.e. bottom left) of the rectangle.
\param radius The radius of the corner arc.
\param r The red value of the rectangle to draw.
\param g The green value of the rectangle to draw.
\param b The blue value of the rectangle to draw.
\param a The alpha value of the rectangle to draw.
\returns Returns 0 on success, -1 on failure.
=#
#function roundedRectangleRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
function aaRoundRectangleRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
#Sint16 tmp;
#Sint16 w, h;
#Sint16 xx1, xx2;
#Sint16 yy1, yy2;
#=
* Check renderer
=#
if (renderer == C_NULL)
return -1;
end
#=
* Check radius for valid range
=#
if (radius < 0)
return -1;
end
#=
* Special case - no rounding
=#
if (radius <= 1)
return rectangleRGBA(renderer, x1, y1, x2, y2, r, g, b, a);
end
#=
* Test for special cases of straight lines or single point
=#
if (x1 == x2)
if (y1 == y2)
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
else
return (vlineRGBA(renderer, x1, y1, y2, r, g, b, a));
end
else
if (y1 == y2)
return (hlineRGBA(renderer, x1, x2, y1, r, g, b, a));
end
end
#=
* Swap x1, x2 if required
=#
if (x1 > x2)
tmp = x1;
x1 = x2;
x2 = tmp;
end
#=
* Swap y1, y2 if required
=#
if (y1 > y2)
tmp = y1;
y1 = y2;
y2 = tmp;
end
#=
* Calculate width&height
=#
w = x2 - x1;
h = y2 - y1;
#=
* Maybe adjust radius
=#
if ((radius * 2) > w)
radius = w / 2;
end
if ((radius * 2) > h)
radius = h / 2;
end
#=
* Draw corners
=#
xx1 = x1 + radius;
xx2 = x2 - radius;
yy1 = y1 + radius;
yy2 = y2 - radius;
result |= arcRGBA(renderer, xx1, yy1, radius, 180, 270, r, g, b, a);
result |= arcRGBA(renderer, xx2, yy1, radius, 270, 360, r, g, b, a);
result |= arcRGBA(renderer, xx1, yy2, radius, 90, 180, r, g, b, a);
result |= arcRGBA(renderer, xx2, yy2, radius, 0, 90, r, g, b, a);
#=
* Draw lines
=#
if (xx1 <= xx2)
result |= hlineRGBA(renderer, xx1, xx2, y1, r, g, b, a);
result |= hlineRGBA(renderer, xx1, xx2, y2, r, g, b, a);
end
if (yy1 <= yy2)
result |= vlineRGBA(renderer, x1, yy1, yy2, r, g, b, a);
result |= vlineRGBA(renderer, x2, yy1, yy2, r, g, b, a);
end
return result;
end
#1810
#=
from ellipse
result |= pixelRGBAWeight(renderer, xp, yp, r, g, b, a, iweight);
result |= pixelRGBAWeight(renderer, xx, yp, r, g, b, a, iweight);
=#
#-===========================================================================
function pixelColor(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, color::SDL_Color)
#Uint8 *c = (Uint8 *)&color;
return pixelRGBA(renderer, x, y, color.r, color.g, color.b, color.a);
end
#-=====================
#=!
\brief Draw pixel with blending enabled if a<255.
\param renderer The renderer to draw on.
\param x X (horizontal) coordinate of the pixel.
\param y Y (vertical) coordinate of the pixel.
\param r The red color value of the pixel to draw.
\param g The green color value of the pixel to draw.
\param b The blue color value of the pixel to draw.
\param a The alpha value of the pixel to draw.
\returns Returns 0 on success, -1 on failure.
=#
function pixelRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawPoint(renderer, x, y);
return result;
end
#-=====================
function pixel(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64)
return SDL_RenderDrawPoint(renderer, x, y);
end
#-=====================
function hlineRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, x2::Int64, y::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawLine(renderer, x1, y, x2, y);
return result;
end
#----------
function vlineRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y1::Int64, y2::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
result |= SDL_RenderDrawLine(renderer, x, y1, x, y2);
return result;
end
#-============================================================================================================
function aaRoundRectRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
# Check renderer
if (renderer == C_NULL)
return -1;
end
SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
#----------
# Check radius for valid range
if (radius < 0)
return -1;
end
#----------
# Special case - no rounding of corners
if (radius <= 1)
return rectangleRGBA(renderer, x1, y1, x2, y2, r, g, b, a);
end
#----------
# Test for special cases of straight lines or single point
if (x1 == x2)
if (y1 == y2)
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
else
return (vlineRGBA(renderer, x1, y1, y2, r, g, b, a));
end
else
if (y1 == y2)
return (hlineRGBA(renderer, x1, x2, y1, r, g, b, a));
end
end
#----------
# Swap x1, x2 if required
if (x1 > x2)
tmp = x1;
x1 = x2;
x2 = tmp;
end
#----------
# Swap y1, y2 if required
if (y1 > y2)
tmp = y1;
y1 = y2;
y2 = tmp;
end
#----------
# Calculate width&height
w = x2 - x1;
h = y2 - y1;
#----------
# Maybe adjust radius
if ((radius * 2) > w)
radius = w / 2;
end
if ((radius * 2) > h)
radius = h / 2;
end
#----------
# Now we start with Matt's stuff
# Draw Sides
#----------
# left side
vlineRGBA(renderer, x1, y1+radius-1, y2-radius+1, r, g, b, a)
#----------
# right side
vlineRGBA(renderer, x2, y1+radius-1, y2-radius+1, r, g, b, a)
# bottom side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y1, r, g, b, a)
# top side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y2, r, g, b, a)
#----------
# Below is the Wu aa circle algorithm adapted to draw the corners
radiusY = radius # circle
radiusX2 = radius * radius;
radiusY2 = radiusY * radiusY;
#maxTransparency::Float64 = 127;
maxTransparency::Float64 = 255;
quarter = round(radiusX2 / sqrt(radiusX2 + radiusY2));
#for(float _x = 0; _x <= quarter; _x++)
for _x in 0:1:quarter
_y = radiusY * sqrt(1 - _x * _x / radiusX2);
error = _y - floor(_y);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
#(renderer,cx, cy, _x, floor(_y), r, g, b, alpha)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y),
r, g, b, alpha)
#setRoundRectPixel4(renderer,cx, cy, _x, floor(_y) - 1, r, g, b, alpha2)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y) - 1,
r, g, b, alpha2)
end
quarter = round(radiusY2 / sqrt(radiusX2 + radiusY2));
#for(float _y = 0; _y <= quarter; _y++) {
for _y in 0:1:quarter
_x = radius * sqrt(1 - _y * _y / radiusY2);
error = _x - floor(_x);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
#setRoundRectPixel4(renderer, cx, cy, floor(_x), _y, r, g, b, alpha)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x), _y,
r, g, b, alpha)
#setRoundRectPixel4(renderer, cx, cy, floor(_x) - 1, _y, r, g, b, alpha2)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x)- 1, _y,
r, g, b, alpha2)
end
#=
#----------
# draw corners
# top left
cx::Float64 = x1 + radius
cy::Float64 = y1 + radius
startAng = 180
endAng = 270
for deg in startAng:10:endAng
radians = deg2rad(deg)
x = cx + (cos(radians) * radius)
y = cy + (sin(radians) * radius)
pixelRGBAfloat(renderer, x, y, r, g, b, a)
end
#----------
# top right
cx = x2 - radius
cy = y1 + radius
startAng = 270
endAng = 360
for deg in startAng:10:endAng
radians = deg2rad(deg)
x = cx + (cos(radians) * radius)
y = cy + (sin(radians) * radius)
pixelRGBAfloat(renderer, x, y, r, g, b, a)
end
#----------
# bottom right
cx = x2 - radius
cy = y2 - radius
startAng = 0
endAng = 90
for deg in startAng:10:endAng
radians = deg2rad(deg)
x = cx + (cos(radians) * radius)
y = cy + (sin(radians) * radius)
pixelRGBAfloat(renderer, x, y, r, g, b, a)
end
#----------
# bottom left
cx = x1 + radius
cy = y2 - radius
startAng = 90
endAng = 180
for deg in startAng:10:endAng
radians = deg2rad(deg)
x = cx + (cos(radians) * radius)
y = cy + (sin(radians) * radius)
pixelRGBAfloat(renderer, x, y, r, g, b, a)
end
=#
end
#-============================================================================================================
#
# The logic behind this is to draw two rounded rects into a matrix. Then, starting at the top, and doing
# it seperately for the left and the right, find the points with the highest alpha. Go one over and fill
# between with a horizontal line.
function aaRoundRectRGBAThick(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, thickness::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
# Check renderer
if (renderer == C_NULL)
return -1;
end
SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
#----------
# Check radius for valid range
if (radius < 0)
return -1;
end
#----------
# Special case - no rounding of corners
if (radius <= 1)
return rectangleRGBA(renderer, x1, y1, x2, y2, r, g, b, a);
end
#----------
# Test for special cases of straight lines or single point
if (x1 == x2)
if (y1 == y2)
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
else
return (vlineRGBA(renderer, x1, y1, y2, r, g, b, a));
end
else
if (y1 == y2)
return (hlineRGBA(renderer, x1, x2, y1, r, g, b, a));
end
end
#----------
# Swap x1, x2 if required
if (x1 > x2)
tmp = x1;
x1 = x2;
x2 = tmp;
end
#----------
# Swap y1, y2 if required
if (y1 > y2)
tmp = y1;
y1 = y2;
y2 = tmp;
end
#----------
# Calculate width&height
w = x2 - x1;
h = y2 - y1;
#----------
# Maybe adjust radius
if ((radius * 2) > w)
radius = w ÷ 2; # ÷ is integer divide in Julia. // in Python is integer divide, but in Julia it is fractions (rational number)
end
if ((radius * 2) > h)
radius = h ÷ 2;
end
#----------
# check to see if thickness is 1 or 2. If one, call the regular function, if 2, call the regular function twice
if thickness == 1
aaRoundRectRGBA(renderer, x1, y1, x2, y2, radius, r, g, b, a)
return 0
elseif thickness == 2
aaRoundRectRGBA(renderer, x1, y1, x2, y2, radius, r, g, b, a)
aaRoundRectRGBA(renderer, x1+1, y1+1, x2-1, y2-1, radius-1, r, g, b, a)
return 0
end
alphaMatrix = zeros((w+1, h+1))
x1orig = x1
y1orig = y1
x2orig = x2
y2orig = y2
radiusOrig = radius
thicknesses = [0, thickness]
for thick in thicknesses # the first run does the outer one, then it steps down by the thickness.
# Now we start with Matt's stuff
# Draw Sides
x1 += thick
y1 += thick
x2 -= thick
y2 -= thick
radius -= thick # somehow it became a float at some point
#----------
# Below is the Wu aa circle algorithm adapted to draw the corners
radiusY = radius # circle
radiusX2 = radius * radius;
radiusY2 = radiusY * radiusY;
#maxTransparency::Float64 = 127;
maxTransparency::Float64 = 255;
quarter = round(radiusX2 / sqrt(radiusX2 + radiusY2));
#for(float _x = 0; _x <= quarter; _x++)
for _x in 0:1:quarter
_y = radiusY * sqrt(1 - _x * _x / radiusX2);
error = _y - floor(_y);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
#(renderer,cx, cy, _x, floor(_y), r, g, b, alpha)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y),
r, g, b, alpha)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
_x, floor(_y),
thick,
alpha)
#setRoundRectPixel4(renderer,cx, cy, _x, floor(_y) - 1, r, g, b, alpha2)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y) - 1,
r, g, b, alpha2)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
_x, floor(_y) - 1,
thick,
alpha2)
end
quarter = round(radiusY2 / sqrt(radiusX2 + radiusY2));
#for(float _y = 0; _y <= quarter; _y++) {
for _y in 0:1:quarter
_x = radius * sqrt(1 - _y * _y / radiusY2);
error = _x - floor(_x);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
#setRoundRectPixel4(renderer, cx, cy, floor(_x), _y, r, g, b, alpha)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x), _y,
r, g, b, alpha)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
floor(_x), _y,
thick,
alpha)
#setRoundRectPixel4(renderer, cx, cy, floor(_x) - 1, _y, r, g, b, alpha2)#, data, areasData, false);
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x)- 1, _y,
r, g, b, alpha2)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
floor(_x)- 1, _y,
thick,
alpha2)
end
# Draw lines last, as some of the anti-aliasing was erasing parts
#----------
# left side
vlineRGBA(renderer, x1, y1+radius-1, y2-radius+1, r, g, b, a) # r, g, b, a)
alphaMatrix = vMatrix(alphaMatrix, x1, y1, x1, y1+radius-1, y2-radius+1, thick, a)
#----------
# right side
vlineRGBA(renderer, x2, y1+radius-1, y2-radius+1, r, g, b, a)
alphaMatrix = vMatrix(alphaMatrix, x1, y1, x2, y1+radius-1, y2-radius+1, thick, a)
# bottom side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y1, r, g, b, a)
alphaMatrix = hMatrix(alphaMatrix, x1, y1, x1+radius-1, x2-radius+1, y1, thick, a)
# top side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y2, r, g, b, a)
alphaMatrix = hMatrix(alphaMatrix, x1, y1, x1+radius-1, x2-radius+1, y2, thick, a)
#find the maximum bunds of corners in case a faint anti-alias is being plotted
end
#-------------
# Next, do the horizontal fills. Split matrix in half, and draw horiz between highest 2 values.
#alphaMatrix = zeros((w+1, h+1))
# start at the left hand side+1, find where it goes from max to zero
for y in 2:(h-1)
cX = 1
startX = 1
endX = round(Int64,w/2)
done = false
alphaMax = 0
while !done
cX += 1
if cX == round(Int64,w/2)
done = true
elseif alphaMatrix[cX-1,y] > alphaMax && alphaMatrix[cX,y] == 0
alphaMax = alphaMatrix[cX-1,y]
done = true
startX = cX-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cX += 1
if cX >= round(Int64,w/2)
cX = endX
done = true # stop at midline
elseif alphaMatrix[cX-1,y] == 0 && alphaMatrix[cX,y]> alphaMax # find next side
alphaMax = alphaMatrix[cX,y]
done = true
endX = cX
end
end
if(endX - startX) <= thickness+3 # prevents gaps and bleedthroughs
#hlineRGBA(renderer, x1orig + startX, x1orig + endX-1, y1orig + y-1, 0, 0, 255, 127) #r, g, b, a)
hlineRGBA(renderer, x1orig + startX-1, x1orig + endX-1, y1orig + y-1, r, g, b, a) #r, g, b, a)
end
end
#------------------------
# now the right-hand side
for y in 2:(h-0)
cX = round(Int64,w/2)
startX = 1
endX = -99
done = false
alphaMax = 0
while !done
cX += 1
if cX == w
done = true
elseif alphaMatrix[cX-1,y] > alphaMax && alphaMatrix[cX,y] == 0
alphaMax = alphaMatrix[cX-1,y]
done = true
startX = cX-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cX += 1
if cX > w+1
cX = endX
done = true # stop at midline
elseif alphaMatrix[cX-1,y] == 0 && alphaMatrix[cX,y]> alphaMax # find next side
alphaMax = alphaMatrix[cX,y]
done = true
endX = cX
end
end
if(endX - startX) <= thickness+3 # prevents gaps and bleedthroughs
# hlineRGBA(renderer, x1orig + startX, x1orig + endX-1, y1orig + y-1, 0, 0, 255, 127) #r, g, b, a)
if endX != -99
hlineRGBA(renderer, x1orig + startX-1, x1orig + endX-1, y1orig + y-1, r, g, b, a) #r, g, b, a)
end
end
end
#------------------------
# now the top
for x in 2:(w-1)
cY = 1
startY = 1
endY = round(Int64,h/2)
done = false
alphaMax = 0
while !done
cY += 1
if cY == round(Int64,h/2)
done = true
elseif alphaMatrix[x, cY-1] > alphaMax && alphaMatrix[x, cY] == 0
alphaMax = alphaMatrix[x, cY-1]
done = true
startY = cY-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cY += 1
if cY >= round(Int64,h/2)
cY = endY
done = true # stop at midline
elseif alphaMatrix[x, cY-1] == 0 && alphaMatrix[x, cY]> alphaMax # find next side
alphaMax = alphaMatrix[x, cY]
done = true
endY = cY
end
end
if(endY - startY) <= thickness+3 # prevents gaps and bleedthroughs
#vlineRGBA(renderer, x1orig + x-1, y1orig + startY, y1orig + endY-1, 0, 0, 255, 127) #r, g, b, a)
vlineRGBA(renderer, x1orig + x-1, y1orig + startY-1, y1orig + endY-1, r, g, b, a) #r, g, b, a)
end
end
#------------------------
# finally the bottom
for x in 2:(w-0)
cY = round(Int64,h/2)
startY = 1
endY = -99
done = false
alphaMax = 0
while !done
cY += 1
if cY == h
done = true
elseif alphaMatrix[x, cY-1] > alphaMax && alphaMatrix[x, cY] == 0
alphaMax = alphaMatrix[x, cY-1]
done = true
startY = cY-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cY += 1
if cY > h+1
cY = endY
done = true # stop at midline
elseif alphaMatrix[x, cY-1] == 0 && alphaMatrix[x, cY]> alphaMax # find next side
alphaMax = alphaMatrix[x, cY]
done = true
endY = cY
end
end
if(endY - startY) <= thickness+3 # prevents gaps and bleedthroughs
#vlineRGBA(renderer, x1orig + x-1, y1orig + startY, y1orig + endY-1, 0, 0, 255, 127) #r, g, b, a)
if endY != -99
vlineRGBA(renderer, x1orig + x-1, y1orig + startY-1, y1orig + endY-1, r, g, b, a) #r, g, b, a)
end
end
end
#=
#---------- Debug lines below
x1 = x1orig
y1 = y1orig
x2 = x2orig
y2 = y2orig
radius = radiusOrig
for thick in thicknesses # the first run does the outer one, then it steps down by the thickness.
# Now we start with Matt's stuff
# Draw Sides
x1 += thick
y1 += thick
x2 -= thick
y2 -= thick
radius -= thick # somehow it became a float at some point
# Draw lines last, as some of the anti-aliasing was erasing parts
#----------
# left side
vlineRGBA(renderer, x1, y1+radius-1, y2-radius+1, 0, 0, 255, 255) # r, g, b, a)
#----------
# right side
vlineRGBA(renderer, x2, y1+radius-1, y2-radius+1, 0, 0, 255, 255)
# bottom side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y1, 0, 0, 255, 255)
# top side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y2, 0, 0, 255, 255)
#find the maximum bunds of corners in case a faint anti-alias is being plotted
end
=#
#=
for y in 1:h
# find top 2 peaks for left
max1 = 0
max2 = 0
foundX1 = 1
foundX1 = 2
for x in 1:round(Int64,w/2)
if alphaMatrix[x,y] > max1
max1 = alphaMatrix[x,y]
foundX1 = x # index of found
end
if alphaMatrix[x,y] > max2 && alphaMatrix[x,y] <-=
=#
# save("gray.png", colorview(Gray, alphaMatrix/255))
end
#-==================================================================================
function aaFilledRoundRectRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, radius::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
result::Int64 = 0;
# Check renderer
if (renderer == C_NULL)
return -1;
end
SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
#----------
# Check radius for valid range
if (radius < 0)
return -1;
end
#----------
# Special case - no rounding of corners
if (radius <= 1)
return rectangleRGBA(renderer, x1, y1, x2, y2, r, g, b, a);
end
#----------
# Test for special cases of straight lines or single point
if (x1 == x2)
if (y1 == y2)
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
else
return (vlineRGBA(renderer, x1, y1, y2, r, g, b, a));
end
else
if (y1 == y2)
return (hlineRGBA(renderer, x1, x2, y1, r, g, b, a));
end
end
#----------
# Swap x1, x2 if required
if (x1 > x2)
tmp = x1;
x1 = x2;
x2 = tmp;
end
#----------
# Swap y1, y2 if required
if (y1 > y2)
tmp = y1;
y1 = y2;
y2 = tmp;
end
#----------
# Calculate width&height
w = x2 - x1;
h = y2 - y1;
#----------
# Maybe adjust radius
if ((radius * 2) > w)
radius = w ÷ 2; # ÷ is integer divide in Julia. // in Python is integer divide, but in Julia it is fractions (rational number)
end
if ((radius * 2) > h)
radius = h ÷ 2;
end
#----------
alphaMatrix = zeros((w+1, h+1))
x1orig = x1
y1orig = y1
x2orig = x2
y2orig = y2
radiusOrig = radius
# Now we start with Matt's stuff
# Draw Sides
#----------
# Below is the Wu aa circle algorithm adapted to draw the corners
radiusY = radius # circle
radiusX2 = radius * radius;
radiusY2 = radiusY * radiusY;
maxTransparency::Float64 = 255;
quarter = round(radiusX2 / sqrt(radiusX2 + radiusY2));
#for(float _x = 0; _x <= quarter; _x++)
for _x in 0:1:quarter
_y = radiusY * sqrt(1 - _x * _x / radiusX2);
error = _y - floor(_y);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y),
r, g, b, alpha)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
_x, floor(_y),
0,
alpha)
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
_x, floor(_y) - 1,
r, g, b, alpha2)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
_x, floor(_y) - 1,
0,
alpha2)
end
quarter = round(radiusY2 / sqrt(radiusX2 + radiusY2));
for _y in 0:1:quarter
_x = radius * sqrt(1 - _y * _y / radiusY2);
error = _x - floor(_x);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x), _y,
r, g, b, alpha)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
floor(_x), _y,
0,
alpha)
setRoundRectPixel4(renderer,
x1, y1,
x2, y2,
radius,
floor(_x)- 1, _y,
r, g, b, alpha2)
setRoundRectMAtrix(alphaMatrix,
x1, y1,
x2, y2,
radius,
floor(_x)- 1, _y,
0,
alpha2)
end
# Draw lines last, as some of the anti-aliasing was erasing parts
#----------
# left side
vlineRGBA(renderer, x1, y1+radius-1, y2-radius+1, r, g, b, a) # r, g, b, a)
alphaMatrix = vMatrix(alphaMatrix, x1, y1, x1, y1+radius-1, y2-radius+1, 0, a)
#----------
# right side
vlineRGBA(renderer, x2, y1+radius-1, y2-radius+1, r, g, b, a)
alphaMatrix = vMatrix(alphaMatrix, x1, y1, x2, y1+radius-1, y2-radius+1, 0, a)
# bottom side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y1, r, g, b, a)
alphaMatrix = hMatrix(alphaMatrix, x1, y1, x1+radius-1, x2-radius+1, y1, 0, a)
# top side
hlineRGBA(renderer, x1+radius-1, x2-radius+1, y2, r, g, b, a)
alphaMatrix = hMatrix(alphaMatrix, x1, y1, x1+radius-1, x2-radius+1, y2, 0, a)
#-------------
# Next, do the horizontal fills. Unlike the thick one, we do not need to split the matrix in half
#alphaMatrix = zeros((w+1, h+1))
# start at the left hand side+1, find where it goes from max to zero
for y in 2:h
cX = 1
startX = 1
endX = -99
done = false
alphaMax = 0
while !done
cX += 1
if cX == w
done = true
elseif alphaMatrix[cX-1,y] > alphaMax && alphaMatrix[cX,y] == 0
alphaMax = alphaMatrix[cX-1,y]
done = true
startX = cX-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cX += 1
if cX >= w+1
cX = endX
done = true # stop at midline
elseif alphaMatrix[cX-1,y] == 0 && alphaMatrix[cX,y]> alphaMax # find next side
alphaMax = alphaMatrix[cX,y]
done = true
endX = cX
end
end
if endX != -99
hlineRGBA(renderer, x1orig + startX-1, x1orig + endX-1, y1orig + y-1, r, g, b, a) #r, g, b, a)
end
end
#------------------------
#------------------------
# now vertical
for x in 1:w
cY = 1
startY = 1
endY = -99
done = false
alphaMax = 0
while !done
cY += 1
if cY == h
done = true
elseif alphaMatrix[x, cY-1] > alphaMax && alphaMatrix[x, cY] == 0
alphaMax = alphaMatrix[x, cY-1]
done = true
startY = cY-1
end
end
done = false
alphaMax = 0
while !done # find righthand side
cY += 1
if cY > h+1
cY = endY
done = true # stop at midline
elseif alphaMatrix[x, cY-1] == 0 && alphaMatrix[x, cY]> alphaMax # find next side
alphaMax = alphaMatrix[x, cY]
done = true
endY = cY
end
end
if endY != -99 # prevents gaps and bleedthroughs
vlineRGBA(renderer, x1orig + x-1, y1orig + startY-1, y1orig + endY-1, r, g, b, a) #r, g, b, a)
end
end
end
#-===================================
# filling vertical matrix as if we drew into it
# should rewrite these as in-place functions, i.e. vMatrix!()
function vMatrix(matrix, left, top, x1, y1, y2, thick, alpha)
x = x1- left +1 + thick
startY::Int64 = y1-top +1
endY::Int64 = y2-top + 1
for y in startY:endY
matrix[x,y+ thick] = alpha
end
return matrix
end
#-----------
function hMatrix(matrix, left, top, x1, x2, y1, thick, alpha)
y = y1- top +1 + thick
startX::Int64 = x1-left +1
endX::Int64 = x2-left + 1
for x in startX:endX
matrix[x+ thick,y] = alpha
end
return matrix
end
#-----------
# one down, 2 over for left top
# draw the alpha values of the round corners into a matrix
function setRoundRectMAtrix(matrix,
left::Int64, top::Int64,
right::Int64, bot::Int64,
radius::Int64,
dx::Float64, dy::Float64,
thick::Int64,
alpha::Int64)
# This draws all 4 quarters of a round rect at once.
if alpha > 0
leftBitmap = left
topBitmap = top
left = radius +0 + thick # +1
right -= radius
right -= leftBitmap
# right -= thick
right += thick
right += 2
# right -= 1
top = radius +0 + thick # +1
bot -= radius
bot -= topBitmap
# bot -= thick
bot += thick
bot += 2
# bot -= 1
dxInt = round(Int64, dx)
dyInt = round(Int64, dy)
matrix[right + dxInt, bot + dyInt] = alpha
matrix[left - dxInt, bot + dyInt] = alpha
matrix[right + dxInt, top - dyInt] = alpha
matrix[left - dxInt, top - dyInt] = alpha
end
return matrix
end
#=
left += radius
right -= radius
top += radius
bot -= radius
=#
#-====================================================================================================================
# 1 extend lines by 1 pixel
#=
radius -= 1
left += radius
right -= radius
top += radius
bot -= radius
pixelRGBAfloat(renderer, right + dx, bot + dy, r, g, b, a)
pixelRGBAfloat(renderer, left - dx, bot + dy, r, g, b, a)
pixelRGBAfloat(renderer, right + dx, top - dy, r, g, b, a)
pixelRGBAfloat(renderer, left - dx, top - dy, r, g, b, a)
=#
#-===================================
function wuAACircle(renderer::Ptr{SDL_Renderer}, cx::Float64, cy::Float64, radiusX::Float64, startDeg::Float64, endDeg::Float64, r::Int64, g::Int64, b::Int64, a::Int64)
#float radiusX = endRadius;
#float radiusY = endRadius;
radiusY = radiusX # circle
radiusX2 = radiusX * radiusX;
radiusY2 = radiusY * radiusY;
maxTransparency::Float64 = 255; #
quarter = round(radiusX2 / sqrt(radiusX2 + radiusY2));
#for(float _x = 0; _x <= quarter; _x++)
for _x in 0:1:quarter
_y = radiusY * sqrt(1 - _x * _x / radiusX2);
error = _y - floor(_y);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
setPixel4(renderer,cx, cy, _x, floor(_y), r, g, b, alpha)#, data, areasData, false);
setPixel4(renderer,cx, cy, _x, floor(_y) - 1, r, g, b, alpha2)#, data, areasData, false);
end
quarter = round(radiusY2 / sqrt(radiusX2 + radiusY2));
#for(float _y = 0; _y <= quarter; _y++) {
for _y in 0:1:quarter
_x = radiusX * sqrt(1 - _y * _y / radiusY2);
error = _x - floor(_x);
transparency = round(error * maxTransparency);
alpha::Int64 = round(transparency)
alpha2::Int64 = round(Int64, maxTransparency - transparency)
setPixel4(renderer, cx, cy, floor(_x), _y, r, g, b, alpha)#, data, areasData, false);
setPixel4(renderer, cx, cy, floor(_x) - 1, _y, r, g, b, alpha2)#, data, areasData, false);
end
end
#-===========================
function setPixel4(renderer::Ptr{SDL_Renderer}, centerX::Float64, centerY::Float64, deltaX::Float64, deltaY::Float64, r::Int64, g::Int64, b::Int64, a::Int64)
# This draws all 4 quarters of a circle at once.
pixelRGBAfloat(renderer, centerX + deltaX, centerY + deltaY, r, g, b, a)
pixelRGBAfloat(renderer, centerX - deltaX, centerY + deltaY, r, g, b, a)
pixelRGBAfloat(renderer, centerX + deltaX, centerY - deltaY, r, g, b, a)
pixelRGBAfloat(renderer, centerX - deltaX, centerY - deltaY, r, g, b, a)
end
#-===========================
# instead of drawing the 4 quarters with the same center to make a circle,
# it uses the 4 corners of the rect to make the corners of a round rect
function setRoundRectPixel4(renderer::Ptr{SDL_Renderer},
left::Int64, top::Int64,
right::Int64, bot::Int64,
radius::Int64,
dx::Float64, dy::Float64,
r::Int64, g::Int64, b::Int64, a::Int64)
# This draws all 4 quarters of a round rect at once.
#radius -= 1
left += (radius -1)
right -= (radius-1)
top += (radius -1)
bot -= (radius -1)
pixelRGBAfloat(renderer, right + dx, bot + dy, r, g, b, a)
pixelRGBAfloat(renderer, left - dx, bot + dy, r, g, b, a)
pixelRGBAfloat(renderer, right + dx, top - dy, r, g, b, a)
pixelRGBAfloat(renderer, left - dx, top - dy, r, g, b, a)
end
#-==============================================================================================
# BELOW ARE COMMENTED-OUT POTENTIAL DELETABLE FUNCTIONS
#-==============================================================================================
#=
#- ===================================================================================================================================
#function arcRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, radius::Int64, startDeg::Int64, endDeg::Int64, r::UInt8, g::UInt8, b::UInt8, a::UInt8)
function arcRGBA(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64, radius::Int64, startDeg::Int64, endDeg::Int64, r::Int64, g::Int64, b::Int64, a::Int64)
println("\n start arcRGBA")
cx::Int16 = 0;
cy = convert(Int16, radius)
df = 1 - radius;
d_e = 3;
d_se = -2 * radius + 5;
#Sint16 xpcx, xmcx, xpcy, xmcy;
#Sint16 ypcy, ymcy, ypcx, ymcx;
#Uint8 drawoct;
startoct::Int64 = 0
endoct::Int64 = 0
oct::Int64 = 0
stopval_start::Int64 = 0
stopval_end::Int64 = 0
dstart::Float64 = 0
dend::Float64 = 0
temp::Float64 = 0
#=
* Sanity check radius
=#
if (radius < 0)
return (-1);
end
#=
* Special case for radius=0 - draw a point
=#
if (radius == 0)
return (pixelRGBA(renderer, x, y, r, g, b, a));
end
#=
Octant labeling
\ 5 | 6 /
\ | /
4 \ | / 7
\|/
------+------ +x
/|\
3 / | \ 0
/ | \
/ 2 | 1 \
+y
Initially reset bitmask to 0x00000000
the set whether or not to keep drawing a given octant.
For example: 0x00111100 means we're drawing in octants 2-5
=#
drawoct::UInt8 = 0;
#=
* Fixup angles
=#
startDeg %= 360;
endDeg %= 360;
#= 0 <= start & end < 360; note that sometimes start > end - if so, arc goes back through 0. =#
while (startDeg < 0)
startDeg += 360;
end
while (endDeg < 0)
endDeg += 360;
end
startDeg %= 360;
endDeg %= 360;
#= now, we find which octants we're drawing in. =#
startoct = startDeg / 45;
endoct = endDeg / 45;
oct = startoct - 1;
#= stopval_start, stopval_end; what values of cx to stop at. =#
done = false
while done == false
oct = (oct + 1) % 8;
if (oct == startoct)
#= need to compute stopval_start for this octant. Look at picture above if this is unclear =#
dstart = Float64(startDeg)
if oct == 3
temp = sin(dstart * π / 180.);
elseif oct == 6
temp = cos(dstart * π / 180.);
elseif oct == 5
temp = -cos(dstart * π / 180.);
elseif oct == 7
temp = -sin(dstart * π / 180.);
end
temp *= radius;
stopval_start = Int64(round(temp));
#=
This isn't arbitrary, but requires graph paper to explain well.
The basic idea is that we're always changing drawoct after we draw, so we
stop immediately after we render the last sensible pixel at x = ((int)temp).
and whether to draw in this octant initially
=#
println("pre oct %2 ", oct ,", ", drawoct)
if oct % 2 != 0 #= this is basically like saying drawoct[oct] = true, if drawoct were a bool array =#
drawoct |= 1 << oct
else
drawoct &= 255 - (1 << oct) #= this is basically like saying drawoct[oct] = false =#
end
println("oct %2 ", oct % 2,", ", drawoct)
if (oct == endoct)
#= need to compute stopval_end for this octant =#
dend = Float64(endDeg)
if oct == 3
temp = sin(dend * π / 180);
elseif oct == 6
temp = cos(dend * π / 180);
elseif oct == 5
temp = -cos(dend * π / 180);
elseif oct == 7
temp = -sin(dend * π / 180);
end
temp *= radius;
stopval_end = Int64(temp);
#= and whether to draw in this octant initially =#
if startoct == endoct
# note: we start drawing, stop, then start again in this case
# otherwise: we only draw in this octant, so initialize it to false, it will get set back to true
if startDeg > endDeg
# unfortunately, if we're in the same octant and need to draw over the whole circle,
# we need to set the rest to true, because the while loop will end at the bottom.
drawoct = 255
else
drawoct &= 255 - (1 << oct)
end
elseif (oct % 2)
drawoct &= 255 - (1 << oct);
else
drawoct |= (1 << oct);
end
elseif oct != startoct #&& oct != endoct
drawoct |= 1 << oct
end
if oct == endoct
done = true
end
end
#while (oct != endoct);
#= so now we have what octants to draw and when to draw them. all that's left is the actual raster code. =#
#=
* Set color
=#
result = 0;
result |= SDL_SetRenderDrawBlendMode(renderer, (a == 255) ? SDL_BLENDMODE_NONE : SDL_BLENDMODE_BLEND);
result |= SDL_SetRenderDrawColor(renderer, r, g, b, a);
#=
* Draw arc
=#
done2 = false
#do
while done2 == false
ypcy = y + cy;
ymcy = y - cy;
if cx > 0
xpcx = x + cx
xmcx = x - cx
# always check if we're drawing a certain octant before adding a pixel to that octant.
if drawoct & 4 != 0
result |= pixel(renderer, xmcx, ypcy)
@printf("drawoct & 4 != 0, x,y = [%d, %d]\n", xmcx, ypcy)
end
if drawoct & 2 != 0
result |= pixel(renderer, xpcx, ypcy)
@printf("drawoct & 2 != 0, x,y = [%d, %d]\n", xpcx, ypcy)
end
if drawoct & 32 != 0
result |= pixel(renderer, xmcx, ymcy)
@printf("drawoct & 32 != 0, x,y = [%d, %d]\n", xmcx, ymcy)
end
if drawoct & 64 != 0
result |= pixel(renderer, xpcx, ymcy)
@printf("drawoct & 64 != 0, x,y = [%d, %d], \n", xpcx, ymcy )
end
else
if drawoct & 96 != 0
result |= pixel(renderer, x, ymcy)
@printf("drawoct & 96 != 0, x,y = [%d, %d]\n", x, ymcy)
end
if drawoct & 6 != 0
result |= pixel(renderer, x, ypcy)
@printf("drawoct & 6 != 0, x,y = [%d, %d]\n", x, ypcy)
end
end
xpcy = x + cy;
xmcy = x - cy;
if (cx > 0 && cx != cy)
ypcx = y + cx;
ymcx = y - cx;
println("drawoct & 8", drawoct,", ", drawoct & 8)
if (drawoct & 8) != 0
result |= pixel(renderer, xmcy, ypcx)
@printf("drawoct & 8 != 0, x,y = [%d, %d]\n", xmcy, ypcx)
end
if (drawoct & 1) != 0
result |= pixel(renderer, xpcy, ypcx)
@printf("drawoct & 1 != 0, x,y = [%d, %d]\n", xpcy, ypcx)
end
if (drawoct & 16) != 0
result |= pixel(renderer, xmcy, ymcx)
@printf("drawoct & 16 != 0, x,y = [%d, %d]\n", xmcy, ymcx)
end
if (drawoct & 128) != 0
result |= pixel(renderer, xpcy, ymcx)
@printf("drawoct & 128 != 0, x,y = [%d, %d]\n", xpcy, ymcx)
end
elseif (cx == 0)
if (drawoct & 24) != 0
result |= pixel(renderer, xmcy, y)
@printf("drawoct & 24 != 0, x,y = [%d, %d]\n", xmcy, y)
end
if (drawoct & 129) != 0
result |= pixel(renderer, xpcy, y)
@printf("drawoct & 129 != 0, x,y = [%d, %d]\n", xpcy, y)
end
end
#=
* Update whether we're drawing an octant
=#
if (stopval_start == cx)
#= works like an on-off switch. =#
#= This is just in case start & end are in the same octant. =#
if (drawoct & (1 << startoct)) == 1
drawoct &= 255 - (1 << startoct);
else
drawoct |= (1 << startoct)
end
println("drawoct 1: ", drawoct)
end
if (stopval_end == cx)
if (drawoct & (1 << endoct)) != 0
drawoct &= 255 - (1 << endoct);
else
drawoct |= (1 << endoct);
end
println("drawoct 2: ", drawoct)
end
#=
* Update pixels
=#
if (df < 0)
df += d_e;
d_e += 2;
d_se += 2;
else
df += d_se;
d_e += 2;
d_se += 4;
cy -= 1;
end
cx += 1;
if (cx > cy)
done2 = true
end
end #while (cx <= cy);
return (result);
end
end # just for fun
#-============================================================================================================================================================
function _aalineRGBA(renderer::Ptr{SDL_Renderer}, x1::Int64, y1::Int64, x2::Int64, y2::Int64, r::Int64, g::Int64, b::Int64, a::Int64, draw_endpoint::Bool)
result::Int32 = 0;
intshift::Int32 = 0
erracc::Int32 = 0
erracctmp::Int32 = 0
wgt::Int32 = 0
dx::UInt32 = 0
dy::UInt32 = 0
tmp::Int32 = 0
xdir::Int32 = 0
y0p1::Int32 = 0
x0pxdir::Int32 = 0
#=
* Keep on working with 32bit numbers
=#
xx0::Int32 = x1;
yy0::Int32 = y1;
xx1::Int32 = x2;
yy1::Int32 = y2;
#=
* Reorder points to make dy positive
=#
if (yy0 > yy1)
tmp = yy0;
yy0 = yy1;
yy1 = tmp;
tmp = xx0;
xx0 = xx1;
xx1 = tmp;
end
#=
* Calculate distance
=#
dx = xx1 - xx0;
dy = yy1 - yy0;
#=
* Adjust for negative dx and set xdir
=#
if (dx >= 0)
xdir = 1;
else
xdir = -1;
dx = (-dx);
end
#=
* Check for special cases
=#
if (dx == 0)
#=
* Vertical line
=#
if (draw_endpoint)
return (vlineRGBA(renderer, x1, y1, y2, r, g, b, a));
else
if (dy > 0)
return (vlineRGBA(renderer, x1, yy0, yy0+dy, r, g, b, a));
else
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
end
end
elseif (dy == 0)
#=
* Horizontal line
=#
if (draw_endpoint)
return (hlineRGBA(renderer, x1, x2, y1, r, g, b, a));
else
if (dx > 0)
return (hlineRGBA(renderer, xx0, xx0+(xdir*dx), y1, r, g, b, a));
else
return (pixelRGBA(renderer, x1, y1, r, g, b, a));
end
end
elseif ((dx == dy) && (draw_endpoint))
#=
* Diagonal line (with endpoint)
=#
return (lineRGBA(renderer, x1, y1, x2, y2, r, g, b, a));
end
#=
* Line is not horizontal, vertical or diagonal (with endpoint)
=#
result = 0;
#=
* Zero accumulator
=#
erracc = 0;
#=
* # of bits by which to shift erracc to get intensity level
=#
intshift = 32 - AAbits;
#=
* Draw the initial pixel in the foreground color
=#
result |= pixelRGBA(renderer, x1, y1, r, g, b, a);
#=
* x-major or y-major?
=#
if (dy > dx)
#=
* y-major. Calculate 16-bit fixed point fractional part of a pixel that
* X advances every time Y advances 1 pixel, truncating the result so that
* we won't overrun the endpoint along the X axis
=#
#=
* Not-so-portable version: erradj = ((Uint64)dx << 32) / (Uint64)dy;
=#
#erradj = ((dx << 16) / dy) << 16;
erradj = (dx << 32) / dy
#=
* draw all pixels other than the first and last
=#
x0pxdir = xx0 + xdir;
#while (--dy)
println("\n dy: ", dy,"\n")
while (dy > 0) # << what does this do?
dy -= 1
erracctmp = erracc;
erracc += trunc(erradj);
if (erracc <= erracctmp)
#=
* rollover in error accumulator, x coord advances
=#
xx0 = x0pxdir;
x0pxdir += xdir;
end
yy0 += 1; #= y-major so always advance Y =#
#=
* the AAbits most significant bits of erracc give us the intensity
* weighting for this pixel, and the complement of the weighting for
* the paired pixel.
=#
wgt = (erracc >> intshift) & 255;
result |= pixelRGBAWeight(renderer, convert(Int64, xx0 ), convert(Int64, yy0 ), r, g, b, a, 255 - wgt);
result |= pixelRGBAWeight(renderer, convert(Int64, x0pxdir), convert(Int64, yy0), r, g, b, a, convert(Int64, wgt) );
end
else
#=
* x-major line. Calculate 16-bit fixed-point fractional part of a pixel
* that Y advances each time X advances 1 pixel, truncating the result so
* that we won't overrun the endpoint along the X axis.
=#
#=
* Not-so-portable version: erradj = ((Uint64)dy << 32) / (Uint64)dx;
=#
#erradj = ((dy << 16) / dx) << 16;
erradj = (dx << 32) / dy
#=
* draw all pixels other than the first and last
=#
y0p1 = yy0 + 1;
#while (--dx)
while (dx -= 1)
erracctmp = erracc;
erracc += erradj;
if (erracc <= erracctmp)
#=
* Accumulator turned over, advance y
=#
yy0 = y0p1;
y0p1 += 1;
end
xx0 += xdir; #= x-major so always advance X =#
#=
* the AAbits most significant bits of erracc give us the intensity
* weighting for this pixel, and the complement of the weighting for
* the paired pixel.
=#
wgt = (erracc >> intshift) & 255;
result |= pixelRGBAWeight(renderer, convert(Int64, xx0), convert(Int64, yy0), r, g, b, a, 255 - wgt);
result |= pixelRGBAWeight(renderer, convert(Int64, xx0), convert(Int64, y0p1), r, g, b, a, convert(Int64, wgt) );
end
end
#=
* Do we have to draw the endpoint
=#
if (draw_endpoint)
#=
* Draw final pixel, always exactly intersected by the line and doesn't
* need to be weighted.
=#
result |= pixelRGBA(renderer, x2, y2, r, g, b, a);
end
return (result);
end
=# | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 9779 | # From: https://github.com/GPUWorks/SDL_GUI/blob/e9f7eca21fad733ad4444aede354162dbd175ac1/Source/SDL_TTF_utf8wrapsize.cpp#L16
# Translated to Julia by Matt Peterson, February 2024
using SDL2_ttf_jll
const lineSpace = 2;
function character_is_delimiter(c::Char, delimiters::String)
for d in delimiters
if c == d
return true
end
end
return false
end
#--------------------
function ttf_size_utf8_wrappedAI(font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font}, text::String, wrap_length::Int64)
if isempty(text) || wrap_length == 0
error("Text has zero width or invalid wrap length")
end
wrap_length *= 2 # retina
# Assuming TTF_SizeUTF8 is a function that returns the width and height of the text
# This function needs to be defined or replaced with an equivalent in Julia
#width, height = TTF_SizeUTF8(font, text)
width = Ref{Cint}()
height = Ref{Cint}()
TTF_SizeUTF8(font, text, width, height)
line_space = 2
num_lines = 1
wrap_delims = [' ', '\t', '\r', '\n'] #" \t\r\n"
str_lines = []
str_len = length(text)
str = text
tok = 1
end_pos = str_len
while tok <= end_pos
line_end = findfirst(isequal('\n'), str[tok:end])
if line_end === nothing # === means "is"
line_end = end_pos
else
line_end += tok - 1
end
# Wrap the line if necessary
if wrap_length > 0 && (line_end - tok + 1) > wrap_length
# Find the last delimiter before the wrap length
wrap_spot = tok + wrap_length - 1
while wrap_spot > tok && !character_is_delimiter(str[wrap_spot], wrap_delims)
wrap_spot -= 1
end
if wrap_spot == tok
wrap_spot = tok + wrap_length - 1
end
push!(str_lines, str[tok:wrap_spot])
tok = wrap_spot + 1
else
push!(str_lines, str[tok:line_end])
tok = line_end + 1
end
num_lines += 1
end
# Calculate the final width and height
if num_lines > 1
final_width = wrap_length
else
final_width = width[]
end
final_height = height[] + (num_lines - 1) * (height[] + line_space)
return final_width, final_height
end
# *w = (numLines > 1) ? wrapLength : width;
# *h = height * numLines + (lineSpace * (numLines - 1));
#=
#-********************************* AI version above
function TTF_SizeUTF8_Wrapped(TTF_Font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font},
text::String,
w::Ptr{Int64}, # *w,
h::Ptr{Int64}, #int *h,
wrapLength::Int64)
status = 0;
#int width, height;
width = Ref{Cint}()
height = Ref{Cint}()
#int numLines;
#char *str, **strLines;
# Get the dimensions of the text surface */
if isempty(text) || wrap_length == 0
error("Text has zero width or invalid wrap length")
end
numLines = 1;
str = C_NULL;
strLines = C_NULL;
if (wrapLength > 0 && length(text) >0 )
wrapDelims = " \t\r\n";
#int w, h;
int line = 0;
#char *spot, *tok, *next_tok, *endText;
#char delim;
#str_len = SDL_strlen(text);
str_len = length(text);
numLines = 0;
str = SDL_stack_alloc(char, str_len + 1);
if (str == NULL)
TTF_SetError("Out of memory");
return -1;
end
SDL_strlcpy(str, text, str_len + 1);
tok = str;
endText = str + str_len;
do
strLines = (char **)SDL_realloc(strLines, (numLines + 1) * sizeof(*strLines));
if (!strLines)
TTF_SetError("Out of memory");
return -1;
end
strLines[numLines++] = tok;
# Look for the end of the line */
if ((spot = SDL_strchr(tok, '\r')) != NULL ||
(spot = SDL_strchr(tok, '\n')) != NULL)
if (*spot == '\r')
++spot;
end
if (*spot == '\n')
++spot;
end
else
spot = endText;
end
next_tok = spot;
# Get the longest string that will fit in the desired space */
for (; ; )
# Strip trailing whitespace */
while (spot > tok && CharacterIsDelimiter(spot[-1], wrapDelims))
--spot;
end
if (spot == tok)
if (CharacterIsDelimiter(*spot, wrapDelims))
*spot = '\0';
end
break;
end
delim = *spot;
*spot = '\0';
TTF_SizeUTF8(font, tok, &w, &h);
if ((Uint32)w <= wrapLength)
break;
else
# Back up and try again... */
*spot = delim;
end
while (spot > tok &&
!CharacterIsDelimiter(spot[-1], wrapDelims))
--spot;
end
if (spot > tok)
next_tok = spot;
end
end
tok = next_tok;
end while (tok < endText);
end
if numLines > 1
w[] = wrap_length
else
w[] = width[]
end
#*w = (numLines > 1) ? wrapLength : width;
h[] = height * numLines + (lineSpace * (numLines - 1));
return status;
end
=#
#-===============================================================================
# From: https://github.com/davidsiaw/SDL2_ttf/commit/5f5e8d09095f6ba03f1b92ce1349509d54165d53
# Translated to Julia by Matt Peterson, February 2024
#=
function SDL_bool GetDimensionsOfWrappedTextSurface(width_p::Int64,
height_p::Int64,
text::String,
TTF_Font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font},
numLines_p::Int64,
strLines_p::String,
str::String,
size_t str_len::Int64,
wrapLength::Uint32)
w = Ref{Cint}()
h = Ref{Cint}()
# Get the dimensions of the text surface
#if ( (TTF_SizeUTF8(font, text, &(*width_p), &(*height_p)) < 0) || !(*width_p) )
if ( (TTF_SizeUTF8(font, text, w, h) < 0) || width_p <= 0 )
TTF_SetError("Text has zero width");
return(SDL_FALSE);
end
width_p = 0; # set this to zero. we will find out what the longest line is
numLines_p = 1;
strLines_p = C_NULL;
if ( wrapLength > 0 && length(text) > 0 )
const char *wrapDelims = " \t\r\n";
int w, h;
int line = 0;
char *spot, *tok, *next_tok, *end;
char delim;
*numLines_p = 0;
if ( str == NULL )
TTF_SetError("Out of memory");
return(SDL_FALSE);
end
SDL_strlcpy(str, text, str_len+1);
tok = str;
end = str + str_len;
do
size_t size = (*numLines_p+1)*sizeof(*(*strLines_p));
*strLines_p = (char **)SDL_realloc(*strLines_p, size);
if (!(*strLines_p))
TTF_SetError("Out of memory");
return(SDL_FALSE);
end
(*strLines_p)[(*numLines_p)++] = tok;
# Look for the end of the line
if ((spot = SDL_strchr(tok, '\r')) != NULL || (spot = SDL_strchr(tok, '\n')) != NULL)
if (*spot == '\r')
++spot;
end
if (*spot == '\n')
++spot;
end
else
spot = end;
end
next_tok = spot;
# Get the longest string that will fit in the desired space
for ( ; ; )
# Strip trailing whitespace
while ( spot > tok && CharacterIsDelimiter(spot[-1], wrapDelims) )
--spot;
end
if ( spot == tok )
if (CharacterIsDelimiter(*spot, wrapDelims))
*spot = '\0';
end
break;
end
delim = *spot;
*spot = '\0';
TTF_SizeUTF8(font, tok, &w, &h);
if ((Uint32)w <= wrapLength)
if (w > *width_p)
*width_p = w;
end
break;
else
# Back up and try again...
*spot = delim;
end
while ( spot > tok &&
!CharacterIsDelimiter(spot[-1], wrapDelims) )
--spot;
end
if ( spot > tok )
next_tok = spot;
end
end
tok = next_tok;
end while (tok < end);
end
return SDL_TRUE;
end
#-=====================================================================================================
function TTF_SizeUTF8_Wrapped(TTF_Font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font},
text::String,
wrapLength::Int64,
w::Ptr{Int64}, # *w,
h::Ptr{Int64}, #int *h,
lineCount::Ptr{Int64} #int *lineCount)
)
TTF_CHECKPOINTER(text, NULL);
str = C_NULL;
if (wrapLength > 0 && text)
str_len = SDL_strlen(text);
str = SDL_stack_alloc(char, str_len+1);
end
get_dimension_result = GetDimensionsOfWrappedTextSurface(w,
h,
text,
font,
lineCount,
&strLines,
str,
str_len,
wrapLength);
if (!get_dimension_result)
return(-1);
end
*h *= *lineCount;
return 0;
end
=# | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 15304 | # code for testing the PsychoJL module during development
# working prototype should be abale to draw square, circle, text, pictures and get keyboard input
println("------------------------------------ starting new run --------------------------------------")
using PsychExpAPIs
using SimpleDirectMediaLayer
using SimpleDirectMediaLayer.LibSDL2
using SDL2_ttf_jll
using SDL2_gfx_jll
using Revise
using JET
using Printf
#=
√ missing textbox
√ need down arrows for pop-ups
√ button is missing text
√ need to center OK button at 75%
√ add Cancel button at 25%
√ fix pop-up text and highlighting
√ add event loop
√ change draw functions to just "draw" so I can loop through them
√ add mouse-driven focus
need to return struct full of values
change the spacing of the labels and widgets so that they are closer to eachother
have Window size be based on number of widgets
make pop-ups and text entries prettier
=#
# look at thick lines
# overload int and float versions
#-----------------
const Sint16 = Int16
const Uint8 = UInt8
#println(libsdl2)
libsdl2 ="/Library/Frameworks/SDL.framework/Versions/A/SDL"
function aalineRGBA(renderer, x1, y1, x2, y2, r, g, b, a)
ccall((:aalineRGBA, libsdl2), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, r, g, b, a)
end
#/Users/MattPetersonsAccount/Documents/Development/Julia/PaddleBattle.jl-master/libs/libSDL2-2.0.0.dylib
#-----------------
function DemoWindow()
# resp, entry_text = inputDialog("Subject ID: ", "000")
#println(resp, entry_text)
# displayMessage(" a message")
# displayError(" an error")
# displayWarning(" a warning")
InitPsychoJL()
infoMessage("This is some important information.")
happyMessage("Thank-you for participating.\nYou are free to go.")
warningMessage("Something suspicious happened.")
errorMessage("Critical error: your CPU is melting.\nPlease call the fire department at your earliest convenience.")
#------------------------------------------
exp_info = Dict("subject_nr"=>0, "age"=>0, "handedness"=>("right","left","ambi"),
"gender"=>("male","female","other","prefer not to say"))
new_info = DlgFromDict(exp_info)
println("\n New experiment info from dialog: \n\t", new_info)
displayMessage( "Something happened")
#------------------------------------------
#IDnumber = textInputDialog( "Enter the subject ID number", "000")
#println("Id number received is", IDnumber)
myWin = Window( [2560, 1440], false) # 2560, 1440 [1000,1000]
reportedSize = getSize(myWin)
println("getSize() Window size = ", reportedSize )
newColor = colorToSDL(myWin, "powderblue")
t1 = TextStim(myWin, "powderblue", [100, 300], color = "powderblue")
t2 = TextStim(myWin, "255, 128, 0 ,255", [100, 400], color = [255, 128, 0 ,255])
#t3 = TextStimExp(myWin, "[0, 0.5, 1.0 ,1.0]", [100, 500], color = [0, 0.5, 1.0 ,1.0])
draw(t1)
draw(t2)
c1 = Circle(myWin, [2560, 1440], 200, lineWidth=1, lineColor = [127, 255, 127, 255], fillColor = "green", fill = true)
draw(c1)
c2 = Circle(myWin, [reportedSize[1], reportedSize[2]], 200, lineWidth=1, lineColor = [255, 127, 127, 255], fillColor = "red", fill = true)
draw(c2)
#draw(t3)
flip(myWin)
println("text color = ", newColor)
getKey(myWin)
setColor(t1, "brown")
draw(t1)
flip(myWin)
println("text color = ", newColor)
getKey(myWin)
SDL_SetWindowResizable(myWin.win, SDL_TRUE) # sets it as a resiable Window. Scales contents when resized
#-------- **********************************************
LipsumString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
LipsumText = TextStim(myWin, LipsumString, [100, 300], color = [255, 255, 255])
draw(LipsumText, wrapLength = 500)
LipsumRect = Rect(myWin, 500, 500, [350,282], lineColor = [255,255,0, 255], fillColor = [0,0,0,255], opacity = 0.5 )
draw(LipsumRect)
flip(myWin)
getKey(myWin)
#-------- **********************************************
# renderer = SDL_CreateRenderer(myWin.win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)
mRect = SDL_Rect(250, 150, 200, 200) # wacky Julia struct constructor; x,y, widht, height
wuAACircle(myWin.renderer,
150.0,
600.0,
50.0,
0.0,
90.0,
255, 255, 255, 255)
aaRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
100,
700,
200,
750,
20,
255, 128, 0, 255)
aaRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
102,
702,
198,
748,
18,
255, 128, 0, 255)
aaRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
100,
800,
200,
850,
10,
255, 128, 0, 255)
aaRoundRectRGBAThick(myWin.renderer, #roundedRectangleRGBA
100,
900,
200,
950,
20,
4,
255, 255, 0, 255)
aaRoundRectRGBAThick(myWin.renderer, #roundedRectangleRGBA
100,
600,
300,
675,
30,
7,
255, 255, 0, 255)
aaFilledRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
500,
700,
968,
768,
17,
131, 149, 247, 255)
#454, 54
aaFilledRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
507,
707,
961,
761,
13,
64, 135, 247, 255)
aaRoundRectRGBA(myWin.renderer, #roundedRectangleRGBA
507,
707,
961,
761,
13,
45, 97, 228, 255)
buttonText = TextStim(myWin,
"OK",
[734, 734],
color = [255, 255, 255],
fontSize = 24,
horizAlignment = 0,
vertAlignment = 0,
style = "bold")
draw(buttonText)
#=
TextBox( t::String, font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font}, color::SDL_Color, renderer::Ptr{SDL_Renderer}, wrapWidth::Int64)
myfont = myWin.font
#char CharArray[2000]; // Create a char array
#strcpy_s(CharArray, t.c_str()); // Convert the string into a char array for the surface function.
Surface = TTF_RenderText_Blended_Wrapped(font, t, color, wrapWidth); # Make into a surface.
Texture = SDL_CreateTextureFromSurface(renderer, Surface); # Turn the surface into a texture.
TTF_SizeText(font, CharArray, &w, &h); # Size the texture so it renders the text correctly.
end
=#
psychoRect = Rect(myWin, 100, 100, [400,400], lineColor = [255,0,0], fillColor = [255,128,128] )
SDL_SetRenderDrawColor(myWin.renderer, 255, 255, 255, 255);
#SDL_RenderDrawRect(renderer, mRect)
SDL_RenderDrawRect(myWin.renderer, Ref{SDL_Rect}(mRect)) # that addition mess lets me send the Rect as a pointer to the Rect
SDL_SetRenderDrawColor(myWin.renderer, 255, 255, 0, 255); # <<< this becomes the next background color, during flip()
#SDL_RenderPresent(renderer);
flip(myWin)
SDL_SetRenderDrawColor(myWin.renderer, 255, 0, 0, 255);
mRect = SDL_Rect(300, 300, 200, 200) # wacky Julia struct constructor; x,y, widht, height
SDL_RenderDrawRect(myWin.renderer, Ref{SDL_Rect}(mRect)) # that addition mess lets me send the Rect as a pointer to the Rect
# SDL_RenderPresent(myWin.renderer) # equivalent to win.Flip()
# SDL_PumpEvents() # Must do this after every SDL_RenderPresent
println("start")
SDL_Delay(250)
flip(myWin)
println("\n")
SDL_Delay(250)
draw(psychoRect)
newRect = Rect(myWin, 100, 100, [200,200], lineColor = [255,0,0], fillColor = [255,128,128] )
draw(newRect)
hollowRect = Rect(myWin, 500, 500, [750,750], lineColor = [128,128,128, 255], fillColor = [0,0,0,0] )
draw(hollowRect)
hollowRect2 = Rect(myWin, 500, 500, [250,250], lineColor = [128,128,128, 255], fillColor = [0,0,0,0] )
draw(hollowRect2)
# sdl_ellipse(myWin, 500, 500, 75, 75)
# filledCircleRGBA(myWin.renderer, 550, 600, 50, 255,128, 128, 255)
#drawText(myWin, "does this work?")
myColor = [255, 255, 255, 255]
#myLine = Line(myWin, [50, 150], [150, 1500], width = 1, lineColor = myColor )
myLine = Line(myWin, [500, 875], [1000, 625], width = 1, lineColor = myColor )
draw(myLine)
myColor2 = [0, 255, 0, 255]
# myLine2 = Line(myWin, [500, 750], [1000, 750], width = 2, lineColor = myColor2 ) # ::Vector{Int8}
# draw(myLine2)
myColor3 = [0, 0, 255, 255]
myLine3 = Line(myWin, [500, 500], [1000, 1000], width = 3, lineColor = myColor3 )
draw(myLine3)
myColor4 = [255, 255, 0, 255]
myLine4 = Line(myWin, [750, 500], [750, 1000], width = 4, lineColor = myColor4 )
draw(myLine4)
myColor5 = [255, 0, 255, 255]
myLine5 = Line(myWin, [500, 625], [1000, 875], width = 5, lineColor = myColor5 )
draw(myLine5)
# draw a grid to evaluate where text is drawn
for x in 0:50:250
tempLine = Line(myWin, [x,0], [x,250], width = 1, lineColor = [200, 200, 200, 255] )
draw(tempLine)
end
for y in 0:50:250
tempLine = Line(myWin, [0,y], [250,y], width = 1, lineColor = [200, 200, 200, 255] )
draw(tempLine)
end
myText = TextStim(myWin, "Using a TextStim", [100, 100], color = [255, 255, 128])
draw(myText)
textLine = Line(myWin, [100,100], [400,100], width = 1, lineColor = [128, 255, 255, 255] )
draw(textLine)
textLine = Line(myWin, [100,100], [100,50], width = 1, lineColor = [128, 255, 255, 255] )
draw(textLine)
myLine6 = Line(myWin, [1300, 200], [1305, 1500], width = 1, lineColor = myColor )
draw(myLine6)
myLine7 = Line(myWin, [1320, 200], [1325, 1500], width = 5, lineColor = myColor5 )
draw(myLine7)
myLine8 = Line(myWin, [500, 675], [1000, 925], width = 1, lineColor = myColor5 )
draw(myLine8)
myLine9 = Line(myWin, [500, 725], [1000, 975], width = 2, lineColor = myColor5 )
draw(myLine9)
horizLine = Line(myWin, [500, 1100], [1000, 1100], width = 4, lineColor = [255, 0, 0, 255] )
draw(horizLine)
vertLine = Line(myWin, [1100, 500], [1100, 1000], width = 4, lineColor = [255, 0, 0, 255] )
draw(vertLine)
#= Sans = TTF_OpenFont("Sans.ttf", 24);
White = SDL_Color(255, 255, 255, 255)
render_text(myWin.renderer,
"Does this work?",
Sans,
White,
50,
50)
=#
# aaellipseRGBA(myWin.renderer, 650, 600, 50,50, 128,255, 128, 255)
myellipse1 = Ellipse(myWin, [500, 1200], 120, 80, lineColor = [128, 255, 128, 255], fill = false)
myellipse2 = Ellipse(myWin, [700, 600], 50,50, lineColor = [128, 128, 255, 255], fillColor = [255, 128, 128, 255], fill =true)
draw(myellipse1)
draw(myellipse2)
theCircle = Circle(myWin, [800, 200], 50, lineWidth=20, lineColor = [255, 255, 255, 255], fillColor = [0, 0, 0, 255], fill = false)
draw(theCircle)
theCircle2 = Circle(myWin, [1000, 200], 50, lineWidth=20, lineColor = [255, 255, 255, 255], fillColor = [255, 0, 0, 255], fill = true)
draw(theCircle2)
theCircle3 = Circle(myWin, [600, 200], 50, lineWidth=1, lineColor = [255, 255, 255, 255], fillColor = [0, 0, 0, 0], fill = false)
draw(theCircle3)
oval = Ellipse(myWin, [1000, 400], 100, 50, lineWidth=20, lineColor = [127, 255, 127, 255], fillColor = [0, 0, 255, 255], fill = true)
draw(oval)
vertices =[ [300, 10], [400, 5], [410,150], [320, 100] ,[290, 20] ]
myShapeStim = ShapeStim(myWin, vertices, lineWidth = 3, lineColor = [255,128,128,255])
draw(myShapeStim)
myPoly = Polygon( myWin, [1200, 200], 50, 5, lineWidth = 3, lineColor = [128,128,255,255])
draw(myPoly)
#myColor = MakeInt8Color(255, 0, 255, 255)
#------------------------------------------------------
# This sections is for checking anti-aliasing and subpixels rendering bult-in to SDL2
# SDL_RenderDrawLine, aaline, SDL_RenderDrawLineF
SDL_SetRenderDrawColor(myWin.renderer, 255,255,255,255)
SDL_RenderDrawLine(myWin.renderer, 1500, 10, 1510, 1500 ) # shallow
SDL_RenderDrawLine(myWin.renderer, 1600, 10, 1900, 310 ) # 45°
#----
#=
aalineRGBA(myWin.renderer,
convert(Int16, 1510),
convert(Int16, 10),
convert(Int16, 1520),
convert(Int16, 1500),
convert(UInt8, 255),
convert(UInt8, 255),
convert(UInt8, 255),
convert(UInt8, 255)
)
aalineRGBA(myWin.renderer, 1610, 10, 1910, 1500, 255,255,255,255)
=#
#----
SDL_SetRenderDrawColor(myWin.renderer, 255,255,255,255)
#=
SDL_RenderDrawLineF(myWin.renderer, 1520.5, 10, 1530.5, 1500 ) # shallow
SDL_RenderDrawLineF(myWin.renderer, 1530, 10, 1540, 1500 ) # shallow
SDL_RenderDrawLineF(myWin.renderer, 1620.5, 10, 1920.5, 310 ) # 45°
SDL_RenderDrawLineF(myWin.renderer, 1630, 10, 1930, 310 ) # 45°
=#
theLine = Line(myWin, [1520, 10], [1530, 1500], width = 1, lineColor = myColor )
draw(theLine)
#------------------------------------------------------
imagePath = joinpath(dirname(pathof(SimpleDirectMediaLayer)), "..", "assets", "cat.png")
myImage = ImageStim(myWin, imagePath, [250,400])
draw(myImage, magnification = 10.0)
#---------------------
winSize = getSize(myWin)
x = round(Int64, winSize[2]/2)
widthRatio = winSize[1]/winSize[2]
expLine1 = Line(myWin, [x, 0], [x, winSize[1]], width = 1, lineColor = [255,0,0,255] ) # int coordinates
#expLine2 = Line(myWin, [0.98, 0.0], [0.98, 1.0], width = 1, lineColor = [0,255,0,255] ) # float coordinates
# green is much too short
# and red does not show up at all.
draw(expLine1)
# expLine2 = Line(myWin, [0.0, 0.02], [widthRatio, 0.02], width = 1, lineColor = [0,255,255,255] ) # float coordinates
# draw(expLine2)
# expLine2 = Line(myWin, [0.0, 0.98], [widthRatio, 0.98], width = 1, lineColor = [0,255,255,255] ) # float coordinates
# draw(expLine2)
# expLine2 = Line(myWin, [0.02, 0.00], [0.02, 1.0], width = 1, lineColor = [0,255,255,255] ) # float coordinates
# draw(expLine2)
# expLine2 = Line(myWin, [widthRatio - 0.02, 0.0], [widthRatio - 0.02, 1.0], width = 1, lineColor = [0,255,255,255] ) # float coordinates
# draw(expLine2)
message = @sprintf("width ratio = %4.2f", widthRatio)
myText = TextStim(myWin, message, [100, 300], color = [0, 255, 255, 255])
draw(myText)
#---------------------
flip(myWin)
startTimer(myWin)
#theKey = getKey(myWin)
theKey = waitKeys(myWin, 5000)
timeTaken = stopTimer(myWin)
println("the key ", theKey," was pressed. It took ", timeTaken," milliseconds")
#--------------
for x in 300:100:500
setPos(myImage, [x, 400])
draw(myImage, magnification = 10.0)
waitTime(myWin, 100.0)
flip(myWin)
end
#-----------
SDL_Delay(2000)
#=
for i in 1:10
println(getKey(myWin) )
end
=#
done = false
while done == false
key = getKey(myWin)
if key == "q"
done = true
end
end
closeAndQuitPsychoJL(myWin)
end
#@report_opt DemoWindow()
#font = FC_CreateFont();
#FC_LoadFont(font, renderer, "fonts/FreeSans.ttf", 20, FC_MakeColor(0,0,0,255), TTF_STYLE_NORMAL);
#@report_opt DemoWindow()
#@report_call DemoWindow()
DemoWindow()
SDL_Delay(2000)
#exit()
#=
i should make it unclicked and slection mode
need state to change state with each click
=# | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 1916 | using Images
fpart(x) = mod(x, one(x))
rfpart(x) = one(x) - fpart(x)
function drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer)
steep = abs(y1 - y0) > abs(x1 - x0)
if steep
x0, y0 = y0, x0
x1, y1 = y1, x1
end
if x0 > x1
x0, x1 = x1, x0
y0, y1 = y1, y0
end
dx = x1 - x0
dy = y1 - y0
grad = dy / dx
if iszero(dx)
grad = oftype(grad, 1.0)
end
# handle first endpoint
xend = round(Int, x0)
yend = y0 + grad * (xend - x0)
xgap = rfpart(x0 + 0.5)
xpxl1 = xend
ypxl1 = floor(Int, yend)
if steep
img[ypxl1, xpxl1] = rfpart(yend) * xgap
img[ypxl1+1, xpxl1] = fpart(yend) * xgap
else
img[xpxl1, ypxl1 ] = rfpart(yend) * xgap
img[xpxl1, ypxl1+1] = fpart(yend) * xgap
end
intery = yend + grad # first y-intersection for the main loop
# handle second endpoint
xend = round(Int, x1)
yend = y1 + grad * (xend - x1)
xgap = fpart(x1 + 0.5)
xpxl2 = xend
ypxl2 = floor(Int, yend)
if steep
img[ypxl2, xpxl2] = rfpart(yend) * xgap
img[ypxl2+1, xpxl2] = fpart(yend) * xgap
else
img[xpxl2, ypxl2 ] = rfpart(yend) * xgap
img[xpxl2, ypxl2+1] = fpart(yend) * xgap
end
# main loop
if steep
for x in xpxl1+1:xpxl2-1
img[floor(Int, intery), x] = rfpart(intery)
img[floor(Int, intery)+1, x] = fpart(intery)
intery += grad
end
else
for x in xpxl1+1:xpxl2-1
img[x, floor(Int, intery) ] = rfpart(intery)
img[x, floor(Int, intery)+1] = fpart(intery)
intery += grad
end
end
return img
end
img = fill(Gray(1.0N0f8), 250, 250);
img2 = drawline!(img, 8, 8, 192, 154)
img_path = pwd()
println(img_path)
save("img1.png", img)
save("img2.png", img2) | PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 7984 |
export ButtonStim, ButtonMap, buttonDraw, buttonDrawClicked, buttonStim
# SDL-based buttons for dialog boxes.
"""
Structs
ButtonStim: threee types: default (enter key triggers), other (non-triggered), and custom
ButtonMap: internally used as part of a list of butttons. Used for
detecting button presses, dispatching, etc.
"""
mutable struct ButtonStim
win::Window
pos::Vector{Int64}
size::Vector{Int64}
TextStim::TextStim
type::String # default, other, custom. default can be clicked with enter key
outlineColor::Vector{Int64} # these will need to change to floats to handle Psychopy colors
fillColor::Vector{Int64} # these will need to change to floats to handle Psychopy colors
# other are the non-default buttons.
# custom uses the colors provided.
#----------
function ButtonStim(win::Window,
pos::Vector{Int64} = [10,10],
size::Vector{Int64} = [10,10],
TextStim::TextStim = nothing,
type::String = "other";
outlineColor::Vector{Int64} = fill(128, (4)), # these will need to change to floats to handle Psychopy colors
fillColor::Vector{Int64} = fill(128, (4)) # these will need to change to floats to handle Psychopy colors
)
if TextStim == nothing
error("Buttons require a TextStim.")
end
TextStim.pos[1] = pos[1] * 2 # high dpi
TextStim.pos[2] = pos[2] * 2 # high dpi
outlineColor = colorToSDL(win, outlineColor)
fillColor = colorToSDL(win, fillColor)
new(win,
pos,
size,
TextStim,
type,
outlineColor,
fillColor, # these will need to change to floats to handle Psychopy colors
)
end
end
#----------
function buttonDraw(but::ButtonStim)
# don't need to divide by 2, because high dpi causes everything to be half as large
x1 = (but.pos[1]*2) - but.size[1] #÷ 2 # left; ÷ is integer divide in Julia. // in Python is integer divide, but in Julia it is fractions (rational number)
x2 = (but.pos[1]*2) + but.size[1] #÷ 2 # right
y1 = (but.pos[2]*2) - but.size[2] ÷ 2 # top
y2 = (but.pos[2]*2) + but.size[2] ÷ 2 # bottom
cx = (x1+x2) ÷ 2
cy = (y1+y2) ÷ 2
fillR = but.fillColor[1]
fillG = but.fillColor[2]
fillB = but.fillColor[3]
fillA = but.fillColor[4]
outR = but.outlineColor[1]
outG = but.outlineColor[2]
outB = but.outlineColor[3]
outA = but.outlineColor[4]
if but.type == "other" # white button with black text
aaFilledRoundRectRGBA(but.win.renderer, x1-2, y1-2, x2+3, y2+4, 19, # lightshadow first
238, 238, 238, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1-1, y1-1, x2+2, y2+3, 18, # lightshadow first
230, 230, 230, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2+1, y2+2, 17, # shadow first
203, 203, 203, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 16,
255, 255, 255, 255)
#aaRoundRectRGBA(but.win.renderer,x1, y1, x2, y2, 17,
# 0, 0, 0, 255)
but.TextStim.color = [0, 0, 0]
but.TextStim.fontSize = 24
but.TextStim.horizAlignment = 0
but.TextStim.vertAlignment = 0
#but.TextStim.style = "bold"
draw(but.TextStim)
elseif but.type == "default" # blue highlighted button with white text
aaFilledRoundRectRGBA(but.win.renderer, x1-2, y1-2, x2+4, y2+4, 19, # lightshadow first
238, 238, 238, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1-1, y1-1, x2+3, y2+3, 18, # lightshadow first
230, 230, 230, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2+2, y2+2, 17, # shadow first
203, 203, 203, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 16,
131, 149, 247, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1 + 7, y1 +7, x2-7, y2-7, 12,
64, 135, 247, 255)
aaRoundRectRGBA(but.win.renderer,x1 + 7, y1 +7, x2-7, y2-7, 12,
45, 97, 228, 255)
but.TextStim.color = [255, 255, 255]
but.TextStim.fontSize = 24
but.TextStim.horizAlignment = 0
but.TextStim.vertAlignment = 0
#but.TextStim.style = "bold"
draw(but.TextStim)
elseif but.type == "custom"
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 16,
fillR, fillG, fillB, fillA)
aaRoundRectRGBA(but.win.renderer,x1, y1, x2, y2, 16,
outR, outG, outB, outA)
draw(but.TextStim)
else
error("Invalid button type. Options are 'default', 'other', or 'custom'.")
end
end
#-================================
function buttonDrawClicked(but::ButtonStim)
# don't need to divide by 2, because high dpi causes everything to be half as large
x1 = (but.pos[1]*2) - but.size[1] #÷ 2 # left; ÷ is integer divide in Julia. // in Python is integer divide, but in Julia it is fractions (rational number)
x2 = (but.pos[1]*2) + but.size[1] #÷ 2 # right
y1 = (but.pos[2]*2) - but.size[2] ÷ 2 # top
y2 = (but.pos[2]*2) + but.size[2] ÷ 2 # bottom
cx = (x1+x2) ÷ 2
cy = (y1+y2) ÷ 2
fillR = but.fillColor[1]
fillG = but.fillColor[2]
fillB = but.fillColor[3]
fillA = but.fillColor[4]
outR = but.outlineColor[1]
outG = but.outlineColor[2]
outB = but.outlineColor[3]
outA = but.outlineColor[4]
if but.type == "other" # white button with black text
aaFilledRoundRectRGBA(but.win.renderer, x1-2, y1-2, x2+3, y2+4, 20, # lightshadow first
238, 238, 238, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1-1, y1-1, x2+2, y2+3, 19, # lightshadow first
230, 230, 230, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2+1, y2+2, 18, # shadow first
203, 203, 203, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 17,
239, 239, 239, 255)
#aaRoundRectRGBA(but.win.renderer,x1, y1, x2, y2, 17,
# 0, 0, 0, 255)
but.TextStim.color = [0, 0, 0]
but.TextStim.fontSize = 24
but.TextStim.horizAlignment = 0
but.TextStim.vertAlignment = 0
but.TextStim.style = "bold"
draw(but.TextStim)
elseif but.type == "default" # blue highlighted button with white text
aaFilledRoundRectRGBA(but.win.renderer, x1-2, y1-2, x2+4, y2+4, 20, # lightshadow first
238, 238, 238, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1-1, y1-1, x2+3, y2+3, 19, # lightshadow first
230, 230, 230, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2+2, y2+2, 18, # shadow first
203, 203, 203, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 17,
131, 149, 247, 255)
aaFilledRoundRectRGBA(but.win.renderer, x1 + 7, y1 +7, x2-7, y2-7, 13,
48, 113, 247, 227)
aaRoundRectRGBA(but.win.renderer,x1 + 7, y1 +7, x2-7, y2-7, 13,
45, 97, 228, 255)
but.TextStim.color = [255, 255, 255]
but.TextStim.fontSize = 24
but.TextStim.horizAlignment = 0
but.TextStim.vertAlignment = 0
but.TextStim.style = "bold"
draw(but.TextStim)
elseif but.type == "custom"
aaFilledRoundRectRGBA(but.win.renderer, x1, y1, x2, y2, 17,
fillR, fillG, fillB, fillA)
aaRoundRectRGBA(but.win.renderer,x1, y1, x2, y2, 17,
outR, outG, outB, outA)
draw(but.TextStim)
else
error("Invalid button type. Options are 'default', 'other', or 'custom'.")
end
end
#---------------------------------------------
# button maps are part of a larger list of buttons that is looped through to
# draw and handle events.
mutable struct ButtonMap
button::ButtonStim
message::String # used for dealing with logic of mouse click
state::String # clicked or not
leftTop::Vector{Int64}
rightBottom::Vector{Int64}
function ButtonMap( button::ButtonStim, message::String)
state = "unclicked"
leftTop = [button.pos[1] - button.size[1]÷ 2, button.pos[2] - button.size[2]÷ 2]
rightBottom = [button.pos[1] + button.size[1]÷ 2, button.pos[2] + button.size[2]÷ 2]
new(button, message, state, leftTop, rightBottom )
end
end
| PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
|
[
"MIT"
] | 0.1.0 | 3bb03a80c95594883082fd3fe384f0fe86ffb2cf | code | 7238 | # Translation of psycopy window file to Julia
export InitPsychoJL, MakeInt8Color, waitTime, waitTimeMsec, colorToSDL, SDLcoords
export PsychoColor, PsychoCoords
using Colors
#using SimpleDirectMediaLayer
#using SimpleDirectMediaLayer.LibSDL2
PsychoColor = Union{String, Vector{Int64}, Vector{Float64}}
PsychoCoords = Union{ Vector{Int64}, Vector{Float64}}
#----------
"""
InitPsychoJL()
Initializes PsychoJL module.
**Inputs:** None\n
**Outputs:** None
"""
function InitPsychoJL()
@assert SDL_Init(SDL_INIT_EVERYTHING) == 0 "error initializing SDL: $(unsafe_string(SDL_GetError()))"
@assert TTF_Init() == 0 "error initializing TTF_Init: $(unsafe_string(SDL_GetError()))"
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 16) # the number of multisample anti-aliasing buffers.
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16) # the number of samples used around the current pixel used for multisample anti-aliasing
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 1024) < 0)
println("SDL_mixer could not initialize!", Mix_GetError())
end
end
#-=================================================
#=
"""
MakeInt8Color(r,g,b,a)
Packs 8-bit red, green, blue, alpha values into a 32-bit Int.
inputs: Four integers of any type
outputs: UInt32
"""
=#
function MakeInt8Color(r,g,b,a)
#color::Vector{UInt8} = [mod(r, UInt8), mod(g, UInt8), mod(b, UInt8), mod(a, UInt8)]
color::UInt32 = mod(a, UInt8)
color += mod(b, UInt8) * 256
color += mod(g, UInt8) * 65536
color += mod(r, UInt8) * 16777216
# 16777216 65536 256 1
#------
println("r, g, b, a = ", r,", ",g,", ",b,", ",a)
colorString = dec2hex255(a) #string(mod(r, UInt8) , base=16)
colorString = colorString * dec2hex255(r) #string(mod(g, UInt8), base=16)
colorString = colorString * dec2hex255(g) #string(mod(b, UInt8), base=16)
colorString = colorString * dec2hex255(b) #string(mod(a, UInt8), base=16)
color = parse(UInt32, colorString, base= 16)
println("color = ", color) #, "\n")
#------
return color
end
#-=================================================
"""
waitTime(win::Window, time::Float64)
Pauses for a set amount of time. Time scale (second or milliseconds) is set
when making the Window.
**Inputs:** PsychoJL Window, 64-bit float\n
**Outputs:** Nothing
"""
function waitTime(win::Window, time::Float64)
if win.timeScale == "milliseconds"
SDL_Delay( round(UInt32, time) )
elseif win.timeScale == "seconds"
SDL_Delay( round(UInt32, time * 1000) )
else
error("Invalid timescale: ", win.timeScale)
end
end
#-=================================================
"""
waitTimeMsec(time::Float64)
Pauses for a set amount of time. Time scale is in milliseconds, and does not
require a window to be passed to it..
**Inputs:** 64-bit float\n
**Outputs:** Nothing
"""
function waitTimeMsec(time::Float64)
SDL_Delay(time)
end
#-=================================================
#-=========
function dec2hex255(number)
if number <= 255 && number >=0
if number < 16 # if we don't do this, string() will return a single char without left 0 padding.
hex = "0"
hex = hex * string(mod(number, UInt8) , base=16)
else
hex = string(mod(number, UInt8) , base=16)
end
else
println("*** Error: number should be from 0-255, got this instead: ", number)
end
return hex
end
#-=====================================================================================================
# Changes various types of colors to standard SDL RGB color with an alpha channel
# RGB. Adds alpha channel if length < 4
function colorToSDL(win::Window, inColor::Vector{Int64})
if win.colorSpace != "rgba255" && win.colorSpace != "rgb255"
error("Mismatch between colorspace. Given integer vector, but colorspace is ", win.colorSpace)
end
if length(inColor) == 4
return inColor
elseif length(inColor) == 3
outColor = zeros(Int64, 4)
for i in eachindex(inColor)
outColor[i] = inColor[i]
end
outColor[4] = 255
return outColor
else
error("color is too short. Only ", length(inColor)," values given")
end
end
#-------------------------
# below tranlates decimal (0.0-1.0) and PsychoPy (-1.0 - +1.0) to rgba255
function colorToSDL(win::Window, inColor::Vector{Float64})
if win.colorSpace != "decimal" && win.colorSpace != "PsychoPy"
error("Mismatch between colorspace. Given float vector, but colorspace is ", win.colorSpace)
end
#-----
if win.colorSpace == "decimal"
outColor = zeros(Int64, 4)
for i in eachindex(inColor)
outColor[i] = round(Int64, inColor[i] * 255)
end
if length(inColor) == 3
outColor[4] = 255 # default is alpha of 255
elseif length(inColor) < 3
error("color is too short. Only ", length(inColor)," values given")
end
elseif win.colorSpace == "PsychoPy"
outColor = zeros(Int64, 4)
for i in eachindex(inColor)
outColor[i] = round(Int64, 127.5 + (inColor[i] * 127.5) )
end
if length(inColor) == 3
outColor[4] = 255 # default is alpha of 255
elseif length(inColor) < 3
error("color is too short. Only ", length(inColor)," values given")
end
else
error(win.colorSpace," is an invalid color space")
end
return outColor
end
#-------------------------
# below tranlates strings to rgba255. Ignores color space, and translates
function colorToSDL(win::Window, inColor::String)
if haskey(Colors.color_names, inColor)
theColor = Colors.color_names[inColor] # color is an rgba255
outColor = zeros(Int64, 4)
for i in eachindex(theColor) # have to convert tuple to vector
outColor[i] = theColor[i]
end
if length(theColor) == 3 # add alpha if necessary
outColor[4] = 255
end
return outColor
else
error("Color name ", inColor," could not be found in Colors.jl")
end
end
#-====================================================
function SDLcoords(win::Window, coords::Union{Vector{Int64}, Vector{Float64}})
if win.coordinateSpace == "LT_Pix"
return coords
elseif win.coordinateSpace == "LT_Percent" # origin is left top, width is percent of height
return ConvertFloatCoordsToPixels(win, coords)
elseif win.coordinateSpace == "LB_Percent" # origin is left bott0m, width is percent of height
x = coords[1]
y = 1 - coords[2]
return ConvertFloatCoordsToPixels(win, [x,y])
elseif win.coordinateSpace == "PsychoPy" # origin is left bott0m, width is percent of height
return ConvertPsychoPyToPixels(win, coords)
else
error("Invalid coordinate space given: ", win.coordinateSpace)
end
end
#----------
function ConvertPsychoPyToFloatCoords(coord::Vector{Float64})
x = coord[1] + 0.5
y = -coord[2] + 0.5
return [x,y]
end
#----------
function ConvertFloatCoordsToPixels(win::Window, coord::Vector{Float64})
_, displayHeight = getSize(win)
x = round(Int64, coord[1] * displayHeight)
y = round(Int64, coord[2] * displayHeight)
return [x,y]
end
#----------
function ConvertPsychoPyToPixels(win::Window, coord::Vector{Float64})
coord = ConvertPsychoPyToFloatCoords(coord)
return ConvertFloatCoordsToPixels(win, coord)
end
#----------
# This (the name) makes no sense! Do not write code late at night!
function convertFloatCoordToInt255(coords::Vector{Float64})
out = ones(Int64, 2)
out[1] = round(Int64, coords[1] * 255)
out[2] = round(Int64, coords[2] * 255)
return out
end
| PsychExpAPIs | https://github.com/mpeters2/PsychExpAPIs.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.