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.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
2727
export waitKeys, getKey function waitKeys(win::Window, waitTime::Int64) waitKeys(win, convert(Float64, waitTime)) end """ waitKeys(win::Window, waitTime::Float64) Waits for a predetermined time for a keypress. Returns immediately when a key is pressed or the timer runs out. **Inputs:** * win::Window * waitTime::Float64 *default is milliseconds* **Outputs**: returns the character that was pressed **Limitations**: currently only returns character keys. Arrow keys, tab, return, etc. do not work. """ function waitKeys(win::Window, waitTime::Float64) #println(" win.event: ", win.event) #println(" win.event value: ", win.event[]) if win.timeScale == "milliseconds" waitTime /= 1000 end start = time() while (time() - start) < waitTime while Bool(SDL_PollEvent(win.event)) #while( SDL_PollEvent( win.event ) ) event_ref = win.event evt = event_ref[] evt_ty = evt.type evt_text = evt.text if( evt_ty == SDL_TEXTINPUT ) textTemp = NTupleToString(evt_text.text) if textTemp != nothing SDL_StopTextInput() if textTemp == " " # space return "space" elseif textTemp == " " # tab return "tab" else return textTemp end end end #= if evt_ty == SDL_KEYDOWN println( "Key press detected (", time() - start,")\n" ); elseif evt_ty == SDL_KEYUP println( "Key release detected\n" ); end =# end end end #------------------------------------ """ getKey(win::Window) Waits until a key is pressed. **Inputs:** * win::Window **Outputs**: returns the character that was pressed **Limitations**: currently only returns character keys. Arrow keys, tab, return, etc. do not work. """ function getKey(win::Window) #Enable text input SDL_StartTextInput(); keypressed = "" # ensures that keypressed is not local the while loop #win.firstKey = false # couldn't find a way to inject a Key_UP event in the queue, so did this instead done = false while done == false while Bool(SDL_PollEvent(win.event)) event_ref = win.event evt = event_ref[] evt_ty = evt.type evt_text = evt.text if( evt_ty == SDL_TEXTINPUT ) keypressed = NTupleToString(evt_text.text) if keypressed != nothing SDL_StopTextInput() if keypressed == " " # space keypressed = "space" elseif keypressed == " " # tab keypressed = "tab" end done = true end end end end # wait for KeyUp first so that we can debounce done = false while done == false while Bool(SDL_PollEvent(win.event)) event_ref = win.event evt = event_ref[] evt_ty = evt.type if( evt_ty == SDL_KEYUP ) done = true end end end SDL_StopTextInput() return keypressed end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
53779
# Might want to make a larger Window for instructions, with buttons for OK and Back (incase they went too fast) #using .Gtk: draw as GTKdraw #import Gtk # this prevents namespace collisions between Gtk's draw() and PsychoJL's draw() functions include("guiUtilityFunctions.jl") using Dates export displayMessage, askQuestionDialog, fileOpenDlg, inputDialog, textInputDialog, DlgFromDict export infoMessage, happyMessage, warningMessage, errorMessage # make fileOpenDlg actually work # mask ask dialog look nice const SDLK_BACKSPACE = 8 const SDLK_RETURN = 13 const SDLK_c = 99 const SDLK_v = 118 const KMOD_CTRL = 192 const SDLK_KP_ENTER = 1073741912 const SDLK_LEFT = 1073741904 const SDLK_RIGHT = 1073741903 #-========================================================================================================== function fileOpenDlg() file = Gtk.open_dialog_native("My first file dialog") filehandle = Gtk.open("$file"); Netlist_lines = Gtk.readlines(filehandle); Gtk.close(filehandle); Netlist_lines[1][begin:3] end #-============================================= #!["picture of a displayMessage dialog"](displayMessage.png) """ displayMessage( message::String) Displays a message along with an "OK" button. Use before opening the main window or after closing the main window. Useful for displaying errors or experiment completion messages. **Inputs:** PsychoJL Window, String\n **Outputs:** Nothing\n !["picture of a displayMessage dialog"](displayMessageSmall.png) """ function displayMessage( message::String) SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_INFORMATION, "Alert", message, C_NULL) # debounces by waiting for an SDL_KEYUP event SDLevent = Ref{SDL_Event}() done = false while done == false while Bool(SDL_PollEvent(SDLevent)) event_ref = SDLevent evt = event_ref[] evt_ty = evt.type if( evt_ty == SDL_KEYUP ) done = true end end end end #-============================================= """ infoMessage( message::String) Displays a message along with an "OK" button. Use before opening the main window or after closing the main window. Useful for displaying general information. **Inputs:** String\n **Outputs:** Nothing\n !["picture of a infoMessage dialog"](infoMessage.png) """ function infoMessage( message::String) genericMessage(message, "information.png") end #----------------- """ happyMessage( message::String) Displays a message along with an "OK" button. Use before opening the main window or after closing the main window. Useful for experiment completion messages. **Inputs:** String\n **Outputs:** Nothing\n !["picture of a happyMessage dialog"](happyMessage.png) """ function happyMessage( message::String) genericMessage(message, "HappyFace.png") end #----------------- """ warningMessage( message::String) Displays a message along with an "OK" button. Use before opening the main window or after closing the main window. Useful for displaying non-critical warnings. **Inputs:** String\n **Outputs:** Nothing\n !["picture of a warningMessage dialog"](warningMessage.png) """ function warningMessage( message::String) genericMessage(message, "warning.png") end #----------------- """ errorMessage( message::String) Displays a message along with an "OK" button. Use before opening the main window or after closing the main window. Useful for displaying critical errors. **Inputs:** String\n **Outputs:** Nothing\n !["picture of a errorMessage dialog"](errorMessage.png) """ function errorMessage( message::String) genericMessage(message, "error.png") end #does SDL do text wrap? #Even so, I want to use \n to add new lines #-============================================= function genericMessage( message::String, imageName::String) SCREEN_WIDTH = 360 SCREEN_HEIGHT = 125 CENTERX = SCREEN_WIDTH ÷ 2 CENTERY = SCREEN_HEIGHT ÷ 2 buttonClicked = "NoButton" quit::Bool = false; mX = Ref{Cint}() # pointers that will receive mouse coordinates mY = Ref{Cint}() SDLevent = Ref{SDL_Event}() #Event handler textColor = SDL_Color(0, 0, 0, 0xFF) #Set text color as black dialogWin = Window([SCREEN_WIDTH, SCREEN_HEIGHT], false, title = "") renderer = dialogWin.renderer gFont = dialogWin.font if gFont == C_NULL println("*** Error: gFont is NULL") end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_SetRenderDrawColor(dialogWin.renderer, 250, 250, 250, 255) SDL_RenderClear(dialogWin.renderer) w = Ref{Cint}() h = Ref{Cint}() TTF_SizeText(gFont, message, w::Ref{Cint}, h::Ref{Cint}) label = TextStim(dialogWin, message, [CENTERX + 40, 10 + (1*(h[] + 10)) ], # the centerX * 1.5 seem weird, that's because of retina = 0.75 of width # label = TextStim(dialogWin, message, [round(Int64, SCREEN_WIDTH *0.8), 10 + (1*(h[] + 10)) ], # the centerX * 1.5 seem weird, that's because of retina = 0.75 of width #label = TextStim(dialogWin, message, [round(Int64,CENTERX * 1.5), 10 + (1*(h[] + 10)) ], # the centerX * 1.5 seem weird, that's because of retina = 0.75 of width color = [0, 0, 0], fontSize = 24, horizAlignment = -1, vertAlignment = 1 ) draw(label, wrapLength = round(Int64,SCREEN_WIDTH*1.5)-50 ) # SCREEN_WIDTH seems weird, but retina doubles/halves everything #--------- # draw alert parentDir = pwd() filePath = joinpath(parentDir, "artifacts") filePath = joinpath(filePath, imageName) #symbol = ImageStim( dialogWin, filePath, [round(Int64, SCREEN_WIDTH *0.2), CENTERY] ) symbol = ImageStim( dialogWin, filePath, [CENTERX ÷ 1.5, SCREEN_HEIGHT] ) # This might break with retina draw(symbol, magnification = 0.4) #--------- # draw OK button OKtext = TextStim(dialogWin, "OK", [0, 0]) OKbutton = ButtonStim(dialogWin, #[ 20 + (widestKey), 10 + ((length(labels)+1) * (h[] +10)) ], # was 0.75, buthigh dpi shenanigans #[ widestKey, h[] + 10], [ round(Int64, SCREEN_WIDTH *0.8), SCREEN_HEIGHT - (h[] ÷ 2)], [ (SCREEN_WIDTH ÷ 5) , h[] + 10], OKtext, "default") _, ytemp = OKbutton.pos ytemp ÷= 2 #OKbutton.pos[2] = ytemp buttonDraw(OKbutton) OKmap = ButtonMap(OKbutton, "OK-clicked") #--------- # Play alert sound parentDir = pwd() filePath = joinpath(parentDir, "artifacts") filePath = joinpath(filePath, "qbeep-10db.wav") mySound = SoundStim(filePath) play(mySound) #--------- while( !quit ) while Bool(SDL_PollEvent(SDLevent)) # Handle events on queue event_ref = SDLevent evt = event_ref[] evt_ty = evt.type evt_key = evt.key evt_text = evt.text evt_mouseClick = evt.button # We only want to update the input text texture when we need to so we have a flag that keeps track of whether we need to update the texture. if( evt_ty == SDL_KEYDOWN ) #Special key input #Handle backspace if evt_key.keysym.sym == SDLK_RETURN || evt_key.keysym.sym == SDLK_KP_ENTER SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); closeWinOnly(dialogWin) return "OK" end elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) # new version makes a list of clicked items, and the item with the focus is the winner x = evt_mouseClick.x y = evt_mouseClick.y if (OKmap.rightBottom[1] > x > OKmap.leftTop[1]) && (OKmap.rightBottom[2] > y > OKmap.leftTop[2]) OKmap.state = "clicked" SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); closeWinOnly(dialogWin) return "OK" end end end SDL_SetRenderDrawColor(renderer, 250, 250, 250, 255) SDL_RenderClear( renderer ); #-------------------------------------------- # Update widgets and such draw(label, wrapLength = round(Int64,SCREEN_WIDTH*1.5)-50 ) draw(symbol, magnification = 0.4) #------------------- #Update screen if OKmap.state == "unclicked" buttonDraw(OKmap.button) elseif OKmap.state == "clicked" buttonDrawClicked(OKmap.button) OKmap.state = "unclicked" quit = true buttonClicked = OKmap.button.TextStim.textMessage end SDL_RenderPresent( renderer ); # check for enter or cancel end #-------------- Show stuff SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); #SDL_DestroyWindow(SDL_Window * Window) closeWinOnly(dialogWin) return "OK" end #-============================================= function askQuestionDialog(message::String) println("askQuestionDialog not implemented yet") end #-============================================= function textInputDialog( promptString::String, defaultText::String) SCREEN_WIDTH = 350 SCREEN_HEIGHT = 150 DoubleWidth = SCREEN_WIDTH * 2 # I don't know if this is a workaround for Retina or SDL_WINDOW_ALLOW_HIGHDPI, but a 400 pixel width yields 800 pixels firstRun = true buttonClicked = "NoButton" quit::Bool = false; mX = Ref{Cint}() # pointers that will receive mouse coordinates mY = Ref{Cint}() cursorLocation = 0 # after the last character. This is in charachter units, not pixels # this cycles during each refresh from true to false onTime = 0 # for timing of cursor blinns # these are used later to get the size of the text when moving the cursor w = Ref{Cint}() h = Ref{Cint}() SDLevent = Ref{SDL_Event}() #Event handler textColor = SDL_Color(0, 0, 0, 0xFF) #Set text color as black InitPsychoJL() dialogWin = Window(title = "", [SCREEN_WIDTH, SCREEN_HEIGHT], false) SDLwindow = dialogWin.win renderer = dialogWin.renderer #Globals = SDLGlobals(SDLwindow, renderer, LTexture(C_NULL, 0 ,0), LTexture(C_NULL, 0 ,0) ) gFont = dialogWin.font if gFont == C_NULL println("*** Error: gFont is NULL") end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_RenderClear(renderer) # TTF_SizeText(gFont, "Abcxyz", w, h) #-===== Their code: #The current input text. #inputText::String = "Some Text"; inputText = defaultText #TTF_SetFontStyle(gFont, TTF_STYLE_ITALIC) #Globals.promptTextTexture = loadFromRenderedText(Globals, promptString, textColor, dialogWin.italicFont); # inputText.c_str(), textColor ); #leftX = (SCREEN_WIDTH - Globals.promptTextTexture.mWidth)÷2 promptText = TextStim(dialogWin, promptString, [SCREEN_WIDTH, 20 ], # you would think it would be SCREEN_WIDTH÷2, but hi-res messes it centers at SCREEN_WIDTH÷4. color = [0, 0, 0], fontSize = 24, horizAlignment = 0, vertAlignment = -1, style = "italic" ) #TTF_SetFontStyle(gFont, TTF_STYLE_NORMAL ) #Globals.inputTextTexture = loadFromRenderedText(Globals, inputText, textColor, gFont); # inputText.c_str(), textColor ); myInputBox = InputBox(dialogWin, defaultText, [35, h[]÷2 + 17], [ (DoubleWidth - 140)÷2, h[]÷2 + 5], "" ) #--------- Make buttons buttonList = [] OKtext = TextStim(dialogWin, "OK", [0, 0]) OKbutton = ButtonStim(dialogWin, [ round(Int64, SCREEN_WIDTH * 0.75), round(Int64, SCREEN_HEIGHT * 0.75)], # was 0.75, buthigh dpi shenanigans [ round(Int64, SCREEN_WIDTH * 0.25), 68], OKtext, "default") push!(buttonList, ButtonMap(OKbutton, "OK-clicked") ) CancelText = TextStim(dialogWin, "Cancel", [0, 0]) CancelButton = ButtonStim(dialogWin, [ round(Int64, SCREEN_WIDTH * 0.25), round(Int64, SCREEN_HEIGHT * 0.75)], # was 0.75, buthigh dpi shenanigans [ round(Int64, SCREEN_WIDTH * 0.25), 68], CancelText, "other") push!(buttonList, ButtonMap(CancelButton, "Cancel-clicked") ) #---------- end buttons #---------- Make PopUp popList = [] myPop = PopUpMenu(dialogWin, [70,100], [100, h[] + 10], ["Cat", "Dog", "Bird"] ) push!(popList, PopUpMap(myPop ) ) #---------- end buttons #Enable text input SDL_StartTextInput(); #= Before we go into the main loop we declare a string to hold our text and render it to a texture. We then call SDL_StartTextInput so the SDL text input functionality is enabled. =# #While application is running while( !quit ) renderText::Bool = false; # The rerender text flag while Bool(SDL_PollEvent(SDLevent)) # Handle events on queue event_ref = SDLevent evt = event_ref[] evt_ty = evt.type evt_key = evt.key evt_text = evt.text evt_mouseClick = evt.button # We only want to update the input text texture when we need to so we have a flag that keeps track of whether we need to update the texture. if( evt_ty == SDL_KEYDOWN ) #Special key input #Handle backspace if( evt_key.keysym.sym == SDLK_BACKSPACE && length(inputText) > 0 ) if (length(inputText) - cursorLocation - 1) >= 0 newString = first(inputText, length(inputText) - cursorLocation - 1) else newString = "" end println(cursorLocation," ",newString) inputText = newString * last(inputText, cursorLocation) #inputText = String(chop(inputText, tail = 1)) # remove last item; chop return a substring, so we have to cast it as String renderText = true; cursorLocation += 1 # move cursor as text expands elseif evt_key.keysym.sym == SDLK_RETURN || evt_key.keysym.sym == SDLK_KP_ENTER return ["OK", inputText] elseif evt_key.keysym.sym == SDLK_LEFT cursorLocation += 1 elseif evt_key.keysym.sym == SDLK_RIGHT cursorLocation -= 1 if cursorLocation <= 0 cursorLocation = 0 end end # SDLK_LEFT, SDLK_RIGHT # SDLK_LEFT = 1073741904 # SDLK_RIGHT = 1073741903 #= There are a couple special key presses we want to handle. When the user presses backspace we want to remove the last character from the string. When the user is holding control and presses c, we want to copy the current text to the clip board using SDL_SetClipboardText. You can check if the ctrl key is being held using SDL_GetModState. When the user does ctrl + v, we want to get the text from the clip board using SDL_GetClipboardText. This function returns a newly allocated string, so we should get this string, copy it to our input text, then free it once we're done with it. Also notice that whenever we alter the contents of the string we set the text update flag. =# #Special text input event elseif( evt_ty == SDL_TEXTINPUT ) textTemp = NTupleToString(evt_text.text) if (length(inputText) - cursorLocation ) >= 0 leftString = first(inputText, length(inputText) - cursorLocation ) else leftString = "" end inputText = leftString * textTemp * last(inputText, cursorLocation) #inputText = inputText * textTemp # * is Julila concatenate renderText = true; elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) x = evt_mouseClick.x y = evt_mouseClick.y for butMap in buttonList println(butMap.leftTop,", ",butMap.rightBottom) if (butMap.rightBottom[1] > x > butMap.leftTop[1]) && (butMap.rightBottom[2] > y > butMap.leftTop[2]) butMap.state = "clicked" end end for popMap in popList if (popMap.rightBottom[1] > x > popMap.leftTop[1]) && (popMap.rightBottom[2] > y > popMap.leftTop[2]) #popMap.popUp.state = "clicked" println("pre-state change ", popMap.leftTop,", ",popMap.rightBottom) stateChange(popMap) draw(popMap.popUp, [x,y]) # enter pop-up button drawing and selection loop end end #=elseif( evt_ty == SDL_MOUSEBUTTONUP ) x = evt_mouseClick.x y = evt_mouseClick.y for popMap in popList if (popMap.rightBottom[1] > x > popMap.leftTop[1]) && (popMap.rightBottom[2] > y > popMap.leftTop[2]) #popMap.popUp.state = "unclicked" draw(popMap.popUp, [x,y]) # enter pop-up button drawing and selection loop end end =# end end #= With text input enabled, your key presses will also generate SDL_TextInputEvents which simplifies things like shift key and caps lock. Here we first want to check that we're not getting a ctrl and c/v event because we want to ignore those since they are already handled as keydown events. If it isn't a copy or paste event, we append the character to our input string. =# if( renderText ) # Rerender text if needed if( inputText != "" ) # Text is not empty #Render new text #Globals.inputTextTexture = loadFromRenderedText(Globals, inputText, textColor, gFont); # inputText.c_str(), textColor ); draw(myInputBox) else #Text is empty #Render space texture InputBox.valueText = " " #Globals.inputTextTexture = loadFromRenderedText(Globals, " ", textColor, gFont ); end end #= If the text render update flag has been set, we rerender the texture. One little hack we have here is if we have an empty string, we render a space because SDL_ttf will not render an empty string. =# SDL_SetRenderDrawColor(renderer, 250, 250, 250, 255) SDL_RenderClear( renderer ); #Render text textures draw(promptText) # myInputBox = InputBox( [35, Globals.promptTextTexture.mHeight÷2 + 17], # [ (DoubleWidth - 140)÷2, Globals.inputTextTexture.mHeight÷2 + 5 # ] ) # drawInputBox(renderer, myInputBox) #= SDL_Rect( 70, floor(Int64,(Globals.promptTextTexture.mHeight)) + 35, DoubleWidth - 140, Globals.inputTextTexture.mHeight + 10 ) =# #= render(Globals.renderer, Globals.inputTextTexture, #40, #floor(Int64,( SCREEN_WIDTH - Globals.inputTextTexture.mWidth ) / 2 ), #DoubleWidth - (Globals.inputTextTexture.mWidth + 20), DoubleWidth - 70 - (Globals.inputTextTexture.mWidth + 10), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, Globals.inputTextTexture.mWidth, Globals.inputTextTexture.mHeight ); =# #------------------- # need to get size of text for cursor using cursorLocation TTF_SizeText(gFont, last(inputText, cursorLocation), w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory cursorScootch = w[] #------------------- if (time() - onTime) < 1 thickLineRGBA(renderer, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64, h[]) + 45, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64, h[]) + 75, 3, 0, 0, 0, 255) cursorBlink = false elseif 1 < (time() - onTime) < 2 # show during this time #vlineRGBA(Globals.renderer, DoubleWidth - 70, floor(Int64,(Globals.promptTextTexture.mHeight)), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, 0, 250, 0, 255); thickLineRGBA(renderer, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64, h[]) + 45, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64, h[] ) + 75, 3, 255, 250, 255, 255) cursorBlink = true else # reset after 1 cycle onTime = time() #println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> else ", time() - offTime,", ", time() - onTime) end #Update screen for butMap in buttonList # button maps help with managing clicks if butMap.state == "unclicked" buttonDraw(butMap.button) elseif butMap.state == "clicked" buttonDrawClicked(butMap.button) butMap.state = "unclicked" quit = true buttonClicked = butMap.button.TextStim.textMessage end end #if firstRun == true SDL_GetMouseState(mX, mY) draw(myPop, [ mX[], mY[] ] ) firstRun = false #println("drew popup") #end SDL_RenderPresent( renderer ); # check for enter or cancel end # At the end of the main loop we render the prompt text and the input text. SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); #SDL_DestroyWindow(SDL_Window * Window) closeWinOnly(dialogWin) return [buttonClicked, inputText] end #-============================================= function textInputDialog(dlgTitle::String, promptString::String, defaultText::String) SCREEN_WIDTH = 350 SCREEN_HEIGHT = 150 firstRun = true buttonClicked = "NoButton" quit::Bool = false; mX = Ref{Cint}() # pointers that will receive mouse coordinates mY = Ref{Cint}() cursorLocation = 0 # after the last character. This is in charachter units, not pixels cursorPixels = 0 # negative (leftward) pixels from end of string # this cycles during each refresh from true to false onTime = 0 # for timing of cursor blinns offTime = 0 # these are used later to get the size of the text when moving the cursor w = Ref{Cint}() h = Ref{Cint}() SDLevent = Ref{SDL_Event}() #Event handler textColor = SDL_Color(0, 0, 0, 0xFF) #Set text color as black InitPsychoJL() dialogWin = Window(title = dlgTitle, [SCREEN_WIDTH, SCREEN_HEIGHT], false) SDLwindow = dialogWin.win renderer = dialogWin.renderer Globals = SDLGlobals(SDLwindow, renderer, LTexture(C_NULL, 0 ,0), LTexture(C_NULL, 0 ,0) ) gFont = dialogWin.font #gFont = TTF_OpenFont("/Users/MattPetersonsAccount/Documents/Development/Julia/PsychoJL/sans.ttf", 36); # global font if gFont == C_NULL println("*** Error: gFont is NULL") end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_RenderClear(Globals.renderer) # #-===== Their code: #The current input text. #inputText::String = "Some Text"; inputText = defaultText #TTF_SetFontStyle(gFont, TTF_STYLE_ITALIC) Globals.promptTextTexture = loadFromRenderedText(Globals, promptString, textColor, dialogWin.italicFont); # inputText.c_str(), textColor ); leftX = (SCREEN_WIDTH - Globals.promptTextTexture.mWidth)÷2 promptText = TextStim(dialogWin, promptString, [SCREEN_WIDTH, 20 ], # you would think it would be SCREEN_WIDTH÷2, but hi-res messes it centers at SCREEN_WIDTH÷4. color = [0, 0, 0], fontSize = 24, horizAlignment = 0, vertAlignment = -1, style = "italic" ) #TTF_SetFontStyle(gFont, TTF_STYLE_NORMAL ) Globals.inputTextTexture = loadFromRenderedText(Globals, inputText, textColor, gFont); # inputText.c_str(), textColor ); #--------- Make buttons buttonList = [] OKtext = TextStim(dialogWin, "OK", [0, 0]) OKbutton = ButtonStim(dialogWin, [ round(Int64, SCREEN_WIDTH * 0.75), round(Int64, SCREEN_HEIGHT * 0.75)], # was 0.75, buthigh dpi shenanigans [ round(Int64, SCREEN_WIDTH * 0.25), 68], OKtext, "default") push!(buttonList, ButtonMap(OKbutton, "OK-clicked") ) CancelText = TextStim(dialogWin, "Cancel", [0, 0]) CancelButton = ButtonStim(dialogWin, [ round(Int64, SCREEN_WIDTH * 0.25), round(Int64, SCREEN_HEIGHT * 0.75)], # was 0.75, buthigh dpi shenanigans [ round(Int64, SCREEN_WIDTH * 0.25), 68], CancelText, "other") push!(buttonList, ButtonMap(CancelButton, "Cancel-clicked") ) #---------- end buttons #---------- Make PopUp popList = [] myPop = PopUpMenu(dialogWin, [70,100], [100, Globals.inputTextTexture.mHeight + 10], ["Cat", "Dog", "Bird"] ) # mouse clicks say 14,41 and 57,58 # popUp 20, 75 120, 125 size = 100, 51 # popUpMap 20, 75 120, 125 # new scaled Popmap 10,37 60,62 push!(popList, PopUpMap(myPop ) ) #---------- end buttons #Enable text input SDL_StartTextInput(); #= Before we go into the main loop we declare a string to hold our text and render it to a texture. We then call SDL_StartTextInput so the SDL text input functionality is enabled. =# #While application is running while( !quit ) renderText::Bool = false; # The rerender text flag while Bool(SDL_PollEvent(SDLevent)) # Handle events on queue event_ref = SDLevent evt = event_ref[] evt_ty = evt.type evt_key = evt.key evt_text = evt.text evt_mouseClick = evt.button # We only want to update the input text texture when we need to so we have a flag that keeps track of whether we need to update the texture. if( evt_ty == SDL_KEYDOWN ) #Special key input #Handle backspace if( evt_key.keysym.sym == SDLK_BACKSPACE && length(inputText) > 0 ) if (length(inputText) - cursorLocation - 1) >= 0 newString = first(inputText, length(inputText) - cursorLocation - 1) else newString = "" end println(cursorLocation," ",newString) inputText = newString * last(inputText, cursorLocation) #inputText = String(chop(inputText, tail = 1)) # remove last item; chop return a substring, so we have to cast it as String renderText = true; cursorLocation += 1 # move cursor as text expands elseif evt_key.keysym.sym == SDLK_RETURN || evt_key.keysym.sym == SDLK_KP_ENTER return ["OK", inputText] elseif evt_key.keysym.sym == SDLK_LEFT cursorLocation += 1 elseif evt_key.keysym.sym == SDLK_RIGHT cursorLocation -= 1 if cursorLocation <= 0 cursorLocation = 0 end end # SDLK_LEFT, SDLK_RIGHT # SDLK_LEFT = 1073741904 # SDLK_RIGHT = 1073741903 #= There are a couple special key presses we want to handle. When the user presses backspace we want to remove the last character from the string. When the user is holding control and presses c, we want to copy the current text to the clip board using SDL_SetClipboardText. You can check if the ctrl key is being held using SDL_GetModState. When the user does ctrl + v, we want to get the text from the clip board using SDL_GetClipboardText. This function returns a newly allocated string, so we should get this string, copy it to our input text, then free it once we're done with it. Also notice that whenever we alter the contents of the string we set the text update flag. =# #Special text input event elseif( evt_ty == SDL_TEXTINPUT ) textTemp = NTupleToString(evt_text.text) if (length(inputText) - cursorLocation ) >= 0 leftString = first(inputText, length(inputText) - cursorLocation ) else leftString = "" end inputText = leftString * textTemp * last(inputText, cursorLocation) #inputText = inputText * textTemp # * is Julila concatenate renderText = true; elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) x = evt_mouseClick.x y = evt_mouseClick.y for butMap in buttonList println(butMap.leftTop,", ",butMap.rightBottom) if (butMap.rightBottom[1] > x > butMap.leftTop[1]) && (butMap.rightBottom[2] > y > butMap.leftTop[2]) butMap.state = "clicked" end end for popMap in popList if (popMap.rightBottom[1] > x > popMap.leftTop[1]) && (popMap.rightBottom[2] > y > popMap.leftTop[2]) #popMap.popUp.state = "clicked" println("pre-state change ", popMap.leftTop,", ",popMap.rightBottom) stateChange(popMap) draw(popMap.popUp, [x,y]) # enter pop-up button drawing and selection loop end end #=elseif( evt_ty == SDL_MOUSEBUTTONUP ) x = evt_mouseClick.x y = evt_mouseClick.y for popMap in popList if (popMap.rightBottom[1] > x > popMap.leftTop[1]) && (popMap.rightBottom[2] > y > popMap.leftTop[2]) #popMap.popUp.state = "unclicked" draw(popMap.popUp, [x,y]) # enter pop-up button drawing and selection loop end end =# end end #= With text input enabled, your key presses will also generate SDL_TextInputEvents which simplifies things like shift key and caps lock. Here we first want to check that we're not getting a ctrl and c/v event because we want to ignore those since they are already handled as keydown events. If it isn't a copy or paste event, we append the character to our input string. =# if( renderText ) # Rerender text if needed if( inputText != "" ) # Text is not empty #Render new text Globals.inputTextTexture = loadFromRenderedText(Globals, inputText, textColor, gFont); # inputText.c_str(), textColor ); else #Text is empty #Render space texture Globals.inputTextTexture = loadFromRenderedText(Globals, " ", textColor, gFont ); end end #= If the text render update flag has been set, we rerender the texture. One little hack we have here is if we have an empty string, we render a space because SDL_ttf will not render an empty string. =# SDL_SetRenderDrawColor(renderer, 250, 250, 250, 255) SDL_RenderClear( renderer ); #Render text textures DoubleWidth = SCREEN_WIDTH * 2 # I don't know if this is a workaround for Retina or SDL_WINDOW_ALLOW_HIGHDPI, but a 400 pixel width yields 800 pixels #= render(Globals.renderer, Globals.promptTextTexture, # floor(Int64,DoubleWidth -( DoubleWidth - Globals.promptTextTexture.mWidth ) / 2), #SCREEN_WIDTH - floor( Int64, SCREEN_WIDTH - (Globals.promptTextTexture.mWidth/2) ), 20, Globals.promptTextTexture.mWidth, Globals.promptTextTexture.mHeight ); =# draw(promptText) myInputBox = InputBox( [35, Globals.promptTextTexture.mHeight÷2 + 17], [ (DoubleWidth - 140)÷2, Globals.inputTextTexture.mHeight÷2 + 5 ] ) drawInputBox(renderer, myInputBox) #= SDL_Rect( 70, floor(Int64,(Globals.promptTextTexture.mHeight)) + 35, DoubleWidth - 140, Globals.inputTextTexture.mHeight + 10 ) =# render(Globals.renderer, Globals.inputTextTexture, #40, #floor(Int64,( SCREEN_WIDTH - Globals.inputTextTexture.mWidth ) / 2 ), #DoubleWidth - (Globals.inputTextTexture.mWidth + 20), DoubleWidth - 70 - (Globals.inputTextTexture.mWidth + 10), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, Globals.inputTextTexture.mWidth, Globals.inputTextTexture.mHeight ); #------------------- # need to get size of text for curso using cursorLocation TTF_SizeText(gFont, last(inputText, cursorLocation), w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory cursorScootch = w[] #------------------- if (time() - onTime) < 1 thickLineRGBA(Globals.renderer, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64,(Globals.promptTextTexture.mHeight)) + 45, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64,(Globals.promptTextTexture.mHeight)) + 75, 3, 0, 0, 0, 255) cursorBlink = false elseif 1 < (time() - onTime) < 2 # show during this time #vlineRGBA(Globals.renderer, DoubleWidth - 70, floor(Int64,(Globals.promptTextTexture.mHeight)), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, 0, 250, 0, 255); thickLineRGBA(Globals.renderer, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64,(Globals.promptTextTexture.mHeight)) + 45, DoubleWidth - 70 - 10 - cursorScootch, floor(Int64,(Globals.promptTextTexture.mHeight)) + 75, 3, 255, 250, 255, 255) cursorBlink = true else # reset after 1 cycle onTime = time() #println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> else ", time() - offTime,", ", time() - onTime) end #Update screen for butMap in buttonList # button maps help with managing clicks if butMap.state == "unclicked" buttonDraw(butMap.button) elseif butMap.state == "clicked" buttonDrawClicked(butMap.button) butMap.state = "unclicked" quit = true buttonClicked = butMap.button.TextStim.textMessage end end #if firstRun == true SDL_GetMouseState(mX, mY) draw(myPop, [ mX[], mY[] ] ) firstRun = false #println("drew popup") #end SDL_RenderPresent( renderer ); # check for enter or cancel end # At the end of the main loop we render the prompt text and the input text. SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); #SDL_DestroyWindow(SDL_Window * Window) closeWinOnly(dialogWin) return [buttonClicked, inputText] end #-================================================================================================================== #-================================================================================================================== #-================================================================================================================== #= if key has a dict, its a pull-down menu, else its a text box's default values - find widest key - widest key + padding determines width of left column (there needs to be some minimum - both buttons are as wide as the left column (some minimum width) - right column is the rest of the screen minus padding - need to implement ways to change input widget focus - would love a way to pick TTF from various operating systems =# """ DlgFromDict(dlgDict::Dict) Displays a dialog box constructed from a dictionary. **Inputs:** Dictionary defining the input fields (keys) and pre-filled values (values) for the user dialog\n If the value is a string, that indicates a text input box with a default value. If the value is a tuple, it indicates that the widget should be pop-up menu populated by the choices listed in the tuple\n **Outputs:** Dictionary of responses. Keys are from the input dictionary. Example: ```julia 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) ``` ![alternative text](dlgDictSmall.png) """ function DlgFromDict(dlgDict::Dict) DEBUG = true SCREEN_WIDTH = 350 SCREEN_HEIGHT = 150 firstRun = true buttonClicked = "NoButton" quit::Bool = false; focusedInput = 1 # -99 mX = Ref{Cint}() # pointers that will receive mouse coordinates mY = Ref{Cint}() cursorLocation = 0 # after the last character. This is in charachter units, not pixels cursorPixels = 0 # negative (leftward) pixels from end of string # this cycles during each refresh from true to false onTime = 0 # for timing of cursor blinns offTime = 0 # these are used later to get the size of the text when moving the cursor w = Ref{Cint}() h = Ref{Cint}() SDLevent = Ref{SDL_Event}() #Event handler textColor = SDL_Color(0, 0, 0, 0xFF) #Set text color as black # InitPsychoJL() # Is it bad form to call this here? dialogWin = Window([SCREEN_WIDTH, SCREEN_HEIGHT], false, title = "") SDLwindow = dialogWin.win renderer = dialogWin.renderer #Globals = SDLGlobals(SDLwindow, renderer, LTexture(C_NULL, 0 ,0), LTexture(C_NULL, 0 ,0) ) gFont = dialogWin.font if gFont == C_NULL println("*** Error: gFont is NULL") end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_SetRenderDrawColor(dialogWin.renderer, 250, 250, 250, 255) SDL_RenderClear(dialogWin.renderer) #--- DictDlg really starts here ------------------------ # - find widest key and draw the key labels widestKey = 20 # arbitrary minimum size labels = [] i = 1 outDictionary = deepcopy(dlgDict) # we really just want the keys...we'll replace the values later for (key, value) in dlgDict TTF_SizeText(gFont, key, w::Ref{Cint}, h::Ref{Cint}) if w[] > widestKey widestKey = w[] end println(key,", ", w[]) label = TextStim(dialogWin, key, [20, 10 + (i*(h[] + 10)) ], color = [0, 0, 0], fontSize = 24, horizAlignment = -1, vertAlignment = 1 ) push!(labels, label) i += 1 end widestKey ÷= 2 # Damn hi-res stuff! #--------- # draw labels along left side for label in labels draw(label) end #--------- # draw OK button buttonList = [] OKtext = TextStim(dialogWin, "OK", [0, 0]; color = "white") OKbutton = ButtonStim(dialogWin, #[ 20 + (widestKey), 10 + ((length(labels)+1) * (h[] +10)) ], # was 0.75, buthigh dpi shenanigans #[ widestKey, h[] + 10], [ round(Int64, SCREEN_WIDTH *0.8), SCREEN_HEIGHT - (h[] ÷ 2)], [ (SCREEN_WIDTH ÷ 5) , h[] + 10], OKtext, "default") _, ytemp = OKbutton.pos ytemp ÷= 2 #OKbutton.pos[2] = ytemp push!(buttonList, ButtonMap(OKbutton, "OK-clicked") ) buttonDraw(OKbutton) #--------- # draw Cancel button Canceltext = TextStim(dialogWin, "Cancel", [0, 0]; color = "black") CancelButton = ButtonStim(dialogWin, [ round(Int64, SCREEN_WIDTH *0.5), SCREEN_HEIGHT - (h[] ÷ 2)], [ (SCREEN_WIDTH ÷ 5) , h[] + 10], Canceltext, "other") _, ytemp = CancelButton.pos ytemp ÷= 2 #CancelButton.pos[2] = ytemp push!(buttonList, ButtonMap(CancelButton, "Cancel-clicked") ) buttonDraw(CancelButton) #------------- # draw input widgets inputWidgets = [] inputMapList = [] popUpList = [] i = 0 for (key, value) in dlgDict leftSide = 40 + widestKey topSide = 17 + (i*(h[] + 10)) if value isa String || value isa Number # input text box if value isa Number value = string(value) # convert numbers to strings end if value == "" value = " " #requires at least one charcters end myInputBox = InputBox(dialogWin, value, [leftSide, topSide÷2 ], #-8 [SCREEN_WIDTH - (widestKey + 60), h[]÷2 + 2 ], key ) push!(inputWidgets, myInputBox) push!(inputMapList, InputBoxMap(myInputBox)) draw(myInputBox) i += 1 elseif value isa Tuple #leftSide2 = leftSide + ((SCREEN_WIDTH - leftSide)÷2) # input box is top left, this is center leftSide2 = leftSide + ((SCREEN_WIDTH - (widestKey + 60))÷2) # input box is top left, this is center leftSide2 *= 2 topSide2 = topSide + h[]÷2 myPop = PopUpMenu(dialogWin, #[80 + widestKey*2, 20 + (i*(h[] + 10))*2 ], # center pos #[leftSide2 , topSide2], [leftSide, topSide ], [ (SCREEN_WIDTH - (widestKey + 60))*2, (h[]÷2 + 2)*2 ], collect(value), # collect turns tuple into an array key ) push!(inputWidgets, myPop) push!(inputMapList, PopUpMap(myPop )) push!(popUpList, PopUpMap(myPop )) draw(myPop, [ -99, -99 ] ) i += 1 end end # drawInputBox(renderer, myInputBox) bend = 0 # wait for KeyUp first so that we can debounce # but I don't think it will work for this, as dialogWin is not the main window! # therefore, it contains a different .firstKey! #= done = false while done == false || dialogWin.firstKey == false while Bool(SDL_PollEvent(SDLevent)) event_ref = SDLevent evt = event_ref[] evt_ty = evt.type if( evt_ty == SDL_KEYUP ) done = true end end end =# # win.firstKey = true # couldn't find a way to inject a Key_UP event in the queue, so did this instead SDL_StartTextInput() while( !quit ) renderText::Bool = false; # The rerender text flag while Bool(SDL_PollEvent(SDLevent)) # Handle events on queue event_ref = SDLevent evt = event_ref[] evt_ty = evt.type evt_key = evt.key evt_text = evt.text evt_mouseClick = evt.button # We only want to update the input text texture when we need to so we have a flag that keeps track of whether we need to update the texture. if( evt_ty == SDL_KEYDOWN ) #Special key input #Handle backspace if typeof(inputWidgets[focusedInput]) == InputBox if( evt_key.keysym.sym == SDLK_BACKSPACE && length(inputWidgets[focusedInput].valueText) > 0 ) #if (length(inputText) - cursorLocation - 1) >= 0 # newString = first(inputText, length(inputText) - cursorLocation - 1) if (length(inputWidgets[focusedInput].valueText) - cursorLocation - 1) >= 0 newString = first(inputWidgets[focusedInput].valueText, length(inputWidgets[focusedInput].valueText) - cursorLocation - 1) else newString = "" end println("\n.........",cursorLocation," ",newString) inputWidgets[focusedInput].valueText = newString * last(inputWidgets[focusedInput].valueText, cursorLocation) #inputText = String(chop(inputText, tail = 1)) # remove last item; chop return a substring, so we have to cast it as String renderText = true; cursorLocation += 1 # move cursor as text expands elseif evt_key.keysym.sym == SDLK_LEFT cursorLocation += 1 elseif evt_key.keysym.sym == SDLK_RIGHT cursorLocation -= 1 if cursorLocation <= 0 cursorLocation = 0 end end end if evt_key.keysym.sym == SDLK_RETURN || evt_key.keysym.sym == SDLK_KP_ENTER for inWidgit in inputWidgets outDictionary[inWidgit.key] = inWidgit.valueText end SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); closeWinOnly(dialogWin) return ["OK", outDictionary] end elseif( evt_ty == SDL_TEXTINPUT && typeof(inputWidgets[focusedInput]) == InputBox) #Special text input event textTemp = NTupleToString(evt_text.text) if (length(inputWidgets[focusedInput].valueText) - cursorLocation ) >= 0 leftString = first(inputWidgets[focusedInput].valueText, length(inputWidgets[focusedInput].valueText) - cursorLocation ) else leftString = "" end inputWidgets[focusedInput].valueText = leftString * textTemp * last(inputWidgets[focusedInput].valueText, cursorLocation) #inputText = inputText * textTemp # * is Julila concatenate renderText = true; if DEBUG; println("...",inputWidgets[focusedInput].valueText); end #--------------------------------------------------------------------------------------- #= make list of clicks determine who gets the click if clicks > 1 if focus is one of them focus gets click else give error stating that too many widgets got a click else widget gets click act on the click =# elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) # new version makes a list of clicked items, and the item with the focus is the winner x = evt_mouseClick.x y = evt_mouseClick.y println("evt_mouseClick.x/y = ",x,", ", y ) for butMap in buttonList println(butMap.leftTop,", ",butMap.rightBottom) if (butMap.rightBottom[1] > x > butMap.leftTop[1]) && (butMap.rightBottom[2] > y > butMap.leftTop[2]) butMap.state = "clicked" end end clickedItemIndexes = [] #---------------------- # make list of clicks for i in eachindex(inputMapList) inMap = inputMapList[i] if (inMap.rightBottom[1] > x > inMap.leftTop[1]) && (inMap.rightBottom[2] > y > inMap.leftTop[2]) println("ooooo in a inMap") println(" ooooo state ", inMap.parent.state ) println(" ooooo typeof ", typeof(inMap.parent)) push!(clickedItemIndexes, i) end end #---------------------- # determine who gets the click focusClicked = false focusIndex = -99 for ci in clickedItemIndexes if inputMapList[ci].parent.focus == true focusClicked = true focusIndex = ci end end #---------------------- # if more than one item clicked, use focus as a tie-break (the focused item is expanded and covering another widget). if length(clickedItemIndexes) > 1 # for now, we assume focus was clicked...but might need to check if typeof(inputMapList[focusIndex]) == ButtonMap inputMapList[focusIndex].state = "clicked" elseif typeof(inputMapList[focusIndex]) == PopUpMap stateChange(inputMapList[focusIndex]) draw(inputMapList[focusIndex].parent, [x,y]) end elseif length(clickedItemIndexes) == 1 index = clickedItemIndexes[1] if typeof(inputMapList[index]) == ButtonMap inputMapList[i].state = "clicked" elseif typeof(inputMapList[index]) == PopUpMap stateChange(inputMapList[index]) draw(inputMapList[index].parent, [x,y]) end focusedInput = index for i in eachindex(inputMapList) if i == focusedInput inputMapList[i].parent.focus = true else inputMapList[i].parent.focus = false end end else println(".......", evt_ty," ,",typeof(inputWidgets[focusedInput])) end end #= elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) # new version makes a list of clicked items, and the item with the focus is the winner x = evt_mouseClick.x y = evt_mouseClick.y println("evt_mouseClick.x/y = ",x,", ", y ) clickedItemIndexes = [] for i in eachindex(inputMapList) inMap = inputMapList[i] if (inMap.rightBottom[1] > x > inMap.leftTop[1]) && (inMap.rightBottom[2] > y > inMap.leftTop[2]) println("ooooo in a inMap") println(" ooooo state ", inMap.parent.state ) println(" ooooo typeof ", typeof(inMap.parent)) push!(clickedItemIndexes, i) end end focusFound = false for i in clickedItemIndexes if inputMapList[i].parent.focus == true # we found a winner! focusFound = true if typeof(inputMapList[i]) == ButtonMap inputMapList[i].state = "clicked" elseif typeof(inputMapList[i]) == PopUpMap stateChange(inputMapList[i]) draw(inputMapList[i].parent, [x,y]) end elseif focusFound == false # we never found the focus, so go with the only one on the list. If list is>0, send error if length(clickedItemIndexes) == 1 inMap = inputMapList[i] # set focus flags if (inMap.rightBottom[1] > x > inMap.leftTop[1]) && (inMap.rightBottom[2] > y > inMap.leftTop[2]) focusedInput = i inMap.parent.focus = true println("focus = ", inMap.leftTop, inMap.rightBottom) else inMap.parent.focus = false we are in a subset of clicked items. Need all so that we can unfocus the others. end # do widget specific stuff if typeof(inputMapList[i]) == ButtonMap inputMapList[i].state = "clicked" elseif typeof(inputMapList[i]) == PopUpMap stateChange(inputMapList[i]) draw(inputMapList[i].parent, [x,y]) end focusedInput = i else #buf = error("\n*** You have a problem, as two or more widgets received a click \n", clickedItemIndexes,"\n") end end end end =# #----------------------------------------------------------------------------------------------------- # what about the lines setting and unsetting focus? # old version below #= elseif( evt_ty == SDL_MOUSEBUTTONDOWN ) x = evt_mouseClick.x y = evt_mouseClick.y println("evt_mouseClick.x/y = ",x,", ", y ) clickOverlap = false # skip next part of mouse click overlaps with a popup whose state is "clicked" for i in eachindex(inputMapList) inMap = inputMapList[i] if (inMap.rightBottom[1] > x > inMap.leftTop[1]) && (inMap.rightBottom[2] > y > inMap.leftTop[2]) println("ooooo in a inMap") println(" ooooo state ", inMap.parent.state ) println(" ooooo typeof ", typeof(inMap.parent)) if inMap.parent.state == "clicked" && typeof(inMap.parent) == PopUpMenu clickOverlap = true println(">>>> clickOverlap = true") stateChange(inMap) draw(inMap.parent, [x,y]) # CALLED # enter pop-up button drawing and selection loop end end end if clickOverlap == false # skip these if the mouse click was in an open pop-up for i in eachindex(inputMapList) inMap = inputMapList[i] if (inMap.rightBottom[1] > x > inMap.leftTop[1]) && (inMap.rightBottom[2] > y > inMap.leftTop[2]) focusedInput = i inMap.parent.focus = true println("focus = ", inMap.leftTop, inMap.rightBottom) else inMap.parent.focus = false end end for butMap in buttonList if (butMap.rightBottom[1] > x > butMap.leftTop[1]) && (butMap.rightBottom[2] > y > butMap.leftTop[2]) butMap.state = "clicked" end end for popMap in popUpList if (popMap.rightBottom[1] > x > popMap.leftTop[1]) && (popMap.rightBottom[2] > y > popMap.leftTop[2]) #popMap.popUp.state = "clicked" println("pre-state change ", popMap.leftTop,", ",popMap.rightBottom) stateChange(popMap) println("post-state change ", popMap.leftTop,", ",popMap.rightBottom) draw(popMap.parent, [x,y]) # CALLED # enter pop-up button drawing and selection loop end end end println(">>>>>>>>>> button end ", bend) bend+=1 end # evt_ty == SDL_MOUSEBUTTONDOWN =# end #= With text input enabled, your key presses will also generate SDL_TextInputEvents which simplifies things like shift key and caps lock. Here we first want to check that we're not getting a ctrl and c/v event because we want to ignore those since they are already handled as keydown events. If it isn't a copy or paste event, we append the character to our input string. =# if( renderText ) # Rerender text if needed if typeof(inputWidgets[focusedInput]) == InputBox if( inputWidgets[focusedInput].valueText != "" ) # Text is not empty #Render new text #Globals.inputTextTexture = loadFromRenderedText(Globals, inputText, textColor, gFont); # inputText.c_str(), textColor ); draw(inputWidgets[focusedInput]) else #Text is empty #Render space texture inputWidgets[focusedInput].valueText = " " println("- draw 654: ", focusedInput) end end end SDL_SetRenderDrawColor(renderer, 250, 250, 250, 255) SDL_RenderClear( renderer ); #-------------------------------------------- # Update widgets and such for label in labels draw(label) end for i in eachindex(inputWidgets) if i != focusedInput # draw the non-focus widgets first draw(inputWidgets[i]) # CALLED end end if focusedInput != -99 # we do this to make sure any exanded widgets are on top and not drawn over draw(inputWidgets[focusedInput]) # CALLED end #Render text textures DoubleWidth = SCREEN_WIDTH * 2 # I don't know if this is a workaround for Retina or SDL_WINDOW_ALLOW_HIGHDPI, but a 400 pixel width yields 800 pixels #= myInputBox = InputBox( [35, Globals.promptTextTexture.mHeight÷2 + 17], [ (DoubleWidth - 140)÷2, Globals.inputTextTexture.mHeight÷2 + 5 ] ) drawInputBox(renderer, myInputBox) render(Globals.renderer, Globals.inputTextTexture, #40, #floor(Int64,( SCREEN_WIDTH - Globals.inputTextTexture.mWidth ) / 2 ), #DoubleWidth - (Globals.inputTextTexture.mWidth + 20), DoubleWidth - 70 - (Globals.inputTextTexture.mWidth + 10), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, Globals.inputTextTexture.mWidth, Globals.inputTextTexture.mHeight ); =# #------------------- if focusedInput > 0 && typeof(inputWidgets[focusedInput]) == InputBox # only blink cursor in a textbox that is the focus in = inputWidgets[focusedInput] # need to get size of text for curso using cursorLocation TTF_SizeText(dialogWin.font, last(in.valueText, cursorLocation), w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory cursorScootch = w[] #------------------- if (time() - onTime) < 1 thickLineRGBA(dialogWin.renderer, in.textRect.x + in.textRect.w -6 - cursorScootch, in.textRect.y +10, in.textRect.x + in.textRect.w -6 - cursorScootch, in.textRect.y +10 + h[]-10, 3, 255, 0, 0, 255) cursorBlink = false elseif 1 < (time() - onTime) < 2 # show during this time #vlineRGBA(Globals.renderer, DoubleWidth - 70, floor(Int64,(Globals.promptTextTexture.mHeight)), floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, 0, 250, 0, 255); thickLineRGBA(dialogWin.renderer, in.textRect.x + in.textRect.w -6 - cursorScootch, in.textRect.y +10, in.textRect.x + in.textRect.w -6 - cursorScootch, in.textRect.y +10 + h[]-10, 3, 255, 250, 255, 255) cursorBlink = true else # reset after 1 cycle onTime = time() #println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> else ", time() - offTime,", ", time() - onTime) end end #Update screen for butMap in buttonList # button maps help with managing clicks if butMap.state == "unclicked" buttonDraw(butMap.button) elseif butMap.state == "clicked" buttonDrawClicked(butMap.button) butMap.state = "unclicked" quit = true buttonClicked = butMap.button.TextStim.textMessage end end #if firstRun == true SDL_GetMouseState(mX, mY) for myPop in popUpList if myPop.parent.focus == true draw(myPop.parent, [ mX[], mY[] ] ) end end firstRun = false #println("drew popup") #end SDL_RenderPresent( renderer ); # check for enter or cancel end #-------------- Show stuff SDL_StopTextInput(); #Disable text input hideWindow(dialogWin) SDL_RenderPresent( renderer ); #SDL_DestroyWindow(SDL_Window * Window) closeWinOnly(dialogWin) for inWidgit in inputWidgets outDictionary[inWidgit.key] = inWidgit.valueText end return [buttonClicked, outDictionary] end #-===================================================================================== # Utility functions #-===================================================================================== #- GTK versions (unused) ============================================================= #= function askQuestionDialog(message::String) Gtk.ask_dialog("Do you like chocolate ice cream?", "Not at all", "I like it") && println("That's my favorite too.") end #-=================================================== function inputDialog(message::AbstractString, entry_default::AbstractString) # input_dialog(message::AbstractString, entry_default::AbstractString, buttons = (("Cancel", 0), ("Accept", 1)), parent = GtkNullContainer()) resp, entry_text = Gtk.input_dialog(message, entry_default) #buttons = (("Cancel", 0), ("Accept", 1))) return resp, entry_text end =#
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
6215
export InputBox #-========================================================================================================== mutable struct SDLGlobals SDLwindow renderer inputTextTexture promptTextTexture end #-========================================================================================================== # more global shit from here: https:# pastebin.com/HvWxcZKv mutable struct LTexture # Initialize mTexture mWidth mHeight end #-================================== function NTupleToString(NTuple) theString::String = "" i = 1 done = false while !done theChar = NTuple[i] if theChar == 0 # 0 terminated Cstring done = true else theChar = Char(theChar) # convert ascii interger to char theString = theString * theChar i += 1 end end return theString end #-================================== mutable struct InputBox win::Window valueText::String leftTop::Vector{Int64} size::Vector{Int64} focus::Bool textTexture::LTexture rightBottom::Vector{Int64} pos::Vector{Int64} textRect::SDL_Rect #Ref{SDL_Rect} # for drawing the text state::String key::String # dictionary key function InputBox( win::Window, valueText::String, leftTop::Vector{Int64}, size::Vector{Int64}, key::String = "no-key-given") # should probably check to see if theses are valid, or flip their order if needed if valueText == "" valueText = " " end textTexture = loadFromRenderedText(win, valueText, SDL_Color(0,0,0,255)) rightBottom = [ leftTop[1] + size[1],leftTop[2] + size[2] ] pos = [(leftTop[1] + rightBottom[1])÷2,(leftTop[2] + rightBottom[2])÷2] textRect = SDL_Rect( leftTop[1] *2 , leftTop[2] *2 , size[1] *2 , size[2] *2 ) new(win, valueText, leftTop, size, false, textTexture, rightBottom, pos, textRect, "unused", key ) end end #-================================== mutable struct InputBoxMap parent::InputBox state::String # clicked or not leftTop::Vector{Int64} rightBottom::Vector{Int64} function InputBoxMap( inBox::InputBox) state = "unclicked" leftTop = [inBox.pos[1] - inBox.size[1]÷ 2, inBox.pos[2] - inBox.size[2]÷ 2] #leftTop[1] ÷= 2 #leftTop[2] ÷= 2 rightBottom = [inBox.pos[1] + inBox.size[1]÷ 2, inBox.pos[2] + inBox.size[2]÷ 2] #rightBottom[1] ÷= 2 #rightBottom[2] ÷= 2 #left = inBox.leftTop[1]# + (in.size[1] ÷2) #top = inBox.leftTop[2]# + (in.size[2] ÷2) new(inBox, state, leftTop, rightBottom ) end end #-================================== function draw(in::InputBox) # drawInputBox # left = in.leftTop[1]# + (in.size[1] ÷2) # top = in.leftTop[2]# + (in.size[2] ÷2) # myRect = SDL_Rect( left *2 , top *2 , in.size[1] *2 , in.size[2] *2 ) drawInputBox(in, in.textRect, in.focus) end #-- function drawInputBox(in::InputBox, R::SDL_Rect, focus::Bool) #drawInputBox # first draw filled Rect SDL_SetRenderDrawColor(in.win.renderer, 255, 255, 255, 255) SDL_RenderFillRect( in.win.renderer, Ref{SDL_Rect}(R)) # then draw outline if focus == false SDL_SetRenderDrawColor(in.win.renderer, 0, 0, 0, 255) else SDL_SetRenderDrawColor(in.win.renderer, 0, 0, 255, 255) end SDL_RenderDrawRect( in.win.renderer, Ref{SDL_Rect}(R)) #----------------------------------------------- in.textTexture = loadFromRenderedText(in.win, in.valueText, SDL_Color(0,0,0,255)) render(in.win.renderer, in.textTexture, #DoubleWidth - 70 - (Globals.inputTextTexture.mWidth + 10), #floor(Int64,(Globals.promptTextTexture.mHeight)) + 40, #R.x, R.y, convert(Int32, R.x + R.w -6 - in.textTexture.mWidth), # -22 convert(Int32, R.y +8), #Globals.inputTextTexture.mWidth, #Globals.inputTextTexture.mHeight in.textTexture.mWidth, in.textTexture.mHeight #R.w, R.h ) end #-========================================================================================================== # from https:# gist.github.com/TomMinor/855879407c5acca83225 # same person, but on github 13 years earlier #function loadFromRenderedText(Globals::SDLGlobals, textureText::String, textColor::SDL_Color, gFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} ) function loadFromRenderedText(win::Window, textureText::String, textColor::SDL_Color ) # Render text surface #textSurface = TTF_RenderText_Blended( gFont, textureText, textColor ); # should anti-alias compared to solid? textSurface = TTF_RenderText_Blended( win.font, textureText, textColor ); # should anti-alias compared to solid? if( textSurface == C_NULL ) println( "Unable to render text surface! SDL_ttf Error: %s\n", SDL_GetError() ) #TTF_GetError() ); return false; end # Create texture from surface pixels # font_texture = SDL_CreateTextureFromSurface( Globals.renderer, textSurface ); font_texture = SDL_CreateTextureFromSurface( win.renderer, textSurface ); if( font_texture == C_NULL ) println( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); return false; end # Get image dimensions w = Ref{Cint}() h = Ref{Cint}() #TTF_SizeText(gFont, textureText, w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory TTF_SizeText(win.font, textureText, w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory mWidth = w[] mHeight = h[] #Get rid of old surface SDL_FreeSurface( textSurface ); # Return success tempTextTexture = LTexture(font_texture, mWidth ,mHeight) return tempTextTexture end #-========================================================================================================== function render(renderer::Ptr{SDL_Renderer}, ltexture::LTexture, x::Int32, y::Int32, mWidth::Int32, mHeight::Int32) render(renderer, ltexture, convert(Int64, x), convert(Int64, y), mWidth, mHeight) end #----------------- function render(renderer::Ptr{SDL_Renderer}, ltexture::LTexture, x::Int64, y::Int64, mWidth::Int32, mHeight::Int32) renderQuad = SDL_Rect( x, y, mWidth, mHeight ) SDL_RenderCopyEx( renderer, ltexture.mTexture, C_NULL, Ref{SDL_Rect}(renderQuad), 0.0, C_NULL, SDL_FLIP_NONE ); end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
3635
export imageStim #-================================================================== """ ImageStim() Constructor for an ImageStim object **Constructor inputs:** * win::Window\n * imageName::String.......*includes path*\n * pos::Vector{Int64}\n **Optional constructor inputs:** * image::Ptr{SDL_Texture} * width::Int64 * height::Int64 **Methods:** * draw() **Notes:** width and height are automatically calculated during ImageStim construction. """ mutable struct ImageStim #{T} win::Window imageName::String pos::PsychoCoords image::Ptr{SDL_Texture} width::Int64 # this will need to change to floats for Psychopy height coordiantes height::Int64 _pos::Vector{Int64} # opacity::Int64 # these will need to change to floats to handle Psychopy colors #---------- function ImageStim( win::Window, imageName::String, pos::PsychoCoords = [20,20]; # just far enough to be visible width = 0, # this will need to change to floats for Psychopy height coordiantes height = 0 # opacity::Int64 = 255 # these will need to change to floats to handle Psychopy colors ) surface = IMG_Load(imageName) # loads a picture from a file into a surface buffer. Surfaces are usually transfered to something else image = SDL_CreateTextureFromSurface(win.renderer, surface) # Now we create a texture from our intial surface if image == C_NULL error("Could not open image file") end SDL_FreeSurface(surface) # Delete the surface, as we no longer need it. w_ref, h_ref = Ref{Cint}(0), Ref{Cint}(0) # These create C integer pointers: https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/ SDL_QueryTexture(image, C_NULL, C_NULL, w_ref, h_ref) # get the attributes of a texture, such as width and height w, h = w_ref[], h_ref[] _pos = SDLcoords(win, pos) #------- # change the position so that it draws at the center of the image and not the top-left #pos[1] -= w÷2 #pos[2] -= h÷2 #------- new(win, imageName, pos, # [ round(Int64, winW/2), round(Int64, winH/2)], image, w, # this will need to change to floats for Psychopy height coordiantes h, _pos ) end end #---------- """ draw(theImageStim::ImageStim; magnification::Float64) Draws an ImageStim to the back buffer. **Inputs:** * theImageStim::ImageStim **Optional Inputs:** * magnification::Float64 """ function draw(theImageStim::ImageStim; magnification::Float64) if magnification == 0 centX = theImageStim._pos[1] - theImageStim.width÷2 centY = theImageStim._pos[2] - h÷2 dest_ref = Ref(SDL_Rect(centX, centY, theImageStim.width, theImageStim.height)) else centX = theImageStim._pos[1] - (theImageStim.width * magnification)÷2 centY = theImageStim._pos[2] - (theImageStim.height * magnification)÷2 dest_ref = Ref(SDL_Rect(centX, centY, theImageStim.width * magnification, theImageStim.height * magnification ) ) end # dest_ref[] = SDL_Rect(theImageStim.pos[1], theImageStim.pos[2], theImageStim.width, theImageStim.height) #println(theImageStim.pos[1],", ",theImageStim.pos[2],", ",theImageStim.width,", ",theImageStim.height) SDL_RenderCopy(theImageStim.win.renderer, theImageStim.image, C_NULL, dest_ref) end #----------------------- """ setPos(image::ImageStim, coords::, coordinates) Set the position of the image, usually the center unless specified otherwise. See "Setter Functions" in side tab for more information. """ function setPos(image::ImageStim, coords::PsychoCoords) image._pos = SDLcoords(image.win, coords) image.pos = coords end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
11487
export PopUpMenu, PopUpMap mutable struct PopUpMenu win::Window pos::Vector{Int64} size::Vector{Int64} options::Array # list of strings that can be selected selectionIndex::Int64 # index option that is selected valueText::String # text of option that is selected #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 selectionColor::Vector{Int64} textColor::Vector{Int64} selectionTextColor::Vector{Int64} selectionHeight::Int64 state::String leftTop::Vector{Int64} # these change when the state changes, reflecting that the menu has grown rightBottom::Vector{Int64} fullLT::Vector{Int64} # this is the full size it expands to when clicked. fullRB::Vector{Int64} menuTexts::Vector{TextStim} smallLT::Vector{Int64} smallRB::Vector{Int64} horizAlignment::Int64 # -1 for left, 0 for center, +1 for right vertAlignment::Int64 # -1 aligns at top, 0 for center, +1 aligns at bottom focus::Bool key::String # dictionary key function PopUpMenu( win::Window, pos::Vector{Int64}, size::Vector{Int64}, options::Array, key = "no-key-given"; horizAlignment = -1, vertAlignment = -1) if vertAlignment == -1 # top anchored pos[2] += size[2]÷2 elseif vertAlignment == 0 # center anchored pos[2] = pos[2] elseif vertAlignment == +1 # bottom anchored pos[2] -= size[2]÷2 else error("invalid popUp vertical popUp alignment parameter") end #--------- if horizAlignment == -1 # left anchored pos[1] += size[1]÷2 elseif horizAlignment == 0 # center justification pos[1] = pos[1] elseif horizAlignment == +1 # right anchored pos[1] -= size[1]÷2 else error("invalid popUp horizontal popUp alignment parameter") end state = "unclicked" leftTop = [ 2*(pos[1] - size[1]÷ 2), pos[2] - size[2]÷ 2] rightBottom = [leftTop[1] + size[1], leftTop[2] + size[2]] #rightBottom = [pos[1] + size[1]÷ 2, pos[2] + size[2]÷ 2] #----- calculate full expanded size w = Ref{Cint}() h = Ref{Cint}() count = length(options) halfCount = count/2 maxWidth = 0 for opt in options TTF_SizeText(win.font, opt, w::Ref{Cint}, h::Ref{Cint}) if w[] > maxWidth maxWidth = w[] end end maxWidth += 10 if maxWidth < size[1] # size is user defined size of the unclicked box maxWidth = size[1] end height = h[] #* length(options[1]) + 10 #= fullLT = [pos[1] - maxWidth ÷ 2, pos[2] - height ÷ 2] fullRB = [pos[1] + maxWidth ÷ 2, pos[2] + height ÷ 2] =# fullLT = [leftTop[1], pos[2] - round(Int64, (height * halfCount)) - 4] # pos[1] - maxWidth ÷ 2, fullRB = [rightBottom[1], pos[2] + round(Int64, (height * halfCount)) + 4 ] #pos[1] + maxWidth ÷ 2, #----- txtColor = [0,0,0,255] selectTextColor = [255,255,255,255] selectColor = [64, 135, 247, 255] background = [250, 250, 250, 255] selectHeight = height + 4 #----- menuTexts::Vector{TextStim} = [] for i in eachindex(options) # make text stimuli for each entry popUpText = TextStim(win, options[i], [0, 0]; color = txtColor) #popUpText.pos = [leftTop[1] + 4 , pos[2] ] popUpText.pos = [leftTop[1] + 10 , rightBottom[2]-4 ] #popUpText.color = txtColor popUpText.fontSize = 24 popUpText.horizAlignment = -1 popUpText.vertAlignment = +1 #popUpText.style = "bold" push!(menuTexts, popUpText) end #----- smallLT = leftTop smallRB = rightBottom #----- new(win, pos, size, options, 1, options[1], [200,200,200,255], background, selectColor, txtColor, selectTextColor, selectHeight, "unclicked", leftTop, rightBottom, fullLT, fullRB, menuTexts, smallLT, smallRB, horizAlignment,vertAlignment, # horizAlignment, vertAlignment false, key ) end end #---------------------------- function drawPopUpArrows(popUp::PopUpMenu) verts = [ [-8, -8], [+8, -8], [0, +8]] verts1 = [ [-8, 2], [0, +10], [+8, 2]] verts2 = [ [-8, -2], [0, -10], [+8, -2]] cX = popUp.rightBottom[1] - 19 cY = popUp.pos[2] for i in 1:(length(verts1)-1) draw( Line(popUp.win, [cX + verts1[i][1], cY + verts1[i][2]], [cX + verts1[i+1][1], cY + verts1[i+1][2]], width = 4, lineColor = [255,255,255,255] ) ) end #draw( line(popUp.win, [cX + verts1[3][1], cY + verts1[3][2]], [cX + verts1[1][1], cY + verts1[1][2]], width = 4, lineColor = [255,255,255,255] ) ) # [160,160,255,255] for i in 1:(length(verts2)-1) draw( Line(popUp.win, [cX + verts2[i][1], cY + verts2[i][2]], [cX + verts2[i+1][1], cY + verts2[i+1][2]], width = 4, lineColor = [255,255,255,255] ) ) end #draw( line(popUp.win, [cX + verts2[3][1], cY + verts2[3][2]], [cX + verts2[1][1], cY + verts2[1][2]], width = 4, lineColor = [255,255,255,255] ) ) # [160,160,255,255] end #---------------------------- function draw(popUp::PopUpMenu, mousePos::Vector{Int64} = [-99,-99]) # Int32 because that is what SDL returns for coordinates draw(popUp, [ convert(Int32, mousePos[1]), convert(Int32, mousePos[2]) ] ) end #-------- # unicode triangle pointing down is \u25BC: function draw(popUp::PopUpMenu, mousePos::Vector{Int32} ) # Int32 because that is what SDL returns for coordinates fC = popUp.fillColor oC = popUp.outlineColor if popUp.state == "unclicked" # draw fill #SDL_SetRenderDrawColor(popUp.win.renderer, fC[1], fC[2], fC[3], fC[4]) #mRect = SDL_Rect(popUp.leftTop[1], popUp.leftTop[2], popUp.size[1], popUp.size[2]) # wacky Julia struct constructor; x,y, widht, height #SDL_RenderFillRect(popUp.win.renderer, Ref{SDL_Rect}(mRect)) # that addition mess lets me send the rect as a pointer to the rect aaFilledRoundRectRGBA(popUp.win.renderer, popUp.leftTop[1] , popUp.leftTop[2], popUp.rightBottom[1], popUp.rightBottom[2], 8, fC[1], fC[2], fC[3], fC[4]) #--------- # draw outline if popUp.focus == false aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.leftTop[1], popUp.leftTop[2], popUp.rightBottom[1], popUp.rightBottom[2], 8, oC[1], oC[2], oC[3], oC[4]) else aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.leftTop[1]-1, popUp.leftTop[2]-1, popUp.rightBottom[1]+1, popUp.rightBottom[2]+1, 8, 0, 0, 255, 255) end #--------- # draw text ...maybe move this inside the constructor popUpText = popUp.menuTexts[popUp.selectionIndex] # TextStim(popUp.win, popUp.options[selection], [0, 0]) #popUpText.pos = [popUp.leftTop[1] + 4 , popUp.pos[2] ] popUpText.pos = [popUp.leftTop[1] + 10 , popUp.rightBottom[2]-4 ] draw(popUpText) # ******************** #popUpSymbol = TextStim(popUp.win, "▼", [0, 0]) aaFilledRoundRectRGBA(popUp.win.renderer, popUp.rightBottom[1] - 36, popUp.leftTop[2]+4, popUp.rightBottom[1]-4, popUp.rightBottom[2]-4, 8, 64, 134, 237, 255) drawPopUpArrows(popUp) # ******************** elseif popUp.state == "clicked" # this enters the pop-up button selection loop # println("I was clicked ", mousePos) mousePos[1] *= 2 # Hi Res stuff mousePos[2] *= 2 # Hi Res stuff #----------- # find which item is selected selectedItem = -99 # we don't use popUp.selectionIndex in case coords are out-of-bounds for i in eachindex(popUp.options) yCoordTop = popUp.fullLT[2] + (popUp.selectionHeight * (i-1)) yCoordBottom = yCoordTop + popUp.selectionHeight #[popUp.leftTop[1] + 4 , yCoord ] if (popUp.rightBottom[1] > mousePos[1] > popUp.leftTop[1]) && (yCoordBottom > mousePos[2] > yCoordTop) selectedItem = i popUp.selectionIndex = i popUp.valueText = popUp.menuTexts[i].textMessage end end #------------------------- # draw expanded menu aaFilledRoundRectRGBA(popUp.win.renderer, popUp.fullLT[1], popUp.fullLT[2], popUp.fullRB[1], popUp.fullRB[2], 8, fC[1], fC[2], fC[3], fC[4]) #------ # draw outline if popUp.focus == false aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.fullLT[1], popUp.fullLT[2], popUp.fullRB[1], popUp.fullRB[2], 8, oC[1], oC[2], oC[3], oC[4]) else aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.fullLT[1]-1, popUp.fullLT[2]-1, popUp.fullRB[1]+2, popUp.fullRB[2]+7, 8, 0, 0, 128, 255) aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.fullLT[1], popUp.fullLT[2], popUp.fullRB[1]+1, popUp.fullRB[2]+6, 8, 127, 127, 255, 255) aaRoundRectRGBA(popUp.win.renderer, #roundedRectangleRGBA popUp.fullLT[1]-1, popUp.fullLT[2]-1, popUp.fullRB[1]+1, popUp.fullRB[2]+6, 8, 0, 0, 255, 255) end #------ for i in eachindex(popUp.options) #options[i] yCoord = popUp.fullLT[2] + (popUp.selectionHeight * (i-1)) #popUp.menuTexts[i].pos = [popUp.leftTop[1] + 4 , yCoord + (popUp.selectionHeight÷2)] popUp.menuTexts[i].pos[2] = yCoord + (popUp.selectionHeight÷1) draw(popUp.menuTexts[i]) #println("Ycoord = ", yCoord,", top = ", popUp.fullLT[2],", bottom = ", popUp.fullRB[2]) # set coords of each then draw if i == selectedItem # highlight selected item SDL_SetRenderDrawColor(popUp.win.renderer, 0, 0, 255, 64) mRect = SDL_Rect(popUp.leftTop[1], yCoord, popUp.size[1], popUp.selectionHeight) #popUp.size[2]) # wacky Julia struct constructor; x,y, widht, height SDL_RenderFillRect(popUp.win.renderer, Ref{SDL_Rect}(mRect)) # that addition mess lets me send the rect as a pointer to the rect end end #------------------------- # do event loop #------------------------- # draw screen # SDL_RenderPresent( popUp.win.renderer ) else errString = "invalid popUp menu state. Got: " * popUp.state error(errString) end end #--------------------------------------------- # popup maps are part of a larger list of buttons that is looped through to # draw and handle events. mutable struct PopUpMap parent::PopUpMenu state::String # clicked or not leftTop::Vector{Int64} rightBottom::Vector{Int64} function PopUpMap( parent::PopUpMenu) state = "unclicked" leftTop = [parent.pos[1] - parent.size[1]÷ 2, parent.pos[2] - parent.size[2]÷ 2] leftTop[1] ÷= 2 leftTop[2] ÷= 2 rightBottom = [parent.pos[1] + parent.size[1]÷ 2, parent.pos[2] + parent.size[2]÷ 2] rightBottom[1] ÷= 2 rightBottom[2] ÷= 2 new(parent, state, leftTop, rightBottom ) end end #---------------------------- function stateChange(popMap::PopUpMap) if popMap.state == "clicked" popMap.state = "unclicked" popMap.parent.state = "unclicked" popMap.leftTop = deepcopy(popMap.parent.smallLT) # change size based on state popMap.leftTop[1] ÷= 2 popMap.leftTop[2] ÷= 2 popMap.rightBottom = deepcopy(popMap.parent.smallRB) popMap.rightBottom[1] ÷= 2 popMap.rightBottom[2] ÷= 2 else popMap.state = "clicked" popMap.parent.state = "clicked" popMap.leftTop = deepcopy(popMap.parent.fullLT) # change size based on state popMap.rightBottom = deepcopy(popMap.parent.fullRB) popMap.leftTop[1] ÷= 2 popMap.leftTop[2] ÷= 2 popMap.rightBottom[1] ÷= 2 popMap.rightBottom[2] ÷= 2 end println("changed popMap state to ", popMap.state) end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
37926
#= Psychopy defines and uses shapes like this: myRectPy = visual.Rect(win, size = (0.1, 0.1), pos = (x,y), lineColor = (1,1,-1), fillColor = None) myRectPy.draw() In Psychopy, shapes are objects. In PsychoJL, shapes are structs. myRectJL = rect(myWin, 100, 100, [400,400] ) # width, height, position array, myRectJL is a Rect structure draw(myRectJL) =# export Rect, Ellipse, draw export Line, Circle, ShapeStim, Polygon export setColor, setLineColor, setFillColor, setPos #= new functions needed: SetColor SetPos also for images =# #-================================================================== """ Line() Constructor for a Line object **Constructor inputs:** * win::Window\n * startPoint::Vector{Int64}\n * endPoint::Vector{Int64}\n * width::Int64 * lineColor::PsychoColor\n **Outputs:** None **Methods:** * draw() """ mutable struct Line win::Window startPoint::PsychoCoords endPoint::PsychoCoords width::Int64 # this will need to change to floats for Psychopy height coordiantes lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors _lineColor::Vector{Int64} _startPoint::Vector{Int64} _endPoint::Vector{Int64} #---------- function Line( win::Window, startPoint::PsychoCoords = [0,0], endPoint::PsychoCoords = [10,10]; width::Int64 = 1, lineColor::PsychoColor = fill(128, (3)), # these will need to change to floats to handle Psychopy colors # opacity::Int64 = 255 # these will need to change to floats to handle Psychopy colors ) # might want to add length and orientation # Int8Color = if length(endPoint) != 2 message = "endPoint needs two coordinates, got " * String(length(endPoint)) * " instead." error(message) end if length(startPoint) != 2 message = "startPoint needs two coordinates, got " * String(length(startPoint)) * " instead." error(message) end _startPoint = SDLcoords(win, startPoint) _endPoint = SDLcoords(win, endPoint) _lineColor = colorToSDL(win, lineColor) new(win, startPoint, endPoint, width, lineColor, _lineColor, _startPoint, _endPoint ) end end #---------- function draw(L::Line) if L.width == 1 # draw a single anti-aliased line WULinesAlpha(L.win, convert(Float64, L._startPoint[1]), convert(Float64, L._startPoint[2]), convert(Float64, L._endPoint[1]), convert(Float64, L._endPoint[2]), convert(UInt8, L._lineColor[1]), convert(UInt8, L._lineColor[2]), convert(UInt8, L._lineColor[3]), convert(UInt8, L._lineColor[4]) ) else # If we were really cool, we would center even lines by somehow antialiasing the sides # in order to make the lines look centered at the start point instead of offset. WULinesAlphaWidth(L.win, convert(Float64, L._startPoint[1]), convert(Float64, L._startPoint[2]), convert(Float64, L._endPoint[1]), convert(Float64, L._endPoint[2]), convert(UInt8, L._lineColor[1]), convert(UInt8, L._lineColor[2]), convert(UInt8, L._lineColor[3]), convert(UInt8, L._lineColor[4]), L.width ) end # drawStartPoint(L.win.renderer,L.startPoint[1] ,L.startPoint[2] ) end #-========================== """ setColor(::Line, ::Union{String, Vector{Int64}, Vector{Int64}) Used to update the color of a Line object. """ function setColor(line::Line, color::PsychoColor) line._lineColor = colorToSDL(line.win, color) end #-========================== #-------- function drawStartPoint(renderer::Ptr{SDL_Renderer}, x::Int64, y::Int64) # 4 points are drawning like the 5 on dice. the missing center one is x, y SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderDrawPoint(renderer, x-1, y-1) SDL_RenderDrawPoint(renderer, x-1, y+1) SDL_RenderDrawPoint(renderer, x+1, y-1) SDL_RenderDrawPoint(renderer, x+1, y+1) end #-========================== function getLineLength(L::Line) return sqrt( ((L.startPoint[1] - L.endPoint[1]) ^2) + ((L.startPoint[2] - L.endPoint[2])^2) ) end #-===================================================================================================== #= #- Line2 experiments with using multiple dispatch for coordinate systems mutable struct Line2 win::Window startPoint::Vector{Real} endPoint::Vector{Real} width::Int64 # this will need to change to floats for Psychopy height coordiantes lineColor::Vector{Int64} # these will need to change to floats to handle Psychopy colors _startPoint::Vector{Int64} _endPoint::Vector{Int64} #---------- function Line2( win::Window, startPoint::Vector{Int64} = [0,0], endPoint::Vector{Int64} = [10,10]; width::Int64 = 1, lineColor::Vector{Int64} = fill(128, (4)), # these will need to change to floats to handle Psychopy colors _startPoint::Vector{Int64} = [0,0], _endPoint::Vector{Int64} = [10,10] ) if length(endPoint) != 2 message = "endPoint needs two coordinates, got " * String(length(endPoint)) * " instead." error(message) end if length(startPoint) != 2 message = "startPoint needs two coordinates, got " * String(length(startPoint)) * " instead." error(message) end lineColor = colorToSDL(win, lineColor) new(win, startPoint, endPoint, width, convert(Vector{Int64},lineColor), startPoint, endPoint ) end #---------- function Line2( win::Window, startPoint::Vector{Float64} = [0.1,0.1], endPoint::Vector{Float64} = [0.2,0.2]; width::Int64 = 1, lineColor::Vector{Int64} = fill(128, (4)), # these will need to change to floats to handle Psychopy colors _startPoint::Vector{Int64} = [0,0], _endPoint::Vector{Int64} = [10,10] ) if length(endPoint) != 2 message = "endPoint needs two coordinates, got " * String(length(endPoint)) * " instead." error(message) end if length(startPoint) != 2 message = "startPoint needs two coordinates, got " * String(length(startPoint)) * " instead." error(message) end _, displayHeight = getSize(win) if win.coordinateSpace == "PsychoPy" _startPoint[1] = round(Int64, (startPoint[1]+0.5) * displayHeight) # convert PsychoPy to Percent coordinates first then percentage to pixels _startPoint[2] = round(Int64, (-startPoint[2]+0.5) * displayHeight) _endPoint[1] = round(Int64, (endPoint[1]+0.5) * displayHeight) _endPoint[2] = round(Int64, (-endPoint[2]+0.5) * displayHeight) else _startPoint[1] = round(Int64, startPoint[1] * displayHeight) # convert percentage to pixels _startPoint[2] = round(Int64, startPoint[2] * displayHeight) _endPoint[1] = round(Int64, endPoint[1] * displayHeight) _endPoint[2] = round(Int64, endPoint[2] * displayHeight) end new(win, startPoint, endPoint, width, convert(Vector{Int64},lineColor), _startPoint, _endPoint ) end end #---------- #---------- function draw(L::Line2) if L.width == 1 # draw a single anti-aliased line WULinesAlpha(L.win, convert(Float64, L._startPoint[1]), convert(Float64, L._startPoint[2]), convert(Float64, L._endPoint[1]), convert(Float64, L._endPoint[2]), convert(UInt8, L.lineColor[1]), convert(UInt8, L.lineColor[2]), convert(UInt8, L.lineColor[3]), convert(UInt8, L.lineColor[4]) ) else # If we were really cool, we would center even lines by somehow antialiasing the sides # in order to make the lines look centered at the start point instead of offset. WULinesAlphaWidth(L.win, convert(Float64, L._startPoint[1]), convert(Float64, L._startPoint[2]), convert(Float64, L._endPoint[1]), convert(Float64, L._endPoint[2]), convert(UInt8, L.lineColor[1]), convert(UInt8, L.lineColor[2]), convert(UInt8, L.lineColor[3]), convert(UInt8, L.lineColor[4]), L.width ) end end =# #-===================================================================================================== # Floating point version shelved for now, as you can not do multiple dispatch with optional arguments. """ Rect() Constructor for a Rect object **Constructor inputs:** * win::Window, * width::Int64 * height::Int64 * pos::Vector{Int64} **position** **Optional constructor inputs:** * units::String......*(default is "pixel"* * lineWidth::Int64......*(default is 1)* * lineColor::PsychoColor......*default is (128, 128, 128)* * fillColor::PsychoColor......*default is (128, 128, 128)* * ori::Float64 = 0.0......*(orientation in degrees)* * opacity::Float......*(default is 1.0, indepenent of alpha)* **Full list of fields** * win::Window * width::Int64 * height::Int64 * pos::Vector{Int64} * units::String * lineWidth::Int64 * lineColor::PsychoColor * fillColor::PsychoColor * ori::Float64 * opacity::Int64 * SDLRect::SDL_Rect **Methods:** * draw() * setLineColor() * setFillColor() * setPos() """ mutable struct Rect #{T} win::Window width::Int64 # this will need to change to floats for Psychopy height coordiantes height::Int64 pos::PsychoCoords units::String lineWidth::Int64 # this will need to change to floats for Psychopy height coordiantes lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor # these will need to change to floats to handle Psychopy colors ori::Float64 # The orientation of the stimulus (in degrees). opacity::Float64 # these will need to change to floats to handle Psychopy colors SDLRect::SDL_Rect _lineColor::Vector{Int64} _fillColor::Vector{Int64} _pos::Vector{Int64} #---------- function Rect( win::Window, width::Int64 = 1, height::Int64 = 1, pos::PsychoCoords = [10,10]; # position units::String = "pixel", lineWidth::Int64 = 1, lineColor::PsychoColor = fill(128, (3)), # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor = fill(128, (3)), # these will be Psychopy colors ori::Float64 = 0.0, opacity::Float64 = 1.0 # these will need to change to floats to handle Psychopy colors ) # NOTE: SDL uses the upper left corner. I'm converting the to the center of the rect like Psychopy centerX::Int64 = round(pos[1] - (width/2)) centerY::Int64 = round(pos[2] - (height/2)) _pos = [ centerX, centerY] SDLRect = SDL_Rect(_pos[1], _pos[2], width, height) _lineColor = colorToSDL(win, lineColor) _fillColor = colorToSDL(win, fillColor) #= if length(lineColor) == 3 # will need to be changed later when other formats can be used push!(lineColor, 255) end if length(fillColor) == 3 # will need to be changed later when other formats can be used push!(fillColor, 255) end =# new(win, width , height, pos, units, lineWidth, lineColor, # these will need to change to floats to handle Psychopy colors fillColor, # these will be Psychopy colors ori, opacity, # these will need to change to floats to handle Psychopy colors SDLRect, # SDL rectangle object _lineColor, _fillColor, _pos ) end end #---------- """ draw(various shape types) Draws the shape (Line, Rect, Ellipse, TextStim, etc.) into the back buffer. Example: ```julia newRect = Rect(myWin, 100, # width 100, # height [200,200], # position lineColor = [255,0,0], fillColor = [255,128,128] ) draw(newRect) # in PsychoPy this would have been newRect.draw() ``` """ function draw(R::Rect) # first draw filled Rect SDL_SetRenderDrawColor(R.win.renderer, R._fillColor[1], R._fillColor[2], R._fillColor[3], round(Int64, R._fillColor[4] * R.opacity ) ) SDL_RenderFillRect( R.win.renderer, Ref{SDL_Rect}(R.SDLRect)) #println("resulting alpha = ", round(Int64, R._fillColor[4] * R.opacity )," ,", R._fillColor[4]," ,", R.opacity) #println(R._fillColor) # then draw outline SDL_SetRenderDrawColor(R.win.renderer, R._lineColor[1], R._lineColor[2], R._lineColor[3], round(Int64, R._lineColor[4] * R.opacity) ) SDL_RenderDrawRect( R.win.renderer, Ref{SDL_Rect}(R.SDLRect)) end #-===================================================================================================== """ Ellipse() Constructor for an Ellipse object **Inputs:** * win::Window * pos::Vector{Int64} * rx::Int64 ......*horizontal radius* * ry::Int64 ......*vertical radius* * lineWidth::Int64 * lineColor::PsychoColor * fillColor::PsychoColor * fill::Bool ......*fill or not* **Outputs:** None **Methods:** * draw * setLineColor() * setFillColor() * setPos() """ mutable struct Ellipse win::Window pos::PsychoCoords rx::Union{Int64, Float64} # Horizontal radius in pixels of the aa-ellipse ry::Union{Int64, Float64} # vertical radius in pixels of the aa-ellipse lineWidth::Int64 lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor # these will need to change to floats to handle Psychopy colors fill::Bool # these will need to change to floats to handle Psychopy colors _lineColor::Vector{Int64} _fillColor::Vector{Int64} _pos::Vector{Int64} _rx::Int64 _ry::Int64 #aaellipseRGBA #---------- #MethodError: no method matching Ellipse(::Window, ::Vector{Int64}, ::Int64, ::Int64, ::Int64, ::Vector{Int64}, ::Vector{Int64}, ::Bool) # Ellipse(::Window, ::Vector{Int64}, ::Int64, ::Int64; lineWidth, lineColor, fillColor, fill) function Ellipse(win::Window, pos::PsychoCoords = [10,10], # position rx::Union{Int64, Float64} = 20, # Horizontal radius in pixels of the aa-ellipse ry::Union{Int64, Float64} = 10; # vertical radius in pixels of the aa-ellipse lineWidth::Int64 = 1, lineColor::PsychoColor = fill(128, (4)), # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor = fill(128, (4)), # these will be Psychopy colors fill::Bool = false ) _lineColor = colorToSDL(win, lineColor) _fillColor = colorToSDL(win, fillColor) if win.coordinateSpace != "LT_Pix" _, displayHeight = getSize(win) # get true height of window _rx = round(Int64, rx * displayHeight) # convert percent to pixels _ry = round(Int64, ry * displayHeight) # convert percent to pixels _pos = SDLcoords(win, pos) else _rx = rx _ry = ry _pos = pos end new(win, pos, rx, ry, lineWidth, lineColor, # these will need to change to floats to handle Psychopy colors fillColor, # these will be Psychopy colors fill, _lineColor, _fillColor, _pos, _rx, _ry ) end end #---------- #MethodError: Cannot `convert` an object of type Int64 to an object of type Vector{Int64} #Ellipse(win::Window, pos::Vector{Float64}, rx::Int64, ry::Int64; lineWidth::Int64, lineColor::String, fillColor::Vector{Float64}, fill::Bool) function draw(El::Ellipse) if El.fill == true aaFilledEllipseRGBA(El.win.renderer, El._pos[1], El._pos[2], El._rx, El._ry, El._fillColor[1], El._fillColor[2], El._fillColor[3], El._fillColor[4]) # I need to check if linecolor exists or has an alpha>0, and then draw the outline _aaellipseRGBA(El.win.renderer,El._pos[1], El._pos[2], El._rx, El._ry, El._lineColor, El.fill) end if El.lineWidth > 1 # we need to anti-alias the outside. When thickness is >1, radius increases by thickness / 2 # outside antialias first newrX = El._rx + (El.lineWidth ÷ 2) #-1 newrY = El._ry + (El.lineWidth ÷ 2) -1 _aaellipseRGBA(El.win.renderer,El._pos[1]-1, El._pos[2], newrX, newrY, El.lineColor, El.fill) thickEllipseRGBA(El.win.renderer, El._pos[1], El._pos[2], El._rx, El._ry, El._lineColor[1], El._lineColor[2], El._lineColor[3], El._lineColor[4], El.lineWidth) # inside antialias first newrX = El._rx - (El.lineWidth ÷ 2) #+1 newrY = El._ry - (El.lineWidth ÷ 2) _aaellipseRGBA(El.win.renderer,El._pos[1]-1, El._pos[2], newrX, newrY, El._lineColor, El.fill) else _aaellipseRGBA(El.win.renderer,El._pos[1], El._pos[2], El._rx, El._ry, El._lineColor, El.fill) end # below is my lame way of drawing a filled ellipse inside an anti-aliased ellipse # in reality, I show modify aaelipse fill #= if El.fill == true # filled filledEllipseRGBA(El.win.renderer,El.pos[1], El.pos[2], El.rx, El.ry, convert(UInt8, El.lineColor[1]), convert(UInt8, El.lineColor[2]), convert(UInt8, El.lineColor[3]), convert(UInt8, El.lineColor[4]) ) end =# end #-===================================================================================================== """ Circle() Constructor for an Circle object **Inputs:** * win::Window * pos::Vector{Int64} * rad::Int64 ......*radius* * lineWidth::Int64 * lineColor::PsychoColor * fillColor::PsychoColor * fill::Bool ......*fill or not* **Outputs:** None **Methods:** * draw() * setLineColor() * setFillColor() * setPos() """ mutable struct Circle win::Window pos::PsychoCoords rad::Union{Int64, Float64} # radius in pixels of the aa-ellipse lineWidth::Int64 lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor # these will need to change to floats to handle Psychopy colors fill::Bool # these will need to change to floats to handle Psychopy colors circlesEllipse::Ellipse _lineColor::Vector{Int64} _fillColor::Vector{Int64} _pos::Vector{Int64} _rad::Int64 function Circle(win::Window, pos::PsychoCoords = [10,10], # position rad::Union{Int64, Float64} = 20; # Horizontal radius in pixels of the aa-ellipse lineWidth::Int64 = 1, lineColor::PsychoColor = fill(128, (4)), # these will need to change to floats to handle Psychopy colors fillColor::PsychoColor = fill(128, (4)), # these will be Psychopy colors fill::Bool = false ) _lineColor = colorToSDL(win, lineColor) _fillColor = colorToSDL(win, fillColor) if win.coordinateSpace != "LT_Pix" _, displayHeight = getSize(win) # get true height of window _rad = round(Int64, rad * displayHeight) # convert percent to pixels _pos = SDLcoords(win, pos) else _rad = rad _pos = pos end circlesEllipse = Ellipse(win, pos, rad, rad, lineWidth=lineWidth,lineColor=lineColor,fillColor=fillColor, fill=fill) new(win, pos, rad, lineWidth, lineColor, # these will need to change to floats to handle Psychopy colors fillColor, # these will be Psychopy colors fill, circlesEllipse, _lineColor, _fillColor, _pos, _rad ) end end #---------- function draw(Circ::Circle) draw(Circ.circlesEllipse) end #-===================================================================================================== # Floating point version shelved for now, as you can not do multiple dispatch with optional arguments. """ ShapeStim() Constructor for a ShapeStim object, which is a polygon defined by vertices. **Constructor inputs:** * win::Window, * vertices::Vector{Vector{Int64}} **Optional constructor inputs:** * units::String......*(default is "pixel"* * lineWidth::Int64......*(default is 1)* * lineColor::PsychoColor......*default is (128, 128, 128)* **Full list of fields** * win::Window * vertices::Vector{Vector{Int64}} Example: *[ [300, 10], [400, 5], [410,150], [320, 100] ,[290, 20] ]* * units::String * lineWidth::Int64 * lineColor::PsychoColor **Methods:** * draw() """ mutable struct ShapeStim #{T} win::Window vertices::Vector{Vector{Int64}} #Vector{Int64} units::String lineWidth::Int64 # this will need to change to floats for Psychopy height coordiantes lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors #---------- function ShapeStim( win::Window, vertices::Vector{Vector{Int64}} = [[10,10]]; # a single vertex placeholder units::String = "pixel", lineWidth::Int64 = 1, lineColor::PsychoColor = fill(128, (4)), # these will need to change to floats to handle Psychopy colors ) lineColor = colorToSDL(win, lineColor) new(win, vertices, units, lineWidth, lineColor, # these will need to change to floats to handle Psychopy colors ) end end #---------- function draw(S::ShapeStim) numCoords = length(S.vertices) if S.lineWidth == 1 # draw a single anti-aliased line for i in 2:numCoords WULinesAlpha(S.win, convert(Float64, S.vertices[i-1][1]), convert(Float64, S.vertices[i-1][2]), convert(Float64, S.vertices[i][1]), convert(Float64, S.vertices[i][2]), convert(UInt8, S.lineColor[1]), convert(UInt8, S.lineColor[2]), convert(UInt8, S.lineColor[3]), convert(UInt8, S.lineColor[4]) ) end # close the shape WULinesAlpha(S.win, convert(Float64, S.vertices[1][1]), convert(Float64, S.vertices[1][2]), convert(Float64, S.vertices[numCoords][1]), convert(Float64, S.vertices[numCoords][2]), convert(UInt8, S.lineColor[1]), convert(UInt8, S.lineColor[2]), convert(UInt8, S.lineColor[3]), convert(UInt8, S.lineColor[4]) ) else # If we were really cool, we would center even lines by somehow antialiasing the sides # in order to make the lines look centered at the start point instead of offset. for i in 2:numCoords WULinesAlphaWidth(S.win, convert(Float64, S.vertices[i-1][1]), convert(Float64, S.vertices[i-1][2]), convert(Float64, S.vertices[i][1]), convert(Float64, S.vertices[i][2]), convert(UInt8, S.lineColor[1]), convert(UInt8, S.lineColor[2]), convert(UInt8, S.lineColor[3]), convert(UInt8, S.lineColor[4]), S.lineWidth ) # close the shape WULinesAlphaWidth(S.win, convert(Float64, S.vertices[1][1]), convert(Float64, S.vertices[1][2]), convert(Float64, S.vertices[numCoords][1]), convert(Float64, S.vertices[numCoords][2]), convert(UInt8, S.lineColor[1]), convert(UInt8, S.lineColor[2]), convert(UInt8, S.lineColor[3]), convert(UInt8, S.lineColor[4]), S.lineWidth ) end end end #-===================================================================================================== # Floating point version shelved for now, as you can not do multiple dispatch with optional arguments. """ Polygon() Constructor for a regular Polygon object, such as a pentagon or hexagon. **Constructor inputs:** * win::Window, * pos::Vector{Int64}......*[x,y] coordinates of center* * rad::Int64......*radius* * sides::Int64 **Optional constructor inputs:** * units::String......*(default is "pixel"* * lineWidth::Int64......*(default is 1)* * lineColor::PsychoColor......*default is (128, 128, 128)* **Full list of fields** * win::Window, * pos::Vector{Int64} * rad::Int64......*radius* * sides::Int64 * units::String * lineWidth::Int64 * lineColor::PsychoColor **Methods:** * draw() """ mutable struct Polygon #{T} win::Window pos::Vector{Int64} rad::Int64 sides::Int64 units::String lineWidth::Int64 # this will need to change to floats for Psychopy height coordiantes lineColor::PsychoColor # these will need to change to floats to handle Psychopy colors #---------- function Polygon( win::Window, pos::Vector{Int64} = [10,10], # a single vertex placeholder rad::Int64 = 10, sides::Int64 = 5; units::String = "pixel", lineWidth::Int64 = 1, lineColor::PsychoColor = fill(128, (4)) # these will need to change to floats to handle Psychopy colors ) lineColor = colorToSDL(win, lineColor) new(win, pos, rad, sides, units, lineWidth, lineColor, # these will need to change to floats to handle Psychopy colors ) end end #---------- function draw(P::Polygon) # it would be more efficient to initially fill this with pairs of zeros (pre-allocate) vertices = [] for i in 1:P.sides x = P.pos[1] + P.rad * sin(2 * pi * i/P.sides) # this is technically wrong, but I swap sine and cos y = P.pos[2] + P.rad * cos(2 * pi * i/P.sides) # so that their bases will be on the bottom push!(vertices, [round(Int64, x),round(Int64, y)]) end if P.lineWidth == 1 # draw a single anti-aliased line for i in 2:P.sides WULinesAlpha(P.win, convert(Float64, vertices[i-1][1]), convert(Float64, vertices[i-1][2]), convert(Float64, vertices[i][1]), convert(Float64, vertices[i][2]), convert(UInt8, P.lineColor[1]), convert(UInt8, P.lineColor[2]), convert(UInt8, P.lineColor[3]), convert(UInt8, P.lineColor[4]) ) end # close the shape WULinesAlpha(P.win, convert(Float64, vertices[1][1]), convert(Float64, vertices[1][2]), convert(Float64, vertices[P.sides][1]), convert(Float64, vertices[P.sides][2]), convert(UInt8, P.lineColor[1]), convert(UInt8, P.lineColor[2]), convert(UInt8, P.lineColor[3]), convert(UInt8, P.lineColor[4]) ) else # If we were really cool, we would center even lines by somehow antialiasing the sides # in order to make the lines look centered at the start point instead of offset. for i in 2:P.sides WULinesAlphaWidth(P.win, convert(Float64, vertices[i-1][1]), convert(Float64, vertices[i-1][2]), convert(Float64, vertices[i][1]), convert(Float64, vertices[i][2]), convert(UInt8, P.lineColor[1]), convert(UInt8, P.lineColor[2]), convert(UInt8, P.lineColor[3]), convert(UInt8, P.lineColor[4]), P.lineWidth ) # close the shape WULinesAlphaWidth(P.win, convert(Float64, vertices[1][1]), convert(Float64, vertices[1][2]), convert(Float64, vertices[P.sides][1]), convert(Float64, vertices[P.sides][2]), convert(UInt8, P.lineColor[1]), convert(UInt8, P.lineColor[2]), convert(UInt8, P.lineColor[3]), convert(UInt8, P.lineColor[4]), P.lineWidth ) end end end #-========================== """ setLineColor(various shape types, color) Sets the outline color for various solid shapes (Rect, Ellipse, Circle, etc.). NEED link to colors ``` """ function setLineColor(solidShape::Union{Rect, Ellipse, Circle}, color::PsychoColor) solidShape._lineColor = colorToSDL(rect.win, color) end #-========== """ setFillColor(various shape types, color) Sets the fill color for various solid shapes (Rect, Ellipse, Circle, etc.) NEED link to colors ``` """ function setFillColor(solidShape::Union{Rect, Ellipse, Circle}, color::PsychoColor) solidShape._fillColor = colorToSDL(rect.win, color) end #-===================================================================================================== """ setPos(solidShape::Union{Rect, Ellipse, Circle, Polygon}, coordinates) Set the position of the object, usually the center unless specified otherwise. See "Setter Functions" in side tab for more information. """ function setPos(solidShape::Union{Rect, Ellipse, Circle, Polygon}, coords::PsychoCoords) solidShape._pos = SDLcoords(solidShape.win, coords) solidShape.pos = coords if typeof(solidShape) == Circle solidShape.circlesEllipse._pos = solidShape._pos # update the ellipse owned by the circle solidShape.circlesEllipse.pos = solidShape.pos # update the ellipse owned by the circle end end #-====================================================================================================================== #-====================================================================================================================== #= #----------# from https://stackoverflow.com/questions/38334081/how-to-draw-circles-arcs-and-vector-graphics-in-sdl #draw one quadrant arc, and mirror the other 4 quadrants function sdl_ellipse(win::Window, x0::Int64, y0::Int64, radiusX::Int64, radiusY::Int64) # const pi::Float64 = 3.14159265358979323846264338327950288419716939937510 piHalf::Float64 = π / 2.0; # half of pi #drew 28 lines with 4x4 circle with precision of 150 0ms #drew 132 lines with 25x14 circle with precision of 150 0ms #drew 152 lines with 100x50 circle with precision of 150 3ms precision::Int64 = 27 # precision value; value of 1 will draw a diamond, 27 makes pretty smooth circles. theta::Float64 = 0; # angle that will be increased each loop #starting point x::Int64 = int(radiusX * cos(theta)) #(Float64)radiusX * cos(theta) # start point y::Int64 = int(radiusY * sin(theta)) #(float)radiusY * sin(theta) # start point x1::Int64 = x y1::Int64 = y #repeat until theta >= 90; step::Float64 = piHalf/precision #pih/(float)prec; # amount to add to theta each time (degrees) #for(theta=step; theta <= pih; theta+=step)//step through only a 90 arc (1 quadrant) for theta in step:step:piHalf # step through only a 90 arc (1 quadrant) # get new point location x1 = int(radiusX * cos(theta) + 0.5) # (float)radiusX * cosf(theta) + 0.5; # new point (+.5 is a quick rounding method) y1 = int(radiusY * sin(theta) + 0.5) # new point (+.5 is a quick rounding method) # draw line from previous point to new point, ONLY if point incremented if( (x != x1) || (y != y1) ) #only draw if coordinate changed SDL_RenderDrawLine(win.renderer, x0 + x, y0 - y, x0 + x1, y0 - y1 ); # quadrant TR SDL_RenderDrawLine(win.renderer, x0 - x, y0 - y, x0 - x1, y0 - y1 ); # quadrant TL SDL_RenderDrawLine(win.renderer, x0 - x, y0 + y, x0 - x1, y0 + y1 ); # quadrant BL SDL_RenderDrawLine(win.renderer, x0 + x, y0 + y, x0 + x1, y0 + y1 ); # quadrant BR end # save previous points x = x1 #; //save new previous point y = y1 #;//save new previous point end # arc did not finish because of rounding, so finish the arc if(x!=0) x=0; SDL_RenderDrawLine(win.renderer, x0 + x, y0 - y, x0 + x1, y0 - y1 ); # quadrant TR SDL_RenderDrawLine(win.renderer, x0 - x, y0 - y, x0 - x1, y0 - y1 ); # quadrant TL SDL_RenderDrawLine(win.renderer, x0 - x, y0 + y, x0 - x1, y0 + y1 ); # quadrant BL SDL_RenderDrawLine(win.renderer, x0 + x, y0 + y, x0 + x1, y0 + y1 ); # quadrant BR end end #-==================================================================== function draw(L::Line) #= SDL_SetRenderDrawColor(L.win.renderer, L.lineColor[1], L.lineColor[2], L.lineColor[3], L.opacity) SDL_RenderDrawLine( L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2]) =# #= thickLineRGBA( L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2], L.width, L.lineColor[1], L.lineColor[2], L.lineColor[3], L.lineColor[4], ) =# #= _aalineRGBA(L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2], L.lineColor[1], L.lineColor[2], L.lineColor[3], L.lineColor[4], true ) =# #= DrawWuLine(L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2], L.lineColor[1], L.lineColor[2], L.lineColor[3], L.lineColor[4] ) =# if L.width == 1 # draw a single anti-aliased line WULinesAlpha(L.win, convert(Float64, L.startPoint[1]), convert(Float64, L.startPoint[2]), convert(Float64, L.endPoint[1]), convert(Float64, L.endPoint[2]), convert(UInt8, L.lineColor[1]), convert(UInt8, L.lineColor[2]), convert(UInt8, L.lineColor[3]), convert(UInt8, L.lineColor[4]) ) #= elseif L.width%2 == 0 # even number line width println("I haven't implemenet even number widths yet, so I'm giving you a line width of 1") WULinesAlpha(L.win, convert(Float64, L.startPoint[1]), convert(Float64, L.startPoint[2]), convert(Float64, L.endPoint[1]), convert(Float64, L.endPoint[2]), ≈, convert(UInt8, L.lineColor[2]), convert(UInt8, L.lineColor[3]), convert(UInt8, L.lineColor[4]) ) =# else # odd nubmer will draw width-2 jaggy lines in the middle flanked by anti-aliased versions println("I'm trying to draw a wide line ", L.width) deltaY = L.endPoint[2] - L.startPoint[2] deltaX = L.endPoint[1] - L.startPoint[1] radians = atan( deltaY / deltaX ) angleDegrees = rad2deg(radians)-90 # yep, that's the pi-symbol for π. Aint Julia cool! GeometricLength = round(getLineLength(L)) centerX::Int64 = round( (L.startPoint[1] + L.endPoint[1])/2) # average, not local center round(L.width/2) centerY::Int64 = round( (L.startPoint[2] + L.endPoint[2])/2) # average, not local center round(GeometricLength/2)# # 120, 825 for average # 2, 677 for width and height /2 #centerX = convert(Int64, round( L.startPoint[2]/100)) #centerY = L.startPoint[2] #centerX = 1000 #centerX = L.startPoint[1] #centerY = L.startPoint[2] #centerX = L.endPoint[1] #centerX = L.endPoint[1] centerX = L.startPoint[1] centerY = L.startPoint[2] println("center = ", centerX, ", ", centerY) println("startPoint = ", L.startPoint[1], ", ", L.startPoint[2]) println("startPoint = ", L.endPoint[1], ", ", L.endPoint[2]) #center = SDL_Point(Cint(centerX), Cint(centerY)) center = SDL_Point(Cint(0), Cint(0)) #center::SDL_Point = [centerX, centerY] SDL_SetRenderDrawColor(L.win.renderer, L.lineColor[1], L.lineColor[2], L.lineColor[3], L.lineColor[4]) if L.width > 1 # only one jaggy #SDL_RenderDrawLine( L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2]) # (1) create surface the size of the line lineSurface = SDL_CreateRGBSurface(0, L.width, round(GeometricLength), 32,0,0,0,0) println("GeometricLength = ", GeometricLength) SDL_SetSurfaceBlendMode(lineSurface, SDL_BLENDMODE_BLEND) # (2) Fill the surface with a rect #destinationRect = SDL_Rect(centerX, centerY, L.width, convert(UInt32, round(GeometricLength)) ) destinationRect = SDL_Rect(L.startPoint[1], L.startPoint[2], L.width, convert(UInt32, round(GeometricLength)) ) tempColor = MakeInt8Color(L.lineColor[1], L.lineColor[2], L.lineColor[3], L.lineColor[4]) # SDL_FillRect(lineSurface::Ptr{SDL_Surface}, Ref{SDL_Rect}(lineRect), convert(UInt32, tempColor) ) SDL_FillRect(lineSurface::Ptr{SDL_Surface}, C_NULL, convert(UInt32, tempColor) ) # C_NULL = fill entire surface # this next part puts a notch at the Start end notchColor = MakeInt8Color(0, 0, 0,255) notchRect = SDL_Rect(0, 10, L.width,20) SDL_FillRect(lineSurface::Ptr{SDL_Surface}, Ref{SDL_Rect}(notchRect), convert(UInt32, notchColor) ) # C_NULL = fill entire surface tempSurface = IMG_Load( "sec_hand.png" ); if tempSurface == C_NULL println("*** error loading texture: sec_hand.png") println("current directory is ", pwd()) end tagRect = SDL_Rect(0,0, 100, 4) # used to color code the hands SDL_FillRect(tempSurface::Ptr{SDL_Surface}, Ref{SDL_Rect}(tagRect), convert(UInt32, tempColor) ) tempSDLTexture = SDL_CreateTextureFromSurface( L.win.renderer, tempSurface ); w_ref, h_ref = Ref{Cint}(0), Ref{Cint}(0) # These create C integer pointers: https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/ SDL_QueryTexture(tempSDLTexture, C_NULL, C_NULL, w_ref, h_ref) # get the attributes of a texture, such as width and height width = w_ref[] height = h_ref[] tempRect = SDL_Rect(L.startPoint[1], L.startPoint[2], width, height) # 160, 160 # tempRect = SDL_Rect(centerX, centerY, width, height) # tempPoint = SDL_Point(centerX, centerY) # tempPoint = SDL_Point(10, 10) tempPoint = SDL_Point(10, 10) angleDegrees2 = angleDegrees + 90 # positve 90 is down println("angle of line: ", angleDegrees) println("angle of arrow: ", angleDegrees2, "\n") SDL_RenderCopyEx( L.win.renderer, tempSDLTexture, C_NULL, Ref{SDL_Rect}(tempRect), angleDegrees2, Ref{SDL_Point}(tempPoint), SDL_FLIP_NONE ); SDL_FreeSurface( tempSurface ); #==# #If think there is disagreement between the center of lineRect for SDLFillRect and SDL_RenderCopyEx #function SDL_FillRect(dst, rect, color) # ccall((:SDL_FillRect, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Uint32), dst, rect, color) # (3) copy it to a texture lineTexture = SDL_CreateTextureFromSurface(L.win.renderer, lineSurface) SDL_FreeSurface(lineSurface) # Delete the surface, as we no longer need it. # (4) rotate it and copy to the window # SDL_RenderCopyEx(L.win.renderer, lineTexture, C_NULL, C_NULL, angleDegrees, Ref{SDL_Point}(center), SDL_FLIP_NONE) # SDL_RenderCopyEx(L.win.renderer, lineTexture, Ref{SDL_Rect}(lineRect), Ref{SDL_Rect}(lineRect), angleDegrees, Ref{SDL_Point}(center), SDL_FLIP_NONE) SDL_RenderCopyEx(L.win.renderer, lineTexture, C_NULL, Ref{SDL_Rect}(destinationRect), angleDegrees, Ref{SDL_Point}(center), SDL_FLIP_NONE) # SDL_RenderCopyEx( renderer, timeTexture.texture, C_NULL, Ref{SDL_Rect}(timeTexture.rect), timeTexture.angle, Ref{SDL_Point}(timeTexture.center), SDL_FLIP_NONE ); # SDL_RenderCopyEx(L.win.renderer, lineTexture, C_NULL, Ref{SDL_Rect}(destinationRect), angleDegrees, C_NULL, SDL_FLIP_NONE) # (5) destroy it and clean up SDL_DestroyTexture(lineTexture) # no longer need the texture, so delete it end #= for inner in 1:L.width -2 should probably countdown from top, middle, bottom... SDL_RenderDrawLine( L.win.renderer, L.startPoint[1], L.startPoint[2], L.endPoint[1], L.endPoint[2]) end =# end #prinln(startPoint, endPoint) # thickLineRGBA(renderer, x1, y1, x2, y2, width, r, g, b, a) end =#
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
2599
export ErrSound, SoundStim, play """ SoundStim() Constructor for a SoundStim object **Constructor inputs:** * filePath::string ......**the entire path to the file, including file name and extension**\n **Outputs:** None **Methods:** play() """ struct SoundStim filePath::String soundData::Ptr{Mix_Chunk} #---------- function SoundStim( filePath::String) if isfile(filePath) soundData = Mix_LoadWAV_RW(SDL_RWFromFile(filePath, "rb"), 1) else error("$filePath not found") end new(filePath, soundData ) end end #---------- struct ErrSound soundData::Ptr{Mix_Chunk} #---------- function ErrSound() parentDir = pwd() filePath = joinpath(parentDir, "artifacts") filePath = joinpath(filePath, "ErrSound-10db.wav") if isfile(filePath) soundData = Mix_LoadWAV_RW(SDL_RWFromFile(filePath, "rb"), 1) else error("ErrSound() $filePath not found") end new( soundData ) end end #---------- """ play(sound::SoundStim; repeats::Int64) Plays a SoundStim **Inputs:** SoundStim\n **Optional Inputs:** repeats\n **Outputs:** None """ function play(S::Union{SoundStim, ErrSound}; repeats::Int64 = 0) Mix_PlayChannel(-1, S.soundData, repeats) #no method matching unsafe_convert(::Type{Ptr{Mix_Chunk}}, ::typeof(errSound)) end #-======================================================= # play(loops=None, function testSound() #if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 1024) < 0) # println("SDL_mixer could not initialize!", Mix_GetError()) #end #Load the music aud_files = dirname(@__FILE__) parentDir = pwd() #println("original directory: ", originalDir) # artifacts #parentDir = splitdir(pwd())[1] #println("parent directory: ", parentDir) # artifacts filePath = joinpath(parentDir, "artifacts") filePath = joinpath(filePath, "ErrSound.wav") if isfile("$aud_files/beat.wav") println("FOUND ErrSound.wave AUDIO FILE!!!!!!!!!!!") end music = Mix_LoadMUS(filePath) if (music == C_NULL) println(">>> >>>", unsafe_string(SDL_GetError() ) ) error("$filePath not found.") end errSound = Mix_LoadWAV_RW(SDL_RWFromFile(filePath, "rb"), 1) Mix_PlayChannel(-1, errSound, 0) end #= scratch = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/scratch.wav", "rb"), 1) high = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/high.wav", "rb"), 1) med = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/medium.wav", "rb"), 1) low = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/low.wav", "rb"), 1) Mix_PlayChannelTimed(-1, med, 0, -1) Mix_PlayMusic(music, -1) sleep(1) Mix_PauseMusic() sleep(1) Mix_ResumeMusic() sleep(1) Mix_HaltMusic() =#
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
16233
export draw, TextStim, TextStimExp, setColor #-================================================================================================================ # TextStim # Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} """ TextStim() Constructor for a TextStim object **Constructor inputs:** * win::Window * textMessage::String.........*default = "future text"* * pos::Vector{Int64}........*position: default = [10,10]* **Optional constructor inputs:** * color::PsychoColor.........*default = (128, 128, 128)* * fontName::String = "", * fontSize::Int64 = 12,.........*default = 12* * scale::Float64 = 1.0,.........*not the same as font size* * font::Any.........*default is taken from Window* * horizAlignment::Int64.........*default = -1, 0 = center, +1 = right* * vertAlignment::Int64 = 1.........*default = 1, 0 = center, -1 = bottom* * style::String.........*default = "normal", options include "bold" and "italic"* * orientation.........*orientation in degrees* **Methods:** * draw() **Notes:** Using different font sizes requires loading them as different fonts. For now it is easier to load a large version of a font and using *scale* to scale the size of the resulting image. """ mutable struct TextStim #{T} win::Window textMessage::String # this will need to change to floats for Psychopy height coordiantes pos::Vector{Int64} color::PsychoColor # Union of strings, and float and int vectors fontName::String fontSize::Int64 scale::Float64 font::Ptr{TTF_Font} horizAlignment::Int64 # -1 for left, 0 for center, +1 for right vertAlignment::Int64 # -1 aligns at top, 0 for center, +1 aligns at bottom style::String # bold, italic, etc. orientation::Int64 _color::Vector{Int64} #---------- function TextStim(win::Window, textMessage::String = "future text", pos::Vector{Int64} = [10,10]; color::PsychoColor = "white", # these will need to change to floats to handle Psychopy colors fontName::String = "", fontSize::Int64 = 12, scale::Float64 = 1.0, font::Any = nothing, # font is for internal use and is a pointer to a TTF horizAlignment::Int64 = -1, vertAlignment::Int64 = +1, style::String = "normal", orientation::Int64 = 0, _color::Vector{Int64} = fill(128, (4)) # internal SDL color ) if fontName == "" font = win.font else println("*** Notice: have not implemented loading from system fonts yet") end _color = colorToSDL(win, color) new(win, textMessage , pos, color, fontName, fontSize, scale, font, # these will need to change to floats to handle Psychopy colors horizAlignment, vertAlignment, style, orientation, _color ) end end #---------- #---------- """ draw(text::TextStim; wrapLength::Int64) Draws an TextStim to the back buffer. **Inputs:** * text::TextStim **Optional Inputs:** * wrapLength::Int64......*in pixels (for now)* """ function draw(text::TextStim; wrapLength::Int64 = -1) if length(text._color) == 4 _color = SDL_Color(text._color[1], text._color[2] , text._color[3], text._color[4]) elseif length(text._color) == 3 _color = SDL_Color(text._color[1], text._color[2] , text._color[3], 255) else println("Error in draw(textStim): colors too short, should have length of 3 or 4") println("Length = ", length(text._color)) println("Values = ", text._color) end #------------------- if text.style == "normal" text.font = text.win.font elseif text.style == "italic" text.font = text.win.italicFont elseif text.style == "bold" text.font = text.win.boldFont else error("Unrecognized font style. 'normal', 'italic', 'bold', and 'underline' are recognized.") end #--------- if wrapLength == -1 surfaceMessage = TTF_RenderUTF8_Blended(text.font, text.textMessage, _color) # text.win.font Message = SDL_CreateTextureFromSurface(text.win.renderer, surfaceMessage); #else # surfaceMessage = TTF_RenderUTF8_Blended_Wrapped(text.font, text.textMessage, color, wrapLength) end # now you can convert it into a texture #@engineerX you can get dimensions of rendered text with TTF_SizeText(TTF_Font *font, const char *text, int *w, int *h) w = Ref{Cint}() h = Ref{Cint}() if wrapLength == -1 TTF_SizeText(text.font, text.textMessage, w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory singleHeight = h[] else TTF_SizeText(text.font, text.textMessage, w::Ref{Cint}, h::Ref{Cint}) # Ref is used if Julia controls the memory singleHeight = h[] #println("conventional width and height are: ", w[],", ",h[]," for the text: ",text.textMessage) #w[], h[] = ttf_size_utf8_wrappedAI(text.font, text.textMessage, wrapLength) strings, widths, h[] = wrapText(text.font, text.textMessage, wrapLength) #println("wrap width and height are: ", w[],", ",h[]," for the text: ",text.textMessage) end if text.vertAlignment == -1 # top anchored y = text.pos[2] cy = 0 elseif text.vertAlignment == 0 # center anchored y = text.pos[2] - round(Int64, h[]/2) cy = h[]÷2 elseif text.vertAlignment == +1 # bottom anchored y = text.pos[2] - h[] if y < singleHeight + 5 # enforce a minimum height so it doesn't go off the top. y = 5 end cy = h[] else error("invalid text vertical text alignment parameter") end #--------- if text.horizAlignment == -1 # left anchored x = text.pos[1] cx = 0 elseif text.horizAlignment == 0 # center justification x = text.pos[1] - round(Int64, w[]/2) cx = w[]÷2 elseif text.horizAlignment == +1 # right anchored x = text.pos[1] - w[] cx = w[] else error("invalid text horizontal text alignment parameter") end #--------- if text.scale != 1 # scale the text. Not the same as changing the font size. Message_rect = SDL_Rect(x, y, round(Int64, w[] * text.scale), round(Int64, h[] * text.scale) ) else if wrapLength == -1 Message_rect = SDL_Rect(x, y, w[], h[]) else Message_rect = SDL_Rect(x, y + h[]÷2, w[], h[]) end end #SDL_RenderCopy(text.win.renderer, Message, C_NULL, Ref{SDL_Rect}(Message_rect) ); # &Message_rect) if text.orientation == 0 if wrapLength == -1 SDL_RenderCopy(text.win.renderer, Message, C_NULL, Ref{SDL_Rect}(Message_rect) ); # &Message_rect) else for s in 1:length(strings) # loop through the sub-strings of wrapped text. surfaceMessage = TTF_RenderUTF8_Blended(text.font, strings[s], _color) # text.win.font Message = SDL_CreateTextureFromSurface(text.win.renderer, surfaceMessage) Message_rect = SDL_Rect(x, y + (s-1)*singleHeight, round(Int64, widths[s] * text.scale), round(Int64, singleHeight * text.scale) ) SDL_RenderCopy(text.win.renderer, Message, C_NULL, Ref{SDL_Rect}(Message_rect) ) end end else center = SDL_Point(cx, cy) SDL_RenderCopyEx(text.win.renderer, Message, C_NULL, Ref{SDL_Rect}(Message_rect), text.orientation, Ref{SDL_Point}(center), SDL_FLIP_NONE) # SDL_RenderCopyExF( <<< FUTURE WITH FLOATS end # Don't forget to free your surface and texture SDL_FreeSurface(surfaceMessage); SDL_DestroyTexture(Message); end #---------- """ setColor(text::TextStim; color::Union{String, Vector{Int64}, Vector{Float64}}) Update the textStim's color **Inputs:** * text::TextStim * color is a string, Vector of integers, or vector of floats. NEED A LINK TO THE COLORS PAGE """ function setColor(text::TextStim, color::PsychoColor) text._color = colorToSDL(text.win, color) end #---------- function setSize(text::TextStim, fontSize::Int64) println("setSize(::TextStim, fontsize) is a future placeholder for loading a font of the specific size") end #---------- function setFont(text::TextStim, fontName::String) println("setFont(::TextStim, fontName) is a future placeholder for loading a font of the specified name") end #------------------------------- const lineSpace = 2; #-============================================================================= function character_is_delimiter(c::Char, delimiters) for d in delimiters if c == d return true end end return false end #-============================================================================= # returns a list of strings for plotting, as well as the resulting width and height function wrapText(font, original::String, wrapWidth) if wrapWidth <= 0 error("wrapWidth must be > 0") end line_space = 2 strings = [] w = Ref{Cint}() h = Ref{Cint}() TTF_SizeText(font, original, w, h) # Ref is used if Julia controls the memory #------------------- # return if string does not need to be wrapped if w[] < wrapWidth push!(strings, original) return strings, w[], h[] end #------------------- wrap_delims = [' ', '\t', '\r', '\n'] lineBreak_delims = ['\r', '\n'] currentStr = original startSpot = 1 endSpot = length(original) done = false c = 1 lastFound = 1 while done == false currentChar = currentStr[c] if character_is_delimiter(currentChar, wrap_delims) == true TTF_SizeText(font, currentStr[startSpot:c], w, h) if character_is_delimiter(currentChar, lineBreak_delims) == true # line break if lastFound == 1 push!(strings, currentStr[startSpot:c-1]) currentStr = currentStr[c+1:endSpot] else push!(strings, currentStr[startSpot:c-1] ) #lastFound-1]) currentStr = currentStr[c+1:endSpot] #lastFound+1:endSpot] end endSpot = length(currentStr) lastFound = 1 c = 0 TTF_SizeText(font, currentStr[1:endSpot], w, h) # check to see if the next string is short enough if w[] < wrapWidth done = true push!(strings, currentStr) c = endSpot end elseif w[] <= wrapWidth lastFound = c elseif w[] > wrapWidth push!(strings, currentStr[startSpot:lastFound-1]) currentStr = currentStr[lastFound+1:endSpot] endSpot = length(currentStr) lastFound = 1 c = 0 TTF_SizeText(font, currentStr[1:endSpot], w, h) # check to see if the next string is short enough if w[] < wrapWidth done = true push!(strings, currentStr) c = endSpot end end end c += 1 if c >= endSpot done = true TTF_SizeText(font, currentStr[startSpot:c-1], w, h) if w[] > wrapWidth push!(strings, currentStr[startSpot:lastFound-1]) currentStr = currentStr[lastFound+1:endSpot] push!(strings, currentStr) end end end returnWidth = 0 widths = [] # this is written to return max width, but instead we are returning widths of each string for s in strings TTF_SizeText(font, s, w, h) push!(widths, w[]) if w[] > returnWidth returnWidth = w[] end end returnHeight = h[] + (length(strings) - 1) * (h[] + line_space) return strings, widths, returnHeight end #= function wrapTextBackwards(font, original::String, wrapWidth) if wrapWidth <= 0 error("wrapWidth must be > 0") end strings = [] w = Ref{Cint}() h = Ref{Cint}() TTF_SizeText(font, original, w, h) # Ref is used if Julia controls the memory #------------------- # return if string does not need to be wrapped if w[] < wrapWidth push!(strings, original) return strings, w[], h[] end #------------------- wrap_delims = [' ', '\t', '\r', '\n'] lineBreak_delims = ['\r', '\n'] currentStr = original startSpot = 1 endSpot = length(original) done = false c = endSpot while done == false #for c in endSpot:-1:startSpot # work backwards, find a delimiter, and if <, add to strings[] currentChar = currentStr[c] if character_is_delimiter(currentChar, wrap_delims) == true TTF_SizeText(font, currentStr[startSpot:c], w, h) if character_is_delimiter(currentChar, lineBreak_delims) == true # line break push!(strings, currentStr[startSpot:c-1]) currentStr = currentStr[c+1:endSpot] endSpot = length(currentStr) c = endSpot+1 TTF_SizeText(font, currentStr[startSpot:c-1], w, h) # check to see if the next string is short enough if w[] < wrapWidth done = true push!(strings, currentStr) c = 0 end elseif w[] < wrapWidth push!(strings, currentStr[startSpot:c-1]) currentStr = currentStr[c+1:endSpot] endSpot = length(currentStr) c = endSpot+1 TTF_SizeText(font, currentStr[startSpot:c-1], w, h) # check to see if the next string is short enough if w[] < wrapWidth done = true push!(strings, currentStr) c = 0 end end end c -= 1 #end if c== 0 done = true push!(strings, currentStr) end end return strings, w[], h[] end =# #= find delimiter. break on delimiter < length. make new string for next line. return strings. rules: break on a delimeter must break on \r or \n 1) scan for delims 2)if no delim is found, find length of string. If too big: a) chop at the 2nd-last char b) add a hyphen c) add left side to Strings d) make ride side the next thing to scan 3) if delim is < width, scan until you find the next that is not or find the end. wrap_delims = [' ', '\t', '\r', '\n'] break_delims = ['\r', '\n'] findfirst(isequal('\n'), str[tok:end]) Strings = [] done = false while done = false end return strings, width, height =# #= mutable struct TextStim #{T} win::Window textMessage::String # this will need to change to floats for Psychopy height coordiantes pos::Vector{Int64} color::Vector{Int64} # these will need to change to floats to handle Psychopy colors fontName::String fontSize::Int64 scale::Float64 font::Ptr{TTF_Font} horizAlignment::Int64 # -1 for left, 0 for center, +1 for right vertAlignment::Int64 # -1 aligns at top, 0 for center, +1 aligns at bottom style::String # bold, italic, etc. orientation::Int64 end #---------- function textStim(win::Window, textMessage::String = "future text", pos::Vector{Int64} = [10,10]; color::Vector{Int64} = fill(128, (3)), # these will need to change to floats to handle Psychopy colors fontName::String = "", fontSize::Int64 = 12, scale::Float64 = 1.0, font::Any = nothing, # font is for internal use and is a pointer to a TTF horizAlignment::Int64 = 1, vertAlignment::Int64 = 1, style::String = "normal", orientation::Int64 = 0 ) if fontName == "" font = win.font else println("*** Notice: have not implemented loading from system fonts yet") end textStruct = TextStim(win, textMessage , pos, color, fontName, fontSize, scale, font, # these will need to change to floats to handle Psychopy colors horizAlignment, vertAlignment, style, orientation ) return textStruct end =# mutable struct TextStimExp win::Window textMessage::String # this will need to change to floats for Psychopy height coordiantes pos::Vector{Int64} color::PsychoColor # these will need to change to floats to handle Psychopy colors fontName::String fontSize::Int64 scale::Float64 font::Ptr{TTF_Font} horizAlignment::Int64 # -1 for left, 0 for center, +1 for right vertAlignment::Int64 # -1 aligns at top, 0 for center, +1 aligns at bottom style::String # bold, italic, etc. orientation::Int64 #---------- function TextStimExp(win::Window, textMessage::String = "future text", pos::Vector{Int64} = [10,10]; color::PsychoColor = fill(128, (3)), # these will need to change to floats to handle Psychopy colors fontName::String = "", fontSize::Int64 = 12, scale::Float64 = 1.0, font::Any = nothing, # font is for internal use and is a pointer to a TTF horizAlignment::Int64 = -1, vertAlignment::Int64 = +1, style::String = "normal", orientation::Int64 = 0 ) if fontName == "" font = win.font else println("*** Notice: have not implemented loading from system fonts yet") end color = colorToSDL(win, color) new(win, textMessage , pos, color, fontName, fontSize, scale, font, # these will need to change to floats to handle Psychopy colors horizAlignment, vertAlignment, style, orientation ) end end #----------
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
747
export startTimer, stopTimer """ startTimer(win::Window) Starts a timer. Only one timer can run at a time. If you need more than tha one timer, use Julia's time() function. **Inputs:** * win::Window * waitTime::Float64 *default is milliseconds* **Outputs:** nothing """ function startTimer(win::Window) win.startTime = time() end """ stopTimer(win::Window) Stops the global timer and returns the time taken. If you need more than one timer, use Julia's time() function. **Inputs:** * win::Window **Outputs:** The time in [default] milliseconds. """ function stopTimer(win::Window) stopTime = time() if win.timeScale == "milliseconds" return (stopTime - win.startTime)*1000.0 else return (stopTime - win.startTime) end end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
12822
# Translation of psycopy window file to Julia export Window, closeAndQuitPsychoJL, flip, closeWinOnly, hideWindow, getPos, getSize, setFullScreen export mouseVisible # int(x) = floor(Int, x) # for typecasting floats to ints when indexing """ Window() Constructor for a Window object **Constructor inputs:** * size::MVector{2, Int64} * fullScreen::Bool **Optional constructor inputs:** * color::MVector{3, Int64} * colorSpace::String .......*Future. Not implemented yet* * pos::MVector{2, Float64} ......*position* * timeScale::String .......*default = "milliseconds"* * title::String ......*default = "Window"* **Full list of fields** * win::Ptr{SDL_Window} * size::MVector{2, Int64} * pos::MVector{2, Int64} ......*position* * color::MVector{3, Int64} * colorSpace::String * coordinateSpace::String ......*placeholder for now* * renderer::Ptr{SDL_Renderer} * font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * boldFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * italicFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * event::Base.RefValue{SDL_Event} * fullScreen::Bool * timeScale::String .......*defaults is milliseconds. Other option is seconds* * title::String * startTime::Float64 .......*global proximy for startTime() and stopTime()* **Methods:** * closeAndQuitPsychoJL() * closeWinOnly() * flip() * getPos() * getSize() * hideWindow() * mouseVisible() * setFullScreen() """ mutable struct Window #{T} win::Ptr{SDL_Window} size::MVector{2, Int64} # window size; static array (stay away from tuples) pos::MVector{2, Int64} # position color::MVector{3, Int64} # these will be Psychopy colors colorSpace::String # rgb255, rgba255, decimal, PsychoPy coordinateSpace::String # LT_Pix, LT_Percent, LB_Percent, PsychoPy renderer::Ptr{SDL_Renderer} font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} boldFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} italicFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} event::Base.RefValue{SDL_Event} #SDL_Event fullScreen::Bool timeScale::String title::String startTime::Float64 firstKey::Bool # used for debouncing first keypress #---------- function Window(size, # window size; static array (stay away from tuples) fullScreen = false; color = fill(0, (3)), # these will be Psychopy colors colorSpace = "rgba255", # might need to revist for colors.jl coordinateSpace = "LT_Pix", pos = [SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED], # position timeScale = "milliseconds", title = "Window" ) winPtr = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, size[1], size[2], SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI )#| SDL_WINDOW_INPUT_GRABBED) #winPtr = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, size[1], size[2], SDL_WINDOW_SHOWN)# | SDL_WINDOW_ALLOW_HIGHDPI )#| SDL_WINDOW_INPUT_GRABBED) if timeScale != "seconds" && timeScale != "milliseconds" println("* timeScale can only be 'seconds' or 'milliseconds'.") println("** ", timeScale, " was given as the value for timeScale.") println("* default to milliseconds for timing.") timeScale = "milliseconds" end # for default size, try to use a version of the fullscreen size, taking Retina into account displayInfo = Ref{SDL_DisplayMode}() SDL_GetCurrentDisplayMode(0, displayInfo) screenWidth = displayInfo[].w screenHeight = displayInfo[].h pos = [screenWidth ÷ 2, screenHeight ÷ 2] println("screenWidth = ", screenWidth) println("screenHeight = ", screenHeight) println("asked for window size = ", size) SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2"); renderer = SDL_CreateRenderer(winPtr, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND) baseFilePath = pwd() baseFilePath =joinpath(baseFilePath,"fonts") baseFilePath =joinpath(baseFilePath,"Roboto") fontFilePath =joinpath(baseFilePath,"Roboto-Regular.ttf") font = TTF_OpenFont(fontFilePath, 30); if font == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #---------------- # canned BOLD versions look better than asking SDL to bold the font fontFilePath =joinpath(baseFilePath,"Roboto-Bold.ttf") boldFont = TTF_OpenFont(fontFilePath, 30); if boldFont == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #----------- # canned italic versions look better than asking SDL to bold the font fontFilePath =joinpath(baseFilePath,"Roboto-Italic.ttf") italicFont = TTF_OpenFont(fontFilePath, 30); if italicFont == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #---------------- event = Ref{SDL_Event}() if fullScreen == true SDL_SetWindowFullscreen(winPtr, SDL_WINDOW_FULLSCREEN) end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_RenderClear(renderer) # <<< Had to do this to clear out the noise. #--------- firstKey = true #--------- new(winPtr, size, pos, color, colorSpace, coordinateSpace, renderer, font, boldFont, italicFont, event, fullScreen, timeScale, title, firstKey ) end end #---------- """ closeAndQuitPsychoJL(win::Window) Attempts to close a PsychoJL Window and quit SDL. """ function closeAndQuitPsychoJL(win::Window) # SDL_DestroyTexture(tex) # this nees to get more complicated, where it loops through a list of textures println("pre SDL_SetWindowFullscreen") exit() SDL_SetWindowFullscreen(win.win, SDL_FALSE) SDL_DestroyRenderer(win.renderer) # this nees to get more complicated, where it loops through a list of renderers SDL_DestroyWindow(win.win) println("pre SDL_Quit") #SDL_Quit() exit() end #---------- """ flip(win::Window) Flips the offscreen buffer on screen. In other words, all of the visual objects that you have drawn offscreen prior to the flip will now become visible. """ function flip(win::Window) SDL_RenderPresent(win.renderer) SDL_PumpEvents() SDL_SetRenderDrawColor(win.renderer, win.color[1], win.color[2], win.color[3], 255) SDL_RenderClear(win.renderer) # <<< Had to do this to clear out the noise. end #---------- """ closeWinOnly(win::Window) Attempts to close a PsychoJL Window without quiting SDL. """ function closeWinOnly(win::Window) SDL_DestroyRenderer(win.renderer) # this nees to get more complicated, where it loops through a list of renderers SDL_DestroyWindow(win.win) end #---------- """ hideWindow(win::Window) Attempts to hide a PsychoJL Window. """ function hideWindow(win::Window) SDL_HideWindow(win.win) end #---------- """ getPos(win::Window) Returns the center of the window. This, as well as the dimensions, can chage when going to full screen """ function getPos(win::Window) #= displayInfo = Ref{SDL_DisplayMode}() SDL_GetCurrentDisplayMode(0, displayInfo) screenWidth = displayInfo[].w screenHeight = displayInfo[].h =# w = Ref{Cint}() h = Ref{Cint}() SDL_GL_GetDrawableSize(win.win, w, h) screenWidth = w[] screenHeight = h[] win.pos = [screenWidth ÷ 2, screenHeight ÷ 2] # integer division return win.pos end #---------- """ getSize(win::Window) Returns the width and height of the window. Dimensions can chage when going to full screen. """ function getSize(win::Window) w = Ref{Cint}() h = Ref{Cint}() SDL_GL_GetDrawableSize(win.win, w, h) screenWidth = w[] screenHeight = h[] win.size = [screenWidth, screenHeight ] return win.size end #---------- """ setFullScreen(win::Window, mode::Bool) Allows you to flip between windowed and full-screen mode. """ function setFullScreen(win::Window, mode::Bool) if mode == true SDL_SetWindowFullscreen(win.win, SDL_WINDOW_FULLSCREEN) else SDL_SetWindowFullscreen(win.win, SDL_WINDOW_FULLSCREEN_DESKTOP) end end #---------- """ mouseVisible(mode::Bool) Hides or shows the cursor """ function mouseVisible(visibility::Bool) if visibility == true SDL_ShowCursor(SDL_ENABLE) else SDL_ShowCursor(SDL_DISABLE) end end #-=============================================== # /System/Library/Fonts #= mutable struct Window #{T} win::Ptr{SDL_Window} size::MVector{2, Int64} # window size; static array (stay away from tuples) pos::MVector{2, Float64} # position color::MVector{3, Int64} # these will be Psychopy colors colorSpace::String # might need to revist for colors.jl renderer::Ptr{SDL_Renderer} font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} boldFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} italicFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} event::Base.RefValue{SDL_Event} #SDL_Event fullScreen::Bool timeScale::String title::String end #---------- function window( size, # window size; static array (stay away from tuples) fullScreen = false; color = fill(0, (3)), # these will be Psychopy colors colorSpace = "rgb", # might need to revist for colors.jl pos = [SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED], # position timeScale = "milliseconds", title = "Window" ) winPtr = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, size[1], size[2], SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI )#| SDL_WINDOW_INPUT_GRABBED) if timeScale != "seconds" || timeScale != "milliseconds" println("**** timeScale can only be 'seconds' or 'milliseconds'.") println("****", timeScale, " was given as the value for timeScale.") println("**** default to milliseconds for timing.") timeScale = "milliseconds" end SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2"); renderer = SDL_CreateRenderer(winPtr, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) # SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND) baseFilePath = pwd() baseFilePath =joinpath(baseFilePath,"fonts") baseFilePath =joinpath(baseFilePath,"Roboto") fontFilePath =joinpath(baseFilePath,"Roboto-Regular.ttf") # baseFilePath =joinpath(baseFilePath,"Noto_Serif") # fontFilePath =joinpath(baseFilePath,"NotoSerif-VariableFont_wdth,wght.ttf") # font = TTF_OpenFont("/Users/MattPetersonsAccount/Documents/Development/Julia/PsychoJL/sans.ttf", 24); font = TTF_OpenFont(fontFilePath, 30); if font == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #---------------- # canned BOLD versions look better than asking SDL to bold the font fontFilePath =joinpath(baseFilePath,"Roboto-Bold.ttf") boldFont = TTF_OpenFont(fontFilePath, 30); if boldFont == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #----------- # canned italic versions look better than asking SDL to bold the font fontFilePath =joinpath(baseFilePath,"Roboto-Italic.ttf") italicFont = TTF_OpenFont(fontFilePath, 30); if italicFont == C_NULL if isfile(fontFilePath) == false error("Could not open file path: " * fontFilePath) end error("*** Error: font is NULL") end #---------------- event = Ref{SDL_Event}() winStruct = Window(winPtr, size, pos, color, colorSpace, renderer, font, boldFont, italicFont, event, fullScreen, timeScale, title) if fullScreen == true SDL_SetWindowFullscreen(winStruct.win, SDL_WINDOW_FULLSCREEN) end SDL_PumpEvents() # this erases whatever random stuff was in the backbuffer SDL_RenderClear(renderer) # <<< Had to do this to clear out the noise. return winStruct end =# #= """ Window() Constructor for a Window object constructor inputs: * size::MVector{2, Int64} * fullScreen::Bool optional constructor inputs: * color::MVector{3, Int64} * colorSpace::String # Future. Not implemented yet * pos::MVector{2, Float64} # position * timeScale::String # default = "milliseconds", * title::String # default = "Window" parameters: * win::Ptr{SDL_Window} * size::MVector{2, Int64} * pos::MVector{2, Float64} # position * color::MVector{3, Int64} # these will be Psychopy colors * colorSpace::String # might need to revist for colors.jl * renderer::Ptr{SDL_Renderer} * font::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * boldFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * italicFont::Ptr{SimpleDirectMediaLayer.LibSDL2._TTF_Font} * event::Base.RefValue{SDL_Event} #SDL_Event * fullScreen::Bool * timeScale::String * title::String """ =#
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
code
97
using PsychExpAPIs using Test @testset "PsychExpAPIs.jl" begin # Write your tests here. end
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
544
# PsychExpAPIs #### or PsychoJL for short PsychoJL is a module for writing psychology and psychophysics experiments. The general framework and style is inspired by PsychoPy, but there has been no collaboration with the authors of PsychoPy. Matt Peterson, 2023-2024 [Click here for the manual](https://mpeters2.github.io/PsychExpAPIs.jl/dev/) [![Build Status](https://github.com/mpeters2/PsychoJL.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mpeters2/PsychoJL.jl/actions/workflows/CI.yml?query=branch%3Amain)
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
4095
### Color spaces in PsychoJL The colorspace for your experiment is specified when you make your window. For example: ```julia myWin = Window( [2560, 1440], false, colorSpace = "rgba255") ``` #### Colorspaces `rgb255` red, green, and blue values from 0 to 255. Alpha (opacity) is assumed to be 255 (100%) * black = [0,0,0] * 50% gray = [127, 127, 127] * white = [255, 255, 255] `rgba255` red, green, blue, and alpha values from 0 to 255. * black = [0, 0, 0, 255] * 50% gray = [127, 127, 127, 255] * white = [255, 255, 255, 255] `decimal` red, green, blue, and alpha values from 0.0 to 1.0. 0.0 is black and 1.0 is 100% * black = [0.0, 0.0, 0.0, 1.0] * 50% gray = [0.5, 0.5, 0.5, 1.0] * white = [1.0, 1.0, 1.0, 1.0] `PsychoPy` red, green, blue, and alpha values from -1.0 to 1.0. A value of 0.0 is gray, and +1.0 is 100% * black = [-1.0, -1.0, -1.0, +1.0] * 50% gray = [0.0, 0.0, 0.0, +1.0] * white = [+1.0, +1.0, +1.0, +1.0] \ Internally, all of these colors will be translated to rgba255 so that they work with SDL (the cross-platform graphics engine that PsychoJL uses). ##### Color fields Because of the color conversions, you should not access color fields directly. Internally, the color you set is translated to an SDL color and saved in another variable, which is the variable used for drawing. In order to translate (and update!) the color, colors should be set either when making the stimulus or using the `setColor()` function.\ For example, while making a new Textstim: ```julia myText = TextStim(myWin, "Using a TextStim", [100, 100], color = [255, 255, 128]) ``` Example using `setColor()` ```julia setColor(myText, "red") ``` see [Color setting functions](@ref) #### Colors in PsychoJL Shapes and TextStim use PsychoColor as their color Type. `PsychoColor = Union{String, Vector{Int64}, Vector{Float64}}` What does that gobbledy-gook mean? It means that the constructors and functions accept strings, Vectors of Int64 (from 0-255) and Vectors of Float 64 (either -1.0...+1.0, or 0.0...+1.0) as inputs. You can pass a string, an integer vector, or a floating point vector as a color. Keep in mind that the values you pass must be legal in the color space. For example, if you set the color space to `rgba255` and try to set the color using a floating point vector, it will throw an error.\ \ Strings are legal in all cases. ##### When the color space is rgb255 or rgba255... String inputs will be accepted (see [Colors.jl](https://github.com/JuliaGraphics/Colors.jl/blob/master/src/names_data.jl) for a list of color names).\ \ Integer Vectors with a length of 3 (RGB) or a length of 4 (RGBA) will also be accepted. If the length is 3, alpha (opacity) is assumed to be 255 (100%). Example: ```julia newRect = Rect(myWin, 100, # width 100, # height [200,200], # position lineColor = "dodgerblue", # strings are kosher fillColor = [255,128,128] # this works if the window's color space is rgb255 or rgba255 ) draw(newRect) # in PsychoPy this would have been newRect.draw() ``` ##### When the color space is decimal or PsychoPy... String inputs will be accepted (see [Colors.jl](https://github.com/JuliaGraphics/Colors.jl/blob/master/src/names_data.jl) for a list of color names).\ \ Float Vectors need a length of 4 (RGBA). How they are interpreted depends on the color space. If the color space is `decimal`, a value of 0.0 is considered 'black' (in that color channel), and 0.5 is considered gray (50% in that channel). On the other hand, if the color space is `PsychoPy`, -1.0 s considered 'black' (in that color channel), 0.0 is considered gray (50% in that channel), and +1.0 is considered white (100% in that channel). see [Colorspaces](@ref) for example values. Example: ```julia newRect = Rect(myWin, 100, # width 100, # height [200,200], # position lineColor = "beige", # strings are kosher fillColor = [1.0, 0.5, 0.5] # this works if the window's color space is decimal or PsychoPy, ) draw(newRect) # in PsychoPy this would have been newRect.draw() ``` """
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
2439
## Coordinate systems PsychoJL has several diferent coordinate systems available. * LT_Pix *left top in pixels* * LT_Percent *left top in percent of height* * LB_Percent *left bottom in percent of height* * PsychoPy *Psychopy-style height units* --- ### LT_Pix The origin is in the left-top corner, positive y-values go downward, and the units of measure are pixels. The size of the dimensions are determined by the size of your window. All units are in integers (Int64). !["picture of an LT_Pix screen"](assets/LT_Pix.png) ##### Note on fullscreen mode If you set the draw area of your window to less than the full screen size, then draws in full-screen mode will be truncated to the dimensions of the window you made. This can be confusing, as the screen can appear all black, but drawing is limited to the subsection of the screen you specified. --- ### LT_Percent The origin is in the left-top corner, positive y-values go downward, and the units of measure are percentage of the height. The height dimension always ranges from 0.0 to 1.0, but width varies depending on the aspect ratio of the window. In the example below, the aspect ratio is 1.7778:1 (2560 x 1440). All units are floating point (Float64). !["picture of an LT_Percent screen"](assets/LT_Percent.png) --- ### LB_Percent The origin is in the left-bottom corner, positive y-values go upward, and the units of measure are percentage of the height. The height dimension always ranges from 0.0 to 1.0, but width varies depending on the aspect ratio of the window. In the example below, the aspect ratio is 1.7778:1 (2560 x 1440). All units are floating point (Float64). !["picture of an LB_Percent screen"](assets/LB_Percent.png) --- ### Psychopy The origin is in the middle of the screen, positive y-values go upward, and the units of measure are percentage of the height. The height dimension always ranges from -0.5 to +0.5, but width varies depending on the aspect ratio of the window. In the example below, the aspect ratio is 1.7778:1 (2560 x 1440). All units are floating point (Float64). --- ### https://github.com/mpeters2/PsychoJL.jl/blob/main/docs/src/assets/Psychopy.png ``` !["picture of an PsychoPy screen"](assets/PsychoPy.png) docs/src/showcase.md ![Enter a descriptive caption for the image](assets/logo.png) docs/src/assets/logo.png ME: docs/src/Coordinates.md docs/src/assets/Psychopy.png ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
200
```@docs displayMessage( message::String) happyMessage( message::String) infoMessage( message::String) warningMessage( message::String) errorMessage( message::String) DlgFromDict(dlgDict::Dict) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
78
```@docs ImageStim draw(theImageStim::ImageStim; magnification::Float64) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
64
```@docs InitPsychoJL() waitTime(win::Window, time::Float64) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
73
```@docs getKey(win::Window) waitKeys(win::Window, waitTime::Float64) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
2745
## Setter functions Setter function are used to set the values of the various/struct objects, and should be used instead of accessing the fields directly. The reason for not accessing them directly is that often the data you send to the objects needs to be translated to a different representation.\ \ For example: * "Red" needs to be translated to [255,0,0,255] * If you are using PsychoPy coordinatse, the coordinate [-0.6, +0.5] might need to be translated to [100, 0]. ### Color setting functions see [Color spaces in PsychoJL](@ref) and [Colors in PsychoJL](@ref) `setColor(someObject::stimulusType, color::Union{String, Vector{Int64}, Vector{Float64})`\ * where the stimulusType is textStim or Line `setLineColor(someObject::stimulusType, color::Union{String, Vector{Int64}, Vector{Float64})`\ * where the stimulusType is Rect, Ellipse, or Circle `setFillColor(someObject::stimulusType, color::Union{String, Vector{Int64}, Vector{Float64})`\ * where the stimulusType is Rect, Ellipse, or Circle ### Position setting functions see [Coordinate systems](@ref) Because coordinates may need to be translated to another coordinate system, you should use the `setPos()` function to update your stimulus' position. The example code below draws a circle, and updates its position periodically. Example: ```julia using PsychExpAPIs # 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 20% 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) # move circle to the right by 10% of the height setPos(myCirc, [x, 0]) # Use setPos() to convert PsychoPy to SDL coordinates draw(myCirc) # everything draws into memory flip(win) # copies to screen waitTime(win, 0.1) end closeWinOnly(win) end #-=============================================================== main() ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
469
see [Setter functions](@ref) ```@docs Circle Ellipse Line Polygon Rect ShapeStim ``` #### draw(various shape types) - Method Draws the shape (Line, Rect, Ellipse, TextStim, etc.) into the back buffer. Example: ```julia newRect = Rect(myWin, 100, # width 100, # height [200,200], # position lineColor = [255,0,0], fillColor = [255,128,128] ) draw(newRect) # in PsychoPy this would have been newRect.draw() ``` """ ```@docs setPos ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
29
```@docs SoundStim play ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
64
```@docs TextStim draw(text::TextStim; wrapLength::Int64) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
579
```@docs startTimer(win::Window) stopTimer(win::Window) ``` #### Alternative approach An alterntiave to calling these functions is to use Julia's built-in `time()` function, which returns the current time in seconds. Example: ```julia ... draw(myStim) # draw stimulus flip(win) # flip the window onto the screen startTime = time() # get the current time keypressed = getKey(win) # wait for a keypress stopTime = time() # get the current time timeTaken = stopTime - startTime println("It took ", timeTaken * 1000," milliseconds for a keypress.") ``` """
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
235
```@docs Window closeAndQuitPsychoJL(win::Window) closeWinOnly(win::Window) flip(win::Window) getPos(win::Window) getSize(win::Window) hideWindow(win::Window) mouseVisible(visibility::Bool) setFullScreen(win::Window, mode::Bool) ```
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
7169
# Introduction to PsychoJL PsychoJL is a module for writing psychology and psychophysics experiments. The general framework and style is inspired by PsychoPy, but there has been no collaboration with the authors of PsychoPy. Matt Peterson, 2023-2024 ## Manual Outline ```@contents ``` ## Overview PsychoJL is a module for writing psychology experiments. Typically, before a trial begins, stimuli are drawn offscreen into the video buffer. When it is time to present the stimuli, the flip() function is called and the offscreen image is displayed. ## Differences between PsychoPy and PsychoJL The main difference between the two involves how objects are called in Julia. For example, to make and draw a TextStim, you would write something like this in PsychoPy: ```python stim = visual.TextStim(win, 'Hello World!', pos=(0.0, 0.0), # center of the screen color=(1, 0, 0), colorSpace='rgb') TextStim.draw() ``` In Julia, it would look like this: ```julia stim = TextStim(win, "Hello World!", [300, 100], # position color=(255, 0, 0)) draw(stim) ``` Notice that Julia does not use the Object.method() syntax of Python. Instead, the stimulus is passed to the draw() function. Python: `object.function(param)`\ Julia: `function(object, param)` Examples: ```python myImage.setPos( (0.0, 0.0) ) ``` ```julia setPos(myImage, [0.0, 0.0]) # assuming you are using PsychoPy coordinates ``` In addition, Julia objects are really structures (data) with a constructor function of the same name. For example, I can make a new `TextStim` using the `TextStim()` constructor function, and later change one of its properties using dot notation. ```julia stim = TextStim(win, "Hello World!", [300, 100], # position color=(255, 0, 0)) stim.textMessage = "Goodbye, world!" ``` ## Performance Tips Julia can be many orders of magnitude faster than Python. My biggest performance tip is, despite their similarities, do not write Julia programs like you would write a Python program. ##### Global Variables For example, although Julia can use global variables, the use of global variables (global constants are OK) [prevents the optimizing compiler from optimizing](https://docs.julialang.org/en/v1/manual/performance-tips/). Instead, pass around structs containing what would have been written as global variables in a Python program. The VisualSearchMain.jl example experiment shows this in action. It uses a struct called ExperimentalDesign. Although the struct definition is in the global scope, an instance of this structure is created in the function `makeExperimentalDesign()` and passed around from function-to-function. ```julia 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 ``` PsychoJL also makes use of this through the Window instance you create. You may have noticed that most PsychoJL functions require a window to be passed as one of their parameters. For example, `startTimer()` and `stopTimer()` require a Window to be passed as one of their arguments. What in the world does timing have to do with a graphical window? Nothing. However, PsychoJL uses it as a struct that can hold what would have otherwise been a global variable in another language. Calling `startTimer()` causes it to store the starting time in the Window you passsed to it. Likewise, `stopTimer()` uses the information stored in the Window structure to calculate the elapsed time. ##### Variable Typing Like Python, Julia can infer variables' types. However, Julia can be faster when it does not need to infer types. For example, the parameter for this function is perfectly legal (from a syntactic point of view): ```julia function fancyMath(myArray) answer = doSomeStuff(myArray) return answer end ``` But, this is even better, because it explicitely states the parameter's type: ```julia function fancyMath(myArray::Vector{Float64}) answer = doSomeStuff(myArray) return answer end ``` As you might have noticed by the documentation, PsychoJL is strongly typed. Future versions, through multiple-dispatch (i.e. overloading) will be less strict with their types. For example, for the `startPoint` and `endPoint`, `Line()` requires a vector of two integers. In the future, it will allow vectors of floats. [edit: the future is here!] ##### Integer Division When dividing variables that should remain integers, Julia's integer division operand `÷` (not `/`!) is extremely useful. Dividing integers using the standard division operand `\` can return a float. For example: ```julia julia> x = 255 ÷ 2 127 ``` vs ```julia julia> x = 255 / 2 127.5 ``` Integer division truncates. In other situations `round(Int64, x)` might make more sense. ## Usage Rules 1. The function `InitPsychoJL()` just be called before any PsychoJL functions are called. 2. The `Window()` constructor for the main window should be called before using any PsychoJL functions, other than GUI calls. 3. GUI dialog windows should be called before the main `Window` has been made. 4. GUI dialog windows can be callled after the main `Window has` been closed. 5. Do not taunt Happy Fun Ball. ## Example The function ```julia using PsychExpAPIs function DemoWindow() InitPsychoJL() myWin = Window( [1000,1000], false) # dimensions, fullscreen = false newRect = Rect(myWin, 100, # width 100, # height [200,200], # position lineColor = [255,0,0], fillColor = [255,128,128] ) draw(newRect) # in PsychoPy this would have been newRect.draw() myText = TextStim(myWin, # window "Using a textStim", # text [300, 100], # position color = [255, 255, 128] ) draw(myText) # in PsychoPy this would have been myText.draw() flip(myWin) wait(2000) # core.wait in Psychopy. Default timeScale (see Window) is in milliseconds. end #------ DemoWindow() ``` ## Missing Functionality mouse events\n timers (timing can be done by using Julia's time() function)\n pie-wedges\n ## Known issues ### Manual The manual is a work in progress, and needs reorganization. ### Timescales The default timescale is `milliseconds`, but `seconds` is also an option. The timescale used for your experiment is set by passing `milliseconds` or `seconds` as one of the optional parameters when creating a main window. ### Monitors There are some issues that need to be worked out when using high-resolution displays suchs Retina displays. Currently, fullscreen mode draws correctly, but when fullscreen = false, the image is smaller than expected. ## Technology All graphics and input are handled by SDL.jl. I translated parts of SDL2_gfxPrimitives from C to Julia, with some code replaced with more efficient algorithms (and sometimes I couldn't figure out the orignal C code!).
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
0.1.0
3bb03a80c95594883082fd3fe384f0fe86ffb2cf
docs
319
Missing Functionality 1) ShapeStim, Polygon need to be fillable. 2) Timescale not implemented 3) Rotations not implemented. Also need to specify the rotation point 4) setPos() for lines 5) Tutorial/Concepts/References side bar 6) Visual Search needs feedback beep 7) Opacity for imageStims 8) Opacity for all shapes
PsychExpAPIs
https://github.com/mpeters2/PsychExpAPIs.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1466
using Perceptrons # training a linear perceptron (solving the OR problem) X_train = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y_train = [1; 1; 1; 0.0] X_test = [.8 .9; .01 1; .9 0.2; 0.1 0.2] model = Perceptrons.fit(X_train,Y_train) Y_pred = Perceptrons.predict(model,X_test) println("[Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a voted perceptron (solving the OR problem) model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="voted") Y_pred = Perceptrons.predict(model,X_test) println("[Voted Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a averaged perceptron (solving the OR problem) model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="averaged") Y_pred = Perceptrons.predict(model,X_test) println("[Averaged Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a kernel perceptron (solving the XOR problem) X_train = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y_train = [0.0 ; 1.0; 1.0; 0.0] X_test = X_train .+ .03 # adding noise model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="kernel",kernel="rbf",width=.01) Y_pred = Perceptrons.predict(model,X_test) println("[Kernel Perceptron] accuracy : $(acc(Y_train,Y_pred))") # if you want to save your model Perceptrons.save(model,filename=joinpath(homedir(),"perceptron_model.jld")) # if you want to load back your model model = Perceptrons.load(filename=joinpath(homedir(),"perceptron_model.jld"))
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
3181
module Perceptrons using JLD include("utils.jl") include("types.jl") include("linear_perceptron.jl") include("kernel_perceptron.jl") include("voted_perceptron.jl") include("averaged_perceptron.jl") """ fit(X::Matrix{:<AbstractFloat},Y::AbstractArray{:<AbstractFloat}; copydata::Bool=true, centralize::Bool=true, kernel="linear", width=1.0, alpha=1.0e-2, shuffle_epoch = true, random_state = true, max_epochs = 5, mode = "linear" ) Perceptron algorithm. # Arguments - `copydata::Bool = true`: If you want to use the same input matrix or a copy. - `centralize::Bool = true`: If you want to z-score columns. Recommended if not z-scored yet. - `kernel::AbstractString = "rbf"`: If you want to apply a nonlinear Perceptron with gaussian Kernel. - `width::AbstractFloat = 1.0`: Rbf Kernel width (Only if kernel="rbf"). - `alpha::Real = 1.0e-2`: learning rate. - `shuffle_epoch::Bool = true`: Shuffle dataset for each epoch. Improves convergency. - `random_state::Int = 42`: Use a seed to force same results trhough the same dataset. - `max_epochs::Int = 5`: Maximum epochs. - `mode::String = "linear"`: modes are "linear", "kernel", "voted" and "averaged" perceptron. """ function fit(X::AbstractArray{T}, Y::AbstractArray{T}; copydata::Bool = true, centralize::Bool = true, kernel::String = "linear", width::AbstractFloat = 1.0, alpha::AbstractFloat = 1.0e-2, shuffle_epoch::Bool = true, random_state::Int = 42, max_epochs::Int = 50, mode = "linear" ) where T<:AbstractFloat X = X[:,:] check_constant_cols(X) check_constant_cols(Y) check_params(kernel,mode) check_data(X, Y) Xi = (copydata ? deepcopy(X) : X) Yi = (copydata ? deepcopy(Y) : Y) check_linear_binary_labels(Yi) model = Model(X, alpha, shuffle_epoch, random_state, max_epochs, centralize, kernel, width, mode) Xi = (centralize ? centralize_data(Xi,model.mx,model.sx) : Xi) model.centralize = ( centralize ? true : false ) trainer(model,Xi,Yi) return model end """ predict(model::Perceptron.Model; X::AbstractArray{:<AbstractFloat}; copydata::Bool=true) A Perceptron predictor. # Arguments - `copydata::Bool = true`: If you want to use the same input matrix or a copy. """ function predict(model::PerceptronModel{T}, X::AbstractArray{T}; copydata::Bool=true) where T<:AbstractFloat X = X[:,:] check_data(X,model.nfeatures) Xi = (copydata ? deepcopy(X) : X) Xi = (model.centralize ? centralize_data(Xi,model.mx,model.sx) : Xi) Yi = predictor(model,Xi) return Yi end dir(path...) = joinpath(dirname(dirname(@__FILE__)),path...) end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1752
import Random function trainer(model::AveragedPerceptron{T}, X::AbstractArray{T}, Y::Vector{T}) where T<:AbstractFloat shuffle_epoch = model.shuffle_epoch random_state = model.random_state max_epochs = model.max_epochs if random_state!=-1 Random.seed!(random_state) end n,m = size(X) X = hcat(X,ones(n,1)) # adding bias history = [] nerrors,nlast_errors = Inf,0 epochs = 0 Θ,α = Random.rand(m+1),model.α step = float(n*max_epochs) #while nerrors>0 && epochs < max_epochs while epochs < max_epochs # stops when error is equal to zero or grater than last_error or reached max iterations # shuffle dataset if shuffle_epoch sind = Random.shuffle(1:n) x = X[sind,:] y = Y[sind] end nerrors = 0 # weight updates for all samples for i=1:n xi = x[i,:] ξ = sinal(Θ'*xi) - y[i] if ξ!=0 nerrors+=1 Θ = Θ - (step/(n*max_epochs))* α * ξ * xi end step = step - 1 end nlast_errors = nerrors epochs+=1 push!(history,nerrors) end if nerrors > 0 warn("Perceptron: Not converged. Max epochs $(max_epochs) reached. Error history: $(history) \n Try to increase max_epochs or may be you have a non linear problem.") end model.Θ = Θ model.history = history end function predictor(model::AveragedPerceptron{T}, X::AbstractArray{T}) where T<:AbstractFloat Θ = model.Θ α = model.α n = size(X,1) y = zeros(Real,n) X = hcat(X,ones(n,1)) # adding bias for i=1:n y[i] = sinal(Θ'*X[i,:]) end y end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
2896
# A gaussian kernel function @inline function Φ(x::Vector{T}, y::Vector{T}, r::T=1.0) where T<:AbstractFloat n = 1.0 / sqrt(2π*r) s = 1.0 / (2r^2) return n*exp(-s*sum((x.-y).^2)) end # A kernel matrix function ΦΦ(X::AbstractArray{T}, r::T=1.0) where T<:AbstractFloat n = size(X,1) K = zeros(n,n) for i=1:n for j=1:i K[i, j] = Φ(X[i, :], X[j, :],r) K[j, i] = K[i, j] end K[i, i] = Φ(X[i, :], X[i, :],r) end K end # A kernel matrix for test data function ΦΦ(X::AbstractArray{T}, Z::AbstractArray{T}, r::T=1.0) where T<:AbstractFloat (nx,mx) = size(X) (nz,mz) = size(Z) K = zeros(T,nz, nx) for i=1:nz for j=1:nx K[i, j] = Φ(Z[i, :], X[j, :],r) end end K end @inline ∑(λ,y,n,K) = sum(λ .* y .* K) function trainer(model::KernelPerceptron{T}, X::AbstractArray{T}, Y::Vector{T}) where T<:AbstractFloat Y[Y .== 0] .= -1 # fix in the future outside this function max_epochs = model.max_epochs λ = model.λ # langrange multipliers K = ΦΦ(X,model.width) # computing the kernel gram matrix n = size(X,1) history = [] nerrors = Inf epochs = 0 while nerrors>0 && epochs < max_epochs # stops when error is equal to zero or grater than last_error or reached max iterations nerrors = 0 # weight updates for all samples for i=1:n yp = sign(∑(λ,Y,n,K[:,i])) if Y[i] != yp nerrors +=1 λ[i] += 1 # missclassification counter for sample i end end epochs+=1 push!(history,nerrors) end if nerrors > 0 warn("[Kernel Perceptron] Train not converged. Max epochs $(max_epochs) reached. Error history: $(history) \n Try to increase max_epochs or change kernel params.") end # storing only the tough samples ("support vectors") sv = λ .> 0 model.λ = λ[sv] model.sv_x = vec(X[sv,:]) model.sv_y = Y[sv] model.history = history model.last_epoch = epochs #println("[Kernel perceptron] #$(length(model.λ)) support vectors out of $(n) samples.") end function predictor(model::KernelPerceptron{T}, X::AbstractArray{T}) where T<:AbstractFloat width = model.width sv_x,sv_y,λ = model.sv_x,model.sv_y,model.λ k = size(sv_y,1) n = size(X,1) y = zeros(T,n) for i=1:n s = .0 for j=1:k # can be vectorized in the future. s += λ[j] * sv_y[j] * Φ(X[i,:],sv_x[j,:],width) # this is simply a weighted voting into a kernel space end y[i] = s end y = sign.(y) y[y .== -1] .= 0 # fix in the future outside this function!! return y end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1741
# use in linear perceptron @inline h(Θ,x) = sinal(Θ'*x) import Random function trainer(model::LinearPerceptron{T}, X::AbstractArray{T}, Y::Vector{T}) where T<:AbstractFloat shuffle_epoch = model.shuffle_epoch random_state = model.random_state max_epochs = model.max_epochs if random_state!=-1 Random.seed!(random_state) end n,m = size(X) X = hcat(X,ones(n,1)) # adding bias history = [] nerrors,nlast_errors = Inf,0 epochs = 0 Θ = Random.rand(m+1) # already with bias α = model.α # learning rate while nerrors>0 && epochs < max_epochs # stops when error is equal to zero or grater than last_error or reached max iterations # shuffle dataset if shuffle_epoch sind = Random.shuffle(1:n) x = X[sind,:] y = Y[sind] end nerrors = 0 # weight updates for all samples for i=1:n xi = x[i,:] ξ = h(Θ,xi) - y[i] if ξ!=0 nerrors+=1 Θ = Θ - α * ξ * xi end end nlast_errors = nerrors epochs+=1 push!(history,nerrors) end if nerrors > 0 warn("Perceptron: Not converged. Max epochs $(max_epochs) reached. Error history: $(history) \n Try to increase max_epochs or may be you have a non linear problem.") end model.Θ = Θ model.α = α model.history = history end function predictor(model::LinearPerceptron{T}, X::AbstractArray{T}) where T<:AbstractFloat Θ = model.Θ α = model.α n,m = size(X) y = zeros(Real,n) X = hcat(X,ones(n,1)) # adding bias for i=1:n y[i] = h(Θ,X[i,:]) end y end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
7604
#### Constants const MODEL_FILENAME = "perceptron_model.jld" # jld filename for storing the model const MODEL_ID = "perceptron_model" # if od the model in the filesystem jld data using Statistics #### An abstract perceptron model abstract type PerceptronModel{T} end #### Linear Perceptron type mutable struct LinearPerceptron{T<:AbstractFloat} <: PerceptronModel{T} α::T Θ::Vector{T} shuffle_epoch::Bool random_state::Integer max_epochs::Integer last_epoch::Integer history::Vector{Integer} mx::Matrix{T} # mean stat after for z-scoring input data (X) sx::Matrix{T} # standard deviation stat after for z-scoring target data (X) centralize::Bool nfeatures::Integer end function LinearPerceptron(X::AbstractArray{T}, alpha, shuffle_epoch, random_state, max_epochs, centralize) where T<:AbstractFloat return LinearPerceptron(alpha, # I will refactor to a constructor. Cleaner Vector{T}(undef,1), shuffle_epoch, random_state, max_epochs, 0, Vector{Integer}(undef,1), mean(X,dims=1), std(X,dims=1), centralize, size(X,2)) end #################################################################################### #### Linear Perceptron type mutable struct VotedPerceptron{T<:AbstractFloat} <: PerceptronModel{T} α::T Θ#::Dict{Integer,Vector{T}} c#::Dict{Integer,Integer} k::Integer shuffle_epoch::Bool random_state::Integer max_epochs::Integer last_epoch::Integer history::Vector{Integer} mx::Matrix{T} # mean stat after for z-scoring input data (X) sx::Matrix{T} # standard deviation stat after for z-scoring target data (X) centralize::Bool nfeatures::Integer end function VotedPerceptron(X::AbstractArray{T}, alpha, shuffle_epoch, random_state, max_epochs, centralize) where T<:AbstractFloat return VotedPerceptron(alpha, # I will refactor to a constructor. Cleaner nothing, nothing, 0, shuffle_epoch, random_state, max_epochs, 0, Vector{Integer}(undef,1), mean(X,dims=1), std(X,dims=1), centralize, size(X,2)) end #################################################################################### #### Kernel Perceptron type mutable struct KernelPerceptron{T<:AbstractFloat} <: PerceptronModel{T} λ::Vector{T} # lagrange vector max_epochs::Integer last_epoch::Integer history::Vector{Integer} mx::Matrix{T} # mean stat after for z-scoring input data (X) sx::Matrix{T} # standard deviation stat after for z-scoring target data (X) centralize::Bool nfeatures::Integer kernel::String width::T sv_x::Vector{T} sv_y::Vector{T} end function KernelPerceptron(X::AbstractArray{T}, max_epochs, centralize, kernel, width) where T<:AbstractFloat return KernelPerceptron(zeros(T,size(X,1)), max_epochs, 0, Vector{Integer}(undef,1), mean(X,dims=1), std(X,dims=1), centralize, size(X,2), kernel, width, Vector{T}(undef,1), Vector{T}(undef,1)) end #################################################################################### #### Averaged Perceptron type mutable struct AveragedPerceptron{T<:AbstractFloat} <: PerceptronModel{T} α::T Θ shuffle_epoch::Bool random_state::Integer max_epochs::Integer last_epoch::Integer history::Vector{Integer} mx::Matrix{T} # mean stat after for z-scoring input data (X) sx::Matrix{T} # standard deviation stat after for z-scoring target data (X) centralize::Bool nfeatures::Integer end function AveragedPerceptron(X::AbstractArray{T}, alpha, shuffle_epoch, random_state, max_epochs, centralize) where T<:AbstractFloat return AveragedPerceptron(alpha, # I will refactor to a constructor. Cleaner 0, shuffle_epoch, random_state, max_epochs, 0, Vector{Integer}(undef,1), mean(X,dims=1), std(X,dims=1), centralize, size(X,2)) end ## choosing types ###################################################################################################### function Model(X,#::AbstractArray{T}, alpha, shuffle_epoch, random_state, max_epochs, centralize, kernel, width, mode) where T<:AbstractFloat println("size",size(X)) if mode == "linear" return LinearPerceptron(X, alpha, shuffle_epoch, random_state, max_epochs, centralize) elseif mode == "kernel" return KernelPerceptron(X, max_epochs, centralize, kernel, width) elseif mode == "voted" return VotedPerceptron(X, alpha, shuffle_epoch, random_state, max_epochs, centralize) elseif mode == "averaged" return AveragedPerceptron(X, alpha, shuffle_epoch, random_state, max_epochs, centralize) else error("Invalid perceptron mode name: $(mode). \n Cadidates are: linear, kernel, voted or averaged") end end ###################################################################################################### ## Load and Store models (good for production) function load(; filename::AbstractString = MODEL_FILENAME, modelname::AbstractString = MODEL_ID) local M jldopen(filename, "r") do file M = read(file, modelname) end M end function save(M::PerceptronModel; filename::AbstractString = MODEL_FILENAME, modelname::AbstractString = MODEL_ID) jldopen(filename, "w") do file write(file, modelname, M) end end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
2401
## Auxiliary functions export acc @inline acc(yt,yp) = count(x->x==true, yt .== yp)/length(yt) # used in linear and voted perceptron @inline sinal(x) = ( x>=0 ? 1.0 : 0.0 ) # used in kernel perceptron @inline sign(val) = ( val >=0 ? 1.0 : -1.0 ) ## checks PLS input data and params function check_data(X::Matrix{T},Y::Union{Vector{T},Matrix{T}}) where T<:AbstractFloat !isempty(X) || throw(DimensionMismatch("Empty input data (X).")) !isempty(Y) || throw(DimensionMismatch("Empty target data (Y).")) size(X, 1) == size(Y, 1) || throw(DimensionMismatch("Incompatible number of rows of input data (X) and target data (Y).")) end function check_data(X::Matrix{T},nfeatures::Int) where T<:AbstractFloat !isempty(X) || throw(DimensionMismatch("Empty input data (X).")) size(X, 2) == nfeatures || throw(DimensionMismatch("Incompatible number of columns of input data (X) and original training X columns.")) end function check_params(kernel::AbstractString,mode::AbstractString) kernel in ["rbf","linear"] || error("kernel must be 'linear' or 'rbf'") mode in ["kernel","linear","voted","averaged"] || error("mode must be 'linear' or 'kernel' or 'voted' or 'averaged'") end ## checks constant columns check_constant_cols(X::Matrix{T}) where {T<:AbstractFloat} = size(X,1)>1 && !any(all(X .== X[1,:]',dims=1)) || error("You must remove constant columns of input data (X) before train") check_constant_cols(Y::Vector{T}) where {T<:AbstractFloat} = length(Y)>1 && length(unique(Y)) > 1 || error("Your target values are constant. All values are equal to $(Y[1])") ## Preprocessing data using z-score statistics. this is due to the fact that if X and Y are z-scored, than X'Y returns for W vector a pearson correlation for each element! :) centralize_data(D::AbstractArray{T}, m::AbstractArray{T}, s::AbstractArray{T}) where {T<:AbstractFloat} = (D .-m)./s centralize_data(D::Vector{T}, m::T, s::T) where {T<:AbstractFloat} = (D -m)/s decentralize_data(D::AbstractArray{T}, m::AbstractArray{T}, s::AbstractArray{T}) where {T<:AbstractFloat} = D .*s .+m decentralize_data(D::Vector{T}, m::T, s::T) where {T<:AbstractFloat} = D *s +m check_linear_binary_labels(Y::Vector{T}) where {T<:Number} = length(setdiff(Y,[0.,1.]))==0 || error("Your target values must be 1 and 0 only. You have $(unique(Y)) distinct labels")
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1975
import Random @inline function vote(Θ,x,c,k) s = 0 for j=1:k s += c[j]*sign(Θ[j]'*x) # voting (+1 or -1 * c[j] weight) end s end function trainer(model::VotedPerceptron{T}, X::AbstractArray{T}, Y::Vector{T}) where T<:AbstractFloat shuffle_epoch = model.shuffle_epoch random_state = model.random_state max_epochs = model.max_epochs if random_state!=-1 Random.seed!(random_state) end n,m = size(X) X = hcat(X,ones(n,1)) # adding bias history = [] nerrors,nlast_errors = Inf,0 epochs = 0 k,Θ,c,α = 1,Dict(1=>Random.rand(m+1)),Dict(1=>0),model.α #while nerrors>0 && epochs < max_epochs while epochs < max_epochs # stops when error is equal to zero or grater than last_error or reached max iterations # shuffle dataset if shuffle_epoch sind = Random.shuffle(1:n) x = X[sind,:] y = Y[sind] end nerrors = 0 # weight updates for all samples for i=1:n xi = x[i,:] ξ = sinal(Θ[k]'*xi) - y[i] if ξ==0 c[k] += 1 else nerrors+=1 c[k+1] = 1 Θ[k+1] = Θ[k] - α * ξ * xi k += 1 end end nlast_errors = nerrors epochs+=1 push!(history,nerrors) end if nerrors > 0 warn("Perceptron: Not converged. Max epochs $(max_epochs) reached. Error history: $(history) \n Try to increase max_epochs or may be you have a non linear problem.") end model.Θ = Θ model.c = c model.k = k model.history = history end function predictor(model::VotedPerceptron{T}, X::AbstractArray{T}) where T<:AbstractFloat Θ = model.Θ α = model.α k = model.k c = model.c n = size(X,1) y = zeros(Real,n) X = hcat(X,ones(n,1)) # adding bias for i=1:n y[i] = sinal(vote(Θ,X[i,:],c,k)) end y end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
2286
using Perceptrons @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "Averaged Perceptron Tests (in sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end end @testset "Averaged Perceptron Tests (out of sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] Xt = X .+ .3 model = Perceptrons.fit(X,Y,centralize=true,mode="averaged",max_epochs=100) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end #@testset "AND function" begin # X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] # Y = [1.0 ; 0.0; 0.0; 0.0] # Xt = X .+ .03 # model = Perceptrons.fit(X,Y,centralize=true,alpha=1.0,mode="averaged",max_epochs=100) # pred = Perceptrons.predict(model,Xt) #end end @testset "Check Labels" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; -1; 0.0; 0.0] try model = Perceptrons.fit(X,Y,mode="averaged",max_epochs=100) catch @test true end end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
2702
using Perceptrons @testset "Kernel Perceptron Tests (in sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "XOR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [0.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="kernel",kernel="rbf",width=.01) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.01) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end end @testset "Kernel Perceptron Tests (out of sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] Xt = X .+ .3 model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] Xt = X .+ .03 model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.1) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end @testset "XOR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [0.0 ; 1.0; 1.0; 0.0] Xt = X .+ .03 model = Perceptrons.fit(X,Y,centralize=true,mode="kernel",kernel="rbf",width=.01) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end end @testset "Check Labels" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; -1; 0.0; 0.0] try model = Perceptrons.fit(X,Y,mode="kernel",kernel="rbf",width=1.0) catch @test true end end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1649
using Perceptrons @testset "Linear Perceptron Tests (in sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end end @testset "Linear Perceptron Tests (out of sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] Xt = X .+ .3 model = Perceptrons.fit(X,Y,centralize=true) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] Xt = X .+ .03 model = Perceptrons.fit(X,Y,centralize=true,alpha=1.0) pred = Perceptrons.predict(model,Xt) end end @testset "Check Labels" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; -1; 0.0; 0.0] try model = Perceptrons.fit(X,Y) catch @test true end end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
204
using Perceptrons using Test include("utils_test.jl") include("linear_perceptron_test.jl") include("kernel_perceptron_test.jl") include("voted_perceptron_test.jl") include("averaged_perceptron_test.jl")
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
1667
using Statistics @testset "Auxiliary Functions Test" begin @testset "check constant columns" begin try Perceptrons.check_constant_cols([1.0 1; 1 2;1 3]) catch @test true end try Perceptrons.check_constant_cols([1.0 1 1][:,:]) catch @test true end try Perceptrons.check_constant_cols([1.0 2 3][:,:]) catch @test true end try Perceptrons.check_constant_cols([1.0; 1; 1][:,:]) catch @test true end @test Perceptrons.check_constant_cols([1.0 1;2 2;3 3]) @test Perceptrons.check_constant_cols([1.0;2;3][:,:]) end @testset "centralize" begin X = [1; 2 ;3.0][:,:] X = Perceptrons.centralize_data(X,mean(X,dims=1),std(X,dims=1)) @test all(X .== [-1,0,1.0]) end @testset "decentralize" begin Xo = [1; 2; 3.0][:,:] Xn = [-1,0,1.0][:,:] Xn = Perceptrons.decentralize_data(Xn,mean(Xo,dims=1),std(Xo,dims=1)) @test all(Xn .== [1; 2; 3.0]) end @testset "checkparams" begin try Perceptrons.check_params("linear") catch @test true end try Perceptrons.check_params("x") catch @test true end end @testset "checkdata" begin try Perceptrons.check_data(zeros(0,0), 0) catch @test true end try Perceptrons.check_data(zeros(1,1), 10) catch @test true end @test Perceptrons.check_data(ones(1,1), 1) end @testset "check binary labels" begin try Perceptrons.check_linear_binary_labels([1,0,2]) catch @test true end try Perceptrons.check_linear_binary_labels([1,-1]) catch @test true end @test Perceptrons.check_linear_binary_labels([1,0]) end end;
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
code
2246
using Perceptrons @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "Voted Perceptron Tests (in sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] model = Perceptrons.fit(X,Y,centralize=false,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) model = Perceptrons.fit(X,Y,centralize=true,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,X) @test all(pred .== Y) end end @testset "Voted Perceptron Tests (out of sample)" begin @testset "OR function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 1.0; 1.0; 0.0] Xt = X .+ .3 model = Perceptrons.fit(X,Y,centralize=true,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,Xt) @test all(pred .== Y) end @testset "AND function" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; 0.0; 0.0; 0.0] Xt = X .+ .03 model = Perceptrons.fit(X,Y,centralize=true,alpha=1.0,mode="voted",max_epochs=100) pred = Perceptrons.predict(model,Xt) end end @testset "Check Labels" begin X = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y = [1.0 ; -1; 0.0; 0.0] try model = Perceptrons.fit(X,Y,mode="voted",max_epochs=100) catch @test true end end
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
1.1.2
b39b905ff0f39236d47a127e0489fe9a699fd9ba
docs
4322
Perceptrons.jl ====== A package with several types of Perceptron classifiers. Perceptrons are fast classifiers and can be used even for big data. Up to now, this package contains a linear perceptron, voted perceptron and a Kernel perceptron for binary classification problems. This project will have the following perceptron classifiers: Multiclass, Kernel, Structured, Voted, Average and Sparse. Some state-of-the-art must be included after these. [![Build Status](https://travis-ci.org/lalvim/Perceptrons.jl.svg?branch=master)](https://travis-ci.org/lalvim/Perceptrons.jl) [![Coverage Status](https://coveralls.io/repos/lalvim/Perceptrons.jl/badge.svg?branch=master&service=github)](https://coveralls.io/github/lalvim/Perceptrons.jl?branch=master) [![codecov.io](http://codecov.io/github/lalvim/Perceptrons.jl/coverage.svg?branch=master)](http://codecov.io/github/lalvim/Perceptrons.jl?branch=master) Install ======= Pkg.add("Perceptrons") Using ===== using Perceptrons Examples ======== using Perceptrons # training a linear perceptron (solving the OR problem) X_train = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y_train = [1; 1; 1; 0.0] X_test = [.8 .9; .01 1; .9 0.2; 0.1 0.2] model = Perceptrons.fit(X_train,Y_train) Y_pred = Perceptrons.predict(model,X_test) println("[Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a voted perceptron (solving the OR problem) model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="voted") Y_pred = Perceptrons.predict(model,X_test) println("[Voted Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a averaged perceptron (solving the OR problem) model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="averaged") Y_pred = Perceptrons.predict(model,X_test) println("[Averaged Perceptron] accuracy : $(acc(Y_train,Y_pred))") # training a kernel perceptron (solving the XOR problem) X_train = [1.0 1.0; 0.0 1.0; 1.0 0.0; 0.0 0.0] Y_train = [0.0 ; 1.0; 1.0; 0.0] X_test = X_train .+ .03 # adding noise model = Perceptrons.fit(X_train,Y_train,centralize=true,mode="kernel",kernel="rbf",width=.01) Y_pred = Perceptrons.predict(model,X_test) println("[Kernel Perceptron] accuracy : $(acc(Y_train,Y_pred))") # if you want to save your model Perceptrons.save(model,filename=joinpath(homedir(),"perceptron_model.jld")) # if you want to load back your model model = Perceptrons.load(filename=joinpath(homedir(),"perceptron_model.jld")) What is Implemented ====== * Voted Perceptron * Averaged Perceptron * Kernel Perceptron * Linear Perceptron What is Upcoming ======= * Multiclass Perceptron * Structured Perceptron * Sparse Perceptron Method Description ======= * Perceptrons.fit - learns from input data and its related single target * X::Matrix{:<AbstractFloat} - A matrix that columns are the features and rows are the samples * Y::Vector{:<AbstractFloat} - A vector with float values. * copydata::Bool = true: If you want to use the same input matrix or a copy. * centralize::Bool = true: If you want to z-score columns. Recommended if not z-scored yet. * mode::AbstractString = "linear": modes are "linear", "kernel", "voted" and "averaged" perceptron. * kernel::AbstractString = "rbf": If you want to apply a nonlinear Perceptron with gaussian Kernel. * width::AbstractFloat = 1.0: Rbf Kernel width (Only if kernel="rbf"). * alpha::Real = 1.0e-2: learning rate. * shuffle_epoch::Bool = true: Shuffle dataset for each epoch. Improves convergency. * random_state::Int = 42: Use a seed to force same results trhough the same dataset. * max_epochs::Int = 5: Maximum epochs. * Perceptrons.predict - predicts using the learnt model extracted from fit. * model::Perceptrons.Model - A Perceptron model learnt from fit. * X::Matrix{:<AbstractFloat} - A matrix that columns are the features and rows are the samples. * copydata::Bool = true - If you want to use the same input matrix or a copy. References ======= TODO License ======= The Perceptrons.jl is free software: you can redistribute it and/or modify it under the terms of the MIT "Expat" License. A copy of this license is provided in ``LICENSE.md``
Perceptrons
https://github.com/lalvim/Perceptrons.jl.git
[ "MIT" ]
0.1.1
6cd44b55d4a3c30540a40f5de15815073974f5ac
code
9426
module PkgBake using PackageCompiler using ProgressMeter using MethodAnalysis #stdlibs using Artifacts, Base64, CRC32c, Dates, DelimitedFiles, Distributed, FileWatching, InteractiveUtils, LazyArtifacts, Libdl, LibGit2, LinearAlgebra, Logging, Markdown, Mmap, Printf, Profile, Random, REPL, Serialization, SHA, SharedArrays, Sockets, SparseArrays, TOML, Test, Unicode, UUIDs, ArgTools, Downloads, NetworkOptions, Pkg, Statistics, Tar const base_stdlibs = [Base, Artifacts, Base64, CRC32c, Dates, DelimitedFiles, Distributed, FileWatching, InteractiveUtils, LazyArtifacts, Libdl, LibGit2, LinearAlgebra, Logging, Markdown, Mmap, Printf, Profile, Random, REPL, Serialization, SHA, SharedArrays, Sockets, SparseArrays, TOML, Test, Unicode, UUIDs, ArgTools, Downloads, NetworkOptions, Pkg, Statistics, Tar] function get_all_modules() mods = Module[] for lib in base_stdlibs visit(lib) do obj if isa(obj, Module) push!(mods, obj) return true # descend into submodules end false # but don't descend into anything else (MethodTables, etc.) end end return vcat(mods, base_stdlibs) end const bakeable_libs = get_all_modules() const __BAKEFILE = "bakefile.jl" global __PRECOMPILE_CURSOR = 0 global __TRACE_PATH = "" # Avoid getting GC'ed function __init__() init_dir() if !have_trace_compile() path, io = mktemp(;cleanup=false) close(io) # we don't need it open global __TRACE_PATH = path force_trace_compile(__TRACE_PATH) end end function init_dir() isempty(DEPOT_PATH) && @error "DEPOT_PATH is empty!" dir = joinpath(DEPOT_PATH[1],"pkgbake") !isdir(dir) && mkdir(dir) return abspath(dir) end function init_project_dir(project::String) project_dict = Pkg.Types.parse_toml(project) if haskey(project_dict, "uuid") uuid = project_dict["uuid"] else uuid = "UNAMED" # TODO, need to resolve for v1.x somehow as they don't have UUIDs end project_dir = joinpath(init_dir(), uuid) !isdir(project_dir) && mkdir(project_dir) end """ bake Add additional precompiled methods to Base and StdLibs that are self contained. """ function bake(;project=dirname(Base.active_project()), yes=false, useproject=false, replace_default=true) pkgbakedir = init_dir() if useproject add_project_runtime_precompiles(project) end precompile_lines = readlines(abspath(joinpath(init_dir(), "bakefile.jl"))) unique!(sort!(precompile_lines)) pc_unsanitized = joinpath(pkgbakedir, "pkgbake_unsanitized.jl") @info "PkgBake: Writing unsanitized precompiles to $pc_unsanitized" open(pc_unsanitized, "w") do io for line in precompile_lines println(io, line) end end original_len = length(precompile_lines) sanitized_lines = sanitize_precompile(precompile_lines) sanitized_len = length(sanitized_lines) pc_sanitized = joinpath(pkgbakedir, "pkgbake_sanitized.jl") @info "PkgBake: Writing sanitized precompiles to $pc_sanitized" open(pc_sanitized, "w") do io for line in sanitized_lines println(io, line) end end @info "PkgBake: Found $sanitized_len new precompilable methods for Base out of $original_len generated statements" !yes && println("Make new sysimg? [y/N]:") if yes || readline() == "y" @info "PkgBake: Generating sysimage" PackageCompiler.create_sysimage(; precompile_statements_file=pc_sanitized, replace_default=replace_default) push_bakefile_back() end nothing end function add_project_runtime_precompiles(project) @info "PkgBake: Observing load-time precompile statements for project: $project" ctx = create_pkg_context(project) deps = values(Pkg.dependencies(create_pkg_context(project))) precompile_lines = String[] progress = Progress(length(deps), 1) bakefile_io() do io println(io, pkgbake_stamp()) for dep in deps next!(progress, showvalues = [(:dep,dep.name), (:statements, length(precompile_lines))]) # skip stdlibs and non-direct deps # TODO: Not sure if direct_dep means what i think it does if in(dep.name, string.(bakeable_libs)) || !dep.is_direct_dep continue end pc_temp = tempname() touch(pc_temp) cmd = `$(get_julia_cmd()) --project=$dir --startup-file=no --trace-compile=$pc_temp -e $("using $(dep.name)")` try run(pipeline(cmd, devnull)) catch err if isa(err, InterruptException) @warn "PkgBake: Interrupted by user" exit() else continue end end for l in eachline(pc_temp,keep=true) write(io, l) end rm(pc_temp) end end end const N_HISTORY = 10 bakefile_n(n) = abspath(joinpath(init_dir(), "bakefile_$(n).jl")) function push_bakefile_back() dir = init_dir() bake = abspath(joinpath(dir, "bakefile.jl")) isfile(bakefile_n(N_HISTORY)) && rm(bakefile_n(N_HISTORY)) # push back the history stack for n in (N_HISTORY-1):1 isfile(bakefile_n(n)) && mv(bakefile_n(n), bakefile_n(n+1),force=true) end mv(bake, bakefile_n(1),force=true) touch(bake) return nothing end """ sanitize_precompile() Prepares and sanitizes a julia file for precompilation. This removes any non-concrete methods and anything non-Base or StdLib. """ function sanitize_precompile(precompile_lines::Vector{String}) lines = String[] for line in precompile_lines # Generally any line with where is non-concrete, so we can skip. # Symbol is also runtime dependent so skip as well if isempty(line) || contains(line, '#') || contains(line, "where") || contains(line, "Symbol(") continue else try if can_precompile(Meta.parse(line)) push!(lines, line) end catch err show(err) end end end lines end """ can_precompile Determine if this expr is something we can precompile. """ function can_precompile(ex::Expr) if ex.head !== :call && ex.args[1] !== :precompile return false else return is_bakeable(ex) end end # TODO: Some Base are marked nospecialize, so we should filter these out also """ recurse through the call and make sure everything is in Base, Core, or a StdLib """ function is_bakeable(ex::Expr) # handle submodule (this might not be robust) if ex.head === :. && is_bakeable(ex.args[1]) return true end for arg in ex.args #@show arg, typeof(arg) if is_bakeable(arg) continue else return false end end return true end function is_bakeable(ex::Symbol) for lib in bakeable_libs if isdefined(lib, ex) return true else continue end end return false end function is_bakeable(ex::QuoteNode) return is_bakeable(ex.value) end function is_bakeable(n::T) where T <: Number return true end function get_julia_cmd() julia_path = joinpath(Sys.BINDIR, Base.julia_exename()) cmd = `$julia_path --color=yes --startup-file=no` end function create_pkg_context(project) project_toml_path = Pkg.Types.projectfile_path(project) if project_toml_path === nothing error("could not find project at $(repr(project))") end return Pkg.Types.Context(env=Pkg.Types.EnvCache(project_toml_path)) end function pkgbake_stamp() "\n\t#version = $(VERSION); date = $(Dates.now())" end function bakefile_io(f) bake = abspath(joinpath(init_dir(), "bakefile.jl")) !isfile(bake) && touch(bake) open(f, bake, "a") end function have_trace_compile() jloptstc = Base.JLOptions().trace_compile jloptstc == C_NULL && return false return true end structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)]; trace_compile_path() = unsafe_string(Base.JLOptions().trace_compile) current_process_sysimage_path() = unsafe_string(Base.JLOptions().image_file) """ force_trace_compile(::String) Force the trace compile to be enabled for the given file. """ function force_trace_compile(path::String) # find trace-compile field offset trace_compile_offset = 0 for i = 1:fieldcount(Base.JLOptions) if fieldname(Base.JLOptions, i) === :trace_compile trace_compile_offset = fieldoffset(Base.JLOptions, i) break end end unsafe_store!(cglobal(:jl_options, Ptr{UInt8})+trace_compile_offset, pointer(path)) end """ atexit hook for caching precompile files add to .julia/config/startup.jl ``` using PkgBake atexit(PkgBake.atexit_hook) ``` """ function atexit_hook() !have_trace_compile() && return trace_path = trace_compile_path() isempty(trace_path) && return trace_file = open(trace_path, "r") bakefile_io() do io println(io, pkgbake_stamp()) for l in eachline(trace_file, keep=true) write(io, l) end end close(trace_file) end end
PkgBake
https://github.com/sjkelly/PkgBake.jl.git
[ "MIT" ]
0.1.1
6cd44b55d4a3c30540a40f5de15815073974f5ac
code
110
using PkgBake using Test @testset "options probe" begin @test PkgBake.have_trace_compile() == true end
PkgBake
https://github.com/sjkelly/PkgBake.jl.git
[ "MIT" ]
0.1.1
6cd44b55d4a3c30540a40f5de15815073974f5ac
docs
5371
# PkgBake.jl PkgBake is designed to enable safe and easy speedups of Julia code loading for Package Developers. It consists of two elements: - A precompile caching system - A method sanitiser ## Using Inside your `.julia/config/startup.jl` add the following: ```julia import PkgBake atexit(PkgBake.atexit_hook) ``` PkgBake will enable the `--trace-compile` equivalent automatically for you, and cache the files into `.julia/pkgbake/`. If you call julia with `--trace-compile`, PkgBake will copy the files at exit. To "bake" in the new precompiled statements that are exclusive to Base and Stdlibs, run: ```julia julia> PkgBake.bake() ``` With this, you should notice anywhere from a 5-15% performance improvment, as Base and Stdlib method have been added to the sysimg. Of course, this still allows you to change projects and such. ## Design and Use When the Julia sysimage is created, it knows nothing of downstream package use. PkgBake is a mechanism to provide specific `precompile` statements only for Base and Stdlibs to save time and stay out of your way. Since the methods added are only in and for Base and the Stdlibs, this should have little to no effect on development environments. This is accomplished by "sanitizing" the precompile statements such that only additional methods targeting Base and the Stdlib are added to the sysimg. This is mostly a managment layer over Pkg, PackageCompiler, and MethodAnalysis. There is some possibility to turning `PkgBake` into a general `precompile` database. Right now, this is just fun hacks with some marginal profit :) ## Design Possibilities ### 1 - Local Cache The precompile and loading is done locally. ### 2 - Ecosystem Cache We pregenerate a Base-only precompile file for each julia version. The user will then just need to pull this file and run. This will work for every published package. ### 3 - Upstream Target This can be similar to a Linux distro popcon. PkgBake users upload their sanitized precompile files and the most common precompiled methods get PRed to base. ### 4 - PkgEval Integration This is similar to 3, except it is run as part of PkgEval on a new release. This might require PkgEval to run twice. ### Future Base only methods do not provide a significant speedup, only 2-5% from what has been observed so far. A possible way forward is to actually manage the trace-compiles _and_ environments. e.g. `__init__`s take a good deal of time and can be managed by the project tree. When extracting the trace compiles we organize by project and manage sysimgs. ### Results (so far) ``` ^[[Asteve@sjkdsk1:~$ juliarc (c, typeof(c)) = (Dict{String,Any}(), Dict{String,Any}) _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.5.0-beta1.0 (2020-05-28) _/ |\__'_|_|_|\__'_| | |__/ | julia> @time using Plots 5.647230 seconds (7.96 M allocations: 496.850 MiB, 1.25% gc time) julia> @time scatter!(rand(50)) 5.901242 seconds (10.30 M allocations: 534.544 MiB, 4.81% gc time) julia> ^C julia> steve@sjkdsk1:~$ juliarc --trace-compile=`mktemp` (c, typeof(c)) = (Dict{String,Any}(), Dict{String,Any}) _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.5.0-beta1.0 (2020-05-28) _/ |\__'_|_|_|\__'_| | |__/ | julia> @time using Plots 5.627413 seconds (7.96 M allocations: 496.846 MiB, 1.24% gc time) julia> @time scatter!(rand(50)) 6.068422 seconds (10.29 M allocations: 534.059 MiB, 3.97% gc time) julia> ^C julia> steve@sjkdsk1:~$ juliarc (c, typeof(c)) = (Dict{String,Any}(), Dict{String,Any}) _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.5.0-beta1.0 (2020-05-28) _/ |\__'_|_|_|\__'_| | |__/ | julia> PkgBake.bake() [ Info: PkgBake: Writing unsanitized precompiles to /home/steve/.julia/pkgbake/pkgbake_unsanitized.jl [ Info: PkgBake: Writing sanitized precompiles to /home/steve/.julia/pkgbake/pkgbake_sanitized.jl [ Info: PkgBake: Found 156 new precompilable methods for Base out of 577 generated statements [ Info: PkgBake: Generating sysimage [ Info: PackageCompiler: creating system image object file, this might take a while... [ Info: PackageCompiler: default sysimg replaced, restart Julia for the new sysimg to be in effect julia> ^C julia> steve@sjkdsk1:~$ juliarc (c, typeof(c)) = (Dict{String,Any}(), Dict{String,Any}) _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.5.0-beta1.0 (2020-05-28) _/ |\__'_|_|_|\__'_| | |__/ | julia> @time using Plots 5.466470 seconds (7.61 M allocations: 479.033 MiB, 1.98% gc time) julia> @time scatter!(rand(50)) 5.376421 seconds (9.41 M allocations: 488.071 MiB, 2.19% gc time) ```
PkgBake
https://github.com/sjkelly/PkgBake.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
304
push!(LOAD_PATH, "../src/") using Bactos using Documenter makedocs( sitename = "Bactos.jl", modules = [Bactos], pages = [ "Home" => "index.md", "Tutorial" => "tutorial.md", "Validation" => "checks.md" ] ) deploydocs(; repo = "github.com/mastrof/Bactos.jl" )
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1284
using Bactos using Distributions using Plots θs = [π/6, π/4, π/3, π/2, π] α = cos.(θs) U = 30.0 # μm/s τ = 1.0 # s ω = 1 / τ nmicrobes = 100 microbes = [ [ Microbe{3}( id = n, turn_rate = ω, motility = RunTumble(speed=[U], polar=[θ,-θ]) ) for n in 1:nmicrobes ] for θ in θs ] dt = 0.05 # s L = 500.0 # μm models = [ initialise_model(; microbes = microbes[i], timestep = dt, extent = L ) for i in eachindex(microbes) ] nsteps = round(Int, 100τ_run / dt) adata = [:pos] adfs = [run!(model, microbe_step!, nsteps; adata)[1] for model in models] MSD = hcat(msd.(adfs; L=L)...) begin t = (1:nsteps).*dt T = @. τ / (1-α') s = t ./ T D = @. U^2*T/3 MSD_theoretical = @. 6D*T * (s - 1 + exp(-s)) logslice = round.(Int, exp10.(range(0,3,length=10))) plot( xlab = "Δt / τ", ylab = "MSD / (Uτ)²", legend = :bottomright, legendtitle = "1-α", scale = :log10, yticks = exp10.(-2:2:2), xticks = exp10.(-2:2) ) scatter!(t[logslice,:]./τ, MSD[logslice,:]./(U*τ)^2, m=:x, ms=6, msw=2, lab=false, lc=axes(α,1)' ) plot!(t./τ, MSD_theoretical./(U*τ)^2, lw=2, lab=round.(1 .- α,digits=2)', lc=axes(α,1)' ) end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1703
using Bactos using Plots U = 30.0 # μm/s τ_run = 1.0 # s ω = 1 / τ_run # 1/s Δt = 0.01 # s extent = 1e4 # μm n = 200 microbes_runtumble = [ Microbe{3}(id=i, turn_rate=ω, motility=RunTumble(speed=[U]) ) for i in 1:n ] microbes_runrev = [ Microbe{3}(id=n+i, turn_rate=ω, motility=RunReverse(speed_forward=[U]) ) for i in 1:n ] microbes_runrevflick = [ Microbe{3}(id=2n+i, turn_rate=ω, motility=RunReverseFlick(speed_forward=[U]) ) for i in 1:n ] microbes = vcat( microbes_runtumble, microbes_runrev, microbes_runrevflick ) model = initialise_model(; microbes, extent, periodic = true, timestep = Δt ) nsteps = round(Int, 100τ_run / Δt) adata = [:vel] adf, = run!(model, microbe_step!, nsteps; adata) adf_runtumble = filter(:id => id -> model.agents[id].motility isa RunTumble, adf; view=true) adf_runrev = filter(:id => id -> model.agents[id].motility isa RunReverse, adf; view=true) adf_runrevflick = filter(:id => id -> model.agents[id].motility isa RunReverseFlick, adf; view=true) adfs = [adf_runtumble, adf_runrev, adf_runrevflick] Φ = hcat([autocorrelation(a,:vel) for a in adfs]...) t = range(0, (nsteps-1)*Δt; step=Δt) Φ_theoretical = hcat([ exp.(-t ./ τ_run), exp.(-t ./ (τ_run / 2)), (1 .- t ./ (2τ_run)) .* exp.(-t ./ τ_run), ]...) # Taktikos et al. 2013 PLoS ONE plot( xlims=(0,6τ_run), ylims=(-0.1, 1.05), xlab="Δt / τ", ylab="velocity autocorrelation", ) plot!(t, Φ_theoretical, lw=2, lc=[1 2 3], label=["Run-Tumble" "Run-Reverse" "Run-Reverse-Flick"]) scatter!(t[1:15:end], Φ[1:15:end,:] ./ U^2, m=:x, mc=[1 2 3], label=false) hline!([0.0], lw=0.8, ls=:dash, lc=:black, lab=false)
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1467
using Bactos using Plots conc_field(x,y,C,σ,x₀,y₀) = C * exp(-((x-x₀)^2+(y-y₀)^2)/(2σ^2)) function conc_grad(x,y,C,σ,x₀,y₀) cfield = conc_field(x,y,C,σ,x₀,y₀) σ² = σ*σ return [ -(x-x₀)/σ² * cfield, -(y-y₀)/σ² * cfield ] end # function nmicrobes = 10 microbes = [Brumley{2}(id=i) for i in 1:nmicrobes] dt = 0.1 # s L = 500.0 # μm # field properties C = 0.1 # μM σ = 20.0 # μm x₀ = y₀ = L/2 # μm concentration_field(pos) = conc_field(pos[1], pos[2], C, σ, x₀, y₀) concentration_gradient(pos) = conc_grad(pos[1], pos[2], C, σ, x₀, y₀) model_properties = Dict( :concentration_field => (pos,_) -> concentration_field(pos), :concentration_gradient => (pos,_) -> concentration_gradient(pos), :concentration_time_derivative => (_,_) -> 0.0, :compound_diffusivity => 500.0, # μm²/s ) model = initialise_model(; microbes = microbes, timestep = dt, extent = L, periodic = false, model_properties = model_properties ) my_microbe_step!(microbe, model) = microbe_step!( microbe, model; affect! = brumley_affect!, turnrate = brumley_turnrate ) adata = [:pos] nsteps = 1000 adf, = run!(model, my_microbe_step!, nsteps; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' contourf( 0:L/50:L, 0:L/50:L, (x,y) -> concentration_field((x,y)), color=:bone, ratio=1 ) plot!( x, y, lw=0.5, colorbar=false, legend=false, xlims=(0,L), ylims=(0,L) )
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1884
using Bactos using Plots #== CONCENTRATION FIELD ==# conc_field(x,y,C₀,∇C) = C₀ + ∇C*x function conc_grad(x,y,C₀,∇C) return [∇C, 0.0] end # function #== DOMAIN PARAMETERS ==# Lx, Ly = 1000.0, 500.0 # μm extent = (Lx, Ly) # μm periodic = false #== MICROBE POPULATION ==# n = 50 microbes_brumley = [ Brumley{2}(id=i, pos=(0,rand()*Ly), chemotactic_precision=1) for i in 1:n ] microbes_brown = [ BrownBerg{2}(id=n+i, pos=(0,rand()*Ly)) for i in 1:n ] microbes = [microbes_brumley; microbes_brown] #== FIELD PARAMETERS ==# C₀ = 0.0 # μM ∇C = 0.01 # μM/μm concentration_field(pos) = conc_field(pos..., C₀, ∇C) concentration_gradient(pos) = conc_grad(pos..., C₀, ∇C) #== MODEL SETUP ==# timestep = 0.1 # s model_properties = Dict( :concentration_field => (pos,_) -> concentration_field(pos), :concentration_gradient => (pos,_) -> concentration_gradient(pos), :concentration_time_derivative => (_,_) -> 0.0, :compound_diffusivity => 500.0, # μm²/s ) model = initialise_model(; microbes, timestep, extent, periodic, model_properties, random_positions = false ) #== RUN! ==# adata = [:pos] nsteps = 1000 adf, = run!(model, microbe_step!, nsteps; adata) #== POST PROCESSING ==# traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' #== PLOTTING ==# lc = [typeof(m) <: Brumley ? 1 : 2 for m in microbes] |> permutedims for t in axes(x,1)[1:4:end] contourf( 0:Lx/50:Lx, 0:Ly/50:Ly, (x,y) -> concentration_field((x,y)), color=:bone, ratio=1, xlims=(0,Lx), ylims=(0,Ly), xlab="x (μm)", ylab="y (μm)", colorbar_title="C (μM)", levels=100, ) t₀ = max(1, t-20) xt = @view x[t₀:t,:] yt = @view y[t₀:t,:] plot!( xt, yt, lw=0.5, lc=lc, legend=false, ) it = lpad(t, 4, '0') savefig("frame_$it.png") end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2455
using Bactos using Plots θ(a,b) = a>b ? 1.0 : 0.0 function concentration_field(pos, model) C₀ = model.C₀ C₁ = model.C₁ t₁ = model.t₁ t₂ = model.t₂ dt = model.timestep t = model.t * dt concentration_field(t, C₀, C₁, t₁, t₂) end concentration_field(t,C₀,C₁,t₁,t₂) = C₀+C₁*θ(t,t₁)*(1-θ(t,t₂)) concentration_gradient(pos, model) = zero.(pos) # not used by Xie concentration_time_derivative(pos, model) = 0.0 # not used by Xie motility_fw = RunReverseFlick(motile_state = MotileState(Forward)) motility_bw = RunReverseFlick(motile_state = MotileState(Backward)) microbes = [ XieNoisy{3}(id=1, turn_rate_forward=0, motility=motility_fw), XieNoisy{3}(id=2, turn_rate_backward=0, motility=motility_bw) ] timestep = 0.1 # s extent = 500.0 # μm C₀ = 0.01 # μM C₁ = 5.0-C₀ # μM T = 60.0 # s t₁ = 20.0 # s t₂ = 40.0 # s nsteps = round(Int, T/timestep) model_properties = Dict( :compound_diffusivity => 608.0, # μm²/s :concentration_field => concentration_field, :concentration_gradient => concentration_gradient, :concentration_time_derivative => concentration_time_derivative, :C₀ => C₀, :C₁ => C₁, :t₁ => t₁, :t₂ => t₂, ) model = initialise_model(; microbes, timestep, extent, model_properties ) β(a) = a.motility.state == Forward ? a.gain_forward : a.gain_backward state(a::AbstractXie) = max(1 + β(a)*a.state, 0) adata = [state, :state_m, :state_z] adf, = run!(model, microbe_step!, model_step!, nsteps; adata) S = vectorize_adf_measurement(adf, :state)' m = (vectorize_adf_measurement(adf, :state_m)')[:,1] # take only fw z = (vectorize_adf_measurement(adf, :state_z)')[:,1] # take only fw # response vs time for fw and bw modes begin _green = palette(:default)[3] plot() x = (0:timestep:T) .- t₁ plot!( x, S, lw=1.5, lab=["Forward" "Backward"] ) plot!(ylims=(-0.1,4.5), ylab="Response", xlab="time (s)") plot!(twinx(), x, t -> concentration_field(t.+t₁,C₀,C₁,t₁,t₂), ls=:dash, lw=1.5, lc=_green, lab=false, tickfontcolor=_green, ylab="C (μM)", guidefontcolor=_green ) end # methylation and dephosphorylation begin x = (0:timestep:T) .- t₁ τ_m = microbes[1].adaptation_time_m τ_z = microbes[1].adaptation_time_z M = m ./ τ_m Z = z ./ τ_z R = M .- Z plot( x, [M Z R], lw=2, lab=["m/τ_m" "z/τ_z" "m/τ_m - z/τ_z"], xlab="time (s)" ) end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2634
using Bactos using DelimitedFiles using StaticArrays using LinearAlgebra using Plots # overlap between spheres isoverlapping(p1, p2, r1, r2) = (norm(p1 .- p2) ≤ r1+r2) isoverlapping(a, b) = isoverlapping(a.pos, b.pos, a.radius, b.radius) # draw a circle function circleShape(x₀,y₀,r,n=500) θ = LinRange(0, 2π, n) x₀ .+ r.*sin.(θ), y₀ .+ r.*cos.(θ) end # function # Physical parameters timestep = 0.1 # s extent = (1000.0, 500.0) # μm periodic = false microbe_radius = 0.5 # μm ω = 1.0 # 1/s U = 30.0 # μm/s motility = RunTumble(speed = Degenerate(U)) Drot = 0.1 # rad²/s n_microbes = 6 # Initialise obstacles (read configuration from file) obstacle_data = readdlm("phi04_rmin10_Lx1000_Ly500.dat") bodyrad = obstacle_data[:,1] # μm max_radius = maximum(bodyrad) bodypos = [Tuple(obstacle_data[i,2:3]) for i in axes(obstacle_data,1)] # μm bodies = [ ObstacleSphere(pos, r, glide!) for (r,pos) in zip(bodyrad,bodypos) ] # Initialise microbes microbes = [ Microbe{2}( id=i, pos=Tuple(rand(2).*extent), vel=rand_vel(2).*U, turn_rate=1.0, radius=0.5, motility=RunTumble(speed=Degenerate(U)), rotational_diffusivity=Drot ) for i in 1:n_microbes ] # Update microbe positions to avoid overlap with obstacles for m in microbes while any(map(b -> isoverlapping(m,b), bodies)) m.pos = Tuple(rand(2) .* extent) end # while end # for # Initialise neighbor list cutoff_radius = 2 * (max_radius + microbe_radius + U*timestep) neighborlist = init_neighborlist(microbes, bodies, extent, cutoff_radius, periodic) model_properties = Dict( :t => 0, :bodies => bodies, :neighborlist => neighborlist, :cfield_params => (C₀, C₁), :concentration_field => concentration_field, :concentration_gradient => concentration_gradient ) model = initialise_model(; microbes, timestep, extent, periodic, model_properties, random_positions = false ) function update_model!(model) model.t += 1 if model.t % 10 == 0 update_neighborlist!(model) end surface_interaction!(model) end # function my_model_step!(model) = model_step!(model; update_model!) adata = [:pos] adf, = run!(model, microbe_step!, my_model_step!, 2000; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' plot( xlims=(0,extent[1]), ylims=(0,extent[2]), palette=:Dark2, legend=false, bgcolor=:black, grid=false, axis=false, ratio=1) for body in bodies plot!( circleShape(body.pos..., body.radius), seriestype=:shape, lw=0, lab=false, c=:white, fillalpha=0.25, ) end # for plot!(x,y)
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2937
using Bactos using DelimitedFiles using StaticArrays using LinearAlgebra using Plots # overlap between spheres isoverlapping(p1, p2, r1, r2) = (norm(p1 .- p2) ≤ r1+r2) isoverlapping(a, b) = isoverlapping(a.pos, b.pos, a.radius, b.radius) # draw a circle function circleShape(x₀,y₀,r,n=100) θ = LinRange(0, 2π, n) x₀ .+ r.*sin.(θ), y₀ .+ r.*cos.(θ) end # function # Physical parameters timestep = 0.1 # s extent = (1000.0, 500.0) # μm periodic = false n_microbes = 6 # Initialise obstacles (read configuration from file) obstacle_data = readdlm("phi04_rmin10_Lx1000_Ly500.dat") bodyrad = obstacle_data[:,1] # μm max_radius = maximum(bodyrad) bodypos = [Tuple(obstacle_data[i,2:3]) for i in axes(obstacle_data,1)] # μm bodies = [ ObstacleSphere(pos, r, glide!) for (r,pos) in zip(bodyrad,bodypos) ] # Initialise microbes at x=0 microbes = [Brumley{2}( id=i, pos=(0,rand()*extent[2])) for i in 1:n_microbes ] # Update microbe positions to avoid overlap with obstacles for m in microbes while any(map(b -> isoverlapping(m,b), bodies)) m.pos = (0, rand()*extent[2]) end # while end # for # Initialise neighbor list cutoff_radius = 3 * max_radius neighborlist = init_neighborlist(microbes, bodies, extent, cutoff_radius, periodic) # Setup concentration field C₀=0.0 C₁=10.0 concentration_field(x,y,C₀,C₁,Lx) = C₀+(C₁-C₀)/Lx*x function concentration_field(pos, model) C₀, C₁ = model.cfield_params Lx = model.space.extent[1] x, y = pos concentration_field(x,y,C₀,C₁,Lx) end function concentration_gradient(pos,model) C₀, C₁ = model.cfield_params Lx = model.space.extent[1] return ((C₁-C₀)/Lx, 0.0) end model_properties = Dict( :bodies => bodies, :neighborlist => neighborlist, :cfield_params => (C₀, C₁), :concentration_field => concentration_field, :concentration_gradient => concentration_gradient ) model = initialise_model(; microbes, timestep, extent, periodic, model_properties, random_positions = false ) function update_model!(model) update_neighborlist!(model) surface_interaction!(model) end # function my_model_step!(model) = model_step!(model; update_model!) adata = [:pos] adf, = run!(model, microbe_step!, my_model_step!, 2000; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' plot( xlims=(0,extent[1]), ylims=(0,extent[2]), palette=:Dark2, legend=false, bgcolor=:black, grid=false, axis=false, colorbar=:bottom, colorbartitle="C (μM)", ratio=1) contourf!( 0:extent[1], 0:extent[2], (x,y) -> concentration_field(x,y,C₀,C₁,extent[1]), color=:cividis, levels=100 ) for body in bodies plot!( circleShape(body.pos..., body.radius), seriestype=:shape, lw=0, lab=false, c=:black, fillalpha=0.5, ) end # for plot!(x,y, lc=(1:n_microbes)', lw=1.5) scatter!(x[end:end,:], y[end:end,:], mc=(1:n_microbes)', ms=8, msc=:black)
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
3047
using Bactos using Agents: get_spatial_index using OrdinaryDiffEq: get_du! using Plots default( thickness_scaling = 1.5, guidefontsize = 12, tickfontsize = 12, legendfontsize = 8, grid = false, framestyle = :box, minorticks = true, tick_direction = :in, color_palette = :Dark2, margin = 3.0Plots.mm ) nmicrobes = 20 microbes = [BrownBerg{1}(id=i) for i in 1:nmicrobes] extent = 1000.0 spacing = 0.5 xs = range(-2*spacing, extent+2*spacing; step=spacing) timestep = 0.1 x₀ = extent/2 C = 10.0 σ = 10.0 D = 10.0 β = 0.004 u₀ = @. C * exp(-(xs-x₀)^2 / (2*σ^2)) ∇u = zero(u₀) # to be used as storage in model ∂ₜu = zero(u₀) # to be used as storage in model finitediff!(∇u, u₀, 1/spacing) function odestep!(du, u, p, t) β, D, _dx, = p a = D * _dx * _dx # diffusion laplacian!(du, u, a) # decay @. du -= β*u # absorbing walls du[1] = du[2] = du[end] = du[end-1] = 0.0 end # function nsteps = round(Int, 500 / timestep) ode_integrator = initialise_ode(odestep!, u₀, (β, D, 1/spacing); dtmax = spacing^2/2D, saveat = (0:nsteps) .* timestep) function concentration_field(pos,model) pos_idx = get_spatial_index(pos, model.xmesh, model) return model.integrator.u[pos_idx] end # function function concentration_gradient(pos, model) pos_idx = get_spatial_index(pos, model.xmesh, model) return model.∇u[pos_idx] end # function function concentration_time_derivative(pos, model) pos_idx = get_spatial_index(pos, model.xmesh, model) return model.∂ₜu[pos_idx] end # function model_properties = Dict( :xmesh => xs, :∇u => ∇u, :∂ₜu => ∂ₜu, :concentration_field => concentration_field, :concentration_gradient => concentration_gradient, :concentration_time_derivative => concentration_time_derivative ) model = initialise_model(; microbes, timestep, extent, spacing, periodic = false, ode_integrator, model_properties ) @info "initialised model" adata = [:pos, :state] u_field(model) = copy(model.integrator.u) mdata = [u_field] when = range(0, nsteps; step=round(Int, 5/timestep)) when_model = range(0, nsteps; step=round(Int, 30/timestep)) function update_model!(model) # update gradient finitediff!(model.∇u, model.integrator.u, 1/model.space.spacing) # update time derivative get_du!(model.∂ₜu, model.integrator) end # function my_model_step!(model) = model_step!(model; update_model!) adf, mdf = run!( model, microbe_step!, my_model_step!, nsteps; adata, mdata, when, when_model ) @info "simulation complete" linecolors = palette(:plasma, size(mdf,1)) p1 = plot(color_palette = linecolors) for row in eachrow(mdf) plot!(p1, xs[3:end-2], row[:u_field][3:end-2], lw=2, lab=false) end # for traj = vectorize_adf_measurement(adf, :pos) p2 = plot( first.(traj)', when.*timestep, lab=false, lw=0.5, line_z=when, color=:plasma, colorbar=false ) plot(p1,p2,xticks=[0,extent/2,extent])
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1568
using Bactos using Plots default( thickness_scaling = 1.5, guidefontsize = 12, tickfontsize = 12, legendfontsize = 8, grid = false, framestyle = :box, minorticks = true, tick_direction = :in, color_palette = :Dark2, margin = 3.0Plots.mm ) concentration_field(x,C,σ,x₀) = C * exp(-(x-x₀)^2/(2*σ^2)) concentration_gradient(x,C,σ,x₀) = -(x-x₀)/σ^2 * concentration_field(x,C,σ,x₀) nmicrobes = 10 microbes = [Microbe{1}(id=i) for i in 1:nmicrobes] extent = 100.0 spacing = 0.2 xs = range(-2*spacing, extent+2*spacing; step=spacing) timestep = 0.1 x₀ = extent/2 C = 5.0 σ = 3.0 concentration_field(x) = concentration_field(x,C,σ,x₀) concentration_gradient(x) = concentration_gradient(x,C,σ,x₀) u₀ = concentration_field.(xs) function odestep!(du, u, p, t) D, _dx, = p a = D * _dx * _dx laplacian!(du, u, a) # absorbing walls du[1] = du[2] = du[end] = du[end-1] = 0.0 end # function ode_integrator = initialise_ode(odestep!, u₀, (1.0, 1/spacing); dtmax = spacing^2/2) model = initialise_model(; microbes, timestep, extent, spacing, ode_integrator ) u_field(model) = copy(model.integrator.u) mdata = [u_field] nsteps = round(Int, 600 / timestep) when_model = range(0, nsteps; step=round(Int, 30/timestep)) _, mdf = run!(model, microbe_step!, model_step!, nsteps; mdata, when_model) linecolors = palette(:plasma, size(mdf,1)) plot(color_palette = linecolors) for row in eachrow(mdf) plot!(xs[3:end-2], row[:u_field][3:end-2], lw=2, lab=false) end # for plot!()
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2630
using Bactos using DelimitedFiles using LinearAlgebra using Plots # overlap between spheres isoverlapping(p1, p2, r1, r2) = (norm(p1 .- p2) ≤ r1+r2) isoverlapping(a, b) = isoverlapping(a.pos, b.pos, a.radius, b.radius) # draw a circle function circleShape(x₀,y₀,r,n=50) θ = LinRange(0, 2π, n) x₀ .+ r.*sin.(θ), y₀ .+ r.*cos.(θ) end # function # Physical parameters timestep = 0.1 # s extent = (1000.0, 500.0) # μm periodic = false n_microbes = 6 # Initialise obstacles (read configuration from file) obstacle_data = readdlm("phi065_rmin5_Lx1000_Ly500.dat") bodyrad = obstacle_data[:,1] # μm max_radius = maximum(bodyrad) bodypos = [Tuple(obstacle_data[i,2:3]) for i in axes(obstacle_data,1)] # μm bodies = [ ObstacleSphere(pos, r) for (r,pos) in zip(bodyrad,bodypos) ] pathfinder = initialise_pathfinder(extent, periodic, 0.5, bodies) # Initialise microbes at x=0 microbes = [Celani{2}( id=i, pos=(0,rand()*extent[2])) for i in 1:n_microbes ] # Update microbe positions to avoid overlap with obstacles for m in microbes while any(map(b -> isoverlapping(m,b), bodies)) m.pos = (0, rand()*extent[2]) end # while end # for # Setup concentration field C₀=0.0 C₁=10.0 concentration_field(x,y,C₀,C₁,Lx) = C₀+(C₁-C₀)/Lx*x function concentration_field(pos, model) C₀, C₁ = model.cfield_params Lx = model.space.extent[1] x, y = pos concentration_field(x,y,C₀,C₁,Lx) end function concentration_gradient(pos,model) C₀, C₁ = model.cfield_params Lx = model.space.extent[1] return ((C₁-C₀)/Lx, 0.0) end model_properties = Dict( :cfield_params => (C₀, C₁), :concentration_field => concentration_field, :concentration_gradient => concentration_gradient, :pathfinder => pathfinder ) model = initialise_model(; microbes, timestep, extent, periodic, model_properties, random_positions = false ) adata = [:pos] @time adf, = run!(model, microbe_step!, model_step!, 8000; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' plot( xlims=(0,extent[1]), ylims=(0,extent[2]), palette=:Dark2, legend=false, bgcolor=:black, grid=false, axis=false, colorbar=:bottom, colorbartitle="C (μM)", ratio=1) contourf!( 0:extent[1], 0:extent[2], (x,y) -> concentration_field(x,y,C₀,C₁,extent[1]), color=:cividis, levels=100 ) for body in bodies plot!( circleShape(body.pos..., body.radius), seriestype=:shape, lw=0, lab=false, c=:black, fillalpha=0.5, ) end # for plot!(x,y, lc=(1:n_microbes)') scatter!(x[end:end,:], y[end:end,:], mc=(1:n_microbes)', ms=8, msc=:black)
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1151
using Bactos using Plots L = 800.0 τ_run = 1.0 ω = 1 / τ_run U = 30.0 D_rot = 0.02 n = 1 m_rt = [ Microbe{2}( id=i, vel=rand_vel(2).*U, turn_rate=ω, motility=RunTumble(speed=Degenerate(U)), rotational_diffusivity=D_rot ) for i in 1:n ] m_rr = [ Microbe{2}( id=n+i, vel=rand_vel(2).*U, turn_rate=ω, motility=RunReverse(speed=Degenerate(U)), rotational_diffusivity=D_rot ) for i in 1:n ] m_rrf = [ Microbe{2}( id=2n+i, vel=rand_vel(2).*U, turn_rate=ω, motility=RunReverseFlick(speed=Degenerate(U)), rotational_diffusivity=D_rot ) for i in 1:n ] microbes = vcat(m_rt, m_rr, m_rrf) Δt = τ_run / 10 model = initialise_model(; microbes = microbes, timestep = Δt, extent = L, periodic = false, ) nsteps = 500 adata = [:pos] adf, = run!(model, microbe_step!, nsteps; adata) trajectories = vectorize_adf_measurement(adf, :pos) x = first.(trajectories) y = last.(trajectories) plot(x', y', lw=0.5, ticks=false, lims=(0,L), lab=["Run-Tumble" "Run-Reverse" "Run-Reverse-Flick"], legend_foreground_color=:white, legendfontsize=5 )
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
732
using Bactos using Plots default( thickness_scaling = 1.5, guidefontsize = 12, tickfontsize = 12, legendfontsize = 8, grid = false, framestyle = :box, minorticks = true, tick_direction = :in, color_palette = :Dark2, margin = 3.0Plots.mm ) dt = 0.1 L = 1e6 nmicrobes = 8 microbes = [Microbe{1}(id=i, pos=(L/2,)) for i in 1:nmicrobes] model = initialise_model(; microbes = microbes, timestep = dt, extent = L, periodic = false, ) nsteps = 1000 adata = [:pos] adf, = run!(model, microbe_step!, nsteps; adata) x = first.(vectorize_adf_measurement(adf, :pos))' x₀ = x[1:1,:] Δx = x .- x₀ plot( (0:nsteps).*dt, Δx, legend = false, xlab = "time", ylab = "position" )
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
590
using Bactos using Plots L = 50.0 τ_run = 1.0 ω = 1 / τ_run nmicrobes = 6 microbes = [ Microbe{2}( id=i, vel=rand_vel(2), turn_rate=ω, motility=RunTumble() ) for i in 1:nmicrobes ] model = initialise_model(; microbes = microbes, timestep = 1.0, extent = L, periodic = false, random_positions = true, ) nsteps = 200 adata = [:pos] adf, = run!(model, microbe_step!, nsteps; adata) trajectories = vectorize_adf_measurement(adf, :pos) x = first.(trajectories) y = last.(trajectories) plot(x', y', lw=0.5, lab=false, ticks=false, lims=(0,L) )
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
883
module Bactos using Agents, Agents.Pathfinding using CellListMap.PeriodicSystems using Distributions using LinearAlgebra using StaticArrays using Random using Rotations using OrdinaryDiffEq: ODEProblem, DEIntegrator, init, Tsit5, step! using FiniteDifferences: central_fdm # Core structures include("distributions.jl") include("motility.jl") include("microbes.jl") # Utility routines include("utils.jl") # ABM setup include("model.jl") # Bodies & neighbor lists include("obstacles_spheres.jl") include("celllistmap.jl") # Stepping export run! # from Agents include("rotations.jl") include("step_microbes.jl") include("step_model.jl") include("finite_differences.jl") # Chemotaxis models include("brown-berg.jl") include("brumley.jl") include("celani.jl") include("xie.jl") # Measurements include("drift.jl") include("msd.jl") include("correlation_functions.jl") end # module
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1980
export BrownBerg, brownberg_affect!, brownberg_turnrate, microbe_step! """ BrownBerg{D} <: AbstractMicrobe{D} Model of chemotactic E.coli from 'Brown and Berg (1974) PNAS'. Default parameters: - motility = RunTumble(speed = Degenerate(30.0)) - turn_rate = 1.49 Hz - state = 0.0 → corresponds to "weighted dPb/dt" in the paper - rotational_diffusivity = 0.035 rad²/s - motor_gain = 660 s - receptor_binding_constant = 100 μM - adaptation_time = 1 s - radius = 0 μm """ Base.@kwdef mutable struct BrownBerg{D} <: AbstractMicrobe{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunTumble(speed = Degenerate(30.0)) vel::NTuple{D,Float64} = rand_vel(D, motility) # μm/s turn_rate::Float64 = 1/0.67 # 1/s state::Float64 = 0.0 # 1 rotational_diffusivity = 0.035 # rad²/s motor_gain::Float64 = 660.0 # s receptor_binding_constant::Float64 = 100.0 # μM adaptation_time::Float64 = 1.0 # s radius::Float64 = 0.0 # μm end # struct function brownberg_affect!(microbe, model) Δt = model.timestep τₘ = microbe.adaptation_time β = Δt / τₘ # memory loss factor KD = microbe.receptor_binding_constant S = microbe.state # weighted dPb/dt at previous step u = model.concentration_field(microbe.pos, model) ∇u = model.concentration_gradient(microbe.pos, model) ∂ₜu = model.concentration_time_derivative(microbe.pos, model) du_dt = dot(microbe.vel, ∇u) + ∂ₜu M = KD / (KD + u)^2 * du_dt # dPb/dt from new measurement microbe.state = β*M + S*exp(-β) # new weighted dPb/dt return nothing end # function function brownberg_turnrate(microbe, model) ν₀ = microbe.turn_rate # unbiased g = microbe.motor_gain S = microbe.state return ν₀*exp(-g*S) # modulated turn rate end # function function microbe_step!(microbe::BrownBerg, model::ABM) microbe_step!( microbe, model; affect! = brownberg_affect!, turnrate = brownberg_turnrate ) end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2322
export Brumley, brumley_affect!, brumley_turnrate """ Brumley{D} <: AbstractMicrobe{D} Model of chemotactic bacterium from 'Brumley et al. (2019) PNAS'. The model is optimized for simulation of marine bacteria and accounts for the presence of (gaussian) sensing noise in the chemotactic pathway. Default parameters: - motility = RunReverseFlick(speed_forward = Degenerate(46.5)) - turn_rate = 2.22 Hz → '1/τ₀' - state = 0.0 → 'S' - rotational_diffusivity = 0.035 rad²/S - adaptation_time = 1.3 s → 'τₘ' - receptor_gain = 50.0 μM⁻¹ → 'κ' - motor_gain = 50.0 → 'Γ' - chemotactic_precision = 6.0 → 'Π' - radius = 0.5 μm → 'a' """ Base.@kwdef mutable struct Brumley{D} <: AbstractMicrobe{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunReverseFlick(speed_forward = Degenerate(46.5)) vel::NTuple{D,Float64} = rand_vel(D, motility) # μm/s turn_rate::Float64 = 1/0.45 # 1/s state::Float64 = 0.0 rotational_diffusivity::Float64 = 0.035 # rad²/s adaptation_time::Float64 = 1.3 # s receptor_gain::Float64 = 50.0 # 1/μM motor_gain::Float64 = 50.0 # 1 chemotactic_precision::Float64 = 6.0 # 1 radius::Float64 = 0.5 # μm end # struct function brumley_affect!(microbe, model) Δt = model.timestep Dc = model.compound_diffusivity τₘ = microbe.adaptation_time α = exp(-Δt/τₘ) # memory persistence factor a = microbe.radius Π = microbe.chemotactic_precision κ = microbe.receptor_gain u = model.concentration_field(microbe.pos, model) ∇u = model.concentration_gradient(microbe.pos, model) ∂ₜu = model.concentration_time_derivative(microbe.pos, model) # gradient measurement μ = dot(microbe.vel, ∇u) + ∂ₜu # mean σ = Π * 0.04075 * sqrt(3*u / (π*a*Dc*Δt^3)) # noise M = rand(Normal(μ,σ)) # measurement # update internal state S = microbe.state microbe.state = α*S + (1-α)*κ*τₘ*M return nothing end # function function brumley_turnrate(microbe, model) ν₀ = microbe.turn_rate # unbiased Γ = microbe.motor_gain S = microbe.state return (1 + exp(-Γ*S)) * ν₀/2 # modulated turn rate end # function function microbe_step!(microbe::Brumley, model::ABM) microbe_step!( microbe, model; affect! = brumley_affect!, turnrate = brumley_turnrate ) end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
3559
export AbstractCelani, Celani, CelaniNoisy, celani_affect!, celani_turnrate, microbe_step! abstract type AbstractCelani{D} <: AbstractMicrobe{D} end """ Celani{D} <: <: AbstractCelani{D} <: AbstractMicrobe{D} Model of chemotactic bacterium using the response kernel from 'Celani and Vergassola (2010) PNAS'. Default parameters: - motility = RunTumble(speed = Degenerate(30.0)) - turn_rate = 1.49 Hz - state = zeros(4) - rotational_diffusivity = 0.26 rad²/s - gain = 50.0 - memory = 1 s - radius = 0 μm """ Base.@kwdef mutable struct Celani{D} <: AbstractCelani{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunTumble(speed = Degenerate(30.0)) vel::NTuple{D,Float64} = rand_vel(D, motility) # μm/s turn_rate::Float64 = 1/0.67 # 1/s state::Vector{Float64} = [0.,0.,0.,1.] # 1 rotational_diffusivity = 0.26 # rad²/s gain::Float64 = 50.0 # 1 memory::Float64 = 1.0 # s radius::Float64 = 0.5 # μm end # struct """ CelaniNoisy{D} <: AbstractCelani{D} <: AbstractMicrobe{D} Model of chemotactic bacterium using the response kernel from 'Celani and Vergassola (2010) PNAS' with a custom implementation of noisy sensing based on 'Berg and Purcell (1977) Biophys J'. The intensity of noise implicit in bacterial sensing is represented by a dimensionless factor `chemotactic_precision` (same approach used by 'Brumley et al. (2019) PNAS'). `chemotactic_precision = 1` represents the minimum theoretical noise. Default parameters: - motility = RunTumble(speed = Degenerate(30.0)) - turn_rate = 1.49 Hz - state = zeros(4) - rotational_diffusivity = 0.26 rad²/s - gain = 50.0 - memory = 1 s - chemotactic_precision = 1.0 - radius = 0 μm """ Base.@kwdef mutable struct CelaniNoisy{D} <: AbstractCelani{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunTumble(speed = Degenerate(30.0)) vel::NTuple{D,Float64} = rand_vel(D, motility) # μm/s turn_rate::Float64 = 1/0.67 # 1/s state::Vector{Float64} = [0.,0.,0.,1.] # 1 rotational_diffusivity = 0.26 # rad²/s gain::Float64 = 50.0 # 1 memory::Float64 = 1.0 # s chemotactic_precision::Float64 = 1.0 # 1 radius::Float64 = 0.5 # μm end # struct function celani_affect!(microbe::Celani, model) Δt = model.timestep u = model.concentration_field(microbe.pos, model) γ = microbe.memory λ = 1/γ β = microbe.gain S = microbe.state S[1] = S[1] + (-λ*S[1] + u)*Δt S[2] = S[2] + (-λ*S[2] + S[1])*Δt S[3] = S[3] + (-λ*S[3] + 2*S[2])*Δt S[4] = 1 - β*(λ^2*S[2] - λ^3/2*S[3]) return nothing end # function function celani_affect!(microbe::CelaniNoisy, model) Δt = model.timestep Dc = model.compound_diffusivity u = model.concentration_field(microbe.pos, model) a = microbe.radius Π = microbe.chemotactic_precision σ = Π * 0.04075 * sqrt(3*u / (5*π*Dc*a*Δt)) # noise (Berg-Purcell) M = rand(Normal(u,σ)) # measurement γ = microbe.memory λ = 1/γ β = microbe.gain S = microbe.state S[1] = S[1] + (-λ*S[1] + M)*Δt S[2] = S[2] + (-λ*S[2] + S[1])*Δt S[3] = S[3] + (-λ*S[3] + 2*S[2])*Δt S[4] = 1 - β*(λ^2*S[2] - λ^3/2*S[3]) return nothing end # function function celani_turnrate(microbe, model) ν₀ = microbe.turn_rate # unbiased S = microbe.state[4] return ν₀*S # modulated turn rate end # function function microbe_step!(microbe::AbstractCelani, model::ABM) microbe_step!( microbe, model; affect! = celani_affect!, turnrate = celani_turnrate ) end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
4792
export init_neighborlist, update_neighborlist!, surface_interaction! """ init_neighborlist( x::AbstractVector, extent::Union{<:Real,NTuple{D,<:Real}}, cutoff::Real, periodic::Bool ) where D Initialise a neighbor list between objects in `x` in a domain of size `extent` with a neighbor cutoff radius given by `cutoff`. `periodic` determines whether the system has periodic boundary conditions. Uses the `PeriodicSystem` interface of `CellListMap`. """ function init_neighborlist( x::AbstractVector, extent::Real, cutoff::Real, periodic::Bool ) D = length(getpos(first(x))) init_neighborlist(x, ntuple(_->extent,D), cutoff, periodic) end function init_neighborlist( x::AbstractVector, extent::NTuple{D,<:Real}, cutoff::Real, periodic::Bool ) where D xpos = getpos.(x) return PeriodicSystem( xpositions = xpos, unitcell = SVector(extent) .+ (periodic ? 0.0 : cutoff), cutoff = cutoff, output = 0.0 ) end # function """ init_neighborlist( x::AbstractVector, y::AbstractVector, extent::Union{<:Real,NTuple{D,<:Real}}, cutoff::Real, periodic::Bool ) where D Initialise a neighbor list between objects in `x` and `y` in a domain of size `extent` with a neighbor cutoff radius given by `cutoff`. `periodic` determines whether the system has periodic boundary conditions. Uses the `PeriodicSystem` interface of `CellListMap`. """ function init_neighborlist( x::AbstractVector, y::AbstractVector, extent::Real, cutoff::Real, periodic::Bool ) D = length(getpos(first(x))) init_neighborlist(x, y, ntuple(_->extent,D), cutoff, periodic) end function init_neighborlist( x::AbstractVector, y::AbstractVector, extent::NTuple{D,<:Real}, cutoff::Real, periodic::Bool ) where D xpos = getpos.(x) ypos = getpos.(y) return PeriodicSystem( xpositions = xpos, ypositions = ypos, unitcell = SVector(extent) .+ (periodic ? 0.0 : cutoff), cutoff = cutoff, output = 0.0 ) end # function getpos(x::AbstractVector) = SVector{length(x)}(x) getpos(x::NTuple{D,<:Real}) where D = SVector{D}(x) getpos(x::AbstractMicrobe{D}) where D = SVector{D}(x.pos) getpos(x::ObstacleSphere{D}) where D = SVector{D}(x.pos) """ update_neighborlist!(model; listname=:neighborlist, x_or_y='x') Update the position of all microbes in a neighbor list in `model`. Must be passed in the `update_model!` function to `model_step!`. ## Keywords * `listname::Symbol = :neighborlist`: name of the neighbor list to update (`model.properties[listname]`); this is useful if different neighbor lists are used (e.g. to evaluate different types of interactions). * `x_or_y::Char = 'x'`: update the `xpositions` or the `ypositions` field in the neighbor list. """ function update_neighborlist!(model::ABM; listname::Symbol = :neighborlist, x_or_y::Char = 'x' ) for microbe in allagents(model) update_neighborlist!(microbe, model; listname, x_or_y) end end """ update_neighborlist!(microbe, model; listname=:neighborlist, x_or_y='x') Update the position of `microbe` in a neighbor list. Must be passed as the `affect!` function to `microbe_step!`. ## Keywords * `listname::Symbol = :neighborlist`: name of the neighbor list to update (`model.properties[listname]`); this is useful if different neighbor lists are used (e.g. to evaluate different types of interactions). * `x_or_y::Char = 'x'`: update the `xpositions` or the `ypositions` field in the neighbor list. """ function update_neighborlist!(microbe::AbstractMicrobe, model::ABM; listname::Symbol = :neighborlist, x_or_y::Char = 'x' ) neighborlist = model.properties[listname] if lowercase(x_or_y) == 'x' neighborlist.xpositions[microbe.id] = SVector(microbe.pos) elseif lowercase(x_or_y) == 'y' neighborlist.ypositions[microbe.id] = SVector(microbe.pos) else throw(ArgumentError( "Value $(x_or_y) not valid for `x_or_y` keyword." )) end return nothing end # function function surface_interaction!(x,y,i,j,d²,f,model) body = model.bodies[j] body.affect!(model[i], body, model) return f end # function """ surface_interaction!(model; listname=:neighborlist) Evaluate the effect of surface interactions between microbes and bodies using the neighborlist for efficient computation. Requires the neighborlist (initialised via `init_neighborlist`) to be set as a model property `model.properties[listname]`. """ function surface_interaction!(model::ABM; listname::Symbol=:neighborlist) map_pairwise!( (x,y,i,j,d²,f) -> surface_interaction!(x,y,i,j,d²,f,model), model.properties[listname] ) return nothing end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1450
export autocorrelation """ autocorrelation(adf, sym::Union{String,Symbol}; tstep::Int=1) Return the non-normalized autocorrelation function of quantity `sym` extracted from the dataframe `adf` (`adf[!,sym]`). The kwarg `tstep` defines the values of time-lags for sampling (defaults to 1). """ function autocorrelation(adf, sym::Union{String,Symbol}; tstep::Int=1) timeseries = vectorize_adf_measurement(adf, sym) autocorrelation(timeseries; tstep=tstep) end # function function autocorrelation(timeseries::T; tstep::Int=1) where {S,T<:AbstractVector{S}} nsteps, = size(timeseries) timelags = range(0, nsteps-2; step=tstep) f = zeros(nsteps-1) for (j,Δt) in enumerate(timelags) for t₀ in 1:nsteps-Δt u = timeseries[t₀] v = timeseries[t₀+Δt] f[j] += dot(u,v) end # for f[j] /= (nsteps-j) end # for return f end # function function autocorrelation(timeseries::T; tstep::Int=1) where {S,T<:AbstractMatrix{S}} nmicrobes, nsteps = size(timeseries) timelags = range(0, nsteps-2; step=tstep) f = zeros(nsteps-1) for (j,Δt) in enumerate(timelags) for t₀ in 1:nsteps-Δt for i in 1:nmicrobes u = timeseries[i, t₀] v = timeseries[i, t₀+Δt] f[j] += dot(u,v) end # for end # for f[j] /= (nmicrobes * (nsteps-j)) end # for return f end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
559
export Degenerate, Arccos struct Degenerate{T<:Real} <: ContinuousUnivariateDistribution x::T end # struct Base.rand(d::Degenerate) = d.x struct Arccos{T<:Real} <: ContinuousUnivariateDistribution a::T b::T Arccos{T}(a::T, b::T) where {T} = new{T}(a::T, b::T) end function Arccos(a::Real, b::Real; check_args::Bool=true) Distributions.@check_args Arccos a<b -1≤a≤1 -1≤b≤1 return Arccos{Float64}(Float64(a), Float64(b)) end # function Arccos() = Arccos(-1,1) Base.rand(rng::AbstractRNG, d::Arccos) = acos(rand(rng, Uniform(d.a, d.b)))
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2312
export driftvelocity_point, driftvelocity_direction """ driftvelocity_point(adf, target; normalize=false) Evaluate the drift velocity of microbes towards a point `target`, extracting their positions and velocities from the agent dataframe `adf` (requires the existence of `:pos` and `:vel` fields). Returns a matrix of instantaneous drift velocities with size (nmicrobes, nsteps). By convention the drift velocity will be positive for motion towards the target point. If `normalize` is set to `true`, drift velocities are normalized by the instantaneous speed of the microbe. """ function driftvelocity_point(adf, target; normalize=false) traj = vectorize_adf_measurement(adf, :pos) vels = vectorize_adf_measurement(adf, :vel) driftvelocity_point(traj, vels, target; normalize=normalize) end # function function driftvelocity_point(traj::T, vels::T, target; normalize=false) where {T<:AbstractMatrix} v_drift = zeros(size(traj)...) for k in eachindex(traj) pos = traj[k] vel = vels[k] # axis is the vector from microbe to target axis = target .- pos # project velocity onto axis v_drift[k] = dot(vel, axis) / norm(axis) if normalize v_drift[k] /= norm(vel) end # if end # for return v_drift end # function """ driftvelocity_direction(adf, target; normalize=false) Evaluate the drift velocity of microbes along a direction `target`, extracting their velocities from the agent dataframe `adf` (requires `:vel` field). Returns a matrix of instantaneous drift velocities with size (nmicrobes, nsteps). By convention the drift velocity will be positive for motion along the target direction. If `normalize` is set to `true`, drift velocities are normalized by the instantaneous speed of the microbe. """ function driftvelocity_direction(adf, target; normalize=false) vels = vectorize_adf_measurement(adf, :vel) driftvelocity_direction(vels, target; normalize=normalize) end # function function driftvelocity_direction(vels::AbstractMatrix, target; normalize=false) if normalize v_drift = map(vel -> dot(vel, target) / norm(target) / norm(vel), vels) else v_drift = map(vel -> dot(vel, target) / norm(target), vels) end # if return v_drift end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
6411
export CFDM_3_1, CFDM_3_2, finitediff!, laplacian!, divergence! # pre-computed finite difference stencils global const CFDM_3_1 = central_fdm(3, 1) global const CFDM_3_2 = central_fdm(3, 2) # derivative functions for internal usage function ∂x(u::AbstractVector{Float64}, i::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i+q] * h end # for return s end # function function ∂x(u::AbstractMatrix{Float64}, i::Int, j::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i+q, j] * h end # for return s end # function function ∂y(u::AbstractMatrix{Float64}, i::Int, j::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i, j+q] * h end # for return s end # function function ∂x(u::AbstractArray{Float64,3}, i::Int, j::Int, k::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i+q, j, k] * h end # for return s end # function function ∂y(u::AbstractArray{Float64,3}, i::Int, j::Int, k::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i, j+q, k] * h end # for return s end # function function ∂z(u::AbstractArray{Float64,3}, i::Int, j::Int, k::Int, FDM) s::Float64 = 0.0 for (q,h) in zip(FDM.grid, FDM.coefs) s += u[i, j, k+q] * h end # for return s end # function """ finitediff!(ux, u, a, FDM=CFDM_3_1) finitediff!(ux, uy, u, ax, ay, FDM=CFDM_3_1) finitediff!(ux, uy, u, a, FDM=CFDM_3_1) finitediff!(ux, uy, uz, u, ax, ay, az, FDM=CFDM_3_1) finitediff!(ux, uy, uz, u, a, FDM=CFDM_3_1) Evaluate derivative of `u` through the finite difference stencil `FDM` and store the results in the appropriate arrays. If `u` has more than one dimension, it is assumed that the dimensions are ordered as (x, y, z). It is required that `size(ux) == size(uy) == size(uz) == size(u)`. By default, `FDM` is set to the 3-point stencil of the first derivative. `ax`, `ay` and `az` are the appropriate discretization factors (1/dx^n, 1/dy^n, 1/dx^n for the n-th derivative); if a single value `a` is given, it is expanded so that `ax = ay = az = a`. """ @views function finitediff!(ux::A, u::A, a::Real, FDM=CFDM_3_1) where {A<:AbstractVector{Float64}} n = length(u) i_start = 1 + abs(FDM.grid[1]) i_end = n - FDM.grid[end] for i in i_start:i_end ux[i] = a * ∂x(u,i,FDM) end # for end # function @views function finitediff!( ux::A, uy::A, u::A, ax::Real, ay::Real, FDM=CFDM_3_1 ) where {A<:AbstractMatrix{Float64}} nx, ny = size(u) i_start = j_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] for j in j_start:j_end, i in i_start:i_end ux[i,j] = ax * ∂x(u,i,j,FDM) uy[i,j] = ay * ∂y(u,i,j,FDM) end # for end # function finitediff!(ux::A, uy::A, u::A, a::Real, FDM=CFDM_3_1) where {A<:AbstractMatrix{Float64}} = finitediff!(ux, uy, u, a, a, FDM) @views function finitediff!( ux::A, uy::A, uz::A, u::A, ax::Real, ay::Real, az::Real, FDM=CFDM_3_1 ) where {A<:AbstractArray{Float64,3}} nx, ny, nz = size(u) i_start = j_start = k_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] k_end = nz - FDM.grid[end] for k in k_start:k_end, j in j_start:j_end, i in i_start:i_end ux[i,j,k] = ax * ∂x(u,i,j,k,FDM) uy[i,j,k] = ay * ∂y(u,i,j,k,FDM) uz[i,j,k] = az * ∂z(u,i,j,k,FDM) end # for end # function finitediff!(ux::A, uy::A, uz::A, u::A, a::Real, FDM=CFDM_3_1) where {A<:AbstractArray{Float64,3}} = finitediff!(ux, uy, uz, u, a, a, a, FDM) """ laplacian!(du, u, a, FDM=CFDM_3_2) laplacian!(du, u, ax, ay, FDM=CFDM_3_2) laplacian!(du, u, ax, ay, az, FDM=CFDM_3_2) Evaluate the finite-difference laplacian of `u` (∇²u), storing the result in `du`. By default, the 3-point stencil of the 2nd derivative is used. """ @views function laplacian!(du::A, u::A, a::Real, FDM=CFDM_3_2) where {A<:AbstractVector{Float64}} finitediff!(du, u, a, FDM) end # function @views function laplacian!( du::A, u::A, ax::Real, ay::Real, FDM=CFDM_3_2 ) where {A<:AbstractMatrix{Float64}} nx, ny = size(u) i_start = j_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] for j in j_start:j_end, i in i_start:i_end du[i,j] = ax*∂x(u,i,j,FDM) + ay*∂y(u,i,j,FDM) end # for end # function @views function laplacian!( du::A, u::A, ax::Real, ay::Real, az::Real, FDM=CFDM_3_2 ) where {A<:AbstractArray{Float64,3}} nx, ny, nz = size(u) i_start = j_start = k_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] k_end = nz - FDM.grid[end] for k in k_start:k_end, j in j_start:j_end, i in i_start:i_end du[i,j,k] = ax*∂x(u,i,j,k,FDM) + ay*∂y(u,i,j,k,FDM) + az*∂z(u,i,j,k,FDM) end # for end laplacian!(du, u, a::Real, FDM=CFDM_3_2) = laplacian!(du, u, ntuple(_->a, ndims(u))..., FDM) """ divergence!(du, u, a, FDM=CFDM_3_1) divergence!(du, ux, uy, ax, ay, FDM=CFDM_3_1) divergence!(du, ux, uy, uz, ax, ay, az, FDM=CFDM_3_1) Evaluate the finite-difference divergence of `u` (∇⋅u), storing the result in `du`. By default, the 3-point stencil of the 1st derivative is used. """ divergence!(du::A, u::A, a::Real, FDM=CFDM_3_1) where {A<:AbstractVector{Float64}} = laplacian!(du, u, a, FDM) @views function divergence!( du::A, ux::A, uy::A, ax::Real, ay::Real, FDM=CFDM_3_1 ) where {A<:AbstractMatrix{Float64}} nx, ny = size(du) i_start = j_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] for j in j_start:j_end, i in i_start:i_end du[i,j] = ax*∂x(ux,i,j,FDM) + ay*∂y(uy,i,j,FDM) end # for end # function @views function divergence!( du::A, ux::A, uy::A, uz::A, ax::Real, ay::Real, az::Real, FDM=CFDM_3_1 ) where {A<:AbstractArray{Float64,3}} nx, ny, nz = size(du) i_start = j_start = k_start = 1 + abs(FDM.grid[1]) i_end = nx - FDM.grid[end] j_end = ny - FDM.grid[end] k_end = nz - FDM.grid[end] for k in k_start:k_end, j in j_start:j_end, i in i_start:i_end du[i,j,k] = ax*∂x(ux,i,j,k,FDM) + ay*∂y(uy,i,j,k,FDM) + az*∂z(uz,i,j,k,FDM) end # for end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1793
export AbstractMicrobe, Microbe """ AbstractMicrobe{D} <: AbstractAgent where {D<:Integer} YourMicrobeType{D} <: AbstractMicrobe{D} All microbe types in Bactos.jl simulations must be instances of user-defined types that are subtypes of `AbstractMicrobe`. The parameter `D` defines the dimensionality of the space in which the microbe type lives (1, 2 and 3 are currently supported). All microbe types should have the following fields: `- id::Int` → id of the microbe `- pos::NTuple{D,Float64}` → position of the microbe `- vel::NTuple{D,Float64}` → velocity of the microbe `- motility` → motile pattern of the microbe `- turn_rate::Float64` → average reorientation rate of the microbe `- rotational_diffusivity::Float64` → rotational diffusion coefficient """ abstract type AbstractMicrobe{D} <: AbstractAgent where {D<:Integer} end """ Microbe{D} <: AbstractMicrobe{D} Basic microbe type for simple simulations. Default parameters: - `id::Int` → identifier used internally by Agents.jl - `pos::NTuple{D,Float64} = ntuple(zero,D)` → position - `motility = RunTumble()` → motile pattern - `vel::NTuple{D,Float64} = rand_vel(D) .* rand(motility.speed)` → velocity vector - `turn_rate::Float64 = 1.0` → frequency of reorientations - `state::Float64` → generic variable for a scalar internal state - `rotational_diffusivity::Float64 = 0.0` → rotational diffusion coefficient - `radius::Float64 = 0.0` → equivalent spherical radius of the microbe """ Base.@kwdef mutable struct Microbe{D} <: AbstractMicrobe{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunTumble() vel::NTuple{D,Float64} = rand_vel(D, motility) turn_rate::Float64 = 1.0 state::Float64 = 0.0 rotational_diffusivity::Float64 = 0.0 radius::Float64 = 0.0 end # struct
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
3066
export initialise_model, initialise_ode, initialise_pathfinder """ initialise_model(; microbes, timestep, extent, spacing = extent/20, periodic = true, random_positions = true, model_properties = Dict(), ) Initialise an `AgentBasedModel` from population `microbes`. Requires the integration `timestep` and the `extent` of the simulation box. When `random_positions = true` the positions assigned to `microbes` are ignored and new ones, extracted randomly in the simulation box, are assigned; if `random_positions = false` the original positions in `microbes` are kept. Any extra property can be assigned to the model via the `model_properties` dictionary. """ function initialise_model(; microbes, timestep, extent, spacing = minimum(extent)/20, periodic = true, random_positions = true, model_properties = Dict(), ) space_dim = length(microbes[1].pos) if typeof(extent) <: Real domain = Tuple(fill(extent, space_dim)) else if length(extent) ≠ space_dim error("Space extent and microbes must have the same dimensionality.") end # if domain = extent end # if properties = Dict( :t => 0, :timestep => timestep, :compound_diffusivity => 608.0, :concentration_field => (pos,model) -> 0.0, :concentration_gradient => (pos,model) -> zero.(pos), :concentration_time_derivative => (pos,model) -> 0.0, model_properties... ) space = ContinuousSpace( domain, spacing = spacing, periodic = periodic ) # falls back to eltype(microbes) if there is a single microbe type, # builds a Union type if eltype(microbes) is abstract MicrobeType = Union{typeof.(microbes)...} model = ABM( MicrobeType, space; properties, scheduler = Schedulers.fastest, ) for microbe in microbes if random_positions add_agent!(microbe, model) else add_agent!(microbe, microbe.pos, model) end # if end # for return model end # function """ initialise_ode(ode_step!, u₀, p; alg=Tsit5(), kwargs...) Initialise an OrdinaryDiffEq integrator, using the in-place stepping algorithm `ode_step!`, initial conditions `u₀` and parameters `p`. Default integration algorithm is `Tsit5` (others can be accessed by importing OrdinaryDiffEq). Any extra parameter can be passed over to the integrator via kwargs. """ function initialise_ode(ode_step!, u₀, p; alg=Tsit5(), kwargs...) prob = ODEProblem(ode_step!, u₀, (0.0, Inf), p) integrator = init(prob, alg; kwargs...) return integrator end # function function initialise_pathfinder( extent::Real, periodic::Bool, walkmap::BitArray{D} ) where D initialise_pathfinder(ntuple(_->extent,D), periodic, walkmap) end function initialise_pathfinder( extent::NTuple{D,<:Real}, periodic::Bool, walkmap::BitArray{D} ) where D space = ContinuousSpace(extent; periodic) AStar(space; walkmap) end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
4103
export AbstractMotility, AbstractMotilityOneStep, AbstractMotilityTwoStep, MotileState, TwoState, Forward, Backward, switch!, RunTumble, RunReverse, RunReverseFlick """ AbstractMotility General abstract interface for motility patterns. """ abstract type AbstractMotility end """ AbstractMotilityOneStep One-step motility patterns (`RunTumble`). Subtypes must have at least the following fields: - `speed`: distribution of microbe speed, new values extracted after each turn - `polar`: distribution of polar angles - `azimuthal`: distribution azimuthal angles For 2-dimensional microbe types, only `polar` defines reorientations and `azimuthal` is ignored. """ abstract type AbstractMotilityOneStep <: AbstractMotility end """ AbstractMotilityTwoStep Two-step motility patterns (`RunReverse` and `RunReverseFlick`), with different properties between forward and backward state of motion. Subtypes must have at least the following fields: - `speed_forward`: distribution of microbe speed, new values extracted after each turn - `polar_forward`: distribution of in-plane reorientations for motile state 0 - `azimuthal_forward`: distribution of out-of-plane reorientations for motile state 0 - `speed_backward`: distribution of microbe speed, new values extracted after each turn - `polar_backward`: distribution of in-plane reorientations for motile state 1 - `azimuthal_backward`: distribution of out-of-plane reorientations for motile state 1 - `motile_state`: defines current motile state (e.g. `Forward` or `Backward` for a `TwoState`) For 2-dimensional microbe types, only `polar_forward` and `polar_backward` define reorientations, while `azimuthal_forward` and `azimuthal_forward` are ignored. """ abstract type AbstractMotilityTwoStep <: AbstractMotility end # just a wrapper to allow state to be mutable mutable struct MotileState state end MotileState() = MotileState(TwoState()) """ TwoState <: Enum{Bool} Represents the state of a two-step motile pattern, can take values `Forward` or `Backward`. """ @enum TwoState::Bool Forward Backward Base.show(io::IO, ::MIME"text/plain", x::TwoState) = x == Forward ? print(io, "Forward") : print(io, "Backward") # choose at random between Forward and Backward if not specified """ TwoState([rng::AbstractRng]) Randomly generate the state of a two-step motile pattern. """ TwoState() = TwoState(Random.default_rng()) TwoState(rng::AbstractRNG) = TwoState(rand(rng, (true, false))) # overload getproperty and setproperty! for more convenient access to state function Base.getproperty(obj::AbstractMotilityTwoStep, sym::Symbol) if sym === :state return obj.motile_state.state else return getfield(obj, sym) end end function Base.setproperty!(value::AbstractMotilityTwoStep, name::Symbol, x) if name === :state return setfield!(value.motile_state, :state, x) else return setfield!(obj, name, x) end end # define rules for switching motile state switch!(::AbstractMotilityOneStep) = nothing """ switch!(m::AbstractMotilityTwoStep) Switch the state of a two-step motility pattern (`m.state`) from `Forward` to `Backward` and viceversa. """ switch!(m::AbstractMotilityTwoStep) = (m.state = ~m.state; nothing) Base.:~(x::TwoState) = TwoState(~Bool(x)) Base.@kwdef struct RunTumble <: AbstractMotilityOneStep speed = Degenerate(30.0) polar = Uniform(-π, π) azimuthal = Arccos(-1, 1) end # struct Base.@kwdef struct RunReverse <: AbstractMotilityTwoStep speed_forward = Degenerate(30.0) polar_forward = Degenerate(π) azimuthal_forward = Arccos(-1,1) speed_backward = speed_forward polar_backward = polar_forward azimuthal_backward = azimuthal_forward motile_state = MotileState() end # struct Base.@kwdef struct RunReverseFlick <: AbstractMotilityTwoStep speed_forward = Degenerate(30.0) polar_forward = Degenerate(π) azimuthal_forward = Arccos(-1,1) speed_backward = speed_forward polar_backward = [-π/2, π/2] azimuthal_backward = Arccos(-1,1) motile_state = MotileState() end # struct
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2752
export msd """ unfold_coord(x₀, x₁, L) Unfold a translation `x₀` ↦ `x₁` in a domain of periodicity `L`. """ function unfold_coord(x₀, x₁, L) dx = x₁ - x₀ sdx = sign(dx) a = round(abs(dx/L)) if abs(dx) > L/2 return x₁ - a*L*sdx else return x₁ end # if end # function """ unfold!(unfolded, cnf₁, cnf₀, L) Unfold spatial configuration `cnf₁` with respect to `cnf₀` in a domain of periodicity `L` and store to `unfolded`. """ function unfold!(unfolded, cnf₁, cnf₀, L) dim = length(first(cnf₁)) nmicrobes, = size(cnf₁) for i in 1:nmicrobes l = typeof(L) <: AbstractArray ? L[μ] : L newx = ntuple(μ -> unfold_coord(cnf₀[i][μ], cnf₁[i][μ], l), dim) unfolded[i] = newx end # for end # function """ unfold(trajectory::T, L) where {S<:Tuple, T<:AbstractArray{S,2}} Unfold `trajectory` in a domain of periodicity `L`. """ function unfold(trajectory::T, L) where {S<:Tuple, T<:AbstractArray{S,2}} nmicrobes, nsteps = size(trajectory) unfolded = Matrix{eltype(trajectory)}(undef, size(trajectory)...) unfolded[:,1] .= trajectory[:,1] for t in 2:nsteps oldcnf = unfolded[:,t-1] newcnf = trajectory[:,t] unfolded_slice = @view unfolded[:,t] unfold!(unfolded_slice, newcnf, oldcnf, L) end # for return unfolded end # function """ msd(adf; tstep::Int=1, L=Inf) Evaluate mean-squared displacement from an agent dataframe `adf` containing the position timeseries of agents (`:pos` field). Assumes that sampled positions are uniformly spaced in time. Parameter `L` defines the periodicity of the domain for unfolding; set `L=Inf` (default) if boundaries are not periodic. msd(trajectory::T, tstep::Int=1) where {S,T<:AbstractArray{S,2}} Evaluate mean-squared displacement of `trajectory`, where different microbes are collected along first dimension, and times along second dimension. """ function msd(adf; tstep::Int=1, L=Inf) trajectory = vectorize_adf_measurement(adf, :pos) if isinf(L) return msd(trajectory, tstep) else trajectory_unfolded = unfold(trajectory, L) return msd(trajectory_unfolded, tstep) end # if end # function function msd(trajectory::T, tstep::Int=1) where {S,T<:AbstractArray{S,2}} nmicrobes, nsteps = size(trajectory) timelags = range(1, nsteps-1; step=tstep) MSD = zeros(nsteps-1) for (j,Δt) in enumerate(timelags) for t₀ in 1:nsteps-Δt for i in 1:nmicrobes u = trajectory[i, t₀] v = trajectory[i, t₀+Δt] MSD[j] += sum(abs2.(u .- v)) end # for end # for MSD[j] /= (nmicrobes * (nsteps-j)) end # for return MSD end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
3999
export ObstacleSphere, get_walkmap, stick!, glide!, bounce! """ struct ObstacleSphere{D} pos::NTuple{D,Float64} radius::Float64 affect!::Function end Spherical obstacle in a D-dimensional space. - `pos`: center position of the sphere - `radius`: radius of the sphere - `affect!`: function with signature `(microbe,sphere,model)`, defines microbe-sphere interaction. Three `affect!` functions are provided out-of-the box: `stick!`, `glide!` and `bounce!`. """ struct ObstacleSphere{D} pos::NTuple{D,Float64} radius::Float64 affect!::Function end # struct ObstacleSphere(pos::NTuple{D,<:Real}, radius::Real, affect!::Function = (_,_,_) -> nothing ) where D = ObstacleSphere{D}(Float64.(pos), Float64(radius), affect!) function initialise_pathfinder( extent, periodic::Bool, r::Real, spheres::AbstractVector{ObstacleSphere{D}}; Δ::Real=r/2 ) where D walkmap = get_walkmap(extent, r, spheres; Δ) initialise_pathfinder(extent, periodic, walkmap) end function get_walkmap( extent::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{ObstacleSphere{D}}; Δ::Real=r/2 )::BitArray{D} where D mesh = ntuple(i -> 0:Δ:extent[i], D) itr = Iterators.product(mesh...) return BitArray([is_walkable(pos, r, spheres) for pos in itr]) end function is_walkable( pos::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{ObstacleSphere{D}} )::Bool where D for sphere in spheres if !is_walkable(pos, r, sphere) return false end end return true end function is_walkable( pos::NTuple{D,<:Real}, r::Real, sphere::ObstacleSphere{D} )::Bool where D norm(pos .- sphere.pos) ≥ r + sphere.radius end """ stick!(microbe, sphere::ObstacleSphere, model) `microbe` sticks to the `sphere` surface at the point of contact. The orientation of the microbe is unchanged. """ function stick!(microbe, sphere::ObstacleSphere, model) x = microbe.pos y = sphere.pos R = microbe.radius + sphere.radius d = norm(x .- y) if d < R s = @. -microbe.vel * model.timestep a = sum(abs2.(s)) b = 2.0 * dot(x.-y, s) c = d*d - R*R ε = -b/2a * (1 - sqrt(1 - 4*a*c/(b*b))) z = @. ε*s walk!(microbe, z, model) end # if end # function """ glide!(microbe, sphere::ObstacleSphere, model) `microbe` sticks to the `sphere` surface while gliding along. """ function glide!(microbe, sphere::ObstacleSphere, model) x = microbe.pos y = sphere.pos R = microbe.radius + sphere.radius d = norm(x .- y) if d < R s = y .- x a = sum(abs2.(s)) c = d*d - R*R ε = 1 - sqrt(1 - c/a) z = @. ε*s walk!(microbe, z, model) end # if end # function """ bounce!(microbe, sphere::ObstacleSphere, model; ζ=1.0) `microbe` is reflected off the `sphere` surface, inverting the direction of its `vel` field. The parameter `ζ` is the elastic coefficient of the collision; for `ζ=1` the collision is perfectly elastic (microbe run length is conserved); for `ζ=0` the microbe sticks to the surface (but vel is inverted). """ function bounce!(microbe, sphere::ObstacleSphere, model; ζ=1.0) if !(0 ≤ ζ ≤ 1) throw(DomainError(ζ, "ζ must have value in the range [0,1].")) end # if x = microbe.pos y = sphere.pos R = microbe.radius + sphere.radius d = norm(x .- y) if d < R s = @. -microbe.vel * model.timestep a = sum(abs2.(s)) b = 2.0 * dot(x.-y, s) c = d*d - R*R ε = -b/2a * (1 - sqrt(1 - 4*a*c/(b*b))) z = @. (1+ζ)*ε*s # hit surface z₁ = @. ε*s walk!(microbe, z₁, model) # reorient r_hat = (y.-x)./d deflection = -2 .* dot(microbe.vel, r_hat) .* r_hat microbe.vel = @. ζ * (microbe.vel + deflection) # bounce z₂ = @. ε * (microbe.vel * model.timestep) walk!(microbe, z₂, model) end # if end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2437
export rotate, turn!, rotational_diffusion! rotate(w::SVector{1}) = -w rotate(w::SVector{1}, θ) = rotate(w) rotate(w::SVector{1}, θ, ϕ) = rotate(w) rotate(w::SVector{2}, θ) = Angle2d(θ) * w rotate(w::SVector{2}, θ, ϕ) = rotate(w, θ) function rotate(w::SVector{3}, θ, ϕ) m = findfirst(w .≠ 0) n = m%3 + 1 u = SVector(0., 0., 0.) u = setindex(u, w[m], n) u = setindex(u, -w[n], m) # rotate w around its normal u a = AngleAxis(θ, u...) * w # rotate a around the original w direction return AngleAxis(ϕ, w...) * a end # function rotate(w::Tuple, θ, ϕ) = rotate(SVector(w), θ, ϕ) rotate(w::Tuple, θ) = rotate(SVector(w), θ) function turn!(microbe::AbstractMicrobe, motility::AbstractMotilityOneStep) # store actual speed U₀ = norm(microbe.vel) # perform reorientation θ = rand(motility.polar) ϕ = rand(motility.azimuthal) microbe.vel = rotate(microbe.vel, θ, ϕ) |> Tuple # extract new speed from distribution U₁ = rand(motility.speed) # update speed microbe.vel = microbe.vel .* (U₁ / U₀) return nothing end # function function turn!(microbe::AbstractMicrobe, motility::AbstractMotilityTwoStep) # store current speed U₀ = norm(microbe.vel) # perform reorientation depending on current motile state if motility.state == Forward # reorient according to forward-state angles θ = rand(motility.polar_forward) ϕ = rand(motility.azimuthal_forward) # extract new speed from backward-state distribution U₁ = rand(motility.speed_backward) elseif motility.state == Backward # reorient according to backward-state angles θ = rand(motility.polar_backward) ϕ = rand(motility.azimuthal_backward) # extract new speed from forward-state distribution U₁ = rand(motility.speed_forward) end # if # reorient microbe.vel = rotate(microbe.vel, θ, ϕ) |> Tuple # switch motile state switch!(motility) # update speed microbe.vel = microbe.vel .* (U₁ / U₀) return nothing end # function rotational_diffusion!(microbe::AbstractMicrobe{1}, dt) = nothing function rotational_diffusion!(microbe::AbstractMicrobe, dt) D_rot = microbe.rotational_diffusivity σ = sqrt(2*D_rot*dt) polar = rand(Normal(0, σ)) azimuthal = rand(Arccos()) microbe.vel = Tuple(rotate(microbe.vel, polar, azimuthal)) return nothing end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1043
export microbe_step! function microbe_step!( microbe::AbstractMicrobe, model::ABM; affect! = (microbe, model) -> nothing, turnrate = (microbe, model) -> microbe.turn_rate, ) dt = model.timestep # integration timestep # update microbe position if haskey(model.properties, :pathfinder) pathfinder_step!(microbe, model, dt) else move_agent!(microbe, model, dt) end # reorient microbe due to rotational diffusion rotational_diffusion!(microbe, dt) # update microbe state affect!(microbe, model) # update reorientation rate ω = turnrate(microbe, model) if rand() < ω*dt # if true reorient microbe turn!(microbe, microbe.motility) end # if return nothing end # function function pathfinder_step!(microbe::AbstractMicrobe, model::ABM, dt::Real) target_position = microbe.pos .+ microbe.vel .* dt U = norm(microbe.vel) plan_route!(microbe, target_position, model.pathfinder) move_along_route!(microbe, model, model.pathfinder, U, dt) end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
687
export model_step! """ model_step!(model; update_model! = (model) -> nothing) Update model properties through the `update_model!` function (defaults to nothing). If `model` contains an OrdinaryDiffEq integrator among its properties (`model.integrator`), also perform an integration step. """ function model_step!(model; update_model!::Function = (model) -> nothing ) # if a diffeq integrator is provided, integrate over a timestep if haskey(model.properties, :integrator) step!(model.integrator, model.timestep, true) end # if # increase step count model.t += 1 # update model properties update_model!(model) return nothing end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1734
export rand_vel, rand_speed, vectorize_adf_measurement """ rand_vel([rng,] N) Generate a random N-tuple of unitary norm. """ function rand_vel(D::Int) v = rand(D) .* 2 .- 1 Tuple(v ./ norm(v)) end # function function rand_vel(rng, D::Int) v = rand(rng, D) .* 2 .- 1 Tuple(v ./ norm(v)) end # function """ rand_speed(m::AbstractMotilityOneStep) Extract value from the speed distribution of the motility pattern `m.speed`. """ rand_speed(m::AbstractMotilityOneStep) = rand(m.speed) """ rand_speed(m::AbstractMotilityTwoStep) Extract value from the speed distribution of the motility pattern. If `motilestate(m) == ForwardState()` extract from `speed_forward`, otherwise from `speed_backward`. """ function rand_speed(m::AbstractMotilityTwoStep) if m.state == Forward return rand(m.speed_forward) else return rand(m.speed_backward) end end """ rand_vel([rng,] N::Int, m::AbstractMotility) Generate a random N-tuple, with norm defined by the speed distribution of `m`. """ rand_vel(D::Int, m::AbstractMotility) = rand_vel(D) .* rand_speed(m) rand_vel(rng, D::Int, m::AbstractMotility) = rand_vel(rng, D) .* rand_speed(m) """ vectorize_adf_measurement(adf, sym) Collect quantity `sym` from the agent dataframe `adf` and return it in matrix form with dimensions (microbes, times). """ function vectorize_adf_measurement(adf, sym) nmicrobes = unique(adf[!,:id]) |> length nsteps = unique(adf[!,:step]) |> length datatype = typeof(adf[1,sym]) s = Matrix{datatype}(undef, nmicrobes, nsteps) for t in 1:nsteps for i in 1:nmicrobes s[i,t] = adf[i + (t-1)*nmicrobes, sym] end # for end # for return s end # function
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
3578
export AbstractXie, Xie, XieNoisy, xie_affect!, xie_turnrate abstract type AbstractXie{D} <: AbstractMicrobe{D} end Base.@kwdef mutable struct Xie{D} <: AbstractXie{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunReverseFlick(speed_forward = Degenerate(46.5)) vel::NTuple{D,Float64} = rand_vel(D, motility) turn_rate_forward::Float64 = 2.3 # 1/s turn_rate_backward::Float64 = 1.9 # 1/s state_m::Float64 = 0.0 # s state_z::Float64 = 0.0 # s state::Float64 = 0.0 # s adaptation_time_m::Float64 = 1.29 # s adaptation_time_z::Float64 = 0.28 # s gain_forward::Float64 = 2.7 # 1/s gain_backward::Float64 = 1.6 # 1/s binding_affinity::Float64 = 0.39 # μM rotational_diffusivity::Float64 = 0.26 # rad²/s radius::Float64 = 0.5 # μm end Base.@kwdef mutable struct XieNoisy{D} <: AbstractXie{D} id::Int pos::NTuple{D,Float64} = ntuple(zero, D) motility = RunReverseFlick(speed_forward = Degenerate(46.5)) vel::NTuple{D,Float64} = rand_vel(D, motility) turn_rate_forward::Float64 = 2.3 # 1/s turn_rate_backward::Float64 = 1.9 # 1/s state_m::Float64 = 0.0 # s state_z::Float64 = 0.0 # s state::Float64 = 0.0 # s adaptation_time_m::Float64 = 1.29 # s adaptation_time_z::Float64 = 0.28 # s gain_forward::Float64 = 2.7 # 1/s gain_backward::Float64 = 1.6 # 1/s binding_affinity::Float64 = 0.39 # μM chemotactic_precision::Float64 = 6.0 # 1 rotational_diffusivity::Float64 = 0.26 # rad²/s radius::Float64 = 0.5 # μm end function xie_affect!(microbe::Xie, model) Δt = model.timestep c = model.concentration_field(microbe.pos, model) K = microbe.binding_affinity ϕ = log(1.0 + c/K) τ_m = microbe.adaptation_time_m τ_z = microbe.adaptation_time_z a₀ = (τ_m*τ_z)/(τ_m - τ_z) m = microbe.state_m z = microbe.state_z m += (ϕ - m/τ_m)*Δt z += (ϕ - z/τ_z)*Δt microbe.state_m = m microbe.state_z = z microbe.state = a₀ * (m/τ_m - z/τ_z) return nothing end function xie_affect!(microbe::XieNoisy, model; ε=1e-16) Δt = model.timestep Dc = model.compound_diffusivity c = model.concentration_field(microbe.pos, model) K = microbe.binding_affinity a = microbe.radius Π = microbe.chemotactic_precision σ = Π * 0.04075 * sqrt(3*c / (5*π*Dc*a*Δt)) M = rand(Normal(c,σ)) ϕ = log(1.0 + max(M/K, -1+ε)) τ_m = microbe.adaptation_time_m τ_z = microbe.adaptation_time_z a₀ = (τ_m*τ_z)/(τ_m - τ_z) m = microbe.state_m z = microbe.state_z m += (ϕ - m/τ_m)*Δt z += (ϕ - z/τ_z)*Δt microbe.state_m = m microbe.state_z = z microbe.state = a₀ * (m/τ_m - z/τ_z) return nothing end function xie_turnrate(microbe, model) if microbe.motility isa AbstractMotilityTwoStep return xie_turnrate_twostep(microbe, model) else return xie_turnrate_onestep(microbe, model) end end function xie_turnrate_onestep(microbe, model) S = microbe.state ν₀ = microbe.turn_rate_forward β = microbe.gain_forward return ν₀*(1 + β*S) end function xie_turnrate_twostep(microbe, model) S = microbe.state if microbe.motility.state == Forward ν₀ = microbe.turn_rate_forward β = microbe.gain_forward else ν₀ = microbe.turn_rate_backward β = microbe.gain_backward end return ν₀*(1 + β*S) end function microbe_step!(microbe::AbstractXie, model::ABM) microbe_step!( microbe, model; affect! = xie_affect!, turnrate = xie_turnrate ) end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
4005
using Test, Bactos, Random @testset "Finite differences" begin ≃(x,y) = isapprox(x,y;atol=1e-3) # \simeq @testset "One dimension" begin n = 256 x = range(0, 2π; length=n) # reset x with ghost cells m = 2 dx = x.step.hi x = range(x[1]-m*dx, x[end]+m*dx; step=dx) # initial function y₀ = sin.(x) # analytical first derivative y₁ = cos.(x) # analytical second derivative y₂ = -sin.(x) # initialize arrays for numerical derivatives dy₀ = zero(y₀) d²y₀ = zero(y₀) ddy₀ = zero(y₀) dy₁ = zero(y₀) ∇y₀ = zero(y₀) ∇²y₀ = zero(y₀) divy₀ = zero(y₀) # evaluate numerical derivatives # first derivative finitediff!(dy₀, y₀, 1/dx) # first derivative of analytical first derivative finitediff!(dy₁, y₁, 1/dx) # first derivative of numerical first derivative finitediff!(ddy₀, dy₀, 1/dx) # second derivative finitediff!(d²y₀, y₀, 1/dx^2, CFDM_3_2) # with a 1st order stencil, laplacian equates first derivative laplacian!(∇y₀, y₀, 1/dx, CFDM_3_1) # actual laplacian, in 1d corresponds to second derivative laplacian!(∇²y₀, y₀, 1/dx^2) # divergence, in 1d corresponds to first derivative divergence!(divy₀, y₀, 1/dx) # ghost cells must be excluded from the test @test all((dy₀ .≃ y₁)[1+m:end-m]) @test all((dy₁ .≃ y₂)[1+m:end-m]) @test all((ddy₀ .≃ y₂)[1+m:end-m]) @test all((d²y₀ .≃ y₂)[1+m:end-m]) @test ∇y₀ == dy₀ @test ∇²y₀ == d²y₀ @test divy₀ == dy₀ end @testset "Two dimensions" begin nx = 256 ny = 512 x = range(0, 2π; length=nx) y = range(0, 2π; length=ny) # reset x and y with ghost cells m = 2 dx = x.step.hi dy = y.step.hi x = range(x[1]-m*dx, x[end]+m*dx; step=dx) y = range(y[1]-m*dy, y[end]-m*dy; step=dy) u₀ = @. sin(x) * cos(y)' ux = @. cos(x) * cos(y)' uy = @. - sin(x) * sin(y)' lapu = @. -2 * u₀ myux = zero(u₀) myuy = zero(u₀) mylapu = zero(u₀) mylapu_2 = zero(u₀) finitediff!(myux, myuy, u₀, 1/dx, 1/dy) laplacian!(mylapu, u₀, 1/dx^2, 1/dy^2) divergence!(mylapu_2, myux, myuy, 1/dx, 1/dy) @test all((myux .≃ ux)[1+m:end-m,1+m:end-m]) @test all((myuy .≃ uy)[1+m:end-m,1+m:end-m]) @test all((mylapu .≃ lapu)[1+m:end-m,1+m:end-m]) @test all((mylapu_2 .≃ lapu)[1+m:end-m,1+m:end-m]) # ∇⋅∇ = ∇² end @testset "Three dimensions" begin nx = 128 ny = 128 nz = 64 x₁, x₂ = 0.0, 2π y₁, y₂ = 0.0, 2π z₁, z₂ = 0.0, 1.0 dx = (x₂-x₁)/(nx-1) dy = (y₂-y₁)/(ny-1) dz = (z₂-z₁)/(nz-1) # domain with ghost cells m = 2 x = range(x₁-m*dx, x₂+m*dx; step=dx) y = range(y₁-m*dy, y₂+m*dy; step=dy) z = range(z₁-m*dz, z₂+m*dz; step=dz) u₀ = zeros(nx+2m, ny+2m, nz+2m) ux = zero(u₀) uy = zero(u₀) uz = zero(u₀) ∇²u = zero(u₀) for k in axes(u₀,3), j in axes(u₀,2), i in axes(u₀,1) u₀[i,j,k] = cos(x[i])*sin(y[j])*z[k] ux[i,j,k] = -sin(x[i])*sin(y[j])*z[k] uy[i,j,k] = cos(x[i])*cos(y[j])*z[k] uz[i,j,k] = cos(x[i])*sin(y[j]) ∇²u[i,j,k] = -2*u₀[i,j,k] end myux = zero(u₀) myuy = zero(u₀) myuz = zero(u₀) my∇²u = zero(u₀) finitediff!(myux, myuy, myuz, u₀, 1/dx, 1/dy, 1/dz) laplacian!(my∇²u, u₀, 1/dx^2, 1/dy^2, 1/dz^2) @test all((myux .≃ ux)[m+1:end-m,m+1:end-m,m+1:end-m]) @test all((myuy .≃ uy)[m+1:end-m,m+1:end-m,m+1:end-m]) @test all((myuz .≃ uz)[m+1:end-m,m+1:end-m,m+1:end-m]) @test all((my∇²u .≃ ∇²u)[m+1:end-m,m+1:end-m,m+1:end-m]) end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
4088
using Test, Bactos, Random @testset "Measurements" begin ≃(x,y) = isapprox(x,y,atol=1e-8) # \simeq @testset "Chemotactic drift velocity" begin # with turn_rate=0 motility is ignored and vel never changes m1 = Microbe{1}(id=1, pos=(4.0,), vel=(1.0,), turn_rate=0) m2 = Microbe{1}(id=2, pos=(6.0,), vel=(-1.0,), turn_rate=0) m3 = Microbe{1}(id=3, pos=(3.0,), vel=(3.0,), turn_rate=0) dt = 1.0 L = 10.0 target_point = (5.0,) target_direction = (1.0,) model = initialise_model(; microbes = [m1, m2, m3], timestep = dt, extent = L, random_positions = false ) adata = [:pos, :vel] adf, = run!(model, microbe_step!, 2; adata) adf1 = filter(:id => id -> id==1, adf; view=true) adf2 = filter(:id => id -> id==2, adf; view=true) adf3 = filter(:id => id -> id==3, adf; view=true) vd1_dir = driftvelocity_direction(adf1, target_direction) vd1_pnt = driftvelocity_point(adf1, target_point) vd2_dir = driftvelocity_direction(adf2, target_direction) vd2_pnt = driftvelocity_point(adf2, target_point) vd3_pnt = driftvelocity_point(adf3, target_point) vd3_pnt_n = driftvelocity_point(adf3, target_point; normalize=true) # m1 is moving along target_direction at all timepoints @test vd1_dir == [1.0 1.0 1.0] # m1 is moving towards target_point at initial timepoint @test vd1_pnt[1] == 1.0 # at final timepoint, m1 overshoots target_point and moves in opposite direction @test vd1_pnt[3] == -1.0 # m2 is moving against target_direction at all timepoints @test vd2_dir == [-1.0 -1.0 -1.0] # m2 is moving towards target_point at initial timepoint @test vd2_pnt[1] == 1.0 # at final timepoint, m2 overshoots target_point and moves in opposite direction @test vd2_pnt[3] == -1.0 # same as m1, but now test if normalize kwarg works # not normalized @test vd3_pnt[1] == 3.0 @test vd3_pnt[3] == -3.0 # normalized @test vd3_pnt_n[1] == 1.0 @test vd3_pnt_n[3] == -1.0 end @testset "Mean-squared displacement" begin U = 2.0 extent = 50.0 # if turn_rate=0 motility is ignored and vel never changes # so the microbe is moving ballistically with speed U microbes = [Microbe{1}(id=0, turn_rate=0, vel=(U,), pos=(extent/2,))] timestep = 0.1 model = initialise_model(; microbes, extent, timestep, random_positions=false) adata = [:pos] nsteps = 10 adf, = run!(model, microbe_step!, nsteps; adata) # total displacement obeys ballistic motion Δx = adf[end,:pos][1] .- adf[1,:pos][1] @test Δx ≃ U*nsteps*timestep MSD = msd(adf) |> vec # for ballistic motion MSD(t) = U²t² for n in 1:nsteps @test MSD[n] ≃ (U*n*timestep)^2 end # for # same ballistic test over longer times # this time using `L=extent` keyword to unwrap periodic boundaries nsteps = 500 adf, = run!(model, microbe_step!, nsteps; adata) MSD = msd(adf; L=extent) |> vec @test MSD[nsteps] ≃ (U*nsteps*timestep)^2 U = 3.0 # turn_rate=Inf in 1D means that the bacterium is reversing at each step microbes = [Microbe{1}(id=0, turn_rate=Inf, vel=(U,), motility=RunTumble(speed=Degenerate(U)))] extent = 50.0 timestep = 0.1 model = initialise_model(; microbes, extent, timestep) nsteps = 4 adf, = run!(model, microbe_step!, nsteps; adata) MSD = msd(adf; L=extent) |> vec # first step is ballistic forward @test MSD[1] ≃ (U*timestep)^2 # second step goes back to initial position @test MSD[2] ≃ 0.0 # same pattern for following timesteps @test MSD[3] ≃ MSD[1] @test MSD[4] ≃ MSD[2] end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
6291
using Test, Bactos, Random using LinearAlgebra: norm @testset "Microbe creation" begin @testset "Default microbe" begin # test type hierarchy @test Microbe <: AbstractMicrobe @test Microbe{1} <: AbstractMicrobe @test Microbe{2} <: AbstractMicrobe @test Microbe{3} <: AbstractMicrobe # test errors for missing arguments @test_throws UndefKeywordError Microbe{3}() @test_throws UndefVarError Microbe(id=0) # test arguments behave as expected, 2D id = rand(Int) m = Microbe{2}(id=id) @test m.id == id @test m.pos isa NTuple{2,Float64} @test all(m.pos .== 0.0) @test norm(m.vel) ≈ 30.0 @test typeof(m.motility) == RunTumble @test m.turn_rate == 1.0 @test m.state == 0.0 @test m.rotational_diffusivity == 0.0 @test m.radius == 0.0 # test constructor works for all types of motility @test_nowarn Microbe{2}(id=0, motility=RunTumble()) @test_nowarn Microbe{2}(id=0, motility=RunReverse()) @test_nowarn Microbe{2}(id=0, motility=RunReverseFlick()) # test some arguments again for 3D id = rand(Int) D = 3 x = rand(D) .* 500.0 |> Tuple v = rand_vel(D) .* 40.0 mot = RunReverseFlick() m = Microbe{D}(id=id, pos=x, vel=v, motility=mot) @test m.id == id @test m.pos isa NTuple{3,Float64} @test m.pos == x @test m.vel isa NTuple{3,Float64} @test m.vel == v @test m.motility isa RunReverseFlick end @testset "Brumley" begin # test type hierarchy @test Brumley{1} <: AbstractMicrobe @test Brumley{2} <: AbstractMicrobe @test Brumley{3} <: AbstractMicrobe # test arguments m = Brumley{3}(id=0) @test m.pos isa NTuple{3,Float64} @test m.vel isa NTuple{3,Float64} @test m.turn_rate == 1/0.45 @test m.state == 0.0 @test m.rotational_diffusivity == 0.035 @test m.adaptation_time == 1.3 @test m.receptor_gain == 50.0 @test m.motor_gain == 50.0 @test m.chemotactic_precision == 6.0 @test m.radius == 0.5 @test m.motility isa RunReverseFlick # default has same speed Degenerate(46.5) for forward and backward modes @test norm(m.vel) ≈ rand(m.motility.speed_forward) @test norm(m.vel) ≈ rand(m.motility.speed_backward) end @testset "Brown-Berg" begin # test type hierarchy @test BrownBerg{1} <: AbstractMicrobe @test BrownBerg{2} <: AbstractMicrobe @test BrownBerg{3} <: AbstractMicrobe # test arguments m = BrownBerg{3}(id=0) @test m.pos isa NTuple{3,Float64} @test m.vel isa NTuple{3,Float64} @test m.turn_rate == 1/0.67 @test m.state == 0.0 @test m.rotational_diffusivity == 0.035 @test m.motor_gain == 660.0 @test m.receptor_binding_constant == 100.0 @test m.adaptation_time == 1.0 @test m.radius == 0.0 @test m.motility isa RunTumble @test norm(m.vel) ≈ rand(m.motility.speed) end @testset "Celani" begin # test type hierarchy @test AbstractCelani <: AbstractMicrobe @test Celani <: AbstractCelani @test CelaniNoisy <: AbstractCelani @test !(CelaniNoisy <: Celani) @test !(Celani <: CelaniNoisy) @test setdiff(fieldnames(CelaniNoisy), fieldnames(Celani)) == [:chemotactic_precision] # test arguments m1 = Celani{3}(id=0) @test m1.pos isa NTuple{3,Float64} @test m1.vel isa NTuple{3,Float64} @test m1.turn_rate == 1/0.67 @test m1.state == [0., 0., 0., 1.] @test m1.rotational_diffusivity == 0.26 @test m1.gain == 50.0 @test m1.memory == 1.0 @test m1.radius == 0.5 @test m1.motility isa RunTumble @test norm(m1.vel) ≈ rand(m1.motility.speed) m2 = CelaniNoisy{3}(id=0) @test m2.pos isa NTuple{3,Float64} @test m2.vel isa NTuple{3,Float64} @test m2.turn_rate == 1/0.67 @test m2.state == [0., 0., 0., 1.] @test m2.rotational_diffusivity == 0.26 @test m2.gain == 50.0 @test m2.memory == 1.0 @test m2.radius == 0.5 @test m2.chemotactic_precision == 1.0 @test m2.motility isa RunTumble @test norm(m2.vel) ≈ rand(m2.motility.speed) end @testset "Xie" begin # test type hierarchy @test AbstractXie <: AbstractMicrobe @test Xie <: AbstractXie @test XieNoisy <: AbstractXie @test !(XieNoisy <: Xie) @test !(Xie <: XieNoisy) @test setdiff(fieldnames(XieNoisy), fieldnames(Xie)) == [:chemotactic_precision] # test arguments m1 = Xie{3}(id=0) @test m1.pos isa NTuple{3,Float64} @test m1.vel isa NTuple{3,Float64} @test m1.turn_rate_forward == 2.3 @test m1.turn_rate_backward == 1.9 @test m1.state_m == 0.0 @test m1.state_z == 0.0 @test m1.state == 0.0 @test m1.rotational_diffusivity == 0.26 @test m1.gain_forward == 2.7 @test m1.gain_backward == 1.6 @test m1.adaptation_time_m == 1.29 @test m1.adaptation_time_z == 0.28 @test m1.binding_affinity == 0.39 @test m1.radius == 0.5 @test m1.motility isa RunReverseFlick @test m1.motility.speed_forward == m1.motility.speed_backward m2 = XieNoisy{3}(id=0) @test m2.pos isa NTuple{3,Float64} @test m2.vel isa NTuple{3,Float64} @test m2.turn_rate_forward == 2.3 @test m2.turn_rate_backward == 1.9 @test m2.state_m == 0.0 @test m2.state_z == 0.0 @test m2.state == 0.0 @test m2.rotational_diffusivity == 0.26 @test m2.gain_forward == 2.7 @test m2.gain_backward == 1.6 @test m2.adaptation_time_m == 1.29 @test m2.adaptation_time_z == 0.28 @test m2.binding_affinity == 0.39 @test m2.radius == 0.5 @test m2.chemotactic_precision == 6.0 @test m2.motility isa RunReverseFlick @test m2.motility.speed_forward == m2.motility.speed_backward end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
4070
using Test, Bactos, Random @testset "Model creation" begin timestep = 1.0 extent = 500.0 pos = Tuple(rand(3)) m = Microbe{3}(id=1, pos = pos) microbes = [m] # test errors # `microbes`, `timestep` and `extent` MUST all be given @test_throws UndefKeywordError initialise_model() @test_throws UndefKeywordError initialise_model(;microbes) @test_throws UndefKeywordError initialise_model(;timestep) @test_throws UndefKeywordError initialise_model(;extent) @test_throws UndefKeywordError initialise_model(;microbes,timestep) @test_throws UndefKeywordError initialise_model(;microbes,extent) @test_throws UndefKeywordError initialise_model(;timestep,extent) model = initialise_model(; microbes, timestep, extent, random_positions = false, ) # test default properties @test model.properties isa Dict{Symbol,Any} @test Set(keys(model.properties)) == Set( (:t, :timestep, :compound_diffusivity, :concentration_field, :concentration_gradient, :concentration_time_derivative) ) @test model.timestep == timestep # the model should contain the agent `m`, not a copy @test model.agents[1] === m # agent position should be conserved since random_positions=false @test model.agents[1].pos == pos model = initialise_model(; microbes, timestep, extent, random_positions = true, ) # agent identity is still the same @test model.agents[1] === m # agent position is changed since random_positions=true @test model.agents[1].pos ≠ pos @test m.pos ≠ pos # the new position should be inside of extent @test all(0 .≤ model.agents[1].pos .< extent) # if extent is a tuple, orthorhombic domains can be created model = initialise_model(; microbes = [Microbe{3}(id=0)], timestep, extent = (300.0,400.0,250.0) ) @test model.space.extent == (300.0, 400.0, 250.0) # if extent is a scalar, the domain is cubic; # if extent is a tuple, the domain can be orthorhombic; # if extent has different size from microbe dimensionality, # errors should be thrown my_init(extent) = initialise_model(; microbes = [Microbe{3}(id=0)], extent, timestep ) @test_throws ErrorException my_init((1.0,)) @test_throws ErrorException my_init((1.0, 1.0)) @test_throws ErrorException my_init((1.0, 1.0, 1.0, 1.0)) model1 = my_init(1.0) model2 = my_init((1.0, 2.0, 3.0)) @test model1.space.extent == (1.0, 1.0, 1.0) @test model2.space.extent == (1.0, 2.0, 3.0) # test mixed species models timestep = 1.0 extent = 1.0 microbes = [Brumley{1}(id=1), Brumley{1}(id=2)] model = initialise_model(; microbes, timestep, extent) @test model.agents isa Dict{Int, Brumley{1}} microbes = [Microbe{1}(id=1), Brumley{1}(id=2), Xie{1}(id=3)] model = initialise_model(; microbes, timestep, extent) @test model.agents isa Dict{Int, Union{Microbe{1}, Brumley{1}, Xie{1}}} @testset "DiffEq Integrator" begin microbes = [Microbe{1}(id=0)] timestep = 0.1 extent = 1.0 model = initialise_model(; microbes, timestep, extent) # simple ode: du/dt = p # solution: u(t) = u(0) + p*t my_ode_step!(du, u, p, t) = (du .= p[1]) u₀ = [0.0] p = (1.0,) integrator = initialise_ode(my_ode_step!, u₀, p) # check integrator is initialised correctly @test integrator.u == u₀ @test !(integrator.u === u₀) @test integrator.p == p @test integrator.p === p model = initialise_model(; microbes, timestep, extent, model_properties = Dict(:integrator => integrator) ) @test model.integrator === integrator # advance ode for n steps of size timestep n = 5 run!(model, microbe_step!, model_step!, n) @test model.integrator === integrator @test integrator.u[1] ≈ p[1] * timestep * n end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
2485
using Test, Bactos, Random using Distributions: Uniform @testset "Motility" begin @testset "Motile state" begin @test instances(TwoState) == (Forward, Backward) # call without argument chooses an instance at random @test TwoState() ∈ instances(TwoState) # bitwise not switches between Forward and Backward @test ~Forward == Backward @test ~Backward == Forward # call to MotileState without argument chooses random state motstate = MotileState() @test motstate.state ∈ instances(TwoState) # or the instance can be specified motstate = MotileState(Forward) @test motstate.state == Forward end @test AbstractMotilityOneStep <: AbstractMotility @test AbstractMotilityTwoStep <: AbstractMotility @test !(AbstractMotilityOneStep <: AbstractMotilityTwoStep) @test RunTumble <: AbstractMotilityOneStep m = RunTumble() @test m.speed == Degenerate(30.0) @test m.polar == Uniform(-π, π) @test m.azimuthal == Arccos() @test RunReverse <: AbstractMotilityTwoStep m = RunReverse() @test m.speed_forward == Degenerate(30.0) @test m.polar_forward == Degenerate(π) @test m.azimuthal_forward == Arccos() @test m.speed_backward === m.speed_forward @test m.polar_backward === m.polar_forward @test m.azimuthal_backward === m.azimuthal_forward @test m.motile_state isa MotileState # no :state field, but due to getproperty! overload # it directly accesses motile_state.state @test !hasfield(RunReverse, :state) @test m.state === m.motile_state.state @test m.state isa TwoState # switching motility equals to switching state s = m.state switch!(m) @test m.state == ~s # state can be set manually due to setproperty! overload m.state = Forward @test m.state == Forward @test RunReverseFlick <: AbstractMotilityTwoStep m = RunReverseFlick() @test m.speed_forward == Degenerate(30.0) @test m.polar_forward == Degenerate(π) @test m.azimuthal_forward == Arccos() @test m.speed_backward === m.speed_forward @test m.polar_backward == [-π/2, π/2] @test m.azimuthal_backward === m.azimuthal_forward @test m.motile_state isa MotileState # no :state field, but due to getproperty! overload # it directly accesses motile_state.state @test !hasfield(RunReverse, :state) @test m.state === m.motile_state.state @test m.state isa TwoState end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
1281
using Test, Bactos, Random using LinearAlgebra: norm @testset "Pathfinder interface" begin walkmap = BitArray(rand((0,1), 10, 10)) L = 10 extent = (L, L) periodic = false pathfinder1 = initialise_pathfinder(extent, periodic, walkmap) pathfinder2 = initialise_pathfinder(L, periodic, walkmap) # initialising with a tuple or a scalar should be the same @test pathfinder1.dims == pathfinder2.dims # pathfinder.walkmap should be just a reference to walkmap @test pathfinder1.walkmap === walkmap spherepos = (5,5) sphereradius = 3 proberadius = 0.5 spheres = [ObstacleSphere(spherepos, sphereradius)] Δ = proberadius # mesh resolution (defaults to proberadius/2) walkmap = get_walkmap(extent, proberadius, spheres; Δ) # walkmap should be false within the sphere area, true otherwise mesh = (x = 0:Δ:L, y = 0:Δ:L) walkmap2 = similar(walkmap) for j in eachindex(mesh[:y]), i in eachindex(mesh[:x]) pos = (mesh[:x][i], mesh[:y][j]) # contact is allowed so if distance = radius the value is true if norm(pos .- spherepos) < sphereradius + proberadius walkmap2[i,j] = false else walkmap2[i,j] = true end end @test walkmap == walkmap2 end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
5147
using Test, Bactos, Random using LinearAlgebra: norm, dot using StaticArrays using Distributions: Uniform, Normal @testset "Microbe reorientations" begin ≊(x,y) = isapprox(x, y, atol=1e-12) # \approxeq @testset "One-dimensional reorientations" begin # all reorientations in 1D should be just reversals motility = RunTumble(speed=[1.0]) vel = (1.0,) m = Microbe{1}(id=1; vel, motility) turn!(m, m.motility) @test vel == .-m.vel turn!(m, m.motility) @test vel == m.vel motile_state = MotileState(Forward) motility = RunReverseFlick(speed_forward=[1.0]; motile_state) vel = (1.0,) m = Microbe{1}(id=1; vel, motility) turn!(m, m.motility) @test vel == .-m.vel @test motility.state == Backward turn!(m, m.motility) @test vel == m.vel @test motility.state == Forward end @testset "Two-dimensional reorientations" begin u = SVector(1.0, 0.0) # a null rotation should leave u unchanged v1 = rotate(u, 0) @test u == v1 v2 = rotate(u, 0, 0) @test u == v2 # 90-degree rotation v3 = rotate(u, π/2) @test v3 ≊ SVector(0.0, 1.0) # azimuthal angle has no effect on 2d rotation v4 = rotate(u, π/2, rand(Uniform(0,2π))) @test v3 ≊ v4 v5 = rotate(u, π) # 180-degree rotation @test u ≊ .-v5 # rotation by multiple of 2π leave u unchanged v6 = rotate(u, 200π) @test u ≊ v6 U = 30.0 vel = rand_vel(2) .* U motility = RunReverseFlick( speed_forward = [U], motile_state = MotileState(Forward), polar_backward = [π/2] # exclude -π/2 ) m = Microbe{2}(id=1; vel, motility) # 5 steps should lead back to initial orientation # reverse (π) turn!(m, m.motility) @test SVector(m.vel) ≊ SVector(-vel[1], -vel[2]) # flick (π/2) turn!(m, m.motility) @test dot(m.vel, vel) ≊ 0 @test SVector(m.vel) ≊ SVector(vel[2], -vel[1]) # reverse (π) turn!(m, m.motility) @test SVector(m.vel) ≊ SVector(-vel[2], vel[1]) # flick (π/2) turn!(m, m.motility) @test SVector(m.vel) ≊ SVector(-vel[1], -vel[2]) # reverse (π) turn!(m, m.motility) @test SVector(m.vel) ≊ SVector(vel) end @testset "Three-dimensional reorientations" begin U = 30.0 vel = rand_vel(3) .* U θ = π/6 polar = [θ] motility = RunTumble( speed = [U], polar = polar, ) m = Microbe{3}(id=1; vel, motility) turn!(m, m.motility) @test dot(m.vel, vel)/U^2 ≊ cos(θ) U = 30.0 vel = (U, 0.0, 0.0) θ = π/4 φ = π/6 polar = [θ] azimuthal = [φ] motility = RunTumble( speed = [U], polar = polar, azimuthal = azimuthal, ) m = Microbe{3}(id=1; vel, motility) turn!(m, m.motility) @test SVector(m.vel) ≊ SVector(U*cos(θ), U*sin(θ)*sin(φ), -U*sin(θ)*cos(φ)) @test dot(m.vel, vel)/U^2 ≊ cos(θ) end @testset "Rotational diffusion" begin dt = 1.0 vel = (1.0,) rotational_diffusivity = 0.3 m = Microbe{1}(id=1; vel, rotational_diffusivity) # in 1D rotational diffusion is deactivated, nothing should happen rotational_diffusion!(m, dt) @test m.vel == vel dt = 1.0 rotational_diffusivity = 0.0 m = Microbe{2}(id=1; rotational_diffusivity) vel = m.vel rotational_diffusion!(m, dt) # if rotational_diffusivity = 0 vel should be unchanged @test m.vel == vel dt = 1.0 rotational_diffusivity = 0.3 σ = sqrt(2*rotational_diffusivity*dt) m = Microbe{2}(id=1; rotational_diffusivity) vel = m.vel U = norm(vel) # fix rng state N = 7 Random.seed!(N) θ = rand(Normal(0,σ)) # reset rng Random.seed!(N) rotational_diffusion!(m, dt) # reorientation should be of an angle θ and norm should be conserved @test dot(m.vel, vel)/U^2 ≊ cos(θ) # same tests for 3d dt = 1.0 rotational_diffusivity = 0.0 m = Microbe{3}(id=1; rotational_diffusivity) vel = m.vel rotational_diffusion!(m, dt) # if rotational_diffusivity = 0 vel should be (approx.) unchanged @test all(m.vel .≊ vel) dt = 1.0 rotational_diffusivity = 0.3 σ = sqrt(2*rotational_diffusivity*dt) m = Microbe{3}(id=1; rotational_diffusivity) vel = m.vel U = norm(vel) # fix rng state N = 7 Random.seed!(N) θ, φ = rand(Normal(0,σ)), rand(Arccos()) # reset rng Random.seed!(N) rotational_diffusion!(m, dt) # reorientation should be of an angle θ and norm should be conserved @test dot(m.vel, vel)/U^2 ≊ cos(θ) end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
312
using Test, Bactos, Random @testset "Bactos.jl Tests" begin include("microbe_creation.jl") include("motility.jl") include("model_creation.jl") include("reorientations.jl") include("step.jl") include("measurements.jl") include("finite_differences.jl") include("pathfinder.jl") end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
code
777
using Test, Bactos, Random using LinearAlgebra: norm using Agents: step! @testset "Stepping" begin @testset "Microbe stepping" begin pos = ntuple(_ -> 0.5, 2) vel = (-0.2, 0.6) m = Microbe{2}(id=1, pos=pos, vel=vel, turn_rate=0.0, rotational_diffusivity=0.0) dt = 0.1 model = initialise_model(; timestep = dt, microbes = [m], extent = 1.0, periodic = true, random_positions = false ) step!(model, microbe_step!) @test m.pos[1] ≈ 0.48 @test m.pos[2] ≈ 0.56 @test m.vel == vel step!(model, microbe_step!, 9) @test m.pos[1] ≈ 0.3 @test m.pos[2] ≈ 0.1 # periodic boundary conditions! @test m.vel == vel end end
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
docs
1031
# Bactos.jl [![Build Status](https://github.com/mastrof/Bactos.jl/workflows/CI/badge.svg)](https://github.com/mastrof/Bactos.jl/actions) [![codecov](https://codecov.io/gh/mastrof/Bactos.jl/branch/main/graphs/badge.svg)](https://codecov.io/gh/mastrof/Bactos.jl) [![Documentation, stable](https://img.shields.io/badge/docs-latest-blue.svg)](https://mastrof.github.io/Bactos.jl/dev/) Bactos.jl is a Julia framework for agent-based simulations of bacterial behavior, built on the amazing [Agents.jl](https://github.com/JuliaDynamics/Agents.jl)). The package is still at an early stage of intense development. Most of the core API should be stable for the foreseeable future, but many tweaks, improvements and additions still need to be made. ## Contribute If you want to point out a bug, request some features or simply ask for info, please don't hesitate to open an issue! If you are interested in taking on a more active part in the development, consider contacting me directly at [email protected]. I'll be happy to have a chat!
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
docs
6798
# Validation It's important to check that our microbes behave as expected. In this section, we compare various `Bactos.jl` functionalities against theoretical results from the literature. If some functionality lacks validation please open an issue. ## Velocity autocorrelation functions The velocity autocorrelation functions for different swimming patterns have been evaluated analytically by Taktikos et al. (2013)<sup>1</sup>. First, we will set identical parameters for all the swimmers. For `RunReverse` and `RunReverseFlick` we will assume that the properties in the forward and backward mode are identical. ```julia U = 30.0 # swimming speed in μm/s τ_run = 1.0 # average unbiased run time in s ω = 1 / τ_run # average unbiased turn rate in 1/s Δt = 0.01 # integration timestep in s extent = 1e4 # domain size in μm ``` We initialise three distinct populations, differing only in their motility, merge them all into a single population and initialise our model ```julia n = 200 # number of microbes in each population microbes_runtumble = [ Microbe{3}(id=i, turn_rate=ω, motility=RunTumble(speed=[U]) ) for i in 1:n ] microbes_runrev = [ Microbe{3}(id=n+i, turn_rate=ω, motility=RunReverse(speed_forward=[U]) ) for i in 1:n ] microbes_runrevflick = [ Microbe{3}(id=2n+i, turn_rate=ω, motility=RunReverseFlick(speed_forward=[U]) ) for i in 1:n ] microbes = vcat( microbes_runtumble, microbes_runrev, microbes_runrevflick ) model = initialise_model(; microbes, extent, periodic = true, timestep = Δt ) ``` To evaluate the velocity autocorrelation functions, we only need to store the `:vel` field of the microbes during the simulation. To get a good statistics we need simulation times that are sufficiently longer than the average run length `τ_run`. ```julia nsteps = round(Int, 100τ_run / Δt) adata = [:vel] adf, = run!(model, microbe_step!, nsteps; adata) ``` We can now separate the dataframes for the three subpopulations by their motility type and evaluate their velocity autocorrelation functions using the built-in `autocorrelation` function. For large amounts of data `autocorrelation` can take some time (O(t<sup>2</sup>n)). ```julia adf_runtumble = filter(:id => id -> model.agents[id].motility isa RunTumble, adf) adf_runrev = filter(:id => id -> model.agents[id].motility isa RunReverse, adf) adf_runrevflick = filter(:id => id -> model.agents[id].motility isa RunReverseFlick, adf) adfs = [adf_runtumble, adf_runrev, adf_runrevflick] Φ = hcat([autocorrelation(a,:vel) for a in adfs]...) ``` The theoretical values (normalized) are given by Taktikos et al. (2013)<sup>1</sup>. ```julia t = range(0, (nsteps-1)*Δt; step=Δt) Φ_theoretical = hcat([ exp.(-t ./ τ_run), exp.(-t ./ (τ_run / 2)), (1 .- t ./ (2τ_run)) .* exp.(-t ./ τ_run), ]...) ``` Agreement between our simulation and theory is great. ```julia plot( xlims=(0,6τ_run), ylims=(-0.1, 1.05), xlab="Δt / τ", ylab="velocity autocorrelation", ) plot!(t, Φ_theoretical, lw=2, lc=[1 2 3], label=["Run-Tumble" "Run-Reverse" "Run-Reverse-Flick"]) # slice simulation data for better visibility scatter!(t[1:15:end], Φ[1:15:end,:] ./ U^2, m=:x, mc=[1 2 3], label=false) hline!([0.0], lw=0.8, ls=:dash, lc=:black, lab=false) ``` ![Comparison between numerical and theoretical velocity autocorrelation functions for bacteria with different motile patterns](velocity_autocorrelations.png) ## Mean-squared displacement It's also easy to evaluate the mean-squared displacement (MSD) of our microbes during a simulation. We will now run simulations of run-tumble bacteria using different reorientation distributions (parameterized by the average inclination angle θ), and compare the MSD as a function of θ to theoretical expectations using the well-known diffusivity formula by Lovely and Dahlquist (1975)<sup>2</sup> ```math D = \dfrac{v^2\tau}{3(1-\alpha)} ``` where ``\alpha = \left< \cos\theta \right>`` represents the directional persistence of the trajectory. Since ``D`` only depends on ``\left< \cos\theta \right>`` and not on the full ``P(\theta)`` distribution, we will simply use degenerate distributions ``P_i(\theta) = \delta(\theta-\bar\theta)`` for different values ``\bar\theta`` and compare the MSD estimated from our simulations to the theoretical expectation. Taktikos et al. (2013)<sup>1</sup> provide the analytical expression for the MSD which interpolates between the short-term ballistic regime and the long-term diffusive regime: ```math {\rm MSD}(t) = 6D\dfrac{\tau}{1-\alpha} \left[ \dfrac{(1-\alpha)t}{\tau}-1+ {\rm exp}\left( -\dfrac{(1-\alpha)t}{\tau} \right) \right] ``` We will setup our systems as usual and then run each simulation independently ```julia using Distributions: Uniform θs = [π/6, π/4, π/3, π/2, π] U = 30.0 # swimming speed in μm/s τ = 1.0 # average run time in s ω = 1 / τ # average turn rate in 1/s nmicrobes = 200 microbes = [ [ Microbe{3}( id = n, turn_rate = ω, motility = RunTumble(speed=[U], polar=[θ,-θ]) ) for n in 1:nmicrobes ] for θ in θs ] dt = 0.05 # s L = 500.0 # μm models = [ initialise_model(; microbes = microbes[i], timestep = dt, extent = L ) for i in eachindex(microbes) ] nsteps = round(Int, 100τ / dt) adata = [:pos] adfs = [run!(model, microbe_step!, nsteps; adata)[1] for model in models] ``` We can now evaluate the MSD for each population using the `msd` function; since the simulations were performed in a periodic domain, we will need to specify the size of the domain as a keyword argument ```julia MSD = msd.(adfs; L=L) ``` We can now slice our experimental data and plot the results. ```julia t = (1:nsteps).*dt logslice = round.(Int, exp10.(range(0,3,length=10))) plot( xlab = "Δt / τ", ylab = "MSD / (Uτ)²", legend = :bottomright, legendtitle = "1-α", scale = :log10 ) scatter!(t[logslice]./τ, hcat(MSD...)[logslice,:]./(U*τ)^2, m=:x, ms=6, msw=2, lab=false) for i in eachindex(θs) α = cos(θs[i]) T = τ / (1-α) D = U^2*T / 3 dr² = @. 6*D*T * (t/T - 1 + exp(-t/T)) plot!(t./τ, dr²./(U*τ)^2, lab=round(1-α,digits=2), lc=i, lw=2) end # for plot!(xticks=exp10.(-1:2), yticks=exp10.(-2:2:2)) ``` ![Mean-squared displacement of run-tumble bacteria with different reorientation distributions](msd_runtumble.png) ## References 1. Taktikos, J.; Stark, H.; Zaburdaev, V. How the Motility Pattern of Bacteria Affects Their Dispersal and Chemotaxis. PLoS ONE 2013, 8 (12), e81936. https://doi.org/10.1371/journal.pone.0081936. 2. Lovely, P.S.; Dahlquist, F.W. Statistical measures of bacterial motility and chemotaxis. Journal of Theoretical Biology 1975, 50 (2), 477-496. https://doi.org/10.1016/0022-5193(75)90094-6
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
docs
1667
# Bactos.jl Agent-based modelling of bacterial motility and chemotaxis in Julia. ## Features - Built on [Agents.jl](https://juliadynamics.github.io/Agents.jl/stable/) - Bacterial motility in 1, 2 and 3 dimensions with customizable motile patterns. - Chemotaxis with different tunable models (Brown-Berg, Brumley, Celani, Xie). - Integration of differential equations in parallel with agent stepping via [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/), using finite differences. - Easy evaluation of quantities of interest (mean-squared displacement, autocorrelation functions...). ### Limitations - The length of the integration timestep also sets the sensing timescale in chemotaxis models (i.e. the time over which a microbe integrates environmental signals). - Reorientations are always assumed to be instantaneous. - No hydrodynamic interactions. ## Future directions - Swimming in flow fields. - More behavioral strategies (chemokinesis, infotaxis...). - Extended set of core functionalities (encounters, interactions...). - Complex environments (non-spherical obstacles). - Steric interactions and non-spherical microbes. ## Citation If you use this package in work that leads to a publication, please cite the GitHub repository: ``` @misc{Foffi2022, author = {Foffi, R.}, title = {Bactos.jl}, year = {2022}, publisher = {GitHub}, journal = {GitHub repository}, howpublished = {\url{https://github.com/mastrof/Bactos.jl}} } ``` ## Acknowledgements This project has received funding from the European Union's Horizon 2020 research and innovation programme under the Marie Skłodowska-Curie grant agreement No 955910.
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.0.1
8f2697805b334b06f4680f13d76453ccb590c77d
docs
7299
# Tutorial Ready-to-run scripts for the functionalities introduced here can be found in the `examples` directory of the [repo](https://github.com/mastrof/Bactos.jl). ## Creating a bacterium Bacteria are represented by custom types, that must be subtypes of the `AbstractAgent` type implemented by Agents.jl. ```@docs AbstractMicrobe ``` By default, `Bactos.jl` provides a basic `Microbe` type, that is usually sufficient for the simplest types of simulations. ```@docs Microbe ``` In order to create a `Microbe` living in a one-dimensional space we can just call ```julia Microbe{1}(id=0) ``` It is *required* to pass a value to the `id` argument (this behavior might change in the future). All the other parameters will be given default values (as described in the type docstring) if not assigned explicitly. Similarly, for bacteria living in two or three dimensions we can use ```julia Microbe{2}(id=0) Microbe{3}(id=0) ``` Custom parameters can be set via kwargs: ```julia Microbe{3}( id = 0, pos = (300.0, 0.0, 0.0), motility = RunTumble(speed = Normal(40.0, 4.0)), vel = rand_vel(3) .* 40.0, turn_rate = 1.5, state = 0.0, rotational_diffusivity = 0.035, radius = 0.5 ) ``` ## Creating a model BacteriaBasedModel provides a fast way to initialise an `AgentBasedModel` (from Agents.jl) via the `initialise_model` function, using a typical procedure. If higher levels of customization are needed, the model will need to be created by hand. ```@docs initialise_model ``` We can now generate a population of microbes and, after choosing an integration timestep and a domain size, we initialise our model, placing the microbes at random locations in the domain. ```julia microbes = [Microbe{3}(id=i) for i in 1:10] timestep = 0.1 extent = 100.0 model = initialise_model(; microbes = microbes, timestep = timestep, extent = extent ) ``` ``` AgentBasedModel with 10 agents of type Microbe space: periodic continuous space with (100.0, 100.0, 100.0) extent and spacing=5.0 scheduler: fastest properties: timestep ``` ## Random walks Now we can already generate random walks. The setup follows previous sections. ```julia timestep = 0.1 extent = 1e6 # just a large value to stay away from boundaries nmicrobes = 8 # initialise all microbes at same position microbes = [Microbe{1}(id=i, pos=(L/2,)) for i in 1:nmicrobes] model = initialise_model(; microbes, timestep, extent, periodic = false, random_positions = false ) ``` Now we need to define the `adata` variable to choose what observables we want to track, throughout the simulation, for each agent in the system. In our case, only the position field ```julia adata = [:pos] ``` Now we can run the simulation; the `microbe_step!` function will take care of the stepping and reorientations according to the properties of each microbe: ```julia nsteps = 1000 adf, = run!(model, microbe_step!, nsteps; adata) ``` ```julia x = first.(vectorize_adf_measurement(adf, :pos))' plot( (0:nsteps).*dt, x, legend = false, xlab = "time", ylab = "position" ) ``` ![One-dimensional random walks of 8 microbes starting from same position](random_walk_1d.png) Similarly for a two-dimensional random walk, using run-reverse-flick motility and non-zero rotational diffusion: ```julia dt = 0.1 L = 1000.0 nmicrobes = 1 microbes = [ Microbe{2}( id=i, pos=(L/2,L/2), motility=RunReverseFlick(), rotational_diffusivity = 0.2, ) for i in 1:nmicrobes ] model = initialise_model(; microbes, timestep = dt, extent, periodic = false, random_positions = false, ) nsteps = 500 adata = [:pos] adf, = run!(model, microbe_step!, nsteps; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' plot( x, y, line_z = (0:nsteps).*dt, legend=false, xlab = "x", ylab = "y", colorbar = true, colorbar_title = "time" ) ``` ![Two-dimensional random walk using run-reverse-flick motility](random_walk_2d.png) Microbes with different motile patterns can also be combined in the same simulation, without extra complications or computational costs: ```julia n = 3 microbes_runtumble = [Microbe{2}(id=i, motility=RunTumble()) for i in 1:n] microbes_runrev = [Microbe{2}(id=n+i, motility=RunReverse()) for i in 1:n] microbes_runrevflick = [Microbe{2}(id=2n+1, motility=RunReverseFlick()) for i in 1:n] microbes = vcat( microbes_runtumble, microbes_runrev, microbes_runrevflick ) ``` ## Chemotaxis in a linear gradient We will now reproduce a classical chemotaxis assay: bacteria in a rectangular channel with a linear attractant gradient. `Bactos.jl` requires three functions to be defined for the built-in chemotaxis models to work: `concentration_field`, `concentration_gradient`, and `concentration_time_derivative`; all three need to take the two arguments `(pos, model)`. First we need to define our concentration field and its gradient (we don't define its time derivative since it will be held constant). We will use a linear gradient in the `x` direction. Here we can define also the gradient analytically, in more complex cases it can be evaluated numerically through the finite difference interface. ```julia concentration_field(x,y,C₀,∇C) = C₀ + ∇C*x function concentration_field(pos, model) x, y = pos C₀ = model.C₀ ∇C = model.∇C concentration_field(x, y, C₀, ∇C) end concentration_gradient(x,y,C₀,∇C) = [∇C, 0.0] function concentration_gradient(pos, model) x, y = pos C₀ = model.C₀ ∇C = model.∇C concentration_gradient(x, y, C₀, ∇C) end ``` We choose the parameters, initialise the population (with two distinct chemotaxers) with all bacteria to the left of the channel, and setup the model providing the functions for our concentration field to the `model_properties` dictionary. ```julia timestep = 0.1 # s Lx, Ly = 1000.0, 500.0 # μm extent = (Lx, Ly) # μm periodic = false n = 50 microbes_brumley = [ Brumley{2}(id=i, pos=(0,rand()*Ly), chemotactic_precision=1) for i in 1:n ] microbes_brown = [ BrownBerg{2}(id=n+i, pos=(0,rand()*Ly)) for i in 1:n ] microbes = [microbes_brumley; microbes_brown] C₀ = 0.0 # μM ∇C = 0.01 # μM/μm model_properties = Dict( :concentration_field => concentration_field, :concentration_gradient => concentration_gradient, :concentration_time_derivative => (_,_) -> 0.0, :compound_diffusivity => 500.0, # μm²/s :C₀ => C₀, :∇C => ∇C, ) model = initialise_model(; microbes, timestep, extent, periodic, model_properties, random_positions = false ) ``` Notice that we also defined an extra property `compound_diffusivity`. This quantity is *required* by the models of chemotaxis that use sensing noise (such as `Brumley`, `XieNoisy`, `CelaniNoisy`). `500 μm²/s` is a typical value for small molecules. We can run the simulation as usual and extract the trajectories. ```julia adata = [:pos] nsteps = 1000 # corresponds to 100s adf, = run!(model, microbe_step!, nsteps; adata) traj = vectorize_adf_measurement(adf, :pos) x = first.(traj)' y = last.(traj)' ``` Comparing the trajectories for the two bacterial species we witness a chemotactic race (`Brumley` in blue, `BrownBerg` in orange). ![Chemotactic race in a linear gradient](lineargradient.gif)
Bactos
https://github.com/mastrof/Bactos.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
540
using Documenter push!(LOAD_PATH, "../../src") using StipplePlotly, StipplePlotly.Charts makedocs( sitename = "StipplePlotly - plotting library for Stipple", format = Documenter.HTML(prettyurls = false), warnonly = true, pages = [ "Home" => "index.md", "StipplePlotly API" => [ "Charts" => "API/charts.md", "Layouts" => "API/layouts.md", "StipplePlotly" => "API/stippleplotly.md", ] ], ) deploydocs( repo = "github.com/GenieFramework/StipplePlotly.jl.git", )
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
2137
module StipplePlotlyPlotlyBaseExt using StipplePlotly using StipplePlotly.Stipple using StipplePlotly.Charts import Stipple.stipple_parse isdefined(Base, :get_extension) ? (using PlotlyBase) : (using ..PlotlyBase) function Base.Dict(p::PlotlyBase.Plot) Dict( :data => p.data, :layout => p.layout, :frames => p.frames, :config => p.config ) end function PlotlyBase.Plot(d::AbstractDict) sd = PlotlyBase._symbol_dict(d) data = haskey(sd, :data) && ! isempty(sd[:data]) ? PlotlyBase.GenericTrace.(sd[:data]) : PlotlyBase.GenericTrace[] layout = haskey(sd, :layout) ? PlotlyBase.Layout(sd[:layout]) : PlotlyBase.Layout() frames = haskey(sd, :frames) && ! isempty(sd[:frames]) ? PlotlyBase.PlotlyFrame.(sd[:frames]) : PlotlyBase.PlotlyFrame[] config = haskey(sd, :config) ? PlotlyBase.PlotConfig(; sd[:config]...) : PlotlyBase.PlotConfig() PlotlyBase.Plot(data, layout, frames; config) end function Stipple.stipple_parse(::Type{PlotlyBase.Plot}, d::AbstractDict) PlotlyBase.Plot(d) end function Stipple.stipple_parse(::Type{Plot{TT, TL, TF}}, d::AbstractDict) where {TT, TL, TF} Plot{TT, TL, TF}( stipple_parse(TT, get(d, "data", get(d, :data, GenericTrace[]))), stipple_parse(TL, get(d, "layout", get(d, :layout, PlotlyBase.Layout()))), stipple_parse(TF, get(d, "frames", get(d, :frames, PlotlyBase.PlotlyFrame[]))), PlotlyBase.uuid4(), stipple_parse(PlotlyBase.PlotConfig, get(d, "config", get(d, :config, PlotlyBase.PlotConfig()))) ) end function Stipple.stipple_parse(::Type{T}, d::AbstractDict) where T <: PlotlyBase.AbstractTrace T === PlotlyBase.AbstractTrace ? GenericTrace(d) : T(d) end function Stipple.stipple_parse(T::Type{PlotlyBase.GenericTrace{D}}, d::AbstractDict) where D <: AbstractDict T(stipple_parse(D, PlotlyBase._symbol_dict(d))) end function Stipple.stipple_parse(::Type{PlotlyBase.Layout}, d::AbstractDict) PlotlyBase.Layout(d) end function Stipple.stipple_parse(::Type{PlotlyBase.Layout{D}}, d::AbstractDict) where D PlotlyBase.Layout(stipple_parse(D, PlotlyBase._symbol_dict(d))) end end
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
39479
module Charts using Genie, Stipple, StipplePlotly using Stipple.Reexport, Stipple.ParsingTools import Stipple: stipple_parse import StipplePlotly._symbol_dict import DataFrames include("Layouts.jl") using .Layouts @reexport using .Layouts:PlotLayoutMapbox, MCenter, GeoProjection, PRotation, PlotLayoutGeo, PlotLayout, PlotAnnotation, ErrorBar, Font, ColorBar, PlotLayoutGrid, PlotLayoutAxis, PlotLayoutTitle, PlotLayoutLegend using .Layouts:optionals! import Genie.Renderer.Html: HTMLString, normal_element, register_normal_element export PlotLayout, PlotData, PlotAnnotation, Trace, plot, ErrorBar, Font, ColorBar, watchplot, watchplots export PlotLayoutGrid, PlotLayoutAxis export PlotConfig, PlotLayoutTitle, PlotLayoutLegend, PlotlyLine, PlotDataMarker export PlotlyEvents, PlotWithEvents, PlotWithEventsReadOnly export plotdata const PLOT_TYPE_LINE = "scatter" const PLOT_TYPE_SCATTER = "scatter" const PLOT_TYPE_SCATTERGL = "scattergl" const PLOT_TYPE_SCATTERGEO = "scattergeo" const PLOT_TYPE_SCATTERMAPBOX = "scattermapbox" const PLOT_TYPE_BAR = "bar" const PLOT_TYPE_PIE = "pie" const PLOT_TYPE_HEATMAP = "heatmap" const PLOT_TYPE_HEATMAPGL = "heatmapgl" const PLOT_TYPE_IMAGE = "image" const PLOT_TYPE_CONTOUR = "contour" const PLOT_TYPE_CHOROPLETH = "choropleth" # const PLOT_TYPE_CHOROPLETHMAPBOX = "choroplethmapbox" const PLOT_TYPE_TABLE = "table" const PLOT_TYPE_BOX = "box" const PLOT_TYPE_VIOLIN = "violin" const PLOT_TYPE_HISTOGRAM = "histogram" const PLOT_TYPE_HISTOGRAM2D = "histogram2d" const PLOT_TYPE_HISTOGRAM2DCONTOUR = "histogram2dcontour" const PLOT_TYPE_OHLC = "ohlc" const PLOT_TYPE_CANDLESTICK = "candlestick" const PLOT_TYPE_WATERFALL = "waterfall" const PLOT_TYPE_FUNNEL = "funnel" const PLOT_TYPE_FUNNELAREA = "funnelarea" const PLOT_TYPE_INDICATOR = "indicator" const PLOT_TYPE_SCATTER3D = "scatter3d" const PLOT_TYPE_SURFACE = "surface" const PLOT_TYPE_MESH3D = "mesh3d" const PLOT_TYPE_CONE = "cone" const PLOT_TYPE_STREAMTUBE = "streamtube" const PLOT_TYPE_VOLUME = "volume" const PLOT_TYPE_ISOSURFACE = "isosurface" const PLOT_TYPE_TIMELINE = "timeline" const DEFAULT_CONFIG_TYPE = Ref{DataType}() const PB_PKGID = Base.PkgId(Base.UUID("a03496cd-edff-5a9b-9e67-9cda94a718b5"), "PlotlyBase") kebapcase(s::String) = lowercase(replace(s, r"([A-Z])" => s"-\1")) kebapcase(s::Symbol) = Symbol(kebapcase(String(s))) register_normal_element("plotly", context = @__MODULE__) function __init__() DEFAULT_CONFIG_TYPE[] = Charts.PlotConfig end function default_config_type() if DEFAULT_CONFIG_TYPE[] == Charts.PlotConfig pkg = get(Base.loaded_modules, PB_PKGID, nothing) if pkg !== nothing DEFAULT_CONFIG_TYPE[] = pkg.PlotConfig end end DEFAULT_CONFIG_TYPE[] end """ function plotly(p::Symbol; layout = Symbol(p, ".layout"), config = Symbol(p, ".config"), configtype = default_config_type(), keepselection = false, kwargs...) This is a convenience function for rendering a PlotlyBase.Plot or a struct with fields data, layout and config # Example ```julia julia> plotly(:plot) "<plotly :data=\"plot.data\" :layout=\"plot.layout\" :config=\"plot.config\"></plotly>" ``` For multiple plots with a common config or layout a typical usage is ```julia julia> plotly(:plot, config = :config) "<plotly :data=\"plot.data\" :layout=\"plot.layout\" :config=\"config\"></plotly>" ``` """ function plotly(p::Symbol, args...; layout = Symbol(p, ".layout"), config = Symbol(p, ".config"), configtype = default_config_type(), keepselection = false, kwargs...) plot("$p.data", args...; layout, config, configtype, keepselection, kwargs...) end """ function watchplot(selector::AbstractString) Generates a js script that forwards plotly events of a DOM element to its respective model fields, e.g. `plot_selected`, `plot_hover`, etc... If no prefix is given, it is taken from the class list which needs to contain at least one entry `'sync_[prefix]'`, e.g `sync_plot`. This function acts on plots that are already present in the UI. It is meant for the rare case of plot-specific event-binding, e.g. in a backend listener. The normal way forwarding plot events is to call `watchplots()` in `js_mounted()`. """ function watchplot(selector::AbstractString) "window.watchPlot(document.querySelector('$selector'), this, $prefix)\n" end function watchplot(selector::AbstractString, prefix) "window.watchGraphDiv(document.querySelector('$selector'), this, $prefix)\n" end """ function watchplot(id::Symbol) Call watchplot with an 'id' instead of a CSS selector string. """ function watchplot(id::Symbol) "window.watchPlot(document.getElementById('$id'), this)\n" end """ function watchplots(model = "this"; observe = true, parentSelector::Union{Nothing, AbstractString} = nothing) Generates a js script that forwards plotly events, e.g. point selection or hovering, to their respective model fields. `model` can be a string, a model or a model type. Dynamically added plots are also covered. The recommended usage is to called it on the mounted event. In that case the model argument can be omitted. `Stipple.js_mounted(::Example) = watchplots()` Plots to be covered by this approach must contain at least one class entry `'sync_[prefix]'`, e.g `sync_plot`. You can use the keyword arguments `syncevents` or `syncprefix` of `plot()` to generate the UI plot nodes: ``` julia> plot("plot.data", syncevents = true) "<plotly :data=\"plot.data\" :layout=\"{}\" class=\"sync_plot\"></plotly>" julia> plot("plot.data", syncprefix = "plot1") "<plotly :data=\"plot.data\" :layout=\"{}\" class=\"sync_plot1\"></plotly>" ``` # Example ```julia @vars Example begin plot::R{Plot} = Plot() plot_selected::R{Dict{String, Any}} = Dict{String, Any}() plot_hover::R{Dict{String, Any}} = Dict{String, Any}() plot1_selected::R{Dict{String, Any}} = Dict{String, Any}() end function ui(model::Example) page(model, class = "container", row(cell(class = "st-module", id = "plotcontainer", [ # syncs plotly events to field plot_selected, plot_hover, etc... plotly(:plot, syncevents = true), # syncs plotly events to field plot1_selected, plot1_hover, etc... plotly(:plot, syncprefix = "plot1", @iif(length(model.plot.data) > 0)), ]))) end Stipple.js_mounted(::Example) = watchplots() function handlers(model) on(model.isready) do isready isready || return push!(model) end on(model.plot_selected) do data haskey(data, "points") && @info "Selection: \$(getindex.(data["points"], "pointIndex"))" end return model end ``` """ function watchplots(model::Union{Symbol, AbstractString} = "this"; observe = true, parentSelector::Union{Nothing, AbstractString} = nothing) """watchPlots($model, $observe, $(isnothing(parentSelector) ? "''" : parentSelector))\n""" end function watchplots(model::Union{M, Type{M}}; observe = true, parentSelector::Union{Nothing, AbstractString} = nothing) where M <: ReactiveModel watchplots(vm(model); observe, parentSelector) end Base.@kwdef mutable struct PlotlyLine # for all Plotly lines: color::Union{String,Nothing} = nothing width::Union{Int,Nothing} = nothing # 2 # Scatter - line: shape::Union{String,Nothing} = nothing # "linear" | "spline" | "hv" | "vh" | "hvh" | "vhv" smoothing::Union{Float64,String,Nothing} = nothing dash::Union{String,Nothing} = nothing # "solid", "dot", "dash", "longdash", "dashdot", "longdashdot" or "5px,10px,2px,2px" simplify::Union{Bool,Nothing} = nothing # Scatter - marker - line: cauto::Union{Bool,Nothing} = nothing cmin::Union{Float64,Nothing} = nothing cmax::Union{Float64,Nothing} = nothing cmid::Union{Float64,Nothing} = nothing colorscale::Union{Matrix,String,Nothing} = nothing autocolorscale::Union{Bool,Nothing} = nothing reversescale::Union{Bool,Nothing} = nothing # Box - marker - line outliercolor::Union{String,Nothing} = nothing outlierwidth::Union{Int,Nothing} = nothing # 1 end function Base.show(io::IO, pdl::PlotlyLine) output = "Layout Legend: \n" for f in fieldnames(typeof(pdl)) prop = getproperty(pdl, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pdl::PlotlyLine) trace = Dict{Symbol, Any}() optionals!(trace, pdl, [:color, :width, :shape, :smoothing, :dash, :simplify, :cauto, :cmin, :cmax, :cmid, :colorscale, :autocolorscale, :reversescale, :outliercolor, :outlierwidth]) end function Stipple.render(pdl::PlotlyLine, fieldname::Union{Symbol,Nothing} = nothing) Dict(pdl) end #===# """ PlotDataMarker() ---------- # Examples ---------- ``` julia> marker = PlotDataMarker( size = [20, 30, 15, 10], color = [10.0, 20.0, 40.0, 50.0], cmin = 0.0, cmax = 50.0, colorscale = "Greens", colorbar = ColorBar(title_text = "Some rate", ticksuffix = "%", showticksuffix = "last"), line = PlotlyLine(color = "black") ) ``` ----------- # Properties ----------- * `autocolorscale::Bool` - Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. Has an effect only if in `marker.color` is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. Default: `true` * `cauto::Bool` - Determines whether or not the color domain is computed with respect to the input data (here in `marker.color`) or the bounds set in `marker.cmin` and `marker.cmax` Has an effect only if in `marker.color` is set to a numerical array. Defaults to `false` when `marker.cmin` and `marker.cmax` are set by the user. * `cmax::Float64,Nothing` - Sets the upper bound of the color domain. Has an effect only if in `marker.color` is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmin` must be set as well. * `cmin::Float64` - Sets the mid-point of the color domain by scaling `marker.cmin` and/or `marker.cmax` to be equidistant to this point. Has an effect only if in `marker.color` is set to a numerical array. Value should have the same units as in `marker.color`. Has no effect when `marker.cauto` is `false`. * `color::Union{String,Vector{Float64}}` - Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. * `coloraxis::String` - Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. * `colorbar::ColorBar` - ColorBar object contains multiple keys. Check correspoing API docs for each key. ex. `ColorBar(title_text = "Some rate", ticksuffix = "%", showticksuffix = "last")` * `colorscale::Union{Matrix,String}` - Sets the colorscale. Has an effect only if in `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. * `line::PlotlyLine` - object contains multiple keys. Check correspoing API docs for each key. ex. `PlotlyLine(color = "black", width = 2)` * `opacity::Union{Float64, Vector{Float64}}` - Sets the marker opacity. Type. number or array of numbers between or equal to 0 and 1 * `reversescale::Bool` - Reverses the color mapping if true. Has an effect only if in `marker.color` is set to a numerical array. If true, `marker.cmin` will correspond to the last color in the array and `marker.cmax` will correspond to the first color. * `showscale::Bool` - Determines whether or not a colorbar is displayed for this trace. Has an effect only if in `marker.color` is set to a numerical array. * `size::Union{Int,Vector{Int}}` - Sets the marker size (in px). * `sizemin::Float64` - Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points. * `sizemode::String` - Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels. * `sizeref::Float64` - Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`. * `symbol::Union{String, Vector{String}}` - Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot-open" to a symbol name. Ex. Default: "circle" """ Base.@kwdef mutable struct PlotDataMarker autocolorscale::Union{Bool,Nothing} = nothing cauto::Union{Bool,Nothing} = nothing cmax::Union{Float64,Nothing} = nothing cmid::Union{Float64,Nothing} = nothing cmin::Union{Float64,Nothing} = nothing # TODO: gradient color::Union{String,Vector{Float64},Nothing} = nothing # color= [2.34, 4.3, 34.5, 52.2] # Specific for Pie charts: colors::Union{Vector{String},Nothing} = nothing coloraxis::Union{String,Nothing} = nothing colorbar::Union{ColorBar,Nothing} = nothing colorscale::Union{Matrix,String,Nothing} = nothing line::Union{PlotlyLine,Nothing} = nothing maxdisplayed::Union{Int,Nothing} = nothing opacity::Union{Float64,Vector{Float64},Nothing} = nothing reversescale::Union{Bool,Nothing} = nothing showscale::Union{Bool,Nothing} = nothing size::Union{Int,Vector{Int},Nothing} = nothing sizemin::Union{Float64,Nothing} = nothing sizemode::Union{String,Nothing} = nothing sizeref::Union{Float64,Nothing} = nothing symbol::Union{String,Vector{String},Nothing} = nothing end function Base.show(io::IO, pdm::PlotDataMarker) output = "Layout Legend: \n" for f in fieldnames(typeof(pdm)) prop = getproperty(pdm, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pdm::PlotDataMarker) trace = Dict{Symbol, Any}() (pdm.line !== nothing) && (trace[:line] = Dict(pdm.line)) (pdm.colorbar !== nothing) && (trace[:colorbar] = Dict(pdm.colorbar)) optionals!(trace, pdm, [ :autocolorscale, :cauto, :cmax, :cmid, :cmin, :color, :colors, :coloraxis, :colorbar, :colorscale, :line, :maxdisplayed, :opacity, :reversescale, :showscale, :size, :sizemin, :sizemode, :sizeref, :symbol]) end function Stipple.render(pdm::PlotDataMarker, fieldname::Union{Symbol,Nothing} = nothing) Dict(pdm) end #===# Base.@kwdef mutable struct PlotData plot::String = PLOT_TYPE_SCATTER align::Union{String,Nothing} = nothing alignmentgroup::Union{String,Nothing} = nothing alphahull::Union{Int,Float64,Nothing} = nothing anchor::Union{String,Nothing} = nothing aspectratio::Union{Float64,Int,Nothing} = nothing autobinx::Union{Bool,Nothing} = nothing autobiny::Union{Bool,Nothing} = nothing autocolorscale::Union{Bool,Nothing} = nothing autocontour::Union{Bool,Nothing} = nothing automargin::Union{Bool,Nothing} = nothing bandwidth::Union{Float64,Int,Nothing} = nothing base::Union{Vector,Float64,Int,String,Nothing} = nothing baseratio::Union{Float64,Int,Nothing} = nothing bingroup::Union{String,Nothing} = nothing box::Union{Dict,Nothing} = nothing boxmean::Union{Bool,String,Nothing} = nothing boxpoints::Union{Bool,String,Nothing} = nothing caps::Union{Dict,Nothing} = nothing cauto::Union{Bool,Nothing} = nothing cells::Union{Dict,Nothing} = nothing cliponaxis::Union{Bool,Nothing} = nothing close::Union{Vector,Nothing} = nothing cmax::Union{Float64,Int,Nothing} = nothing cmid::Union{Float64,Int,Nothing} = nothing cmin::Union{Float64,Int,Nothing} = nothing color::Union{String,Nothing} = nothing coloraxis::Union{String,Nothing} = nothing colorbar::Union{Dict,ColorBar,Nothing} = nothing colorscale::Union{Matrix,String,Nothing} = nothing columnorder::Union{Vector,Nothing} = nothing columnwidth::Union{Float64,Int,Vector,Nothing} = nothing connectgaps::Union{Bool,Nothing} = nothing connector::Union{Dict,Nothing} = nothing constraintext::Union{String,Nothing} = nothing contour::Union{Dict,Nothing} = nothing contours::Union{Dict,Nothing} = nothing cumulative::Union{Dict,Nothing} = nothing customdata::Union{Vector,Nothing} = nothing decreasing::Union{Dict,Nothing} = nothing delaunayaxis::Union{Char,String,Nothing} = nothing delta::Union{Dict,Nothing} = nothing direction::Union{String,Nothing} = nothing dlabel::Union{Int,Nothing} = nothing domain::Union{Dict,Nothing} = nothing dx::Union{Int,Nothing} = nothing dy::Union{Int,Nothing} = nothing error_x::Union{Dict,ErrorBar,Nothing} = nothing error_y::Union{Dict,ErrorBar,Nothing} = nothing error_z::Union{Dict,ErrorBar,Nothing} = nothing facecolor::Union{Vector,Nothing} = nothing fill::Union{String,Nothing} = nothing fillcolor::Union{String,Nothing} = nothing flatshading::Union{Bool,Nothing} = nothing gauge::Union{Dict,Nothing} = nothing geojson::Union{String,Nothing} = nothing groupnorm::Union{String,Nothing} = nothing header::Union{Dict,Nothing} = nothing hidesurface::Union{Bool,Nothing} = nothing high::Union{Vector,Nothing} = nothing histfunc::Union{String,Nothing} = nothing histnorm::Union{String,Nothing} = nothing hole::Union{Float64,Nothing} = nothing hovertext::Union{Vector{String},String,Nothing} = nothing hoverinfo::Union{String,Nothing} = nothing hoverlabel::Union{Dict,Nothing} = nothing hoveron::Union{String,Nothing} = nothing hoverongaps::Union{Bool,Nothing} = nothing hovertemplate::Union{Vector{String},String,Nothing} = nothing i::Union{Vector,Nothing} = nothing intensity::Union{Vector,Nothing} = nothing intensitymode::Union{String,Nothing} = nothing j::Union{Vector,Nothing} = nothing k::Union{Vector,Nothing} = nothing ids::Union{Vector{String},Nothing} = nothing increasing::Union{Dict,Nothing} = nothing insidetextanchor::Union{String,Nothing} = nothing insidetextfont::Union{Font,Nothing} = nothing insidetextorientation::Union{String,Nothing} = nothing isomax::Union{Float64,Int,Nothing} = nothing isomin::Union{Float64,Int,Nothing} = nothing jitter::Union{Float64,Nothing} = nothing labels::Union{Vector,Nothing} = nothing label0::Union{Int,Nothing} = nothing lat::Union{Vector,Nothing} = nothing legendgroup::Union{String,Nothing} = nothing lighting::Union{Dict,Nothing} = nothing lightposition::Union{Dict,Nothing} = nothing line::Union{Dict,PlotlyLine,Nothing} = nothing locations::Union{Vector,Nothing} = nothing locationmode::Union{String,Nothing} = nothing lon::Union{Vector,Nothing} = nothing low::Union{Vector,Nothing} = nothing lowerfence::Union{Vector,Nothing} = nothing marker::Union{Dict,PlotDataMarker,Nothing} = nothing maxdisplayed::Union{Int,Nothing} = nothing mean::Union{Vector,Nothing} = nothing measure::Union{Vector,Nothing} = nothing meanline::Union{Dict,Nothing} = nothing median::Union{Vector,Nothing} = nothing meta::Union{Float64,Int,String,Nothing} = nothing mode::Union{String,Nothing} = nothing name::Union{String,Nothing} = nothing nbinsx::Union{Int,Nothing} = nothing nbinsy::Union{Int,Nothing} = nothing ncontours::Union{Int,Nothing} = nothing notched::Union{Bool,Nothing} = nothing notchwidth::Union{Float64,Nothing} = nothing notchspan::Union{Vector,Nothing} = nothing number::Union{Dict,Nothing} = nothing offset::Union{Float64,Int,Vector,Nothing} = nothing offsetgroup::Union{String,Nothing} = nothing opacity::Union{Float64,Nothing} = nothing opacityscale::Union{Float64,Int,Vector,String,Nothing} = nothing colormodel::Union{String,Nothing} = nothing # image trace color models: "rgb" | "rgba" | "rgba256" | "hsl" | "hsla" open::Union{Vector,Nothing} = nothing orientation::Union{String,Nothing} = nothing outsidetextfont::Union{Font,Nothing} = nothing points::Union{Bool,String,Nothing} = nothing pointpos::Union{Float64,Nothing} = nothing projection::Union{Dict,Nothing} = nothing pull::Union{Float64,Vector,Nothing} = nothing q1::Union{Vector,Nothing} = nothing q3::Union{Vector,Nothing} = nothing quartilemethod::Union{String,Nothing} = nothing reversescale::Union{Bool,Nothing} = nothing rotation::Union{Int,Nothing} = nothing scalegroup::Union{String,Nothing} = nothing scalemode::Union{String,Nothing} = nothing scene::Union{String,Nothing} = nothing sd::Union{Vector,Nothing} = nothing selected::Union{Dict,Nothing} = nothing selectedpoints::Union{Vector{<:Integer},Float64,Int,String,Nothing} = nothing showlegend::Union{Bool,Nothing} = nothing showscale::Union{Bool,Nothing} = nothing side::Union{String,Nothing} = nothing sizemode::Union{String,Nothing} = nothing sizeref::Union{Float64,Int,Nothing} = nothing slices::Union{Dict,Nothing} = nothing sort::Union{Bool,Nothing} = nothing source::Union{String,Nothing} = nothing spaceframe::Union{Dict,Nothing} = nothing span::Union{Vector,Nothing} = nothing spanmode::Union{String,Nothing} = nothing stackgaps::Union{String,Nothing} = nothing stackgroup::Union{String,Nothing} = nothing starts::Union{Dict,Nothing} = nothing surface::Union{Dict,Nothing} = nothing surfaceaxis::Union{Int,String,Nothing} = nothing surfacecolor::Union{String,Nothing} = nothing text::Union{Vector{String},String,Nothing} = nothing textangle::Union{String,Nothing} = nothing textfont::Union{Font,Nothing} = nothing textinfo::Union{String,Nothing} = nothing textposition::Union{String,Nothing} = nothing texttemplate::Union{Vector{String},String,Nothing} = nothing tickwidth::Union{Float64,Nothing} = nothing totals::Union{Dict,Nothing} = nothing transpose::Union{Bool,Nothing} = nothing u::Union{Vector,Nothing} = nothing uirevision::Union{Float64,Int,String,Nothing} = nothing unselected::Union{Dict,Nothing} = nothing upperfence::Union{Vector,Nothing} = nothing v::Union{Vector,Nothing} = nothing values::Union{Vector,Nothing} = nothing vertexcolor::Union{Vector,Nothing} = nothing visible::Union{String,Bool,Nothing} = nothing w::Union{Vector,Nothing} = nothing whiskerwidth::Union{Float64,Nothing} = nothing width::Union{Int,Vector{Int},Nothing} = nothing # x::Union{Vector,Matrix,Nothing} = nothing x::Union{Vector,Nothing} = nothing x_start::Union{Vector,Nothing} = nothing x_end::Union{Vector,Nothing} = nothing x0::Union{Int,String,Nothing} = nothing xaxis::Union{String,Nothing} = nothing xbingroup::Union{String,Nothing} = nothing xbins::Union{Dict,Nothing} = nothing xcalendar::Union{String,Nothing} = nothing xgap::Union{Int,Nothing} = nothing xperiod::Union{Float64,Int,String,Nothing} = nothing xperiodalignment::Union{String,Nothing} = nothing xperiod0::Union{Float64,Int,String,Nothing} = nothing xtype::Union{String,Nothing} = nothing # y::Union{Vector,Matrix,Nothing} = nothing y::Union{Vector,Nothing} = nothing y0::Union{Int,String,Nothing} = nothing yaxis::Union{String,Nothing} = nothing ybingroup::Union{String,Nothing} = nothing ybins::Union{Dict,Nothing} = nothing ycalendar::Union{String,Nothing} = nothing ygap::Union{Int,Nothing} = nothing yperiod::Union{Float64,Int,String,Nothing} = nothing yperiodalignment::Union{String,Nothing} = nothing yperiod0::Union{Float64,Int,String,Nothing} = nothing ytype::Union{String,Nothing} = nothing # z::Union{Vector,Matrix,Nothing} = nothing z::Union{Vector,Nothing} = nothing zauto::Union{Bool,Nothing} = nothing zcalendar::Union{String,Nothing} = nothing zhoverformat::Union{String,Nothing} = nothing zmax::Union{Int,Nothing} = nothing zmid::Union{Int,Nothing} = nothing zmin::Union{Int,Nothing} = nothing zsmooth::Union{String,Nothing} = nothing end const CONFIG_MAPPINGS = Dict( :scrollzoom => :scrollZoom, :staticplot => :staticPlot, :displaymodebar => :displayModeBar, :showlink => :showLink, ) const CONFIG_DEFAULTS = Dict{Symbol, Any}( :scrollZoom => false, :staticPlot => false, :showLink => false, :editable => false, :responsive => true, :displayModeBar => true, :modeBarButtonsToRemove => String[], :modeBarButtonsToAdd => String[], :toImageButtonOptions => Dict( :format => "png", :filename => "newplot", :height => 500, :width => 700, :scale => 1, ) ) const PARSER_MAPPINGS = Dict( :type => :plot ) const Trace = PlotData function plotdata(data::DataFrames.DataFrame, xfeature::Symbol, yfeature::Symbol; groupfeature::Symbol, text::Union{Vector{String}, Nothing} = nothing, mode = "markers", plottype = StipplePlotly.Charts.PLOT_TYPE_SCATTER, kwargs...) :: Vector{PlotData} plot_collection = Vector{PlotData}() for gf in Array(data[:, groupfeature]) |> unique! x_feature_collection, y_feature_collection = Vector{Float64}(), Vector{Float64}() text_collection = Vector{String}() group_indices = data[!, groupfeature] .== gf grouptext = text isa Vector{String} ? text[group_indices] : nothing for (index,r) in enumerate(eachrow(data[group_indices, :])) push!(x_feature_collection, (r[xfeature])) push!(y_feature_collection, (r[yfeature])) text isa Vector{String} ? push!(text_collection, (grouptext[index])) : nothing end plot = PlotData(; x = x_feature_collection, y = y_feature_collection, mode = mode, name = string(gf), plot = plottype, text = isnothing(text) ? text : text_collection, kwargs...) push!(plot_collection, plot) end plot_collection end function Base.show(io::IO, pd::PlotData) output = "$(pd.plot): \n" for f in fieldnames(typeof(pd)) prop = getproperty(pd, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pd::PlotData) trace = Dict{Symbol,Any}( :type => pd.plot ) if pd.textfont !== nothing trace[:textfont] = Dict( :family => pd.textfont.family, :size => pd.textfont.size, :color => pd.textfont.color ) end if pd.insidetextfont !== nothing trace[:insidetextfont] = Dict( :family => pd.insidetextfont.family, :size => pd.insidetextfont.size, :color => pd.insidetextfont.color ) end if pd.outsidetextfont !== nothing trace[:outsidetextfont] = Dict( :family => pd.outsidetextfont.family, :size => pd.outsidetextfont.size, :color => pd.outsidetextfont.color ) end (pd.line !== nothing) && (trace[:line] = Dict(pd.line)) (pd.marker !== nothing) && (trace[:marker] = Dict(pd.marker)) (pd.error_x !== nothing) && (trace[:error_x] = Dict(pd.error_x)) (pd.error_y !== nothing) && (trace[:error_y] = Dict(pd.error_y)) (pd.error_z !== nothing) && (trace[:error_z] = Dict(pd.error_z)) (pd.colorbar !== nothing) && (trace[:colorbar] = Dict(pd.colorbar)) optionals!(trace, pd, [:align, :alignmentgroup, :alphahull, :anchor, :aspectratio, :autobinx, :autobiny, :autocolorscale, :autocontour, :automargin, :bandwidth, :base, :baseratio, :bingroup, :box, :boxmean, :boxpoints, :cauto, :cells, :cliponaxis, :close, :color, :cmax, :cmid, :cmin, :coloraxis, :colorscale, :columnorder, :columnwidth, :connectgaps, :connector, :constraintext, :contour, :contours, :cumulative, :customdata, :decreasing, :delta, :delaunayaxis, :direction, :dlabel, :domain, :dx, :dy, :facecolor, :fill, :fillcolor, :flatshading, :gauge, :groupnorm, :header, :hidesurface, :high, :histfunc, :histnorm, :hole, :hovertext, :hoverinfo, :hovertemplate, :hoverlabel, :hoveron, :hoverongaps, :i, :intensity, :intensitymode, :ids, :increasing, :insidetextanchor, :insidetextorientation, :isomax, :isomin, :j, :jitter, :k, :labels, :label0, :legendgroup, :lighting, :lightposition, :low, :lowerfence, :maxdisplayed, :meanline, :measure, :median, :meta, :mode, :name, :nbinsx, :nbinsy, :ncontours, :notched, :notchwidth, :notchspan, :number, :offset, :offsetgroup, :opacity, :opacityscale, :colormodel, :open, :orientation, :points, :pointpos, :projection, :pull, :q1, :q3, :quartilemethod, :reversescale, :rotation, :scalegroup, :scalemode, :scene, :sd, :selected, :selectedpoints, :showlegend, :showscale, :side, :sizemode, :sizeref, :slices, :sort, :source, :spaceframe, :span, :spanmode, :stackgaps, :stackgroup, :starts, :surface, :surfaceaxis, :surfacecolor, :text, :textangle, :textinfo, :textposition, :texttemplate, :tickwidth, :totals, :transpose, :uirevision, :upperfence, :unselected, :values, :vertexcolor, :visible, :whiskerwidth, :width, :x, :x_start, :x_end, :x0, :xaxis, :xbingroup, :xbins, :xcalendar, :xgap, :xperiod, :xperiodalignment, :xperiod0, :xtype, :y, :y0, :yaxis, :ybingroup, :ybins, :ycalendar, :ygap, :yperiod, :yperiodalignment, :yperiod0, :ytype, :z, :zauto, :zcalendar, :zhoverformat, :zmax, :zmid, :zmin, :zsmooth, :geojson, :lat, :locations, :lon, :locationmode]) end function Stipple.render(pd::PlotData, fieldname::Union{Symbol,Nothing} = nothing) [Dict(pd)] end function Stipple.render(pdv::Vector{PlotData}, fieldname::Union{Symbol,Nothing} = nothing) [Dict(pd) for pd in pdv] end function Stipple.render(pdvv::Vector{Vector{PlotData}}, fieldname::Union{Symbol,Nothing} = nothing) [[Dict(pd) for pd in pdv] for pdv in pdvv] end # ============= # Reference: https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js?package=plotly&version=3.6.0 Base.@kwdef mutable struct PlotConfig responsive::Union{Bool,Nothing} = nothing # default: false editable::Union{Bool,Nothing} = nothing # default: false scrollzoom::Union{Bool,String,Nothing} = nothing # ['cartesian', 'gl3d', 'geo', 'mapbox'], [true, false]; default: gl3d+geo+mapbox' staticplot::Union{Bool,Nothing} = nothing # default: false displaymodebar::Union{Bool,String,Nothing} = nothing # ['hover', true, false], default: "hover" displaylogo::Union{Bool,Nothing} = false # default: true toimage_format::Union{String,Nothing} = nothing # one of ["png", "svg", "jpeg", "webp"] toimage_filename::Union{String,Nothing} = nothing # "newplot" toimage_height::Union{Int,Nothing} = nothing # 500 toimage_width::Union{Int,Nothing} = nothing # 700 toimage_scale::Union{Int,Float64,Nothing} = nothing # 1 end function Base.show(io::IO, pc::PlotConfig) output = "configuration: \n" for f in fieldnames(typeof(pc)) prop = getproperty(pc, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pc::PlotConfig) trace = Dict{Symbol, Any}() if (pc.toimage_format in ["png", "svg", "jpeg", "webp"]) d = Dict{Symbol, Any}(:format => pc.toimage_format) d[:filename] = (pc.toimage_filename === nothing) ? "newplot" : pc.toimage_filename d[:height] = (pc.toimage_height === nothing) ? 500 : pc.toimage_height d[:width] = (pc.toimage_width === nothing) ? 700 : pc.toimage_width d[:scale] = (pc.toimage_scale === nothing) ? 1 : pc.toimage_scale trace[:toImageButtonOptions] = d end optionals!(trace, pc, [:responsive, :editable, :scrollzoom, :staticplot, :displaymodebar, :displaylogo]) Dict{Symbol, Any}(replace(collect(keys(trace)), CONFIG_MAPPINGS...) .=> values(trace)) end function Stipple.render(pc::PlotConfig, fieldname::Union{Symbol,Nothing} = nothing) Dict(pc) end # ============= function jsonrender(x) replace(json(render(x)), "'" => raw"\'", '"' => ''') end """ plot(data::Union{Symbol,AbstractString}, args...; layout::Union{Symbol,AbstractString,LayoutType} = Charts.PlotLayout(), config::Union{Symbol,AbstractString,Nothing,ConfigType} = nothing, configtype = Charts.PlotConfig, syncevents::Bool = false, syncprefix = "", class = "", keepselection::Bool = false, kwargs...) :: String where {LayoutType, ConfigType} Generate a plotly plot with the given data and arguments. Parameters: - `data::Union{Symbol,AbstractString}`: name of the field that holds the plot data - `layout::Union{Symbol,AbstractString,LayoutType}`: The layout of the plot. Default: `Charts.PlotLayout()` - `config::Union{Symbol,AbstractString,Nothing,ConfigType}`: The configuration of the plot. Default: `nothing` - `configtype::ConfigType`: The type of the configuration. Default: `Charts.PlotConfig` - `syncevents::Bool`: Whether to sync events. Default: `false` - `syncprefix::String`: Syncing is controlled via the class attribute of the plot. If left empty, the class is derived from the data name. - `class::String`: additional class attribute for the plot - `args`: further custom arguments - `kwargs`: further custom keyword arguments Forwarding plotly events is achieved by setting `syncevents` to `true` or by providing a `syncprefix`. Model fields that the events are forwarded to are derived from the `syncprefix` and the event type, e.g. `syncprefix = "myplot"` will forward the `plotly_selected` event to the `myplot_selected` model field. The most common event types are `plotly_selected`, `plotly_hover`, `plotly_click`, and `plotly_relayout`, which can be included in the model via `@mixin myplot::PBPlotWithEvents`. An example of event forwarding can be found in the docstring of StipplePlotly. """ function plot(data::Union{Symbol,AbstractString}, args...; layout::Union{Symbol,AbstractString,LayoutType} = Charts.PlotLayout(), config::Union{Symbol,AbstractString,Nothing,ConfigType} = nothing, configtype = Charts.PlotConfig, keepselection::Bool = false, syncevents::Bool = false, syncprefix = "", class = "", kwargs...) :: String where {LayoutType, ConfigType} plotlayout = if layout isa AbstractString Symbol(layout) elseif layout isa Symbol layout else Symbol(jsonrender(layout)) end plotconfig = if config isa AbstractString Symbol(config) elseif config isa Symbol config else # clean dict and default displaylogo to false plotconfig = render(isnothing(config) ? configtype() : config) if plotconfig isa AbstractDict filter!(x -> x[2] ∉ (:null, nothing), plotconfig) plotconfig = LittleDict{Symbol, Any}(replace(keys(plotconfig), CONFIG_MAPPINGS...) .=> values(plotconfig)) haskey(plotconfig, :displaylogo) || push!(plotconfig, :displaylogo => false) plotconfig = js_attr(plotconfig) elseif hasproperty(plotconfig, :displaylogo) && plotconfig.displaylogo === nothing plotconfig.displaylogo = false end plotconfig end if syncevents || ! isempty(syncprefix) if isempty(syncprefix) datastr = String(data) syncprefix = endswith(datastr, "data") && length(datastr) > 4 ? datastr[1:end-4] : datastr syncprefix = join(split(syncprefix, ['_', '.'])[1:end-1], '_') end class = isempty(class) ? "sync_$syncprefix" : "sync_$syncprefix $class" end sync = Pair{Symbol, String}[] isempty(class) || push!(sync, :class => class) plotly("", args...; Stipple.attributes([:layout => plotlayout, :data => Symbol(data), :config => plotconfig, :keepselection => keepselection, kwargs..., sync...])...) end Base.print(io::IO, a::Union{PlotLayout, PlotConfig}) = print(io, Stipple.json(a)) # ============= const PlotlyEvent = Dict{String, Any} Base.@kwdef struct PlotlyEvents _selected::R{PlotlyEvent} = PlotlyEvent() _hover::R{PlotlyEvent} = PlotlyEvent() _click::R{PlotlyEvent} = PlotlyEvent() _relayout::R{PlotlyEvent} = PlotlyEvent() end Base.@kwdef struct PlotWithEvents _data::R{Vector{PlotData}} = PlotData[] _layout::R{PlotLayout} = PlotLayout() _selected::R{PlotlyEvent} = PlotlyEvent() _hover::R{PlotlyEvent} = PlotlyEvent() _click::R{PlotlyEvent} = PlotlyEvent() _relayout::R{PlotlyEvent} = PlotlyEvent() end Base.@kwdef struct PlotWithEventsReadOnly _data::R{Vector{PlotData}} = PlotData[], READONLY _layout::R{PlotLayout} = PlotLayout() _selected::R{PlotlyEvent} = PlotlyEvent() _hover::R{PlotlyEvent} = PlotlyEvent() _click::R{PlotlyEvent} = PlotlyEvent() _relayout::R{PlotlyEvent} = PlotlyEvent() end # #===# # Parsers function stipple_parse(::Type{PlotData}, d::Dict{String, Any}) sd = symbol_dict(d) haskey(sd, :text) && (sd[:text] isa String || (sd[:text] = Vector{String}(sd[:text]))) haskey(sd, :selectedpoints) && (sd[:selectedpoints] = [sd[:selectedpoints]...]) sd = Dict{Symbol, Any}(replace(collect(keys(sd)), PARSER_MAPPINGS...) .=> values(sd)) # PlotData(;sd...) typify(PlotData, sd) end function stipple_parse(::Type{Vector{<:PlotData}}, dd::Vector) PlotData[stipple_parse(PlotData, d) for d in dd] end function stipple_parse(::Type{T}, d::Dict{Symbol, Any}) where T <: Union{Font, PlotLayout, PlotLayoutAxis, PlotLayoutGeo, PlotLayoutGrid, PlotLayoutLegend, PlotLayoutMapbox, PlotLayoutTitle} typify(T, d) end function stipple_parse(::Type{T}, d::Dict{String, Any}) where T <: Union{Font, PlotLayoutAxis, PlotLayoutGeo, PlotLayoutGrid, PlotLayoutLegend, PlotLayoutMapbox, PlotLayoutTitle} stipple_parse(T, symbol_dict(d)) end function stipple_parse(::Type{PlotLayout}, d::Dict{String, Any}) d = symbol_dict(d) haskey(d, :title) && (d[:title] = d[:title] isa String ? PlotLayoutTitle(; text = d[a][:title]) : PlotLayoutTitle(; d[a][:title]...)) haskey(d, :xaxis) && (d[:xaxis] = [stipple_parse(PlotLayoutAxis, d[:xaxis])]) kk = collect(keys(d)) axes = kk[startswith.(string.(kk), r"xaxis\d")] for a in axes push!(get!(Dict{Symbol, Any}, d, :xaxis), PlotLayoutAxis(; d[a]...)) delete!(d, a) end axes = kk[startswith.(string.(kk), r"yaxis\d")] for a in axes push!(get!(Dict{Symbol, Any}, d, :xaxis), PlotLayoutAxis(; d[a]...)) end stipple_parse(PlotLayout, d) end # enhance precompilation #= pl = PlotLayout( xaxis = [ PlotLayoutAxis(index = 1, title = "1"), PlotLayoutAxis(xy = "x", index = 2, title = "2") ], margin_r = 10, margin_t = 20 ) d = JSON3.read(json(render(pl)), Dict{String, Any}) stipple_parse(PlotLayout, d) =# end
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
90517
module Layouts using Genie, Stipple, StipplePlotly import Genie.Renderer.Html: HTMLString, normal_element, register_normal_element using Requires const LAYOUT_TITLE_REF_CONTAINER = "container" const LAYOUT_TITLE_REF_PAPER = "paper" const LAYOUT_AUTO = "auto" const LAYOUT_LEFT = "left" const LAYOUT_CENTER = "center" const LAYOUT_RIGHT = "right" const LAYOUT_TOP = "top" const LAYOUT_MIDDLE = "middle" const LAYOUT_BOTTOM = "bottom" const LAYOUT_ORIENTATION_VERTICAL = "v" const LAYOUT_ORIENTATION_HORIZONTAL = "h" const LAYOUT_ITEMSIZING_TRACE = "trace" const LAYOUT_ITEMSIZING_CONSTANT = "constant" const LAYOUT_CLICK_TOGGLE = "toggle" const LAYOUT_CLICK_TOGGLEOTHERS = "toggleothers" const LAYOUT_HIDE = "hide" const LAYOUT_SHOW = "show" const LAYOUT_ABOVE = "above" const LAYOUT_BELOW = "below" const LAYOUT_OVERLAY = "overlay" const LAYOUT_GROUP = "group" const LAYOUT_STACK = "stack" function optionals!(d::Dict, ptype::Any, opts::Vector{Symbol}) :: Dict for o in opts if getproperty(ptype, o) !== nothing d[o] = getproperty(ptype, o) end end d end #===# Base.@kwdef mutable struct Font family::String = raw"'Open Sans', verdana, arial, sans-serif" size::Union{Int,Float64} = 12 color::String = "#444" end function Font(fontsize::Union{Int,Float64}) fs = Font() fs.size = fontsize return fs end Base.:(==)(x::Font, y::Font) = x.family == y.family && x.size == y.size && x.color == y.color Base.hash(f::Font) = hash("$(f.family)$(f.size)$(f.color)") Base.@kwdef mutable struct Protation lon::Union{Float64, Int64} = -234 lat::Union{Float64, Int64} = -234 roll::Union{Float64, Int64} = -234 end function PRotation(lon::Union{Float64, Int64}, lat::Union{Float64, Int64}, roll::Union{Float64, Int64}) pr = Protation() pr.lon = lon pr.lat = lat pr.roll = roll return pr end """ Mcenter() ----------- # Properties ----------- * `lat::Union{Float64, Int64}` - Sets the latitude of the map's center. For all projection types, the map's latitude center lies at the middle of the latitude range by default. * `lon::Union{Float64, Int64}` - Sets the longitude of the map's center. By default, the map's longitude center lies at the middle of the longitude range for scoped projection and above `projection.rotation.lon` otherwise. """ Base.@kwdef mutable struct Mcenter lon::Union{Float64, Int64} = -234 lat::Union{Float64, Int64} = -234 end function MCenter(lon::Union{Float64, Int64}, lat::Union{Float64, Int64}) mc = Mcenter() mc.lon = lon mc.lat = lat return mc end #===# """ ColorBar() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `bgcolor::String` - Sets the color of padded area. * `bordercolor::String` - Sets the axis line color. Default = `"#444"` * `borderwidth::Int` - Sets the width (in px) or the border enclosing this color bar. Default = `0` * `dtick::Union{Float64,Int,String}` - Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n"dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" * `exponentformat::String` - Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. Default - `"B"` * `len::Union{Float64,Int}` - Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. * `lenmode::String` - Determines whether the length of the color bar is set in units of plot "fraction" or in "pixels". Use `len` to set the value. * `minexponent::Int` - Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". Default - `0` * `nticks::Int` - Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". Default - `0` * `outlinecolor::String` - Sets the axis line color. * `outlinewidth::Int` - Sets the width (in px) of the axis line. * `separatethousands::Bool` - If "true", even 4-digit integers are separated * `showexponent::Bool` - If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. * `showticklabels::Bool` - Determines whether or not the tick labels are drawn. * `showtickprefix::Bool` - If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. * `showticksuffix::Bool` - Same as `showtickprefix` but for tick suffixes. * `thickness::Int` - Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. * `thicknessmode::String` - Determines whether the thickness of the color bar is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. * `tick0::Union{Float64,Int,String}` - Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info), where the axis starts at zero. If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. * `tickangle::Union{String,Int,Float64}` - Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. * `tickcolor::String` - Sets the tick color. * `tickformat::String` - Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, "2016-10-13 09:15:23.456" with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" * `tickformatstops::Dict` - Array of object where each object has one or more of the keys - "dtickrange", "value", "enabled", "name", "templateitemname" * `ticklabeloverflow::String` - Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is "hide past domain". In other cases the default is "hide past div". * `ticklabelposition::String` - Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". Type: enumerated , one of ( "outside" | "inside" | "outside top" | "inside top" | "outside left" | "inside left" | "outside right" | "inside right" | "outside bottom" | "inside bottom" ) Default: "outside" * `ticklabelstep::String` - Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". * `ticklen::Int` - Sets the tick length (in px). Type: number greater than or equal to 0 | Default: 5 * `tickmode::String` - Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). Type: enumerated , one of ( "auto" | "linear" | "array" ) Default: "array" * `tickprefix::String` - Sets a tick label prefix. Type: string Default: "" * `ticks::String` - Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. Type: enumerated , one of ( "outside" | "inside" | "" ) Default: "" * `ticksuffix::String` - Sets a tick label suffix. Type: string Default: "" * `ticktext::Vector{String}` - Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. Type: vector of strings * `tickvals::Vector{Float64}` - Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Type: vector of numbers * `tickwidth::Int` - Sets the tick width (in px). Type: number greater than or equal to 0 | Default: 1 * `title_font::Font` - Sets this color bar's title font. * `title_side::String` - Determines the location of the colorbar title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". * `title_text::String` - Sets the title of the color bar. * `x::Float64` - Sets the x position of the color bar (in plot fraction). Defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". Type: number between or equal to -2 and 3 * `xanchor::String` - Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". Type: enumerated , one of ( "auto" | "left" | "center" | "right" ) * `xpad::Int` - Sets the amount of padding (in px) along the x direction. Type: number greater than or equal to 0 | Default: 0 * `y::Float64` - Sets the y position of the color bar (in plot fraction). Defaults to 0.98 when `orientation` is "v" and 0.5 when `orientation` is "h". Type: number between or equal to -2 and 3 * `yanchor::String` - Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". Type: enumerated , one of ("top" | "middle" | "bottom" ) * `ypad::Int` - Sets the amount of padding (in px) along the y direction. Type: number greater than or equal to 0 | Default: 10 """ Base.@kwdef mutable struct ColorBar bgcolor::Union{String,Nothing} = nothing # "rgba(0,0,0,0)" bordercolor::Union{String,Nothing} = nothing # "#444" borderwidth::Union{Int,Nothing} = nothing # 0 dtick::Union{Float64,Int,String,Nothing} = nothing exponentformat::Union{String,Nothing} = nothing # none" | "e" | "E" | "power" | "SI" | "B", default is B len::Union{Float64,Int,Nothing} = nothing # number greater than or equal to 0 lenmode::Union{String,Nothing} = nothing # "fraction" | "pixels", default is fraction | Default: "fraction" minexponent::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 3 nticks::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 0 orientation::Union{String,Nothing} = nothing # "v" | "h", default is "v" outlinecolor::Union{String,Nothing} = nothing # "#444" outlinewidth::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 1 separatethousands::Union{Bool,Nothing} = nothing # true | false, default is false showexponent::Union{String,Nothing} = nothing # "all" | "first" | "last" | "none", default is "all" showticklabels::Union{Bool,Nothing} = nothing # true | false, default is true showtickprefix::Union{String,Nothing} = nothing # "all" | "first" | "last" | "none", default is all showticksuffix::Union{String,Nothing} = nothing # "all" | "first" | "last" | "none", default is "all" thickness::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 30 thicknessmode::Union{String,Nothing} = nothing # "fraction" | "pixels", default is fraction | Default: "pixels" tick0::Union{Float64,Int,String,Nothing} = nothing # number or categorical coordinate string tickangle::Union{String,Int,Float64,Nothing} = nothing # Default: "auto" tickcolor::Union{String,Nothing} = nothing # Default: "#444" tickfont::Union{Font,Nothing} = nothing # Font Struct tickformat::Union{String,Nothing} = nothing # string, default is "" tickformatstops::Union{Dict,Nothing} = nothing # Dict containing properties ticklabeloverflow::Union{String,Nothing} = nothing # "allow" | "hide past div" | "hide past domain" ticklabelposition::Union{String,Nothing} = nothing # "outside" | "inside" | "outside top" | "inside top" | "outside bottom" | "inside bottom", default is "outside" ticklabelstep::Union{Int,Nothing} = nothing # number greater than or equal to 1 | Default: 1 ticklen::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 5 tickmode::Union{String,Nothing} = nothing # "auto" | "linear" | "array", default is "array" tickprefix::Union{String,Nothing} = nothing # string, default is "" ticks::Union{String,Nothing} = nothing # "outside" | "inside" | "" | Default: "" ticksuffix::Union{String,Nothing} = nothing # string, default is "" ticktext::Union{Vector{String},Nothing} = nothing # Vector of strings tickvals::Union{Vector{Float64},Vector{Int},Nothing} = nothing tickwidth::Union{Int,Nothing} = nothing # number greater than or equal to 0 | Default: 1 x::Union{Float64,Nothing} = nothing # 1.02 xanchor::Union{String,Nothing} = nothing # "left" | "center" | "right", default is left xpad::Union{Int,Nothing} = nothing # 10 yanchor::Union{String,Nothing} = nothing # "top" | "middle" | "bottom", default is middle ypad::Union{Int,Nothing} = nothing # 10 # needs special treatment: title_font::Union{Font,Nothing} = nothing # Font() title_side::Union{String,Nothing} = nothing # LAYOUT_LEFT title_text::Union{String,Nothing} = nothing # "" end function Base.show(io::IO, cb::ColorBar) output = "ColorBar: \n" for f in fieldnames(typeof(cb)) prop = getproperty(cb, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(cb::ColorBar) trace = Dict{Symbol, Any}() d = Dict{Symbol, Any}() (cb.title_text !== nothing) && (d[:text] = cb.title_text) (cb.title_font !== nothing) && (d[:font] = cb.title_font) (cb.title_side !== nothing) && (d[:side] = cb.title_side) (length(d) > 0) && (trace[:title] = d) optionals!(trace, cb, [ :bgcolor, :bordercolor, :borderwidth, :dtick, :exponentformat, :len, :lenmode, :minexponent, :nticks, :orientation, :outlinecolor, :outlinewidth, :separatethousands, :showexponent, :showticklabels, :showtickprefix, :showticksuffix, :thickness, :thicknessmode, :tick0, :tickangle, :tickcolor, :tickfont, :tickformat, :tickformatstops, :ticklabeloverflow, :ticklabelposition, :ticklabelstep, :ticklen, :tickmode, :tickprefix, :ticks, :ticksuffix, :ticktext, :tickvals, :tickwidth, :x, :xanchor, :xpad, :yanchor, :ypad ]) end function Stipple.render(cb::ColorBar, fieldname::Union{Symbol,Nothing} = nothing) Dict(cb) end function ColorBar(text, title_font_size::Union{Int,Float64}, side) cb = ColorBar() cb.title_text = text cb.title_font = Font(title_font_size) cb.title_side = side cb end #===# """ ErrorBar() ---------- # Examples ---------- ``` julia> error_x = ErrorBar( array = [1.2, 2.6, 3.1], type = "data" ) ``` ----------- # Properties ----------- * `array::Vector{Float64}` - Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. * `arrayminus::Vector{Float64}` - Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. * `color::String` - Sets the stoke color of the error bars. * `symmetric::Bool` - Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. * `thickness::Int` - Sets the thickness (in px) of the error bars. Type: greater than or equal to 0. Default: 2 * `traceref::Int` - Type: Integer greater than or equal to 0. Default: 0 * `tracerefminus::Int` - Type: Integer greater than or equal to 0. Default: 0 * `type::String` - Determines the rule used to generate the error bars. If "constant`, the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the square of the underlying data. If "data", the bar lengths are set with data set `array`. Type: enumerated , one of ( "percent" | "constant" | "sqrt" | "data" ) * `value::Float64` - Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") in the case of "constant" `type`. Type: greater than or equal to 0. Default: 10 * `valueminus::Float64` - Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars. Type: number greater than or equal to 0 | Default: 10 * `visible::Bool` - Determines whether or not this set of error bars is visible. * `width::Int` - Sets the width (in px) of the cross-bar at both ends of the error bars. Type: greater than or equal to 0 """ Base.@kwdef mutable struct ErrorBar array::Union{Vector{Float64},Nothing} = nothing # Vector of numbers arrayminus::Union{Vector{Float64},Nothing} = nothing # Vector of numbers color::Union{String,Nothing} = nothing # Color string copy_ystyle::Union{Bool,Nothing} = nothing # true | false symmetric::Union{Bool,Nothing} = nothing thickness::Union{Int,Nothing} = nothing # 2 traceref::Union{Int,Nothing} = nothing # 0 tracerefminus::Union{Int,Nothing} = nothing # 0 type::Union{String,Nothing} = nothing # "percent" | "constant" | "sqrt" | "data" value::Union{Float64,Nothing} = nothing # 10 valueminus::Union{Float64,Nothing} = nothing # 10 visible::Union{Bool,Nothing} = nothing width::Union{Int,Nothing} = nothing # 0 end function Base.show(io::IO, eb::ErrorBar) output = "Errorbar: \n" for f in fieldnames(typeof(eb)) prop = getproperty(eb, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function ErrorBar(error_array::Vector; color::Union{String,Nothing} = nothing) eb = ErrorBar(visible=true, array=error_array, type="data", symmetric=true) (color !== nothing) && (eb.color = color) eb end function ErrorBar(error_array::Vector, error_arrayminus::Vector; color::Union{String,Nothing} = nothing) eb = ErrorBar(visible=true, array=error_array, type="data", symmetric=false, arrayminus=error_arrayminus) (color !== nothing) && (eb.color = color) eb end function ErrorBar(error_value::Number; color::Union{String,Nothing} = nothing) eb = ErrorBar(visible=true, value=error_value, type="percent", symmetric=true) (color !== nothing) && (eb.color = color) eb end function ErrorBar(error_value::Number, error_valueminus::Number; color::Union{String,Nothing} = nothing) eb = ErrorBar(visible=true, value=error_value, type="percent", symmetric=false, valueminus=error_valueminus) (color !== nothing) && (eb.color = color) eb end function Base.Dict(eb::ErrorBar) trace = Dict{Symbol, Any}() optionals!(trace, eb, [ :array, :arrayminus, :color, :copy_ystyle, :symmetric, :thickness, :traceref, :tracerefminus, :type, :value, :valueminus, :visible, :width ]) end function Stipple.render(eb::ErrorBar, fieldname::Union{Symbol,Nothing} = nothing) Dict(eb) end #===# """ PlotAnnotation() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `align::String` -Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. Type: enumerated , one of ( `"left"` | `"center"` | `"right"` ) | Default: `"center"` * `arrowcolor::String` -Sets the color of the annotation arrow. * `arrowhead::Int` - Sets the end annotation arrow head style. Type: integer between or equal to `0` and `8` | Default: `1` * `arrowside::String` - Sets the annotation arrow head position. Type: flaglist string. Any combination of `"end"`, `"start"` joined with a `"+"` OR `"none"` | Default: `"end"` * `arrowsize::Float64` - Sets the size of the end annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line. Type: number greater than or equal to `0.3` | Default: `1` * `arrowwidth::Float64` - Sets the width (in px) of annotation arrow line. Type: number greater than or equal to `0.1` * `ax::Union{String,Int,Float64}` - Sets the x component of the arrow tail about the arrow head. If `axref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from right to left (left to right). If `axref` is not `pixel` and is exactly the same as `xref`, this is an absolute value on that axis, like `x`, specified in the same coordinates as `xref`. Type: number or categorical coordinate string * `axref::String` - Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a ax axis id (e.g. "ax" or "ax2"), the `ax` position refers to a ax coordinate. If set to "paper", the `ax` position refers to the distance from the left of the plotting area in normalized coordinates where "0" ("1") corresponds to the left (right). If set to a ax axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., "ax2 domain" refers to the domain of the second ax axis and a ax position of 0.5 refers to the point between the left and the right of the domain of the second ax axis. In order for absolute positioning of the arrow to work, "axref" must be exactly the same as "xref", otherwise "axref" will revert to "pixel" (explained next). For relative positioning, "axref" can be set to "pixel", in which case the "ax" value is specified in pixels relative to "x". Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point. Type: enumerated , one of ( `"pixel"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"`) | Default: `"pixel"` * `ay::Union{String,Int,Float64}` - Sets the y component of the arrow tail about the arrow head. If `ayref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from bottom to top (top to bottom). If `ayref` is not `pixel` and is exactly the same as `yref`, this is an absolute value on that axis, like `y`, specified in the same coordinates as `yref`. Type: number or categorical coordinate string * `ayref::String` - Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a ay axis id (e.g. "ay" or "ay2"), the `ay` position refers to a ay coordinate. If set to "paper", the `ay` position refers to the distance from the bottom of the plotting area in normalized coordinates where "0" ("1") corresponds to the bottom (top). If set to a ay axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., "ay2 domain" refers to the domain of the second ay axis and a ay position of 0.5 refers to the point between the bottom and the top of the domain of the second ay axis. In order for absolute positioning of the arrow to work, "ayref" must be exactly the same as "yref", otherwise "ayref" will revert to "pixel" (explained next). For relative positioning, "ayref" can be set to "pixel", in which case the "ay" value is specified in pixels relative to "y". Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point. Type: enumerated , one of ( `"pixel"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"`) | Default: `"pixel"` * `bgcolor::String` -Sets the background color of the annotation. Default: `"rgba(0,0,0,0)"` * `bordercolor::String` - Sets the color of the border enclosing the annotation `text`. Default: `"rgba(0,0,0,0)"` * `borderpad::Int` - Sets the padding (in px) between the `text` and the enclosing border. Default: `1` * `borderwidth::Int` - Sets the width (in px) of the border enclosing the annotation `text`. Type: number greater than or equal to 0 | Default: `1` * `captureevents::Bool` - Determines whether the annotation text box captures mouse move and click events, or allows those events to pass through to data points in the plot that may be behind the annotation. By default `captureevents` is "false" unless `hovertext` is provided. If you use the event `plotly_clickannotation` without `hovertext` you must explicitly enable `captureevents`. * `font::Font` - Sets the annotation text font. * `height::Int` - Sets an explicit height for the text box. null (default) lets the text set the box height. Taller text will be clipped. Type: number greater than or equal to `1` * `hoverlabel::Dict` - object containing one or more of the keys listed: `bgcolor` `bordercolor` `font` * `name::String` - When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. * `opacity::Float64` - Sets the opacity of the annotation (text + arrow). Type: number between or equal to `0` and `1` | Default: `1` * `showarrow::Bool` - Determines whether or not the annotation is drawn with an arrow. If "true", `text` is placed near the arrow's tail. If "false", `text` lines up with the `x` and `y` provided. Default: `true` * `standoff::Int` - Sets a distance, in pixels, to move the end arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount. Type: number greater than or equal to `0` | Default: `0` * `startarrowhead::Int` - Sets the start annotation arrow head style. Type: integer between or equal to `0` and `8` | Default: `1` * `startarrowsize::Int` - Sets the size of the start annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line. Type: number greater than or equal to `0.3` | Default: `1` * `startstandoff::Int` - Sets a distance, in pixels, to move the start arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount. Type: number greater than or equal to `0` | Default: `0` * `templateitemname::String` - Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. * `text::String` - Sets the text associated with the annotation. Plotly uses a subset of HTML tags to do things like newline (<br>), bold (<b></b>), italics (<i></i>), hyperlinks (<a href='...'></a>). Tags <em>, <sup>, <sub> <span> are also supported. Type: string * `textangle::Union{Int,Float64}` - Sets the angle at which the `text` is drawn with respect to the horizontal. Type: `angle` | Default: `0` * `valign::String` - Sets the vertical alignment of the `text` within the box. Has an effect only if an explicit height is set to override the text height. Type: enumerated , one of ( `"top"` | `"middle"` | `"bottom"`) | Default: `"middle"` * `visible::Bool` `visible` - Determines whether or not this annotation is visible. Type: boolean | Default: `true` * `width::Int` - Sets an explicit width for the text box. null (default) lets the text set the box width. Wider text will be clipped. Type: number greater than or equal to `1` * `x::Union{String,Int,Float64}` - Sets the annotation's x position. If the axis `type` is "log", then you must take the log of your desired range. If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. * `xanchor::String` - Sets the text box's horizontal position anchor This anchor binds the `x` position to the "left", "center" or "right" of the annotation. For example, if `x` is set to 1, `xref` to "paper" and `xanchor` to "right" then the right-most portion of the annotation lines up with the right-most edge of the plotting area. If "auto", the anchor is equivalent to "center" for data-referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side. Type: enumerated , one of ( `"auto"` | `"left"` | `"center"` | `"right"`) | Default: `"auto"` * `xref::Union{String,Int,Float64}` - Sets the annotation's x coordinate axis. If set to a x axis id (e.g. "x" or "x2"), the `x` position refers to a x coordinate. If set to "paper", the `x` position refers to the distance from the left of the plotting area in normalized coordinates where "0" ("1") corresponds to the left (right). If set to a x axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., "x2 domain" refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis. Type: enumerated , one of ( `"paper"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"` ) * `xshift::Union{Int,Float64}` - Shifts the position of the whole annotation and arrow to the right (positive) or left (negative) by this many pixels. Default: `0` * `y::Union{String,Int,Float64}` - Sets the annotation's y position. If the axis `type` is "log", then you must take the log of your desired range. If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. * `yanchor::Union{String}` - Sets the text box's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the annotation. For example, if `y` is set to 1, `yref` to "paper" and `yanchor` to "top" then the top-most portion of the annotation lines up with the top-most edge of the plotting area. If "auto", the anchor is equivalent to "middle" for data-referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side. Type: enumerated , one of ( `"auto"` | `"top"` | `"middle"` | `"bottom"`) | Default: `"auto"` * `yref::Union{String,Int,Float64}` - Sets the annotation's y coordinate axis. If set to a y axis id (e.g. "y" or "y2"), the `y` position refers to a y coordinate. If set to "paper", the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where "0" ("1") corresponds to the bottom (top). If set to a y axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., "y2 domain" refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis. Type: enumerated , one of ( `"paper"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"` ) * `yshift::Union{Int,Float64}` - Shifts the position of the whole annotation and arrow up (positive) or down (negative) by this many pixels. Default: `0` """ Base.@kwdef mutable struct PlotAnnotation align::Union{String,Nothing} = nothing arrowcolor::Union{String,Nothing} = nothing arrowhead::Union{Int,Nothing} = nothing arrowside::Union{String,Nothing} = nothing arrowsize::Union{Float64,Nothing} = nothing arrowwidth::Union{Float64,Nothing} = nothing ax::Union{String,Int,Float64,Nothing} = nothing axref::Union{String,Nothing} = nothing ay::Union{String,Int,Float64,Nothing} = nothing ayref::Union{String,Nothing} = nothing bgcolor::Union{String,Nothing} = nothing bordercolor::Union{String,Nothing} = nothing borderpad::Union{Int,Nothing} = nothing borderwidth::Union{Int,Nothing} = nothing captureevents::Union{Bool,Nothing} = nothing # TODO: clicktoshow # TODO: xclick # TODO: yclick font::Union{Font,Nothing} = nothing height::Union{Float64,Int,Nothing} = nothing hoverlabel::Union{Dict,Nothing} = nothing name::Union{String,Nothing} = nothing opacity::Union{Float64,Nothing} = nothing showarrow::Union{Bool,Nothing} = nothing standoff::Union{Int,Nothing} = nothing startarrowhead::Union{Int,Nothing} = nothing startarrowsize::Union{Float64,Nothing} = nothing startstandoff::Union{Int,Nothing} = nothing templateitemname::Union{String,Nothing} = nothing text::Union{String,Nothing} = nothing textangle::Union{Float64,Int,Nothing} = nothing valign::Union{String,Nothing} = nothing visible::Union{Bool,Nothing} = nothing width::Union{Float64,Int,Nothing} = nothing x::Union{String,Int,Float64,Nothing} = nothing xanchor::Union{String,Nothing} = nothing xref::Union{String,Int,Float64,Nothing} = nothing xshift::Union{Int,Float64,Nothing} = nothing y::Union{String,Int,Float64,Nothing} = nothing yanchor::Union{String,Nothing} = nothing yref::Union{String,Int,Float64,Nothing} = nothing yshift::Union{Int,Float64,Nothing} = nothing end function Base.show(io::IO, an::PlotAnnotation) output = "Annotation: \n" for f in fieldnames(typeof(an)) prop = getproperty(an, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(an::PlotAnnotation) trace = Dict{Symbol,Any}() if an.font !== nothing trace[:font] = Dict( :family => an.font.family, :size => an.font.size, :color => an.font.color ) end if an.hoverlabel !== nothing trace[:hoverlabel] = an.hoverlabel end optionals!(trace, an, [:align, :arrowcolor, :arrowhead, :arrowside, :arrowsize, :arrowwidth, :ax, :axref, :ay, :ayref, :bgcolor, :bordercolor, :borderpad, :borderwidth, :captureevents, :height, :hoverlabel, :name, :opacity, :showarrow, :standoff, :startarrowhead, :startarrowsize, :startstandoff, :templateitemname, :text, :textangle, :valign, :visible, :width, :x, :xanchor, :xref, :xshift, :y, :yanchor, :yref, :yshift]) end function Stipple.render(anv::Vector{PlotAnnotation}, fieldname::Union{Symbol,Nothing} = nothing) [Dict(an) for an in anv] end #===# """ PlotAnnotation() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `anchor::String` - If set to an opposite-letter axis id (e.g. `x2`, `y`), this axis is bound to the corresponding opposite-letter axis. If set to "free", this axis' position is determined by `position`. Type: enumerated , one of ( `"free"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"` |` "/^y([2-9]|[1-9][0-9]+)?( domain)?\$/"` ) * `automargin::Bool` - Determines whether this axis' margin is computed automatically. Type: boolean * `autorange::Bool` - Determines whether or not the range of this axis is computed in relation to the input data. See `rangemode` for more info. If `range` is provided, then `autorange` is set to "false". Type: enumerated , one of ( `true` | `false` | `"reversed"` ) | Default: `true` * `autotypenumbers::String` - Using "strict" a numeric string in trace data is not converted to a number. Using "convert types" a numeric string in trace data may be treated as a number during automatic axis `type` detection. Defaults to layout.autotypenumbers. Type: enumerated , one of ( `"strict"` | `"convert types"` ) | Default: `"convert types"` * `calendar::String` - Sets the calendar system to use for `range` and `tick0` if this is a date axis. This does not set the calendar for interpreting data on this axis, that's specified in the trace or via the global `layout.calendar`. Type: enumerated , one of ( `"gregorian"` | `"chinese"` | `"coptic"` | `"discworld"` | `"ethiopian"` | `"hebrew"` | `"islamic"` | `"julian"` | `"mayan"` | `"nanakshahi"` | `"nepali"` | `"persian"` | `"jalali"` | `"taiwan"` | `"thai"` | `"ummalqura"` ) | Default: `"gregorian"` * `categoryarray::Vector{Float64}` - Sets the order in which categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. Type: Vector * `categoryorder::String` - Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to "category ascending" or "category descending" if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. Set `categoryorder` to "total ascending" or "total descending" if order should be determined by the numerical order of the values. Similarly, the order can be determined by the min, max, sum, mean or median of all the values. Type: enumerated , one of ( `"trace"` | `"category ascending"` | `"category descending"` | `"array"` | `"total ascending"` | `"total descending"` ) | Default: `"trace"` * `constrain::String` - If this axis needs to be compressed (either due to its own `scaleanchor` and `scaleratio` or those of the other axis), determines how that happens: by increasing the "range", or by decreasing the "domain". Default is "domain" for axes containing image traces, "range" otherwise. Type: enumerated , one of ( `"domain"` | `"range"` ) * `constraintoward::String` - If this axis needs to be compressed (either due to its own `scaleanchor` and `scaleratio` or those of the other axis), determines which direction we push the originally specified plot area. Options are "left", "center" (default), and "right" for x axes, and "top", "middle" (default), and "bottom" for y axes. Type: enumerated , one of ( `"left"` | `"center"` | `"right"` | `"top"` | `"middle"` | `"bottom"` ) * `dividercolor::String` - Sets the color of the dividers Only has an effect on "multicategory" axes. Type: color | Default: `"#444"` * `dividerwidth::Float` - Sets the width (in px) of the dividers Only has an effect on "multicategory" axes. Type: float | Default: `1` * `domain::Vector{Float64}` - Sets the domain of this axis (in plot fraction). Type: Vector * `dtick::Union{Float64,Int,String}` - Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n"dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" * `fixedrange::Bool` - Determines whether or not this axis is zoom-able. If true, then zoom is disabled. * `font::Font` - Check Font structure for signature. * `gridcolor::String` - Sets the color of the grid lines. Type: color | Default: `"#eee"` * `gridwidth::Int` - Sets the width (in px) of the grid lines. Type: float | Default: `1` * `hoverformat::String` - Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, "2016-10-13 09:15:23.456" with tickformat "%H~%M~%S.%2f" would display "09~15~23.46". Default: `""` * `layer::String` - Sets the layer on which this axis is displayed. If "above traces", this axis is displayed above all the subplot's traces If "below traces", this axis is displayed below all the subplot's traces, but above the grid lines. Useful when used together with scatter-like traces with `cliponaxis` set to "false" to show markers and/or text nodes above this axis. Type: enumerated , one of ( `"above traces"` | `"below traces"` ) | Default: `"above traces"` * `linecolor::String` - Sets the axis line color. Type: color | Default: `"#444"` * `linewidth::Int` - Sets the width (in px) of the axis line. Type: float | Default: `1` * `minexponent::Int` - Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". Type: number greater than or equal to `0` | Default: `3` * `mirror::Union{Bool,String}` - Determines if the axis lines or/and ticks are mirrored to the opposite side of the plotting area. If "true", the axis lines are mirrored. If "ticks", the axis lines and ticks are mirrored. If "false", mirroring is disable. If "all", axis lines are mirrored on all shared-axes subplots. If "allticks", axis lines and ticks are mirrored on all shared-axes subplots. Type: `enumerated , one of ( `true` | `"ticks"` | `false` | `"all"` | `"allticks"` )` * `nticks::Int` - Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". Type: number greater than or equal to `0` | Default: `0` * `overlaying::String` - If set a same-letter axis id, this axis is overlaid on top of the corresponding same-letter axis, with traces and axes visible for both axes. If "false", this axis does not overlay any same-letter axes. In this case, for axes with overlapping domains only the highest-numbered axis will be visible. Type: enumerated , one of ( `"free"` | `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"` | `"/^y([2-9]|[1-9][0-9]+)?( domain)?\$/"` ) * `position::Float64` - Sets the position of this axis in the plotting space (in normalized coordinates). Only has an effect if `anchor` is set to "free". Type: number between or equal to `0` and `1` | Default: `0` * `range::Union{Vector{Int},Vector{Float64}}` - Sets the range of this axis. If the axis `type` is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. * `rangemode::String` - If "normal", the range is computed in relation to the extrema of the input data. If "tozero"`, the range extends to 0, regardless of the input data If "nonnegative", the range is non-negative, regardless of the input data. Applies only to linear axes. Type: enumerated , one of ( `"normal"` | `"tozero"` | `"nonnegative"` ) | Default: `"normal"` * `scaleanchor::String` - If set to another axis id (e.g. `x2`, `y`), the range of this axis changes together with the range of the corresponding axis such that the scale of pixels per unit is in a constant ratio. Both axes are still zoomable, but when you zoom one, the other will zoom the same amount, keeping a fixed midpoint. `constrain` and `constraintoward` determine how we enforce the constraint. You can chain these, ie `yaxis: {scaleanchor: "x"}, xaxis2: {scaleanchor: "y"}` but you can only link axes of the same `type`. The linked axis can have the opposite letter (to constrain the aspect ratio) or the same letter (to match scales across subplots). Loops (`yaxis: {scaleanchor: "x"}, xaxis: {scaleanchor: "y"}` or longer) are redundant and the last constraint encountered will be ignored to avoid possible inconsistent constraints via `scaleratio`. Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint is currently forbidden. Type: enumerated , one of ( `"/^x([2-9]|[1-9][0-9]+)?( domain)?\$/"` | `"/^y([2-9]|[1-9][0-9]+)?( domain)?\$/"` ) * `scaleratio::Int` - If this axis is linked to another by `scaleanchor`, this determines the pixel to unit scale ratio. For example, if this value is 10, then every unit on this axis spans 10 times the number of pixels as a unit on the linked axis. Use this for example to create an elevation profile where the vertical scale is exaggerated a fixed amount with respect to the horizontal. Type: number greater than or equal to `0` | Default: `1` * `showdividers::Bool` - Determines whether or not a dividers are drawn between the category levels of this axis. Only has an effect on "multicategory" axes. Type: boolean | Default: `true` * `showexponent::String` - If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. Type: enumerated , one of ( `"all"` | `"first"` | `"last"` | `"none"` ) | Default: `"all"` * `showgrid::Bool` - Determines whether or not grid lines are drawn. If True, the grid lines are drawn at every tick mark. Type: boolean | Default: `true` * `showline::Bool` - Determines whether or not a line bounding this axis is drawn. Type: boolean * `showspikes::Bool` - Determines whether or not spikes (aka droplines) are drawn for this axis. Note: This only takes affect when hovermode = closest. Type: boolean * `showticklabels::Bool` - Determines whether or not the tick labels are drawn. * `side::String` - Determines whether a x (y) axis is positioned at the "bottom" ("left") or "top" ("right") of the plotting area. Type: enumerated , one of ( `"top"` | `"bottom"` | `"left"` | `"right"` ) | Default: `"bottom"` * `spikecolor::String` - Sets the spike color. If undefined, will use the series color * `spikedash::String` - Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). * `spikemode::String` - Determines the drawing mode for the spike line If "toaxis", the line is drawn from the data point to the axis the series is plotted on. If "across", the line is drawn across the entire plot area, and supercedes "toaxis". If "marker", then a marker dot is drawn on the axis the series is plotted on. Type: Any combination of `"toaxis"`, `"across"`, `"marker"` joined with a `"+"` | Examples. `"toaxis"` | `"across"` | `"marker"` | `"toaxis+across"` | `"toaxis+marker"` | `"across+marker"` | `"toaxis+across+marker"` | Default: `"toaxis"` * `spikesnap::String` - Determines whether spikelines are stuck to the cursor or to the closest datapoints. Type: enumerated , one of ( `"data"` | `"cursor"` | `"hovered data"`) | Default: `"hovered data"` * `spikethickness::Int` - Sets the width (in px) of the zero line. Default: 3 * `tick0::Union{Float64,Int,String}` - Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`="L<f>" (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. * `tickangle::Union{String,Int,Float64}` - Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. Default: `"auto"` * `tickcolor::String` - Sets the tick color. Default: `"#444"` * `tickformat::String` - Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, "2016-10-13 09:15:23.456" with tickformat "%H~%M~%S.%2f" would display "09~15~23.46". Default: `""` * `ticklabelmode::String` - Determines where tick labels are drawn with respect to their corresponding ticks and grid lines. Only has an effect for axes of `type` "date" When set to "period", tick labels are drawn in the middle of the period between ticks. Type: enumerated , one of ( `"instant"` | `"period"` ) | Default: `"instant"` * `ticklabeloverflow::String` - Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is "hide past domain". Otherwise on "category" and "multicategory" axes the default is "allow". In other cases the default is "hide past div". Type: enumerated , one of ( `"allow"` |` "hide past div"` | `"hide past domain"` ) * `ticklabelposition::String` - Determines where tick labels are drawn with respect to the axis Please note that top or bottom has no effect on x axes or when `ticklabelmode` is set to "period". Similarly left or right has no effect on y axes or when `ticklabelmode` is set to "period". Has no effect on "multicategory" axes or when `tickson` is set to "boundaries". When used on axes linked by `matches` or `scaleanchor`, no extra padding for inside labels would be added by autorange, so that the scales could match. Type: enumerated , one of ( `"top"` | `"bottom"` | `"left"` | `"right"` | `"outsideleft"` | `"insideleft"` ) | Default: `"outside"` * `ticklen::Int` - Sets the tick length (in px). Default: `5` * `tickmode::String` - Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). Type: enumerated , one of ( `"auto"` | `"linear"` | `"array"` ) * `tickprefix::String` - Sets a tick label prefix. Default: `""` * `ticks::String` - Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. * `tickson::String` - Determines where ticks and grid lines are drawn with respect to their corresponding tick labels. Only has an effect for axes of `type` "category" or "multicategory". When set to "boundaries", ticks and grid lines are drawn half a category to the left/bottom of labels. Type: enumerated , one of (`"labels"` | `"boundaries"` ) | Default: `"labels"` * `ticksuffix::String` - Sets a tick label suffix. Default: `""` * `ticktext::Vector{String}` - Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. * `tickvals::Union{Vector{Float64},Vector{Int}}` - Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. * `tickwidth::Int` - Sets the tick width (in px). Type: number greater than or equal to `0` | Default: `1` * `title::String` - Sets the title of this axis. * `type::String` - Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. Type: enumerated , one of ( `"-"` | `"linear"` | `"log"` | `"date"` | `"category"` | `"multicategory"` ) | Default: `"-"` * `visible::Bool` - A single toggle to hide the axis while preserving interaction like dragging. Default is true when a cheater plot is present on the axis, otherwise false * `zeroline::Bool` - Determines whether or not a line is drawn at along the 0 value of this axis. If "true", the zero line is drawn on top of the grid lines. * `zerolinecolor::String` - Sets the line color of the zero line. Default: `#444` * `zerolinewidth::Int` - Sets the width (in px) of the zero line. Default: `1` #### Important * `xy::String` - Sets a reference to the x or y axis. If "x", the `x` axis will be matched. If "y", the `y` axis will be matched. * `index::Int` - 1 # 1, 2, 3 etc. for subplots * `title_text::String` - Sets the text of the title of this axis. * `title_font::Font` - Sets the title font. * `title_standoff:Int` - Sets the standoff distance between the axis title and the axis labels, in pixels. """ Base.@kwdef mutable struct PlotLayoutAxis anchor::Union{String,Nothing} = nothing automargin::Union{Bool,Nothing} = nothing autorange::Union{Bool,String,Nothing} = nothing autotypenumbers::Union{String,Nothing} = nothing calendar::Union{String,Nothing} = nothing categoryarray::Union{Vector{Float64},Nothing} = nothing categoryorder::Union{String,Nothing} = nothing constrain::Union{String,Nothing} = nothing constraintoward::Union{String,Nothing} = nothing dividercolor::Union{String,Nothing} = nothing dividerwidth::Union{Int,Nothing} = nothing domain::Union{Vector{Float64},Nothing} = nothing dtick::Union{Float64,Int,String,Nothing} = nothing fixedrange::Union{Bool,Nothing} = nothing font::Union{Font,Nothing} = nothing gridcolor::Union{String,Nothing} = nothing gridwidth::Union{Int,Nothing} = nothing hoverformat::Union{String,Nothing} = nothing layer::Union{String,Nothing} = nothing linecolor::Union{String,Nothing} = nothing linewidth::Union{Int,Nothing} = nothing minexponent::Union{Int,Nothing} = nothing mirror::Union{Bool,String,Nothing} = nothing nticks::Union{Int,Nothing} = nothing overlaying::Union{String,Nothing} = nothing position::Union{Float64,Nothing} = nothing range::Union{Vector{Int},Vector{Float64},Nothing} = nothing rangemode::Union{String,Nothing} = nothing scaleanchor::Union{String,Nothing} = nothing scaleratio::Union{Int,Nothing} = nothing showdividers::Union{Bool,Nothing} = nothing showexponent::Union{String,Nothing} = nothing showgrid::Union{Bool,Nothing} = nothing showline::Union{Bool,Nothing} = nothing showspikes::Union{Bool,Nothing} = nothing showticklabels::Union{Bool,Nothing} = nothing side::Union{String,Nothing} = nothing spikecolor::Union{String,Nothing} = nothing spikedash::Union{String,Nothing} = nothing spikemode::Union{String,Nothing} = nothing spikesnap::Union{String,Nothing} = nothing spikethickness::Union{Int,Nothing} = nothing tick0::Union{Float64,Int,String,Nothing} = nothing tickangle::Union{String,Int,Float64,Nothing} = nothing tickcolor::Union{String,Nothing} = nothing tickfont::Union{Font,Nothing} = nothing tickformat::Union{String,Nothing} = nothing ticklabelmode::Union{String,Nothing} = nothing ticklabelposition::Union{String,Nothing} = nothing ticklen::Union{Int,Nothing} = nothing tickmode::Union{String,Nothing} = nothing tickprefix::Union{String,Nothing} = nothing ticks::Union{String,Nothing} = nothing tickson::Union{String,Nothing} = nothing ticksuffix::Union{String,Nothing} = nothing ticktext::Union{Vector{String},Nothing} = nothing tickvals::Union{Vector{Float64},Vector{Int},Nothing} = nothing tickwidth::Union{Int,Nothing} = nothing title::Union{String,Nothing} = nothing # "axis title" type::Union{String,Nothing} = nothing visible::Union{Bool,Nothing} = nothing zeroline::Union{Bool,Nothing} = nothing zerolinecolor::Union{String,Nothing} = nothing zerolinewidth::Union{Int,Nothing} = nothing # needs special treatment xy::String = "x" # "x" or "y" index::Int = 1 # 1, 2, 3 etc. for subplots title_text::Union{String,Nothing} = nothing title_font::Union{Font,Nothing} = nothing title_standoff::Union{Int,Nothing} = nothing end function Base.show(io::IO, la::PlotLayoutAxis) output = "Layout Axis: \n" for f in fieldnames(typeof(la)) prop = getproperty(la, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(la::PlotLayoutAxis, xy::String = "") trace = Dict{Symbol,Any}() if la.title_text !== nothing d = Dict{Symbol,Any}(:text => la.title_text) (la.title_font !== nothing) && (d[:font] = la.title_font) (la.title_standoff !== nothing) && (d[:standoff] = la.title_standoff) trace[:title] = d end d = optionals!(trace, la, [ :anchor, :automargin, :autorange, :autotypenumbers, :calendar, :categoryarray, :categoryorder, :constrain, :constraintoward, :dividercolor, :dividerwidth, :domain, :dtick, :fixedrange, :font, :gridcolor, :gridwidth, :hoverformat, :layer, :linecolor, :linewidth, :minexponent, :mirror, :nticks, :overlaying, :position, :range, :rangemode, :scaleanchor, :scaleratio, :showdividers, :showexponent, :showgrid, :showline, :showspikes, :showticklabels, :side, :spikecolor, :spikedash, :spikemode, :spikesnap, :spikethickness, :tick0, :tickangle, :tickcolor, :tickfont, :tickformat, :ticklabelmode, :ticklabelposition, :ticklen, :tickmode, :tickprefix, :ticks, :tickson, :ticksuffix, :ticktext, :tickvals, :tickwidth, :title, :type, :visible, :zeroline, :zerolinecolor, :zerolinewidth]) k = Symbol(isempty(xy) ? la.xy : xy, "axis", la.index > 1 ? "$(la.index)" : "") Dict(k => d) end function Stipple.render(la::PlotLayoutAxis, fieldname::Union{Symbol,Nothing} = nothing) [Dict(la)] end function Stipple.render(lav::Vector{PlotLayoutAxis}, fieldname::Union{Symbol,Nothing} = nothing) [Dict(la) for la in lav] end #===# Base.@kwdef mutable struct PlotLayoutTitle text::Union{String,Nothing} = nothing # "" font::Union{Font,Nothing} = nothing # Font() xref::Union{String,Nothing} = nothing # LAYOUT_TITLE_REF_CONTAINER yref::Union{String,Nothing} = nothing # LAYOUT_TITLE_REF_CONTAINER x::Union{Float64,String,Nothing} = nothing # 0.5 y::Union{Float64,String,Nothing} = nothing # LAYOUT_AUTO xanchor::Union{String,Nothing} = nothing # LAYOUT_AUTO yanchor::Union{String,Nothing} = nothing # LAYOUT_AUTO pad_t::Union{Int,Nothing} = nothing # 0 pad_r::Union{Int,Nothing} = nothing # 0 pad_b::Union{Int,Nothing} = nothing # 0 pad_l::Union{Int,Nothing} = nothing # 0 end function Base.show(io::IO, plt::PlotLayoutTitle) output = "Layout Title: \n" for f in fieldnames(typeof(plt)) prop = getproperty(plt, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(plt::PlotLayoutTitle) trace = Dict{Symbol, Any}() d = Dict{Symbol, Any}() (plt.pad_t !== nothing) && (d[:t] = plt.pad_t) (plt.pad_r !== nothing) && (d[:r] = plt.pad_r) (plt.pad_b !== nothing) && (d[:b] = plt.pad_b) (plt.pad_l !== nothing) && (d[:l] = plt.pad_l) (length(d) > 0) && (trace[:pad] = d) optionals!(trace, plt, [:text, :font, :xref, :yref, :x, :y, :xanchor, :yanchor]) end function Stipple.render(plt::PlotLayoutTitle, fieldname::Union{Symbol,Nothing} = nothing) Dict(plt) end #===# """ PlotLayoutLegend() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `bgcolor::String` - Sets the legend background color. Defaults to `layout.paper_bgcolor`. Type: `color` * `bordercolor::String` - Sets the color of the border enclosing the legend. Type: `color` | Default: `"#444"` * `borderwidth::Int` - Sets the width (in px) of the border enclosing the legend. Type: `int` | Default: `0` * `font::Font` - Sets the font used to text the legend items. Type: `Font` | Default: `Font()` * `itemclick::Union{String,Bool}` - Determines the behavior on legend item click. "toggle" toggles the visibility of the item clicked on the graph. "toggleothers" makes the clicked item the sole visible item on the graph. "false" disables legend item click interactions. Type: enumerated , one of ( `"toggle"` | `"toggleothers"` | `false` ) | Default: `"toggle"` * `itemdoubleclick::Union{String,Bool}` - Determines the behavior on legend item double-click. "toggle" toggles the visibility of the item clicked on the graph. "toggleothers" makes the clicked item the sole visible item on the graph. "false" disables legend item double-click interactions. Type: enumerated , one of ( `"toggle"` | `"toggleothers"` | `false` ) | Default: `"toggleothers"` * `itemsizing::String` - Determines if the legend items symbols scale with their corresponding "trace" attributes or remain "constant" independent of the symbol size on the graph. Type: enumerated , one of ( `"trace"` | `"constant"` ) | Default: `"trace"` * `itemwidth::Int` - Sets the width (in px) of the legend item symbols (the part other than the title.text). Type: `int` | Default: `30` * `orientation::String` - Sets the orientation of the legend. Type: enumerated , one of ( `"v"` | `"h"` ) | Default: `"v"` * `title_text::String` - Sets the text of the legend's title. Type: `String` * `title_font::Font` - Sets the font used for the legend's title. Type: `Font` * `title_side::String` - Sets the side of the legend. * `tracegroupgap::Int` - Sets the amount of vertical space (in px) between legend groups. Type: number greater than or equal to `0` | Default: `10` * `traceorder::String` - Determines the order at which the legend items are displayed. If "normal", the items are displayed top-to-bottom in the same order as the input data. If "reversed", the items are displayed in the opposite order as "normal". If "grouped", the items are displayed in groups (when a trace `legendgroup` is provided). if "grouped+reversed", the items are displayed in the opposite order as "grouped". Type: flaglist string. Any combination of `"reversed"`, `"grouped"` joined with a `"+"` OR `"normal"`. | Examples: Examples: `"reversed"`, `"grouped"`, `"reversed+grouped"`, `"normal"` * `valign::String` - Sets the vertical alignment of the symbols with respect to their associated text. Type: enumerated , one of ( `"top"` | `"middle"` | `"bottom"` ) | Default: `"middle"` * `x::Union{Int,Float64}` - Sets the x position (in normalized coordinates) of the legend. Defaults to "1.02" for vertical legends and defaults to "0" for horizontal legends. Type: number between or equal to `-2` and `3` * `xanchor::String` - Sets the legend's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the legend. Value "auto" anchors legends to the right for `x` values greater than or equal to 2/3, anchors legends to the left for `x` values less than or equal to 1/3 and anchors legends with respect to their center otherwise. Type: enumerated , one of ( `"left"` | `"center"` | `"right"` | `"auto"` ) | Default: `"left"` * `y::Union{Int,Float64}` - Sets the y position (in normalized coordinates) of the legend. Defaults to "1" for vertical legends, defaults to "-0.1" for horizontal legends on graphs w/o range sliders and defaults to "1.1" for horizontal legends on graph with one or multiple range sliders. Type: number between or equal to `-2` and `3` * `yanchor::String` - Sets the legend's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the legend. Value "auto" anchors legends at their bottom for `y` values less than or equal to 1/3, anchors legends to at their top for `y` values greater than or equal to 2/3 and anchors legends with respect to their middle otherwise. Type: enumerated , one of ( `"top"` | `"middle"` | `"bottom"` | `"auto"` ) """ Base.@kwdef mutable struct PlotLayoutLegend bgcolor::Union{String,Nothing} = nothing bordercolor::Union{String,Nothing} = nothing # "#444" borderwidth::Union{Int,Nothing} = nothing # 0 font::Union{Font,Nothing} = nothing # Font() itemclick::Union{String,Bool,Nothing} = nothing # LAYOUT_CLICK_TOGGLE itemdoubleclick::Union{String,Bool,Nothing} = nothing # LAYOUT_CLICK_TOGGLEOTHERS itemsizing::Union{String,Nothing} = nothing # LAYOUT_ITEMSIZING_TRACE itemwidth::Union{Int,Nothing} = nothing # 30 orientation::Union{String,Nothing} = nothing # LAYOUT_ORIENTATION_VERTICAL title_text::Union{String,Nothing} = nothing # "" title_font::Union{Font,Nothing} = nothing # Font() title_side::Union{String,Nothing} = nothing # LAYOUT_LEFT tracegroupgap::Union{Int,Nothing} = nothing # 10 traceorder::Union{String,Nothing} = nothing # "normal" valign::Union{String,Nothing} = nothing # LAYOUT_MIDDLE x::Union{Int,Float64,Nothing} = nothing # 1.02 xanchor::Union{String,Nothing} = nothing # LAYOUT_LEFT y::Union{Int,Float64,Nothing} = nothing # 1 yanchor::Union{String,Nothing} = nothing # LAYOUT_AUTO # TODO: uirevision::Union{Int,String} = "" end function Base.show(io::IO, pll::PlotLayoutLegend) output = "Layout Legend: \n" for f in fieldnames(typeof(pll)) prop = getproperty(pll, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pll::PlotLayoutLegend) trace = Dict{Symbol, Any}() d = Dict{Symbol, Any}() (pll.title_text !== nothing) && (d[:text] = pll.title_text) (pll.title_font !== nothing) && (d[:font] = pll.title_font) (pll.title_side !== nothing) && (d[:side] = pll.title_side) (length(d) > 0) && (trace[:title] = d) optionals!(trace, pll, [ :bgcolor, :bordercolor, :borderwidth, :font, :orientation, :tracegroupgap, :traceorder, :itemsizing, :itemwidth, :itemclick, :itemdoubleclick, :x, :xanchor, :y, :yanchor, :valign]) end function Stipple.render(pll::PlotLayoutLegend, fieldname::Union{Symbol,Nothing} = nothing) Dict(pll) end #===# """ PlotLayoutGrid() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `columns::String` - The number of columns in the grid. If you provide a 2D `subplots` array, the length of its longest row is used as the default. If you give an `xaxes` array, its length is used as the default. But it's also possible to have a different length, if you want to leave a row at the end for non-cartesian subplots. Type: integer greater than or equal to `1` * `domain_x::Vector{Float64}` - Sets the horizontal domain of this grid subplot (in plot fraction). The first and last cells end exactly at the domain edges, with no grout around the edges. Default: `[0, 1]` * `domain_y::Vector{Float64}` - Sets the vertical domain of this grid subplot (in plot fraction). The first and last cells end exactly at the domain edges, with no grout around the edges. Default: `[0, 1]` * `pattern::String` - If no `subplots`, `xaxes`, or `yaxes` are given but we do have `rows` and `columns`, we can generate defaults using consecutive axis IDs, in two ways: "coupled" gives one x axis per column and one y axis per row. "independent" uses a new xy pair for each cell, left-to-right across each row then iterating rows according to `roworder`. Type: one of `"coupled"` or `"independent"` | Default. `"coupled"` * `roworder::String` - Is the first row the top or the bottom? Note that columns are always enumerated from left to right. enumerated , one of ( `"top to bottom"` | `"bottom to top"` ) | Default: `"top to bottom"` * `rows::Int` - The number of rows in the grid. If you provide a 2D `subplots` array or a `yaxes` array, its length is used as the default. But it's also possible to have a different length, if you want to leave a row at the end for non-cartesian subplots. Type: integer greater than or equal to `1` * `subplots::Matrix{String}` - Used for freeform grids, where some axes may be shared across subplots but others are not. Each entry should be a cartesian subplot id, like "xy" or "x3y2", or "" to leave that cell empty. You may reuse x axes within the same column, and y axes within the same row. Non-cartesian subplots and traces that support `domain` can place themselves in this grid separately using the `gridcell` attribute. * `xaxes::Vector{String}` - Used with `yaxes` when the x and y axes are shared across columns and rows. Each entry should be an x axis id like "x", "x2", etc., or "" to not put an x axis in that column. Entries other than "" must be unique. Ignored if `subplots` is present. If missing but `yaxes` is present, will generate consecutive IDs. * `xgap::Float64` - Horizontal space between grid cells, expressed as a fraction of the total width available to one cell. Defaults to 0.1 for coupled-axes grids and 0.2 for independent grids. Type: number between or equal to `0` and `1` * `xside::String` - Sets where the x axis labels and titles go. "bottom" means the very bottom of the grid. "bottom plot" is the lowest plot that each x axis is used in. "top" and "top plot" are similar. Type: enumerated , one of ( `"bottom"` | `"bottom plot"` | `"top plot"` | `"top"` ) | Default: `"bottom plot"` * `yaxes::Vector{String}` - Used with `yaxes` when the x and y axes are shared across columns and rows. Each entry should be an y axis id like "y", "y2", etc., or "" to not put a y axis in that row. Entries other than "" must be unique. Ignored if `subplots` is present. If missing but `xaxes` is present, will generate consecutive IDs. * `ygap::Float64` - Vertical space between grid cells, expressed as a fraction of the total height available to one cell. Defaults to 0.1 for coupled-axes grids and 0.3 for independent grids. Type: number between or equal to `0` and `1` * `yside::String` - Sets where the y axis labels and titles go. "left" means the very left edge of the grid. "left plot" is the leftmost plot that each y axis is used in. "right" and "right plot" are similar. Type: enumerated , one of ( `"left"` | `"left plot"` | `"right plot"` | `"right"` ) | Default: `"left plot"` """ Base.@kwdef mutable struct PlotLayoutGrid columns::Union{Int,Nothing} = nothing # >= 1 domain_x::Union{Vector{Float64},Nothing} = nothing # fraction, e.g [0, 1] domain_y::Union{Vector{Float64},Nothing} = nothing # fraction, e.g [0, 1] pattern::Union{String,Nothing} = nothing # "independent" | "coupled" roworder::Union{String,Nothing} = nothing # "top to bottom" | "bottom to top" rows::Union{Int,Nothing} = nothing # >= 1 subplots::Union{Matrix{String},Nothing} = nothing xaxes::Union{Vector{String},Nothing} = nothing xgap::Union{Float64,Nothing} = nothing # [0.0, 1.0] xside::Union{String,Nothing} = nothing # "bottom" | "bottom plot" | "top plot" | "top" yaxes::Union{Vector{String},Nothing} = nothing ygap::Union{Float64,Nothing} = nothing # [0.0, 1.0] yside::Union{String,Nothing} = nothing # "bottom" | "bottom plot" | "top plot" | "top" end function Base.show(io::IO, lg::PlotLayoutGrid) output = "Layout Grid: \n" for f in fieldnames(typeof(lg)) prop = getproperty(lg, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(lg::PlotLayoutGrid) trace = Dict{Symbol,Any}() if (lg.domain_x !== nothing) & (lg.domain_y !== nothing) trace[:domain] = Dict( :x => lg.domain_x, :y => lg.domain_y ) elseif lg.domain_x !== nothing trace[:domain] = Dict( :x => lg.domain_x ) elseif lg.domain_y !== nothing trace[:domain] = Dict( :y => lg.domain_y ) end optionals!(trace, lg, [:columns, :domain_x, :domain_y, :pattern, :roworder, :rows, :subplots, :xaxes, :xgap, :xside, :yaxes, :ygap, :yside]) end #===# """ GeoProjection() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `distance::Float64` - For satellite projection type only. Sets the distance from the center of the sphere to the point of view as a proportion of the sphere’s radius. Type: number greater than or equal to `1.001` | Default: `2` * `parallels::Vector{Float64}` - For conic projection types only. Sets the parallels (tangent, secant) where the cone intersects the sphere. * `rotation::Protation` - Check Protation struct for more details * `scale::Float64` - Zooms in or out on the map view. A scale of "1" corresponds to the largest zoom level that fits the map's lon and lat ranges. number greater than or equal to `0` | Default: `1` * `tilt::Float64` - For satellite projection type only. Sets the tilt angle of perspective projection. Type: `number` | Default: `0` * `type::String` - Sets the projection type. Type: enumerated , one of ( `"albers"` | `"albers usa"` | `"azimuthal equal area"` | `"azimuthal equidistant"` | `"conic equal area"` | `"conic conformal"` | `"conic equidistant"` | `"equidistant conic"` | `"gnomonic"` | `"mercator"` | `"natural earth"` | `"orthographic"` | `"stereographic"` | `"transverse mercator"` ) """ Base.@kwdef mutable struct GeoProjection distance::Union{Float64,Nothing} = nothing parallels::Union{Vector{Float64},Nothing} = nothing rotation::Union{Protation, Nothing} = nothing scale::Union{Float64,Nothing} = nothing tilt::Union{Float64,Nothing} = nothing type::Union{String,Nothing} = nothing end function Base.show(io::IO, proj::GeoProjection) output = "Geo Layout Projection: \n" for f in fieldnames(typeof(proj)) prop = getproperty(proj, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(proj::GeoProjection) trace = Dict{Symbol, Any}() optionals!(trace, proj, [:distance, :parallels, :rotation, :scale, :tilt, :type]) end function Stipple.render(proj::GeoProjection, fieldname::Union{Symbol,Nothing} = nothing) Dict(proj) end """ PlotLayoutGeo() ---------- # Examples ---------- ``` julia> ``` ----------- # Properties ----------- * `bgcolor::String` - Set the background color of the map. Type: `color` | Default: `"#fff"` * `center::Mcenter` - Check Mcenter documentation for details. * `coastlinecolor::String` - Set the coastline color. Type: `color` | Default: `"#444"` * `coastlinewidth::Int` - Set the coastline width. Type: `number` | Default: `1` * `countrywidth::Int` - Sets line color of the country boundaries. Type: number greater than or equal to `0` | Default: `1` * `fitbounds::Bool` - Determines if this subplot's view settings are auto-computed to fit trace data. On scoped maps, setting `fitbounds` leads to `center.lon` and `center.lat` getting auto-filled. On maps with a non-clipped projection, setting `fitbounds` leads to `center.lon`, `center.lat`, and `projection.rotation.lon` getting auto-filled. On maps with a clipped projection, setting `fitbounds` leads to `center.lon`, `center.lat`, `projection.rotation.lon`, `projection.rotation.lat`, `lonaxis.range` and `lonaxis.range` getting auto-filled. If "locations", only the trace's visible locations are considered in the `fitbounds` computations. If "geojson", the entire trace input `geojson` (if provided) is considered in the `fitbounds` computations, Defaults to "false". Type: enumerated , one of ( false | "locations" | "geojson" ) * `framecolor::String` - Set the frame color. Type: `color` | Default: `"#444"` * `framewidth::Int` - Sets the stroke width (in px) of the frame. Type: number greater than or equal to `0` | Default: `1` * `lakecolor::String` - Set the color of the lakes. Type: `color` | Default: `"#3399FF"` * `landcolor::String` - Sets the land mass color. Type: `color` | Default: `"#F0DC82"` * `lataxis::PlotLayoutAxis` - Check PlotLayoutAxis documentation for details. * `lonaxis::PlotLayoutAxis` - Check PlotLayoutAxis documentation for details. * `oceancolor::String` - Sets the ocean color. Type: `color` | Default: `"#3399FF"` * `geoprojection::GeoProjection` - Check GeoProjection documentation for details. * `resolution::String` - Sets the resolution of the base layers. The values have units of km/mm e.g. 110 corresponds to a scale ratio of `1:110,000,000`. Type: enumerated , one of ( `"110"` | `"50"` ) | Default: `"110"` * `rivercolor::String` - Sets color of the rivers. Type: `color` | Default: `"#3399FF"` * `riverwidth::Int` - Sets the stroke width (in px) of the rivers. Type: number greater than or equal to `0` | Default: `1` * `scope::String` - Sets the scope of the map. Type: enumerated , one of ( `"world"` | `"usa"` | `"europe"` | `"asia"` | `"africa"` | `"north america"` | `"south america"` ) | Default: `"world"` * `showcoastlines::Bool` - Sets whether or not the coastlines are drawn. * `showcountries::Bool` - Sets whether or not country boundaries are drawn. * `showframe::Bool` - Sets whether or not a frame is drawn around the map. * `showlakes::Bool` - Sets whether or not lakes are drawn. * `showland::Bool` - Sets whether or not land masses are filled in color. * `showocean::Bool` - Sets whether or not oceans are filled in color. * `showrivers::Bool` - Sets whether or not rivers are drawn. * `showsubunits::Bool` - Sets whether or not boundaries of subunits within countries (e.g. states, provinces) are drawn. * `subunitcolor::String` - Sets the color of the subunits boundaries. Type: `color` | Default: `"#444"` * `subunitwidth::Int` - Sets the stroke width (in px) of the subunits boundaries. Type: number greater than or equal to `0` | Default: `1` * `uirevision::Union{String,Int}` - Controls persistence of user-driven changes in the view (projection and center). Defaults to `layout.uirevision`. Type: number or categorical coordinate string * `visible::Bool` - Sets the default visibility of the base layers. Default: `true` """ Base.@kwdef mutable struct PlotLayoutGeo bgcolor::Union{String, Nothing} = nothing # "" center::Union{Mcenter, Nothing} = nothing # MCenter(0, 0) coastlinecolor::Union{String, Nothing} = nothing # "" coastlinewidth::Union{Int, Nothing} = nothing # 1 countrycolor::Union{String, Nothing} = nothing # "" countrywidth::Union{Int, Nothing} = nothing # 1 fitbounds::Union{Bool, Nothing} = nothing # false framecolor::Union{String, Nothing} = nothing # "" framewidth::Union{Int, Nothing} = nothing # 0 lakecolor::Union{String, Nothing} = nothing # "" landcolor::Union{String, Nothing} = nothing # "" lataxis::Union{PlotLayoutAxis,Nothing} = nothing lonaxis::Union{PlotLayoutAxis,Nothing} = nothing oceancolor::Union{String, Nothing} = nothing # "" geoprojection::Union{GeoProjection, Nothing} = nothing resolution::Union{String, Nothing} = nothing # 50 rivercolor::Union{String, Nothing} = nothing # "" riverwidth::Union{Int, Nothing} = nothing # 1 scope::Union{String, Nothing} = nothing # "world" showcoastlines::Union{Bool, Nothing} = nothing # true showcountries::Union{Bool, Nothing} = nothing # true showframe::Union{Bool, Nothing} = nothing # false showlakes::Union{Bool, Nothing} = nothing # true showland::Union{Bool, Nothing} = nothing # true showocean::Union{Bool, Nothing} = nothing # true showrivers::Union{Bool, Nothing} = nothing # true showsubunits::Union{Bool, Nothing} = nothing # true subunitcolor::Union{String, Nothing} = nothing # "" subunitwidth::Union{Int, Nothing} = nothing # 1 uirevision::Union{Int, String, Nothing} = nothing # "number or categorical coordinate string visible::Union{Bool, Nothing} = nothing # true end function Base.show(io::IO, geo::PlotLayoutGeo) output = "Layout Geo: \n" for f in fieldnames(typeof(geo)) prop = getproperty(geo, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(geo::PlotLayoutGeo) trace = Dict{Symbol, Any}() optionals!(trace, geo, [ :bgcolor, :center, :coastlinecolor, :coastlinewidth, :countrycolor, :countrywidth, :fitbounds, :framecolor, :framewidth, :lakecolor, :landcolor, :oceancolor, :geoprojection, :resolution, :rivercolor, :riverwidth, :scope, :showcoastlines, :showcountries, :showframe, :showlakes, :showland, :showocean, :showrivers, :showsubunits, :subunitcolor, :subunitwidth, :uirevision, :visible]) end function Stipple.render(geo::PlotLayoutGeo, fieldname::Union{Symbol,Nothing} = nothing) Dict(geo) end #===# Base.@kwdef mutable struct PlotLayoutMapbox style::Union{String, Nothing} = nothing # "open-street-map" zoom::Union{Float64, Nothing} = nothing # 0 center::Union{Mcenter, Nothing} = nothing # MCenter(0, 0) end function Base.show(io::IO, mapbox::PlotLayoutMapbox) output = "Layout Geo: \n" for f in fieldnames(typeof(mapbox)) prop = getproperty(mapbox, f) if prop !== nothing output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(mapbox::PlotLayoutMapbox) trace = Dict{Symbol, Any}() optionals!(trace, geo, [:style, :zoom, :center]) end function Stipple.render(mapbox::PlotLayoutMapbox, fieldname::Union{Symbol,Nothing} = nothing) Dict(map) end #===# Base.@kwdef mutable struct PlotLayout title::Union{PlotLayoutTitle,Nothing} = nothing xaxis::Union{Vector{PlotLayoutAxis},Nothing} = nothing yaxis::Union{Vector{PlotLayoutAxis},Nothing} = nothing axes::Union{Vector{PlotLayoutAxis},Nothing} = nothing showlegend::Union{Bool,Nothing} = nothing # true legend::Union{PlotLayoutLegend,Nothing} = nothing annotations::Union{Vector{PlotAnnotation},Nothing} = nothing geo::Union{PlotLayoutGeo,Nothing} = nothing grid::Union{PlotLayoutGrid,Nothing} = nothing mapbox::Union{PlotLayoutMapbox,Nothing} = nothing margin_l::Union{Int,Nothing} = nothing # 80 margin_r::Union{Int,Nothing} = nothing # 80 margin_t::Union{Int,Nothing} = nothing # 100 margin_b::Union{Int,Nothing} = nothing # 80 margin_pad::Union{Int,Nothing} = nothing # 0 margin_autoexpand::Union{Bool,Nothing} = nothing # true autosize::Union{Bool,Nothing} = nothing # true width::Union{Int,String,Nothing} = nothing # 700 height::Union{Int,String,Nothing} = nothing # 450 font::Union{Font,Nothing} = nothing uniformtext_mode::Union{String,Bool,Nothing} = nothing # false uniformtext_minsize::Union{Int,Nothing} = nothing # 0 separators::Union{String,Nothing} = nothing # ".," paper_bgcolor::Union{String,Nothing} = nothing # "#fff" plot_bgcolor::Union{String,Nothing} = nothing # "#fff" # TODO: implement the following fields in function Stipple.render(pl::PlotLayout... autotypenumbers::String = "convert types" # TODO: colorscale settings colorway::Vector{String} = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"] modebar_orientation::String = LAYOUT_ORIENTATION_HORIZONTAL modebar_bgcolor::String = "transparent" modebar_color::String = "" modebar_activecolor::String = "" # TODO: modebar_uirevision::String = "" hovermode::Union{String,Bool} = "closest" clickmode::String = "event" dragmode::String = "zoom" selectdirection::String = "any" hoverdistance::Int = 20 spikedistance::Int = 20 hoverlabel_bgcolor::String = "" hoverlabel_bordercolor::String = "" hoverlabel_font::Font = Font() hoverlabel_align::String = LAYOUT_AUTO hoverlabel_namelength::Int = 15 transition_duration::Int = 500 transition_easing::String = "cubic-in-out" transition_ordering::String = "layout first" # TODO: datarevision # TODO: editrevision # TODO: selectionrevision # TODO: template # TODO: meta # TODO: computed calendar::String = "gregorian" newshape_line_color::String = "" newshape_line_width::Int = 4 newshape_line_dash::String = "solid" newshape_fillcolor::String = "rgba(0,0,0,0)" newshape_fillrule::String = "evenodd" newshape_opacity::Float64 = 1.0 newshape_layer::String = LAYOUT_ABOVE newshape_drawdirection::String = "diagonal" activeshape_fillcolor::String = "rgb(255,0,255)" activeshape_opacity::Float64 = 0.5 # TODO: hidesources barmode::Union{String,Nothing} = nothing # LAYOUT_GROUP barnorm::Union{String,Nothing} = nothing bargap::Union{Float64,Nothing} = nothing # 0.5 bargroupgap::Union{Float64,Nothing} = nothing # 0 # TODO: hiddenlabels # TODO: piecolorway extendpiecolors::Bool = true boxmode::String = LAYOUT_OVERLAY boxgap::Float64 = 0.3 boxgroupgap::Float64 = 0.3 violinmode::String = LAYOUT_OVERLAY violingap::Float64 = 0.3 violingroupgap::Float64 = 0.3 waterfallmode::String = LAYOUT_GROUP waterfallgap::Float64 = 0.3 waterfallgroupgap::Float64 = 0.0 funnelmode::String = LAYOUT_STACK funnelgap::Float64 = 0.0 funnelgroupgap::Float64 = 0.0 # TODO: funnelareacolorway extendfunnelareacolors::Bool = true # TODO: sunburstcolorway extendsunburstcolors::Bool = true # TODO: treemapcolorway extendtreemapcolors::Bool = true end function Base.show(io::IO, l::PlotLayout) default = PlotLayout() output = "layout: \n" for f in fieldnames(typeof(l)) prop = getproperty(l, f) if prop != getproperty(default, f) output *= "$f = $prop \n" end end print(io, output) end function Base.Dict(pl::PlotLayout, fieldname::Union{Symbol,Nothing} = nothing) layout = Dict{Symbol, Any}() if pl.font !== nothing layout[:font] = Dict{Symbol, Any}( :family => pl.font.family, :size => pl.font.size, :color => pl.font.color ) end d1 = Dict{Symbol, Any}() (pl.margin_l !== nothing) && (d1[:l] = pl.margin_l) (pl.margin_r !== nothing) && (d1[:r] = pl.margin_r) (pl.margin_t !== nothing) && (d1[:t] = pl.margin_t) (pl.margin_b !== nothing) && (d1[:b] = pl.margin_b) (pl.margin_pad !== nothing) && (d1[:pad] = pl.margin_pad) (pl.margin_autoexpand !== nothing) && (d1[:autoexpand] = pl.margin_autoexpand) (length(d1) > 0) && (layout[:margin] = d1) d2 = Dict{Symbol, Any}() (pl.uniformtext_mode !== nothing) && (d2[:mode] = pl.uniformtext_mode) (pl.uniformtext_minsize !== nothing) && (d2[:minsize] = pl.uniformtext_minsize) (length(d2) > 0) && (layout[:uniformtext] = d2) (pl.title !== nothing) && (layout[:title] = Dict(pl.title)) (pl.legend !== nothing) && (layout[:legend] = Dict(pl.legend)) (pl.annotations !== nothing) && (layout[:annotations] = Dict.(pl.annotations)) (pl.grid !== nothing) && (layout[:grid] = Dict(pl.grid)) optionals!(layout, pl, [ :showlegend, :autosize, :separators, :paper_bgcolor, :plot_bgcolor, :width, :height, :barmode, :barnorm, :bargap, :bargroupgap, :geo, :mapbox ]) if pl.xaxis !== nothing for x in pl.xaxis merge!(layout, Dict(x, "x")) end end if pl.yaxis !== nothing for y in pl.yaxis merge!(layout, Dict(y, "y")) end end if pl.axes !== nothing for d in Dict.(pl.axes) merge!(layout, d) end end layout end function Stipple.render(pl::PlotLayout, fieldname::Union{Symbol,Nothing} = nothing) Dict(pl) end function Stipple.render(pl::Vector{PlotLayout}, fieldname::Union{Symbol,Nothing} = nothing) Dict.(pl) end end
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
2895
module StipplePlotly using Genie, Stipple, Stipple.Reexport, Stipple.ParsingTools using Requires import Genie: Assets.add_fileroute, Assets.asset_path #===# const assets_config = Genie.Assets.AssetsConfig(package = "StipplePlotly.jl") _symbol_dict(x) = x _symbol_dict(d::AbstractDict) = Dict{Symbol,Any}([(Symbol(k), _symbol_dict(v)) for (k, v) in d]) #===# function deps_routes() :: Nothing Genie.Assets.external_assets(Stipple.assets_config) && return nothing basedir = dirname(@__DIR__) add_fileroute(assets_config, "plotly.min.js"; basedir, named = :get_plotlyjs) add_fileroute(assets_config, "ResizeSensor.js"; basedir, named = :get_resizesensorjs) add_fileroute(assets_config, "lodash.min.js"; basedir, named = :get_lodashjs) add_fileroute(assets_config, "vueresize.min.js"; basedir, named = :get_vueresizejs) add_fileroute(assets_config, "vueplotly.min.js"; basedir, named = :get_vueplotlyjs) add_fileroute(assets_config, "sentinel.min.js"; basedir, named = :get_sentineljs) add_fileroute(assets_config, "syncplot.js"; basedir, named = :get_syncplotjs) nothing end function deps() :: Vector{String} [ script(src = asset_path(assets_config, :js, file="plotly.min")), script(src = asset_path(assets_config, :js, file="ResizeSensor")), script(src = asset_path(assets_config, :js, file="lodash.min")), script(src = asset_path(assets_config, :js, file="vueresize.min")), script(src = asset_path(assets_config, :js, file="vueplotly.min")), script(src = asset_path(assets_config, :js, file="sentinel.min")), script(src = asset_path(assets_config, :js, file="syncplot")) ] end #===# include("Charts.jl") @reexport using .Charts include("Layouts.jl") @reexport using .Layouts function __init__() deps_routes() Stipple.deps!(@__MODULE__, deps) isdefined(Stipple, :register_global_components) && Stipple.register_global_components("plotly", legacy = true) @require PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5" begin @static if !isdefined(Base, :get_extension) include("../ext/StipplePlotlyPlotlyBaseExt.jl") end export PBPlotWithEvents, PBPlotWithEventsReadOnly Base.@kwdef struct PBPlotWithEvents var""::R{PlotlyBase.Plot} = PlotlyBase.Plot() _selected::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _hover::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _click::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _relayout::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() end Base.@kwdef struct PBPlotWithEventsReadOnly var""::R{PlotlyBase.Plot} = PlotlyBase.Plot(), READONLY _selected::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _hover::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _click::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() _relayout::R{Charts.PlotlyEvent} = Charts.PlotlyEvent() end end end end # module
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
1415
function create_example_dataframe() xs = [1.0, 2.0, 3.0, 4.0] ys = [10.0, 20.0, 30.0, 40.0] groups = [1, 2, 1, 2] labels = ["A", "C", "B", "D"] return DataFrame(X = xs, Y = ys, Group = groups, Label = labels) end @testset "Scatter Plots" begin @testset "Multiple Groups without Tooltips" begin df = create_example_dataframe() pd = plotdata(df, :X, :Y; groupfeature = :Group) @test length(pd) == 2 @test length(pd[1].x) == length(pd[2].x) @test length(pd[1].y) == length(pd[2].y) @test isnothing(pd[1].text) @test isnothing(pd[2].text) end @testset "Multiple Groups with Tooltips" begin df = create_example_dataframe() pd = plotdata(df, :X, :Y; groupfeature = :Group, text = df.Label) @test length(pd) == 2 @test length(pd[1].x) == length(pd[2].x) == 2 @test length(pd[1].y) == length(pd[2].y) == 2 @test !isnothing(pd[1].text) @test !isnothing(pd[2].text) if !isnothing(pd[1].text) && !isnothing(pd[2].text) @test length(pd[1].text) == length(pd[1].x) == length(pd[1].y) == 2 @test length(pd[2].text) == length(pd[2].x) == length(pd[2].x) == 2 @test pd[1].text[1] == "A" @test pd[1].text[2] == "B" @test pd[2].text[1] == "C" @test pd[2].text[2] == "D" end end end
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
2502
@testset "PlotlyBase extension" begin @testset "Stipple.JSONText" begin @test ! @isdefined(PBPlotWithEvents) || @isdefined(PlotlyBase) using PlotlyBase, PlotlyBase.JSON @test @isdefined PBPlotWithEvents sc = scatter(x = StipplePlotly.JSONText("jsontext"), more_of_this = "a") pl = Plot(sc) @test JSON.json(sc) == "{\"type\":\"scatter\",\"more\":{\"of\":{\"this\":\"a\"}},\"x\":jsontext}" @test contains(JSON.json(pl), "{\"type\":\"scatter\",\"more\":{\"of\":{\"this\":\"a\"}},\"x\":jsontext}") @test Stipple.json(sc) == "{\"type\":\"scatter\",\"more\":{\"of\":{\"this\":\"a\"}},\"x\":jsontext}" @test contains(Stipple.json(pl), "{\"type\":\"scatter\",\"more\":{\"of\":{\"this\":\"a\"}},\"x\":jsontext}") end @testset "Parsing" begin using Stipple import Stipple.stipple_parse @testset "Layout" begin pl = PlotlyBase.Layout(xaxis_range = [1, 2]) pl_d = JSON3.read(Stipple.json(render(pl)), Dict) pl_in = stipple_parse(PlotlyBase.Layout, pl_d) @test pl_in[:xaxis_range] == [1, 2] pl_in = stipple_parse(PlotlyBase.Layout{Dict{Symbol, Any}}, pl_d) pl_in[:xaxis_range] == [1, 2] @static if VersionNumber(Genie.Assets.package_version(Stipple)) >= v"0.30.6" pl_in = stipple_parse(PlotlyBase.Layout{OrderedDict{Symbol, Any}}, pl_d) @test pl_in[:xaxis_range] == [1, 2] end end @testset "GenericTrace" begin tr = scatter(x = [1, 2, 3], y = [3, 4, 5]) tr_d = JSON3.read(Stipple.json(render(tr)), Dict) tr_in = stipple_parse(GenericTrace, tr_d) @test tr_in.x == [1, 2, 3] @test tr_in.y == [3, 4, 5] end @testset "Plot" begin pl = PlotlyBase.Plot([scatter(x = [1, 2, 3], y = [3, 4, 5])], PlotlyBase.Layout(xaxis_range = [1, 2])) pl_d = JSON3.read(Stipple.json(render(pl)), Dict) pl_in = stipple_parse(PlotlyBase.Plot, pl_d) @test length(pl_in.data) == 1 @test pl_in.layout[:xaxis_range] == [1, 2] PlotType = typeof(Plot()) pl_in = stipple_parse(PlotType, pl_d) @test length(pl_in.data) == 1 @test pl_in.data[1][:x] == [1, 2, 3] @test pl_in.layout[:xaxis_range] == [1, 2] end end end pl = PlotlyBase.Layout(xaxis_range = [1, 2])
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
code
275
using StipplePlotly using Stipple using Test using DataFrames files = filter(endswith(".jl"), readdir(@__DIR__)) for file in files file == "runtests.jl" && continue title = file[1:end-3] @testset verbose = true "$title" begin include(file) end end
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
docs
2349
# StipplePlotly Embedding Plotly Charts in Stipple. ### News: The standard API is now PlotlyBase, the StipplePlotly API is considered legacy. ### Example with forwarding of plotly events See the docstrings of `watchplots()` and `watchplot()` for more details! ```julia using Stipple, Stipple.ReactiveTools using StipplePlotly using PlotlyBase @app Example begin @mixin plot::PBPlotWithEvents @in plot_cursor = Dict{String, Any}() @onchange isready begin isready || return p = Plot(scatter(y=1:10)) plot.layout = p.layout plot.data = p.data end @onchange plot_selected begin haskey(plot_selected, "points") && @info "Selection: $(getindex.(plot_selected["points"], "pointIndex"))" end @onchange plot_click begin @info "$plot_click" end @onchange plot_hover begin @info "hovered over $(plot_hover["points"][1]["x"]):$(plot_hover["points"][1]["y"])" # @info "$plot_hover" end @onchange plot_cursor begin @info "cursor moved to $(plot_cursor["cursor"]["x"]):$(plot_cursor["cursor"]["y"])" # @info "$plot_cursor" end end # commented lines below: manual definition of plot_events # @app Example begin # @in plot = Plot() # @in plot_selected = Dict{String, Any}() # @in plot_click = Dict{String, Any}() # @in plot_hover = Dict{String, Any}() # @in plot_cursor = Dict{String, Any}() # end Stipple.js_mounted(::Example) = watchplots() # the keyword argument 'keepselection' (default = false) controls whether the selection outline shall be removed after selection function ui() cell(class = "st-module", [ plotly(:plot, syncevents = true, keepselection = false), ]) end @page("/", ui, model = Example) ``` Possible forwarded events are - '_selected' (Selection changed) - '_hover' (hovered over data point) - '_click' (click event on plot area) - '_relayout' (plot layout changed) - '_cursor' (current mouse position, not covered in PBPlotWithEvents in order to reduce data traffic) For more Stipple Plotly Demos please check: [Stipple Demos Repo](https://github.com/GenieFramework/StippleDemos) ## Acknowledgement Handling of Plotly Events was highly inspired by the [PlotlyJS](https://github.com/JuliaPlots/PlotlyJS.jl) package by [Spencer Lyon](https://github.com/sglyon)
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
docs
48
# StipplePlotly Plotting library for Stipple.jl
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git